textmode.export.js 1.5.0 → 1.5.1

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,7 +1,7 @@
1
- (function(et,K){typeof exports=="object"&&typeof module<"u"?K(exports):typeof define=="function"&&define.amd?define(["exports"],K):K((et=typeof globalThis<"u"?globalThis:et||self).TextmodeExport={})})(this,function(et){"use strict";var Tn=Object.defineProperty;var Cn=(et,K,ot)=>K in et?Tn(et,K,{enumerable:!0,configurable:!0,writable:!0,value:ot}):et[K]=ot;var w=(et,K,ot)=>Cn(et,typeof K!="symbol"?K+"":K,ot);class K{$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 r=t[e+2],a=t[e+3]/255;return{isInverted:!!(1&r),flipHorizontal:!!(2&r),flipVertical:!!(4&r),rotation:Math.round(360*a*100)/100}}}class ot{$downloadFile(t,e){try{const r=this._sanitizeFilename(e),a=URL.createObjectURL(t),s=document.createElement("a");s.href=a,s.download=r,s.style.display="none",s.rel="noopener",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a)}catch(r){console.error("[textmode-export] Failed to download file:",r)}}_sanitizeFilename(t){if(!t)return this._generateDefaultFilename();const e=t.trim();return e?e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,255)||this._generateDefaultFilename():this._generateDefaultFilename()}_generateDefaultFilename(){return`textmode-export-${new Date().toISOString().slice(0,19).replace(/:/g,"-")}`}}const ai=new WeakMap;function la(i){return Math.round(255*i[0])+(Math.round(255*i[1])<<8)}function we(i,t){let e=ai.get(i);if(!e){e=new Map;for(const r of i.characters)e.set(la(r.color),r);ai.set(i,e)}return e.get(t)}function si(i,t){const e=i==="base"?"Base layer":`Layer ${Number.parseInt(i.replace("layer-",""),10)}`;return t._visible===!1?`${e} (hidden)`:e}function oi(i){return[{id:"base",layer:i.layers.base},...i.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:si(t,e),layer:e}))}function Zt(i,t){const e=t??i.layers.base,r=(function(n,l){if(l===n.layers.base)return"base";const c=n.layers.all.indexOf(l);if(c>=0)return`layer-${c+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")})(i,e),a=e.grid,s=e.font,o=e.drawFramebuffer;if(!a||!o)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:r,label:si(r,e),layer:e,grid:a,font:s,drawFramebuffer:o}}function te(i,t){return{r:i[t],g:i[t+1],b:i[t+2],a:i[t+3]}}class ha extends K{_calculateCellPosition(t,e,r){return{x:t,y:e,cellX:t*r.cellWidth,cellY:e*r.cellHeight}}$extractSVGCellData(t,e){const r=[];let a=0;for(let s=0;s<e.rows;s++)for(let o=0;o<e.cols;o++){const n=4*a,l=this.$getEncodedCharacterValue(t.characterPixels,n);let c=te(t.primaryColorPixels,n),d=te(t.secondaryColorPixels,n);const u=this.$extractCellTransform(t.characterPixels,n);if(u.isInverted){const h=c;c=d,d=h}const p=this._calculateCellPosition(o,s,e);r.push({encodedGlyphSlot:l,primaryColor:c,secondaryColor:d,transform:u,position:p}),a++}return r}}class ua{_createGlyphPath(t,e,r,a,s){const o=s/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:r+e.xMin*o,y1:a+-e.yMax*o,x2:r+e.xMax*o,y2:a+-e.yMin*o}),toSVG:()=>this._glyphToSVGPath(e,r,a,o)}}_glyphToSVGPath(t,e,r,a){if(!t||!t.xs)return"";const{xs:s,ys:o,endPts:n,flags:l}=t;if(!(s&&o&&n&&l))return"";let c="",d=0;for(let u=0;u<n.length;u++){const p=n[u];if(!(p<d)){if(p>=d){const h=e+s[d]*a,m=r-o[d]*a;c+=`M${h.toFixed(2)},${m.toFixed(2)}`;let f=d+1;for(;f<=p;)if(1&l[f]){const y=e+s[f]*a,b=r-o[f]*a;c+=`L${y.toFixed(2)},${b.toFixed(2)}`,f++}else{const y=e+s[f]*a,b=r-o[f]*a,_=f+1>p?d:f+1;if(1&l[_]){const T=e+s[_]*a,S=r-o[_]*a;c+=`Q${y.toFixed(2)},${b.toFixed(2)} ${T.toFixed(2)},${S.toFixed(2)}`,f=_+1}else{const T=(y+(e+s[_]*a))/2,S=(b+(r-o[_]*a))/2;c+=`Q${y.toFixed(2)},${b.toFixed(2)} ${T.toFixed(2)},${S.toFixed(2)}`,f=_}}c+="Z"}d=p+1}}return c}$generatePositionedCharacterPath(t,e,r,a,s,o,n,l){if(!l)return null;const c=e.font,d=n/c.head.unitsPerEm,u=r+(s-l.advanceWidth*d)/2,p=a+c.hhea.ascender*d;return this._createGlyphPath(c,l,u,p,n).toSVG()||null}}class pa{constructor(){w(this,"_pathGenerator");this._pathGenerator=new ua}$generateSVGHeader(t){const{width:e,height:r}=t;return`<?xml version="1.0" encoding="UTF-8"?><svg width="${e}" height="${r}" viewBox="0 0 ${e} ${r}" xmlns="http://www.w3.org/2000/svg"><title>textmode.js sketch</title>`}$generateSVGFooter(){return"</g></svg>"}_generateTransformAttribute(t,e){const{transform:r,position:a}=t;if(!r.flipHorizontal&&!r.flipVertical&&!r.rotation)return"";const s=a.cellX+e.cellWidth/2,o=a.cellY+e.cellHeight/2,n=[];if(r.flipHorizontal||r.flipVertical){const l=r.flipHorizontal?-1:1,c=r.flipVertical?-1:1;n.push(`translate(${s} ${o})scale(${l} ${c})translate(${-s} ${-o})`)}return r.rotation&&n.push(`rotate(${r.rotation} ${s} ${o})`),` transform="${n.join(" ")}"`}_generateCellBackground(t,e,r){if(!r.includeBackgroundRectangles||t.secondaryColor.a===0)return"";const{position:a}=t,{r:s,g:o,b:n,a:l}=t.secondaryColor,c=`rgba(${s},${o},${n},${l/255})`;return r.drawMode==="stroke"?`<rect x="${a.cellX}" y="${a.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${c}" fill="none" stroke-width="${r.strokeWidth}"/>`:`<rect x="${a.cellX}" y="${a.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${c}"/>`}_generateCharacterPath(t,e,r,a){const s=we(r,t.encodedGlyphSlot);if(!s)return"";const o=this._pathGenerator.$generatePositionedCharacterPath(s.character,r,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,r.fontSize,s.glyphData);if(!o)return"";const{r:n,g:l,b:c,a:d}=t.primaryColor,u=`rgba(${n},${l},${c},${d/255})`;return a.drawMode==="stroke"?`<path d="${o}" stroke="${u}" stroke-width="${a.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${u}"/>`}$generateCellContent(t,e,r,a){const s=[],o=this._generateCellBackground(t,e,a);o&&s.push(o);const n=this._generateCharacterPath(t,e,r,a);if(n){const l=this._generateTransformAttribute(t,e);s.push(l?`<g${l}>${n}</g>`:n)}return s.join("")}$generateSVGContent(t,e,r,a){const s=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)s.push(this.$generateCellContent(o,e,r,a));return s.push(this.$generateSVGFooter()),s.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}}class ni{_applyDefaultOptions(t){return{includeBackgroundRectangles:t.includeBackgroundRectangles??!0,drawMode:t.drawMode??"fill",strokeWidth:t.strokeWidth??1,filename:t.filename,layer:t.layer}}$generateSVG(t,e={}){const r=new ha,a=new pa,s=this._applyDefaultOptions(e),o=Zt(t,s.layer),n=r.$extractSVGCellData(r.$extractFramebufferData(o.drawFramebuffer),o.grid),l=a.$generateSVGContent(n,o.grid,o.font,s);return a.$optimizeSVGContent(l)}$saveSVG(t,e={}){new ot().$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename)}}const ye={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},ma=".png",fa=".jpg",ga=".webp";class ci{_applyDefaultOptions(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}_validateOptions(t){if(!(t.format in ye))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const r=t,a=document.createElement("canvas"),s=a.getContext("2d"),o=Math.round(r.width*e.scale),n=Math.round(r.height*e.scale);return a.width=o,a.height=n,s.imageSmoothingEnabled=!1,s.clearRect(0,0,o,n),s.drawImage(r,0,0,r.width,r.height,0,0,o,n),await new Promise((l,c)=>{a.toBlob(d=>{d?l(d):c(new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},ye[e.format])})}async $saveImage(t,e={}){const r=this._applyDefaultOptions(e);this._validateOptions(r);const a=await this.$generateImageBlob(t,r);new ot().$downloadFile(a,r.filename)}async $copyImageToClipboard(t,e={}){if(typeof navigator>"u"||!navigator.clipboard||typeof navigator.clipboard.write!="function")throw new Error("Clipboard API is not available in this environment");const r=this._applyDefaultOptions(e);this._validateOptions(r);const a=await this.$generateImageBlob(t,r),s=new ClipboardItem({[ye[r.format]]:a});await navigator.clipboard.write([s])}}class di{_applyDefaultOptions(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}_createTXTContent(t,e){var l;const r=new K,a=Zt(t,e.layer),s=r.$extractFramebufferData(a.drawFramebuffer),o=[];let n=0;for(let c=0;c<a.grid.rows;c++){let d="";for(let u=0;u<a.grid.cols;u++){const p=4*n,h=r.$getEncodedCharacterValue(s.characterPixels,p);d+=((l=we(a.font,h))==null?void 0:l.character)||e.emptyCharacter,n++}e.preserveTrailingSpaces||(d=d.trimEnd()),o.push(d)}return o.join(`
2
- `)}$generateTXT(t,e={}){return this._createTXTContent(t,this._applyDefaultOptions(e))}$saveTXT(t,e={}){const r=this._applyDefaultOptions(e),a=this._createTXTContent(t,r),s=new Blob([a],{type:"text/plain;charset=utf-8"});new ot().$downloadFile(s,r.filename)}}class wa{constructor(){w(this,"_canvas");w(this,"_ctx")}async $record(t,e,r,a){const s=Math.max(1,Math.round(e.frameRate)),o=Math.round(1e3/s),n=Math.max(1,Math.round(e.frameCount));return await new Promise((l,c)=>{const d=[];let u,p=0,h=!1;const m=()=>{u&&(u(),u=void 0)},f=b=>{h||(h=!0,m(),l(b))},y=()=>{if(p>=n)f(d);else try{const b=e.scale,_=Math.max(1,Math.round(t.width*b)),T=Math.max(1,Math.round(t.height*b));this._canvas||(this._canvas=document.createElement("canvas")),this._canvas.width===_&&this._canvas.height===T||(this._canvas.width=_,this._canvas.height=T),this._ctx||(this._ctx=this._canvas.getContext("2d"));const S=this._ctx;S.imageSmoothingEnabled=!1,S.clearRect(0,0,_,T),S.drawImage(t,0,0,t.width,t.height,0,0,_,T);const A={imageData:S.getImageData(0,0,_,T),width:_,height:T,delayMs:o};d.push(A),p+=1,a==null||a({state:"recording",frameIndex:p,totalFrames:n}),p>=n&&f(d)}catch(b){(_=>{if(h)return;h=!0,m();const T=_ instanceof Error?_.message:"GIF recording failed";a==null||a({state:"error",message:T}),c(_ instanceof Error?_:new Error(String(_)))})(b)}};u=r(()=>{y()}),a==null||a({state:"recording",frameIndex:0,totalFrames:n})})}}var li,ee,hi=Object.defineProperty,ya=(li=i=>{function t(u,p,h){return .29889531*u+.58662247*p+.11448223*h}function e(u,p,h){return .59597799*u-.2741761*p-.32180189*h}function r(u,p,h){return .21147017*u-.52261711*p+.31114694*h}function a(u,p){let h=u[0]-p[0],m=u[1]-p[1],f=u[2]-p[2],y=s(u)-s(p);return h*h*.5053+m*m*.299+f*f*.1957+y*y}function s(u){return u[3]!=null?u[3]:255}function o(u,p){return Math.sqrt(a(u,p))}function n(u,p){let[h,m,f]=u,[y,b,_]=p,T=t(h,m,f)-t(y,b,_),S=e(h,m,f)-e(y,b,_),A=r(h,m,f)-r(y,b,_),E=s(u)-s(p);return T*T*.5053+S*S*.299+A*A*.1957+E*E}function l(u,p){return Math.sqrt(n(u,p))}function c(u,p){var h,m=0;for(h=0;h<u.length;h++){let f=u[h]-p[h];m+=f*f}return m}function d(u,p){return Math.sqrt(c(u,p))}hi(i,"__esModule",{value:!0}),((u,p)=>{for(var h in p)hi(u,h,{get:p[h],enumerable:!0})})(i,{colorDifferenceRGBToYIQ:()=>l,colorDifferenceRGBToYIQSquared:()=>n,colorDifferenceYIQ:()=>o,colorDifferenceYIQSquared:()=>a,euclideanDistance:()=>d,euclideanDistanceSquared:()=>c})},()=>(ee||li((ee={exports:{}}).exports,ee),ee.exports)),ba=59;function ui(i=256){let t=0,e=new Uint8Array(i);return{get buffer(){return e.buffer},reset(){t=0},bytesView:()=>e.subarray(0,t),bytes:()=>e.slice(0,t),writeByte(a){r(t+1),e[t]=a,t++},writeBytes(a,s=0,o=a.length){r(t+o);for(let n=0;n<o;n++)e[t++]=a[n+s]},writeBytesView(a,s=0,o=a.byteLength){r(t+o),e.set(a.subarray(s,s+o),t),t+=o}};function r(a){var s=e.length;if(s>=a)return;a=Math.max(a,s*(s<1048576?2:1.125)>>>0),s!=0&&(a=Math.max(a,256));let o=e;e=new Uint8Array(a),t>0&&e.set(o.subarray(0,t),0)}}var va=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],xa=function(i,t,e,r,a,s,o,n){a=a||ui(512),s=s||new Uint8Array(256),o=o||new Int32Array(5003),n=n||new Int32Array(5003);let l=o.length,c=Math.max(2,r);s.fill(0),n.fill(0),I();let d=0,u=0,p=c+1,h=p,m=!1,f=h,y=L(f),b=1<<p-1,_=b+1,T=b+2,S=0,A=e[0],E=0;for(let M=l;M<65536;M*=2)++E;E=8-E,a.writeByte(c),$(b);for(let M=1;M<e.length;M++)D(e[M]);return $(A),$(_),a.writeByte(0),a.bytesView();function C(M){s[S++]=M,S>=254&&V()}function I(){o.fill(-1)}function D(M){let j=(M<<12)+A,W=M<<E^A;if(o[W]===j)A=n[W];else{if(o[W]>=0){let X=W===0?1:l-W;do if(W-=X,W<0&&(W+=l),o[W]===j)return void(A=n[W]);while(o[W]>=0)}$(A),A=M,T<4096?(n[W]=T++,o[W]=j):(I(),T=b+2,m=!0,$(b))}}function V(){S>0&&(a.writeByte(S),a.writeBytesView(s,0,S),S=0)}function L(M){return(1<<M)-1}function $(M){for(d&=va[u],u>0?d|=M<<u:d=M,u+=f;u>=8;)C(255&d),d>>=8,u-=8;if((T>y||m)&&(m?(f=h,y=L(f),m=!1):(++f,y=f==12?4096:L(f))),M==_){for(;u>0;)C(255&d),d>>=8,u-=8;V()}}};function pi(i,t,e){return i<<8&63488|t<<2&992|e>>3&31}function mi(i,t,e,r){return i>>4|240&t|(240&e)<<4|(240&r)<<8}function fi(i,t,e){return i>>4<<8|t>>4<<4|e>>4}function ie(i,t,e){return i<t?t:i>e?e:i}function re(i){return i*i}function gi(i,t,e){for(var r=0,a=1e100,s=i[t],o=s.cnt,n=(s.ac,s.rc),l=s.gc,c=s.bc,d=s.fw;d!=0;d=i[d].fw){var u=i[d].cnt,p=o*u/(o+u);if(!(p>=a)){var h=0;!((h+=p*re(i[d].rc-n))>=a)&&!((h+=p*re(i[d].gc-l))>=a)&&!((h+=p*re(i[d].bc-c))>=a)&&(a=h,r=d)}}s.err=a,s.nn=r}function be(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function _a(i,t,e){let{format:r="rgb565",clearAlpha:a=!0,clearAlphaColor:s=0,clearAlphaThreshold:o=0,oneBitAlpha:n=!1}=e||{},l=e.useSqrt!==!1,c=r==="rgba4444",d=(function(M,j){let W=new Array(j==="rgb444"?4096:65536),X=M.length;if(j==="rgba4444")for(let q=0;q<X;++q){let Y=M[q],U=Y>>24&255,tt=Y>>16&255,wt=Y>>8&255,st=255&Y,Q=mi(st,wt,tt,U),Tt=Q in W?W[Q]:W[Q]=be();Tt.rc+=st,Tt.gc+=wt,Tt.bc+=tt,Tt.ac+=U,Tt.cnt++}else if(j==="rgb444")for(let q=0;q<X;++q){let Y=M[q],U=Y>>16&255,tt=Y>>8&255,wt=255&Y,st=fi(wt,tt,U),Q=st in W?W[st]:W[st]=be();Q.rc+=wt,Q.gc+=tt,Q.bc+=U,Q.cnt++}else for(let q=0;q<X;++q){let Y=M[q],U=Y>>16&255,tt=Y>>8&255,wt=255&Y,st=pi(wt,tt,U),Q=st in W?W[st]:W[st]=be();Q.rc+=wt,Q.gc+=tt,Q.bc+=U,Q.cnt++}return W})(i,r),u=d.length,p=u-1,h=new Uint32Array(u+1);for(var m=0,f=0;f<d.length;++f){let M=d[f];if(M!=null){var y=1/M.cnt;c&&(M.ac*=y),M.rc*=y,M.gc*=y,M.bc*=y,d[m++]=M}}for(re(t)/m<.022&&(l=!1),f=0;f<m-1;++f)d[f].fw=f+1,d[f+1].bk=f,l&&(d[f].cnt=Math.sqrt(d[f].cnt));var b,_,T;for(l&&(d[f].cnt=Math.sqrt(d[f].cnt)),f=0;f<m;++f){gi(d,f);var S=d[f].err;for(_=++h[0];_>1&&!(d[b=h[T=_>>1]].err<=S);_=T)h[_]=b;h[_]=f}var A=m-t;for(f=0;f<A;){for(var E;;){var C=h[1];if((E=d[C]).tm>=E.mtm&&d[E.nn].mtm<=E.tm)break;for(E.mtm==p?C=h[1]=h[h[0]--]:(gi(d,C),E.tm=f),S=d[C].err,_=1;(T=_+_)<=h[0]&&(T<h[0]&&d[h[T]].err>d[h[T+1]].err&&T++,!(S<=d[b=h[T]].err));_=T)h[_]=b;h[_]=C}var I=d[E.nn],D=E.cnt,V=I.cnt;y=1/(D+V),c&&(E.ac=y*(D*E.ac+V*I.ac)),E.rc=y*(D*E.rc+V*I.rc),E.gc=y*(D*E.gc+V*I.gc),E.bc=y*(D*E.bc+V*I.bc),E.cnt+=I.cnt,E.mtm=++f,d[I.bk].fw=I.fw,d[I.fw].bk=I.bk,I.mtm=p}let L=[];var $=0;for(f=0;;++$){let M=ie(Math.round(d[f].rc),0,255),j=ie(Math.round(d[f].gc),0,255),W=ie(Math.round(d[f].bc),0,255),X=255;c&&(X=ie(Math.round(d[f].ac),0,255),n&&(X=X<=(typeof n=="number"?n:127)?0:255),a&&X<=o&&(M=j=W=s,X=0));let q=c?[M,j,W,X]:[M,j,W];if(ka(L,q)||L.push(q),(f=d[f].fw)==0)break}return L}function ka(i,t){for(let e=0;e<i.length;e++){let r=i[e],a=r[0]===t[0]&&r[1]===t[1]&&r[2]===t[2],s=!(r.length>=4&&t.length>=4)||r[3]===t[3];if(a&&s)return!0}return!1}function Ta(i,t,e){let r=(e=e||"rgb565")==="rgb444"?4096:65536,a=new Uint8Array(i.length),s=new Array(r);if(e==="rgba4444")for(let o=0;o<i.length;o++){let n,l=i[o],c=l>>24&255,d=l>>16&255,u=l>>8&255,p=255&l,h=mi(p,u,d,c);s[h]!=null?n=s[h]:(n=Ca(p,u,d,c,t),s[h]=n),a[o]=n}else for(let o=0;o<i.length;o++){let n,l=i[o],c=l>>16&255,d=l>>8&255,u=255&l,p=e==="rgb444"?fi(u,d,c):pi(u,d,c);s[p]!=null?n=s[p]:(n=Ea(u,d,c,t),s[p]=n),a[o]=n}return a}function Ca(i,t,e,r,a){let s=0,o=1e100;for(let n=0;n<a.length;n++){let l=a[n],c=l[0],d=l[1],u=l[2],p=Pt(l[3]-r);p>o||(p+=Pt(c-i),!(p>o)&&(p+=Pt(d-t),!(p>o)&&(p+=Pt(u-e),!(p>o)&&(o=p,s=n))))}return s}function Ea(i,t,e,r){let a=0,s=1e100;for(let o=0;o<r.length;o++){let n=r[o],l=n[0],c=n[1],d=n[2],u=Pt(l-i);u>s||(u+=Pt(c-t),!(u>s)&&(u+=Pt(d-e),!(u>s)&&(s=u,a=o)))}return a}function Pt(i){return i*i}function Sa(i={}){let{initialCapacity:t=4096,auto:e=!0}=i,r=ui(t),a=new Uint8Array(256),s=new Int32Array(5003),o=new Int32Array(5003),n=!1;return{reset(){r.reset(),n=!1},finish(){r.writeByte(ba)},bytes:()=>r.bytes(),bytesView:()=>r.bytesView(),get buffer(){return r.buffer},get stream(){return r},writeHeader:l,writeFrame(c,d,u,p={}){let{transparent:h=!1,transparentIndex:m=0,delay:f=0,palette:y=null,repeat:b=0,colorDepth:_=8,dispose:T=-1}=p,S=!1;if(e?n||(S=!0,l(),n=!0):S=!!p.first,d=Math.max(0,Math.floor(d)),u=Math.max(0,Math.floor(u)),S){if(!y)throw new Error("First frame must include a { palette } option");(function(C,I,D,V,L=8){let $=1,M=0,j=ve(V.length)-1,W=$<<7|L-1<<4|M<<3|j;Ct(C,I),Ct(C,D),C.writeBytes([W,0,0])})(r,d,u,y,_),wi(r,y),b>=0&&(function(C,I){C.writeByte(33),C.writeByte(255),C.writeByte(11),yi(C,"NETSCAPE2.0"),C.writeByte(3),C.writeByte(1),Ct(C,I),C.writeByte(0)})(r,b)}let A=Math.round(f/10);(function(C,I,D,V,L){var $,M;C.writeByte(33),C.writeByte(249),C.writeByte(4),L<0&&(L=0,V=!1),V?($=1,M=2):($=0,M=0),I>=0&&(M=7&I),M<<=2,C.writeByte(0|M|0|$),Ct(C,D),C.writeByte(L||0),C.writeByte(0)})(r,T,A,h,m);let E=!!y&&!S;(function(C,I,D,V){if(C.writeByte(44),Ct(C,0),Ct(C,0),Ct(C,I),Ct(C,D),V){let L=0,$=0,M=ve(V.length)-1;C.writeByte(128|L|$|M)}else C.writeByte(0)})(r,d,u,E?y:null),E&&wi(r,y),(function(C,I,D,V,L=8,$,M,j){xa(D,V,I,L,C,$,M,j)})(r,c,d,u,_,a,s,o)}};function l(){yi(r,"GIF89a")}}function wi(i,t){let e=1<<ve(t.length);for(let r=0;r<e;r++){let a=[0,0,0];r<t.length&&(a=t[r]),i.writeByte(a[0]),i.writeByte(a[1]),i.writeByte(a[2])}}function Ct(i,t){i.writeByte(255&t),i.writeByte(t>>8&255)}function yi(i,t){for(var e=0;e<t.length;e++)i.writeByte(t.charCodeAt(e))}function ve(i){return Math.max(Math.ceil(Math.log2(i)),1)}ya();class Ba{constructor(t,e){w(this,"_recorder");w(this,"_textmodifier");w(this,"_registerPostDrawHook");this._recorder=new wa,this._textmodifier=t,this._registerPostDrawHook=e}async $saveGIF(t={}){const e=this._textmodifier.canvas,r=this._applyDefaultOptions(t),a=t.onProgress;try{const s=await this._recorder.$record(e,r,this._registerPostDrawHook,a),o=Sa(),{repeat:n}=t;for(let d=0;d<s.length;d++){const u=s[d],{width:p,height:h,imageData:m,delayMs:f}=u,y=new Uint32Array(m.data.buffer),b=_a(y,256,{}),_=Ta(y,b);o.writeFrame(_,p,h,{palette:b,delay:f,repeat:d===0?n:-1}),d%2!=0&&d!==s.length-1||(a==null||a({state:"encoding",frameIndex:d+1,totalFrames:s.length}),await new Promise(T=>setTimeout(T,0)))}o.finish();const l=o.bytes(),c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);new ot().$downloadFile(new Blob([c],{type:"image/gif"}),r.filename),a==null||a({state:"completed",totalFrames:r.frameCount})}catch(s){throw a==null||a({state:"error",message:s instanceof Error?s.message:"GIF export failed"}),s}}_applyDefaultOptions(t){const e=Math.abs(Math.round(t.frameCount??300)),r=Math.abs(t.frameRate??60),a=Math.abs(t.scale??1),s=Math.max(-1,Math.round(t.repeat??0));return{filename:t.filename,frameCount:e,frameRate:r,scale:a,repeat:s}}}class Mt extends Error{constructor(e,r,a){super(r);w(this,"code");w(this,"cause");this.name="VideoExportError",this.code=e,this.cause=a}}function bi(){return new Mt("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}class Pa{constructor(t,e,r,a){w(this,"canvas");w(this,"_textmodifier");w(this,"_registerPostDrawHook");w(this,"_context");w(this,"_sourceCanvas");w(this,"_pendingFrame",null);w(this,"_syntheticFrameCount",0);w(this,"_syntheticMillis",0);this._textmodifier=t,this._registerPostDrawHook=e,this._sourceCanvas=t.canvas,this.canvas=this._createStagingCanvas(r,a);const s=this.canvas.getContext("2d");if(!s)throw new Error("Video export requires a 2D canvas context for staging frames.");s.imageSmoothingEnabled=!1,this._context=s}async $render(t){var m;const e=this._textmodifier,r=Math.max(1,Math.round(t.frameCount)),a=Math.max(1,Math.round(t.frameRate)),s=1e3/a,o=e.isLooping(),n=e.frameCount,l=e.millis,c="secs"in e,d=e.secs,u=this._captureMethodSnapshots(),p=this._capturePropertySnapshots(),h=this._registerPostDrawHook(()=>{this._capturePendingFrame()});try{e.noLoop(),this._syntheticFrameCount=n,this._syntheticMillis=l,this._shadowTimingProperties(c),this._shadowTimingMethods(a,s),this._shadowResizeCanvas();for(let f=0;f<r;f++)this._throwIfAborted(t.signal),this._syntheticFrameCount=n+f+1,this._syntheticMillis=1e3*f/a,await this._renderOneFrame(f),this._throwIfAborted(t.signal),await t.onFrame({frameIndex:f,canvas:this.canvas})}finally{h(),(m=this._pendingFrame)==null||m.reject(new Error("Video export frame rendering was interrupted.")),this._pendingFrame=null,this._restoreProperties(p),this._restoreMethods(u),e.frameCount=n,e.millis=l,c&&d!==void 0&&(e.secs=d),o?e.loop():e.noLoop()}}_renderOneFrame(t){if(this._pendingFrame)throw new Error("A video export frame is already pending.");const e=this._textmodifier;return new Promise((r,a)=>{this._pendingFrame={frameIndex:t,resolve:r,reject:a};try{e.redraw(1)}catch(s){this._pendingFrame=null,a(s)}})}_capturePendingFrame(){const t=this._pendingFrame;if(t)try{this._context.clearRect(0,0,this.canvas.width,this.canvas.height),this._context.drawImage(this._sourceCanvas,0,0,this._sourceCanvas.width,this._sourceCanvas.height,0,0,this.canvas.width,this.canvas.height),this._pendingFrame=null,t.resolve()}catch(e){this._pendingFrame=null,t.reject(e)}}_createStagingCanvas(t,e){const r=document.createElement("canvas");return r.width=Math.max(1,Math.round(t)),r.height=Math.max(1,Math.round(e)),r}_captureMethodSnapshots(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._textmodifier,t),value:this._textmodifier[t]}))}_capturePropertySnapshots(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._textmodifier,t),descriptor:Object.getOwnPropertyDescriptor(this._textmodifier,t)}))}_shadowTimingProperties(t){Object.defineProperty(this._textmodifier,"frameCount",{configurable:!0,enumerable:!0,get:()=>this._syntheticFrameCount,set:e=>{this._syntheticFrameCount=e}}),Object.defineProperty(this._textmodifier,"millis",{configurable:!0,enumerable:!0,get:()=>this._syntheticMillis,set:e=>{this._syntheticMillis=e}}),t&&Object.defineProperty(this._textmodifier,"secs",{configurable:!0,enumerable:!0,get:()=>this._syntheticMillis/1e3,set:e=>{this._syntheticMillis=1e3*e}})}_shadowTimingMethods(t,e){const r=this._textmodifier,a=r.frameRate;r.deltaTime=()=>e,r.frameRate=function(s){return s===void 0?t:a.call(this,s)}}_shadowResizeCanvas(){this._textmodifier.resizeCanvas=()=>{}}_restoreMethods(t){const e=this._textmodifier;for(const r of t)r.hadOwnProperty?e[r.key]=r.value:delete e[r.key]}_restoreProperties(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this._textmodifier,e.key,e.descriptor):delete this._textmodifier[e.key]}_throwIfAborted(t){if(t!=null&&t.aborted)throw bi()}}function g(i){if(!i)throw new Error("Assertion failed.")}const vi=i=>{const t=(i%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw new Error(`Invalid rotation ${i}.`)},mt=i=>i&&i[i.length-1],Et=i=>i>=0&&i<2**32,k=i=>{let t=0;for(;i.readBits(1)===0&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+i.readBits(t)},yt=i=>{const t=k(i);return 1&t?t+1>>1:-(t>>1)},Z=i=>i.constructor===Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i),xi=i=>i.constructor===DataView?i:ArrayBuffer.isView(i)?new DataView(i.buffer,i.byteOffset,i.byteLength):new DataView(i),J=new TextEncoder,$t={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},zt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Nt={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},_i=i=>!!(i&&i.primaries&&i.transfer&&i.matrix&&i.fullRange!==void 0),xe=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i);class ki{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(a=>{let s=!1;t=()=>{s||(a(),this.pending--,s=!0)}}),r=this.currentPromise;return this.currentPromise=e,this.pending++,await r,t}}const Ti=(i,t,e)=>{let r=0,a=i.length-1,s=-1;for(;r<=a;){const o=r+(a-r+1)/2|0;e(i[o])<=t?(s=o,r=o+1):a=o-1}return s},_e=()=>{let i,t;return{promise:new Promise((e,r)=>{i=e,t=r}),resolve:i,reject:t}},Vt=i=>{throw new Error(`Unexpected value: ${i}`)},Ma=(i,t,e)=>i.getUint8(t)<<16|i.getUint8(t+1)<<8|i.getUint8(t+2),Ia=(i,t,e,r)=>{e>>>=0,e&=16777215,i.setUint8(t,e>>>16&255),i.setUint8(t+1,e>>>8&255),i.setUint8(t+2,255&e)},Ci=(i,t)=>Math.round(i/t)*t,Ei=(i,t)=>Math.round(i*t)/t,Si=(i,t)=>Math.floor(i*t)/t,Aa=/^[a-z]{3}$/,Lt=1e6*(1+Number.EPSILON);class Fa{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}}let ke=null;const Bi=()=>{var i;return ke!==null?ke:ke=typeof navigator<"u"&&((i=navigator.userAgent)==null?void 0:i.includes("Firefox"))};let Te=null;const Da=()=>{var i;return Te!==null?Te:Te=!(typeof navigator>"u"||!((i=navigator.vendor)!=null&&i.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))};let Ce=null;const Ra=()=>{if(Ce!==null)return Ce;if(typeof navigator>"u")return null;const i=/\bChrome\/(\d+)/.exec(navigator.userAgent);return i?Ce=Number(i[1]):null},Ee=function*(i){for(const t in i){const e=i[t];e!==void 0&&(yield{key:t,value:e})}},Va=i=>{switch(i.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}},La=(i,t)=>{if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++)if(i[e]!==t[e])return!1;return!0},Se=i=>{g(Number.isInteger(i.num)),g(Number.isInteger(i.den)),g(i.den!==0);let t=Math.abs(i.num),e=Math.abs(i.den);for(;e!==0;){const a=t%e;t=e,e=a}const r=t||1;return{num:i.num/r,den:i.den/r}},Pi=(i,t)=>{if(typeof i!="object"||!i)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},Mi=i=>Array.isArray(i)?i:[i];class Ii{constructor(){this._listeners=new Map}on(t,e,r){this._listeners.has(t)||this._listeners.set(t,new Set);const a={fn:e,once:(r==null?void 0:r.once)??!1};return this._listeners.get(t).add(a),()=>{var s;(s=this._listeners.get(t))==null||s.delete(a)}}_emit(...t){const[e,r]=t,a=this._listeners.get(e);if(a)for(const s of a){try{s.fn(r)}catch(o){console.error(o)}s.once&&a.delete(s)}}}const Wa=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(t=>typeof t=="string");class Ai{constructor(t,e){if(this.data=t,this.mimeType=e,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof e!="string")throw new TypeError("mimeType must be a string.")}}class Fi{constructor(t,e,r,a){if(this.data=t,this.mimeType=e,this.name=r,this.description=a,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!==void 0&&typeof e!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(a!==void 0&&typeof a!="string")throw new TypeError("description, when provided, must be a string.")}}class G{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,r=7-(7&this.pos),a=(e&1<<r)>>r;return this.pos++,a}readBits(t){if(t===1)return this.readBit();let e=0;for(let r=0;r<t;r++)e<<=1,e|=this.readBit();return e}writeBits(t,e){const r=this.pos+t;for(let a=this.pos;a<r;a++){const s=Math.floor(a/8);let o=this.bytes[s];const n=7-(7&a);o&=~(1<<n),o|=(e&1<<r-a-1)>>r-a-1<<n,this.bytes[s]=o}this.pos=r}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 t=new G(this.bytes);return t.pos=this.pos,t}}const Be=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Pe=[-1,1,2,3,4,5,6,8],Di=i=>{let t=Be.indexOf(i.sampleRate),e=null;t===-1&&(t=15,e=i.sampleRate);const r=Pe.indexOf(i.numberOfChannels);if(r===-1)throw new TypeError(`Unsupported number of channels: ${i.numberOfChannels}`);let a=13;i.objectType>=32&&(a+=6),t===15&&(a+=24);const s=Math.ceil(a/8),o=new Uint8Array(s),n=new G(o);return i.objectType<32?n.writeBits(5,i.objectType):(n.writeBits(5,31),n.writeBits(6,i.objectType-32)),n.writeBits(4,t),t===15&&n.writeBits(24,e),n.writeBits(4,r),o},nt=["avc","hevc","vp9","av1","vp8"],bt=["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"],ae=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Ut=[...ae,...bt],It=["webvtt"],se=[{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}],Ri=[{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}],Vi=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Li=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Oa=(i,t,e,r)=>{if(i==="avc"){const s=Math.ceil(t/16)*Math.ceil(e/16),o=se.find(l=>s<=l.maxMacroblocks&&r<=l.maxBitrate)??mt(se),n=o?o.level:0;return`avc1.${"64".padStart(2,"0")}00${n.toString(16).padStart(2,"0")}`}if(i==="hevc"){const n=t*e,l=Ri.find(d=>n<=d.maxPictureSize&&r<=d.maxBitrate)??mt(Ri);return`hev1.1.6.${l.tier}${l.level}.B0`}if(i==="vp8")return"vp8";if(i==="vp9"){const a=t*e;return`vp09.00.${(Vi.find(o=>a<=o.maxPictureSize&&r<=o.maxBitrate)??mt(Vi)).level.toString().padStart(2,"0")}.08`}if(i==="av1"){const s=t*e,o=Li.find(l=>s<=l.maxPictureSize&&r<=l.maxBitrate)??mt(Li);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}throw new TypeError(`Unhandled codec '${i}'.`)},$a=i=>{const t=i.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},Wi=i=>{const t=i.split("."),e=Number(t[1]),r=t[2];return[129,(e<<5)+Number(r.slice(0,-1)),((r.slice(-1)==="H"?1:0)<<7)+((Number(t[3])===8?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},Oi=/^pcm-([usf])(\d+)(be)?$/,At=i=>{if(g(bt.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=Oi.exec(i);let e;return g(t),e=t[1]==="u"?"unsigned":t[1]==="s"?"signed":"float",{dataType:e,sampleSize:Number(t[2])/8,littleEndian:t[3]!=="be",silentValue:i==="pcm-u8"?128:0}},za=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Na=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ua=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ha=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ja=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,$i=i=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!za.some(t=>i.decoderConfig.codec.startsWith(t)))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(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectWidth)||i.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectHeight)||i.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectWidth!==void 0!=(i.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(i.decoderConfig.description!==void 0&&!xe(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){const{colorSpace:t}=i.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const e=Object.keys($t);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${e.join(", ")}.`);const r=Object.keys(zt);if(t.transfer!=null&&!r.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const a=Object.keys(Nt);if(t.matrix!=null&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!Na.test(i.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(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!Ua.test(i.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(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!Ha.test(i.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(i.decoderConfig.codec.startsWith("av01")&&!ja.test(i.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/.')},qa=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],zi=i=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!qa.some(t=>i.decoderConfig.codec.startsWith(t)))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(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!xe(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(i.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(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.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(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.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(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.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(i.decoderConfig.codec.startsWith("ac-3")||i.decoderConfig.codec.startsWith("ac3")){if(i.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(i.decoderConfig.codec.startsWith("ec-3")||i.decoderConfig.codec.startsWith("eac3")){if(i.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!bt.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${bt.join(", ")}).`)},Ni=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},Ga=[48e3,44100,32e3],Qa=[24e3,22050,16e3];var vt,it;(function(i){i[i.NON_IDR_SLICE=1]="NON_IDR_SLICE",i[i.SLICE_DPA=2]="SLICE_DPA",i[i.SLICE_DPB=3]="SLICE_DPB",i[i.SLICE_DPC=4]="SLICE_DPC",i[i.IDR=5]="IDR",i[i.SEI=6]="SEI",i[i.SPS=7]="SPS",i[i.PPS=8]="PPS",i[i.AUD=9]="AUD",i[i.SPS_EXT=13]="SPS_EXT"})(vt||(vt={})),(function(i){i[i.RASL_N=8]="RASL_N",i[i.RASL_R=9]="RASL_R",i[i.BLA_W_LP=16]="BLA_W_LP",i[i.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",i[i.VPS_NUT=32]="VPS_NUT",i[i.SPS_NUT=33]="SPS_NUT",i[i.PPS_NUT=34]="PPS_NUT",i[i.AUD_NUT=35]="AUD_NUT",i[i.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",i[i.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(it||(it={}));const Ht=function*(i){let t=0,e=-1;for(;t<i.length-2;){const r=i.indexOf(0,t);if(r===-1||r>=i.length-2)break;t=r;let a=0;t+3<i.length&&i[t+1]===0&&i[t+2]===0&&i[t+3]===1?a=4:i[t+1]===0&&i[t+2]===1&&(a=3),a!==0?(e!==-1&&t>e&&(yield{offset:e,length:t-e}),e=t+a,t=e):t++}e!==-1&&e<i.length&&(yield{offset:e,length:i.length-e})},Ui=function*(i,t){let e=0;const r=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;e+t<=i.length;){let a;t===1?a=r.getUint8(e):t===2?a=r.getUint16(e,!1):t===3?a=Ma(r,e):(g(t===4),a=r.getUint32(e,!1)),e+=t,yield{offset:e,length:a},e+=a}},Hi=i=>31&i,oe=i=>{const t=[],e=i.length;for(let r=0;r<e;r++)r+2<e&&i[r]===0&&i[r+1]===0&&i[r+2]===3?(t.push(0,0),r+=2):t.push(i[r]);return new Uint8Array(t)},ji={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}},Xa=i=>{try{const t=new G(oe(i));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;const e=t.readAlignedByte(),r=t.readAlignedByte(),a=t.readAlignedByte();k(t);let s=1,o=0,n=0,l=0;if((e===100||e===110||e===122||e===244||e===44||e===83||e===86||e===118||e===128)&&(s=k(t),s===3&&(l=t.readBits(1)),o=k(t),n=k(t),t.skipBits(1),t.readBits(1))){for(let I=0;I<(s!==3?8:12);I++)if(t.readBits(1)){const D=I<6?16:64;let V=8,L=8;for(let $=0;$<D;$++)L!==0&&(L=(V+yt(t)+256)%256),V=L===0?V:L}}k(t);const c=k(t);if(c===0)k(t);else if(c===1){t.skipBits(1),yt(t),yt(t);const I=k(t);for(let D=0;D<I;D++)yt(t)}k(t),t.skipBits(1);const d=k(t),u=k(t),p=16*(d+1),h=16*(u+1);let m=p,f=h;const y=t.readBits(1);if(y||t.skipBits(1),t.skipBits(1),t.readBits(1)){const I=k(t),D=k(t),V=k(t),L=k(t);let $,M;(l===0?s:0)===0?($=1,M=2-y):($=s===3?1:2,M=(s===1?2:1)*(2-y)),m-=$*(I+D),f-=M*(V+L)}let b=2,_=2,T=2,S=0,A={num:1,den:1},E=null,C=null;if(t.readBits(1)){if(t.readBits(1)){const V=t.readBits(8);if(V===255)A={num:t.readBits(16),den:t.readBits(16)};else{const L=ji[V];L&&(A=L)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),S=t.readBits(1),t.readBits(1)&&(b=t.readBits(8),_=t.readBits(8),T=t.readBits(8))),t.readBits(1)&&(k(t),k(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const I=t.readBits(1);I&&qi(t);const D=t.readBits(1);D&&qi(t),(I||D)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),k(t),k(t),k(t),k(t),E=k(t),C=k(t))}if(E===null)if(g(C===null),e!==44&&e!==86&&e!==100&&e!==110&&e!==122&&e!==244||!(16&r)){const I=d+1,D=(2-y)*(u+1),V=se.find($=>$.level>=a)??mt(se),L=Math.min(Math.floor(V.maxDpbMbs/(I*D)),16);E=L,C=L}else E=0,C=0;return g(C!==null),{profileIdc:e,constraintFlags:r,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:s,bitDepthLumaMinus8:o,bitDepthChromaMinus8:n,codedWidth:p,codedHeight:h,displayWidth:m,displayHeight:f,pixelAspectRatio:A,colourPrimaries:b,matrixCoefficients:T,transferCharacteristics:_,fullRangeFlag:S,numReorderFrames:E,maxDecFrameBuffering:C}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},qi=i=>{const t=k(i);i.skipBits(4),i.skipBits(4);for(let e=0;e<=t;e++)k(i),k(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},Me=i=>i>>1&63,Ka=i=>{try{const t=[],e=[],r=[],a=[];for(const l of Ht(i)){const c=i.subarray(l.offset,l.offset+l.length),d=Me(c[0]);d===it.VPS_NUT?t.push(c):d===it.SPS_NUT?e.push(c):d===it.PPS_NUT?r.push(c):d!==it.PREFIX_SEI_NUT&&d!==it.SUFFIX_SEI_NUT||a.push(c)}if(e.length===0||r.length===0)return null;const s=(l=>{try{const c=new G(oe(l));c.skipBits(16),c.readBits(4);const d=c.readBits(3),u=c.readBits(1),{general_profile_space:p,general_tier_flag:h,general_profile_idc:m,general_profile_compatibility_flags:f,general_constraint_indicator_flags:y,general_level_idc:b}=Ya(c,d);k(c);const _=k(c);let T=0;_===3&&(T=c.readBits(1));const S=k(c),A=k(c);let E=S,C=A;if(c.readBits(1)){const U=k(c),tt=k(c),wt=k(c),st=k(c);let Q=1,Tt=1;const da=T===0?_:0;da===1?(Q=2,Tt=2):da===2&&(Q=2,Tt=1),E-=(U+tt)*Q,C-=(wt+st)*Tt}const I=k(c),D=k(c);k(c);const V=c.readBits(1);let L=0;for(let U=V?0:d;U<=d;U++)k(c),L=k(c),k(c);k(c),k(c),k(c),k(c),k(c),k(c),c.readBits(1)&&c.readBits(1)&&Ja(c),c.skipBits(1),c.skipBits(1),c.readBits(1)&&(c.skipBits(4),c.skipBits(4),k(c),k(c),c.skipBits(1));const $=k(c);if(Za(c,$),c.readBits(1)){const U=k(c);for(let tt=0;tt<U;tt++)k(c),c.skipBits(1)}c.skipBits(1),c.skipBits(1);let M=2,j=2,W=2,X=0,q=0,Y={num:1,den:1};if(c.readBits(1)){const U=es(c,d);Y=U.pixelAspectRatio,M=U.colourPrimaries,j=U.transferCharacteristics,W=U.matrixCoefficients,X=U.fullRangeFlag,q=U.minSpatialSegmentationIdc}return{displayWidth:E,displayHeight:C,pixelAspectRatio:Y,colourPrimaries:M,transferCharacteristics:j,matrixCoefficients:W,fullRangeFlag:X,maxDecFrameBuffering:L+1,spsMaxSubLayersMinus1:d,spsTemporalIdNestingFlag:u,generalProfileSpace:p,generalTierFlag:h,generalProfileIdc:m,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:y,generalLevelIdc:b,chromaFormatIdc:_,bitDepthLumaMinus8:I,bitDepthChromaMinus8:D,minSpatialSegmentationIdc:q}}catch(c){return console.error("Error parsing HEVC SPS:",c),null}})(e[0]);if(!s)return null;let o=0;if(r.length>0){const l=r[0],c=new G(oe(l));c.skipBits(16),k(c),k(c),c.skipBits(1),c.skipBits(1),c.skipBits(3),c.skipBits(1),c.skipBits(1),k(c),k(c),yt(c),c.skipBits(1),c.skipBits(1),c.readBits(1)&&k(c),yt(c),yt(c),c.skipBits(1),c.skipBits(1),c.skipBits(1),c.skipBits(1);const d=c.readBits(1),u=c.readBits(1);o=d||u?d&&!u?2:!d&&u?3:0:0}const n=[...t.length?[{arrayCompleteness:1,nalUnitType:it.VPS_NUT,nalUnits:t}]:[],...e.length?[{arrayCompleteness:1,nalUnitType:it.SPS_NUT,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:it.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Me(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:n}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},Ya=(i,t)=>{const e=i.readBits(2),r=i.readBits(1),a=i.readBits(5);let s=0;for(let d=0;d<32;d++)s=s<<1|i.readBits(1);const o=new Uint8Array(6);for(let d=0;d<6;d++)o[d]=i.readBits(8);const n=i.readBits(8),l=[],c=[];for(let d=0;d<t;d++)l.push(i.readBits(1)),c.push(i.readBits(1));if(t>0)for(let d=t;d<8;d++)i.skipBits(2);for(let d=0;d<t;d++)l[d]&&i.skipBits(88),c[d]&&i.skipBits(8);return{general_profile_space:e,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:o,general_level_idc:n}},Ja=i=>{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(i.readBits(1)){const r=Math.min(64,1<<4+(t<<1));t>1&&yt(i);for(let a=0;a<r;a++)yt(i)}else k(i)},Za=(i,t)=>{const e=[];for(let r=0;r<t;r++)e[r]=ts(i,r,t,e)},ts=(i,t,e,r)=>{let a=0,s=0,o=0;if(t!==0&&(s=i.readBits(1)),s){t===e?o=t-(k(i)+1):o=t-1,i.readBits(1),k(i);const n=r[o]??0;for(let l=0;l<=n;l++)i.readBits(1)||i.readBits(1);a=r[o]}else{const n=k(i),l=k(i);for(let c=0;c<n;c++)k(i),i.readBits(1);for(let c=0;c<l;c++)k(i),i.readBits(1);a=n+l}return a},es=(i,t)=>{let e=2,r=2,a=2,s=0,o=0,n={num:1,den:1};if(i.readBits(1)){const l=i.readBits(8);if(l===255)n={num:i.readBits(16),den:i.readBits(16)};else{const c=ji[l];c&&(n=c)}}return i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),s=i.readBits(1),i.readBits(1)&&(e=i.readBits(8),r=i.readBits(8),a=i.readBits(8))),i.readBits(1)&&(k(i),k(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(k(i),k(i),k(i),k(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&k(i),i.readBits(1)&&is(i,!0,t)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),o=k(i),k(i),k(i),k(i),k(i)),{pixelAspectRatio:n,colourPrimaries:e,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:o}},is=(i,t,e)=>{let r=!1,a=!1,s=!1;r=i.readBits(1)===1,a=i.readBits(1)===1,(r||a)&&(s=i.readBits(1)===1,s&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),s&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5));for(let o=0;o<=e;o++){let n=!0;i.readBits(1)===1||(n=i.readBits(1)===1);let l=!1;n?k(i):l=i.readBits(1)===1;let c=1;l||(c=k(i)+1),r&&Gi(i,c,s),a&&Gi(i,c,s)}},Gi=(i,t,e)=>{for(let r=0;r<t;r++)k(i),k(i),e&&(k(i),k(i)),i.readBits(1)};var Qi;(function(i){i[i.audAllowed=0]="audAllowed",i[i.beforeFirstVcl=1]="beforeFirstVcl",i[i.afterFirstVcl=2]="afterFirstVcl",i[i.eoBitstreamAllowed=3]="eoBitstreamAllowed",i[i.noMoreDataAllowed=4]="noMoreDataAllowed"})(Qi||(Qi={}));const Xi=i=>{const t=xi(i),e=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),o=t.getUint8(18);let n=null;return o&&(n=i.subarray(19,21+e)),{outputChannelCount:e,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:o,channelMappingTable:n}},rs=(i,t,e)=>{switch(i){case"avc":for(const r of((a,s)=>{if(s.description){const o=3&Z(s.description)[4];return Ui(a,o+1)}return Ht(a)})(e,t)){const a=e[r.offset],s=Hi(a);if(s>=vt.NON_IDR_SLICE&&s<=vt.SLICE_DPC)return"delta";if(s===vt.IDR)return"key";if(s===vt.SEI&&(!Da()||Ra()>=144)){const o=e.subarray(r.offset,r.offset+r.length),n=oe(o);let l=1;do{let c=0;for(;;){const u=n[l++];if(u===void 0||(c+=u,u<255))break}let d=0;for(;;){const u=n[l++];if(u===void 0||(d+=u,u<255))break}if(c===6){const u=new G(n);u.pos=8*l;const p=k(u),h=u.readBits(1);if(p===0&&h===1)return"key"}l+=d}while(l<n.length-1)}}return"delta";case"hevc":for(const r of((a,s)=>{if(s.description){const o=3&Z(s.description)[21];return Ui(a,o+1)}return Ht(a)})(e,t)){const a=Me(e[r.offset]);if(a<it.BLA_W_LP)return"delta";if(a<=it.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return(1&e[0])===0?"key":"delta";case"vp9":{const r=new G(e);if(r.readBits(2)!==2)return null;const a=r.readBits(1);return(r.readBits(1)<<1)+a===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(const{type:a,data:s}of(function*(o){const n=new G(o),l=()=>{let c=0;for(let d=0;d<8;d++){const u=n.readAlignedByte();if(c|=(127&u)<<7*d,!(128&u))break;if(d===7&&128&u)return null}return c>=2**32-1?null:c};for(;n.getBitsLeft()>=8;){n.skipBits(1);const c=n.readBits(4),d=n.readBits(1),u=n.readBits(1);let p;if(n.skipBits(1),d&&n.skipBits(8),u){const h=l();if(h===null)return;p=h}else p=Math.floor(n.getBitsLeft()/8);g(n.pos%8==0),yield{type:c,data:o.subarray(n.pos/8,n.pos/8+p)},n.skipBits(8*p)}})(e))if(a===1){const o=new G(s);o.skipBits(4),r=!!o.readBits(1)}else if(a===3||a===6||a===7){if(r)return"key";const o=new G(s);return o.readBits(1)?null:o.readBits(2)===0?"key":"delta"}return null}default:Vt(i),g(!1)}};var Ki;(function(i){i[i.STREAMINFO=0]="STREAMINFO",i[i.VORBIS_COMMENT=4]="VORBIS_COMMENT",i[i.PICTURE=6]="PICTURE"})(Ki||(Ki={}));const as=[1,2,3,6],Yi=new Uint8Array(0);class jt{constructor(t,e,r,a,s=-1,o,n){if(this.data=t,this.type=e,this.timestamp=r,this.duration=a,this.sequenceNumber=s,t===Yi&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(a)||a<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))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(n!==void 0&&(typeof n!="object"||!n))throw new TypeError("sideData, when provided, must be an object.");if((n==null?void 0:n.alpha)!==void 0&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if((n==null?void 0:n.alphaByteLength)!==void 0&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=n??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Yi}get microsecondTimestamp(){return Math.trunc(Lt*this.timestamp)}get microsecondDuration(){return Math.trunc(Lt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")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(typeof EncodedVideoChunk>"u")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(typeof EncodedAudioChunk>"u")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(t,e){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(t.byteLength);return t.copyTo(r),new jt(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,e)}clone(t){if(t!==void 0&&(typeof t!="object"||t===null))throw new TypeError("options, when provided, must be an object.");if((t==null?void 0:t.data)!==void 0&&!(t.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if((t==null?void 0:t.type)!==void 0&&t.type!=="key"&&t.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if((t==null?void 0:t.timestamp)!==void 0&&!Number.isFinite(t.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if((t==null?void 0:t.duration)!==void 0&&!Number.isFinite(t.duration))throw new TypeError("options.duration, when provided, must be a number.");if((t==null?void 0:t.sequenceNumber)!==void 0&&!Number.isFinite(t.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if((t==null?void 0:t.sideData)!==void 0&&(typeof t.sideData!="object"||t.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new jt((t==null?void 0:t.data)??this.data,(t==null?void 0:t.type)??this.type,(t==null?void 0:t.timestamp)??this.timestamp,(t==null?void 0:t.duration)??this.duration,(t==null?void 0:t.sequenceNumber)??this.sequenceNumber,this.byteLength,(t==null?void 0:t.sideData)??this.sideData)}}class Ie{constructor(t){this.value=t}}class Ae{constructor(t){this.value=t}}class Ji{constructor(t){this.value=t}}class St{constructor(t){this.value=t}}var v;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Duration=17545]="Duration",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.MuxingApp=19840]="MuxingApp",i[i.WritingApp=22337]="WritingApp",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.TrackNumber=215]="TrackNumber",i[i.TrackUID=29637]="TrackUID",i[i.TrackType=131]="TrackType",i[i.FlagEnabled=185]="FlagEnabled",i[i.FlagDefault=136]="FlagDefault",i[i.FlagForced=21930]="FlagForced",i[i.FlagOriginal=21934]="FlagOriginal",i[i.FlagHearingImpaired=21931]="FlagHearingImpaired",i[i.FlagVisualImpaired=21932]="FlagVisualImpaired",i[i.FlagCommentary=21935]="FlagCommentary",i[i.FlagLacing=156]="FlagLacing",i[i.Name=21358]="Name",i[i.Language=2274716]="Language",i[i.LanguageBCP47=2274717]="LanguageBCP47",i[i.CodecID=134]="CodecID",i[i.CodecPrivate=25506]="CodecPrivate",i[i.CodecDelay=22186]="CodecDelay",i[i.SeekPreRoll=22203]="SeekPreRoll",i[i.DefaultDuration=2352003]="DefaultDuration",i[i.Video=224]="Video",i[i.PixelWidth=176]="PixelWidth",i[i.PixelHeight=186]="PixelHeight",i[i.DisplayWidth=21680]="DisplayWidth",i[i.DisplayHeight=21690]="DisplayHeight",i[i.DisplayUnit=21682]="DisplayUnit",i[i.AlphaMode=21440]="AlphaMode",i[i.Audio=225]="Audio",i[i.SamplingFrequency=181]="SamplingFrequency",i[i.Channels=159]="Channels",i[i.BitDepth=25188]="BitDepth",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.Block=161]="Block",i[i.BlockAdditions=30113]="BlockAdditions",i[i.BlockMore=166]="BlockMore",i[i.BlockAdditional=165]="BlockAdditional",i[i.BlockAddID=238]="BlockAddID",i[i.BlockDuration=155]="BlockDuration",i[i.ReferenceBlock=251]="ReferenceBlock",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.Colour=21936]="Colour",i[i.MatrixCoefficients=21937]="MatrixCoefficients",i[i.TransferCharacteristics=21946]="TransferCharacteristics",i[i.Primaries=21947]="Primaries",i[i.Range=21945]="Range",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPoseRoll=30325]="ProjectionPoseRoll",i[i.Attachments=423732329]="Attachments",i[i.AttachedFile=24999]="AttachedFile",i[i.FileDescription=18046]="FileDescription",i[i.FileName=18030]="FileName",i[i.FileMediaType=18016]="FileMediaType",i[i.FileData=18012]="FileData",i[i.FileUID=18094]="FileUID",i[i.Chapters=272869232]="Chapters",i[i.Tags=307544935]="Tags",i[i.Tag=29555]="Tag",i[i.Targets=25536]="Targets",i[i.TargetTypeValue=26826]="TargetTypeValue",i[i.TargetType=25546]="TargetType",i[i.TagTrackUID=25541]="TagTrackUID",i[i.TagEditionUID=25545]="TagEditionUID",i[i.TagChapterUID=25540]="TagChapterUID",i[i.TagAttachmentUID=25542]="TagAttachmentUID",i[i.SimpleTag=26568]="SimpleTag",i[i.TagName=17827]="TagName",i[i.TagLanguage=17530]="TagLanguage",i[i.TagString=17543]="TagString",i[i.TagBinary=17541]="TagBinary",i[i.ContentEncodings=28032]="ContentEncodings",i[i.ContentEncoding=25152]="ContentEncoding",i[i.ContentEncodingOrder=20529]="ContentEncodingOrder",i[i.ContentEncodingScope=20530]="ContentEncodingScope",i[i.ContentCompression=20532]="ContentCompression",i[i.ContentCompAlgo=16980]="ContentCompAlgo",i[i.ContentCompSettings=16981]="ContentCompSettings",i[i.ContentEncryption=20533]="ContentEncryption"})(v||(v={}));const Zi=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,tr=i=>i<256n?1:i<65536n?2:i<1n<<24n?3:i<1n<<32n?4:i<1n<<40n?5:i<1n<<48n?6:i<1n<<56n?7:8,er=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-1048576&&i<1<<20?3:i>=-134217728&&i<1<<27?4:i>=-17179869184&&i<2**34?5:6;class ss{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=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=Zi(t)){let r=0;switch(e){case 6:this.helperView.setUint8(r++,t/2**40|0);case 5:this.helperView.setUint8(r++,t/2**32|0);case 4:this.helperView.setUint8(r++,t>>24);case 3:this.helperView.setUint8(r++,t>>16);case 2:this.helperView.setUint8(r++,t>>8);case 1:this.helperView.setUint8(r++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(t,e=tr(t)){let r=0;for(let a=e-1;a>=0;a--)this.helperView.setUint8(r++,Number(t>>BigInt(8*a)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(t,e=er(t)){t<0&&(t+=2**(8*e)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=(r=>{if(r<127)return 1;if(r<16383)return 2;if(r<2097151)return 3;if(r<268435455)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML varint size not supported "+r)})(t)){let r=0;switch(e){case 1:this.helperView.setUint8(r++,128|t);break;case 2:this.helperView.setUint8(r++,64|t>>8),this.helperView.setUint8(r++,t);break;case 3:this.helperView.setUint8(r++,32|t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 4:this.helperView.setUint8(r++,16|t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 5:this.helperView.setUint8(r++,8|t/2**32&7),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 6:this.helperView.setUint8(r++,4|t/2**40&3),this.helperView.setUint8(r++,t/2**32|0),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(e=>e.charCodeAt(0))))}writeEBML(t){if(t!==null)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(),r=t.size===-1?1:t.size??4;t.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);const a=this.writer.getPos();if(this.dataOffsets.set(t,a),this.writeEBML(t.data),t.size!==-1){const s=this.writer.getPos()-a,o=this.writer.getPos();this.writer.seek(e),this.writeVarInt(s,r),this.writer.seek(o)}}else if(typeof t.data=="number"){const e=t.size??Zi(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if(typeof t.data=="bigint"){const e=t.size??tr(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if(typeof t.data=="string")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 Ie)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof Ae)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof Ji){const e=t.size??er(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof St){const e=J.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else Vt(t.data)}}const os={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",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"},ne=i=>{const t=i.filePos,e=ws(i,9),r=new G(e);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;const a=r.readBits(1),s=r.readBits(2)+1,o=r.readBits(4);if(o===15)return null;r.skipBits(1);const n=r.readBits(3);if(n===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const l=r.readBits(13);r.skipBits(11);const c=r.readBits(2)+1;if(c!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let d=null;return a===1?i.filePos-=2:d=r.readBits(16),{objectType:s,samplingFrequencyIndex:o,channelConfiguration:n,frameLength:l,numberOfAacFrames:c,crcCheck:d,startPos:t}};var ns=function(i,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var r,a;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],e&&(a=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(s){return Promise.reject(s)}}),i.stack.push({value:t,dispose:r,async:e})}else e&&i.stack.push({async:!0});return t},cs=(function(i){return function(t){function e(s){t.error=t.hasError?new i(s,t.error,"An error was suppressed during disposal."):s,t.hasError=!0}var r,a=0;return(function s(){for(;r=t.stack.pop();)try{if(!r.async&&a===1)return a=0,t.stack.push(r),Promise.resolve().then(s);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(o).then(s,function(n){return e(n),s()})}else a|=1}catch(n){e(n)}if(a===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error})()}})(typeof SuppressedError=="function"?SuppressedError:function(i,t,e){var r=new Error(e);return r.name="SuppressedError",r.error=i,r.suppressed=t,r});Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"));let ir=-1/0,rr=-1/0,Ft=null;typeof FinalizationRegistry<"u"&&(Ft=new FinalizationRegistry(i=>{const t=performance.now();i.type==="video"?(t-ir>=1e3&&(console.error("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."),ir=t),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(t-rr>=1e3&&(console.error("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."),rr=t),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));class Dt{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Fe=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ds=new Set(Fe);class rt{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(Lt*this.timestamp)}get microsecondDuration(){return Math.trunc(Lt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(t,e){var r,a,s,o,n,l,c,d;if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.format===void 0||!ds.has(e.format))throw new TypeError("init.format must be one of: "+Fe.join(", "));if(!Number.isInteger(e.codedWidth)||e.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(e.codedHeight)||e.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.layout!==void 0){if(!Array.isArray(e.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const p of e.layout){if(!p||typeof p!="object"||Array.isArray(p))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(p.offset)||p.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(p.stride)||p.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(e.visibleRect!==void 0&&Pi(e.visibleRect,"init.visibleRect"),e.displayWidth!==void 0&&(!Number.isInteger(e.displayWidth)||e.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(e.displayHeight!==void 0&&(!Number.isInteger(e.displayHeight)||e.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(e.displayWidth!==void 0!=(e.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=Z(t).slice(),this._layout=e.layout??us(e.format,e.codedWidth,e.codedHeight),this.format=e.format,this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0;let u=e.colorSpace??null;u===null&&(u=this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new De(u),this.visibleRect={left:((r=e.visibleRect)==null?void 0:r.left)??0,top:((a=e.visibleRect)==null?void 0:a.top)??0,width:((s=e.visibleRect)==null?void 0:s.width)??e.codedWidth,height:((o=e.visibleRect)==null?void 0:o.height)??e.codedHeight},e.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180==0?e.displayWidth:e.displayHeight,this.squarePixelHeight=this.rotation%180==0?e.displayHeight:e.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&t instanceof VideoFrame){if((e==null?void 0:e.rotation)!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if((e==null?void 0:e.timestamp)!==void 0&&!Number.isFinite(e==null?void 0:e.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if((e==null?void 0:e.duration)!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");(e==null?void 0:e.visibleRect)!==void 0&&Pi(e.visibleRect,"init.visibleRect"),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:((n=t.visibleRect)==null?void 0:n.x)??0,top:((l=t.visibleRect)==null?void 0:l.y)??0,width:((c=t.visibleRect)==null?void 0:c.width)??t.codedWidth,height:((d=t.visibleRect)==null?void 0:d.height)??t.codedHeight},this.rotation=(e==null?void 0:e.rotation)??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=(e==null?void 0:e.timestamp)??t.timestamp/1e6,this.duration=(e==null?void 0:e.duration)??(t.duration??0)/1e6,this.colorSpace=new De(t.colorSpace)}else if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof SVGImageElement<"u"&&t instanceof SVGImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new rt(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*Lt),duration:Math.trunc((e.duration??0)*Lt)||void 0}),e);let u=0,p=0;if("naturalWidth"in t?(u=t.naturalWidth,p=t.naturalHeight):"videoWidth"in t?(u=t.videoWidth,p=t.videoHeight):"width"in t&&(u=Number(t.width),p=Number(t.height)),!u||!p)throw new TypeError("Could not determine dimensions.");const h=new OffscreenCanvas(u,p),m=h.getContext("2d",{alpha:Bi(),willReadFrequently:!0});g(m),m.drawImage(t,0,0),this._data=h,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:u,height:p},this.squarePixelWidth=u,this.squarePixelHeight=p,this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new De({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(t instanceof Dt))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!Fe.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.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=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=t.getColorSpace()}this.pixelAspectRatio=Se({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ft==null||Ft.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),this._data instanceof Dt?new rt(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):Gt(this._data)?new rt(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(g(this._layout),new rt(this._data,{format:this.format,layout:this._layout,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})):new rt(this._data,{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})}close(){this._closed||(Ft==null||Ft.unregister(this),this._data instanceof Dt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Gt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(or(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Gt(this._data)?this._data.allocationSize(t):nr(this,t).allocationSize}async copyTo(t,e={}){if(!xe(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(or(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(g(this._data!==null),Gt(this._data))return this._data.copyTo(t,e);if(e.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(e.format)){if(!(this._data instanceof Dt)){if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const c=this.toVideoFrame(),d=await c.copyTo(t,e);return c.close(),d}{const c={stack:[],error:void 0,hasError:!1};try{const d=ns(c,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},e.colorSpace??"srgb"),!1);if(!(d instanceof rt))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(d.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${d.format}' instead.`);return await d.copyTo(t,e)}catch(d){c.error=d,c.hasError=!0}finally{cs(c)}}}const r=nr(this,e);g(this.format);const a=Z(t);if(a.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${a.byteLength}`);const s=ce(this.format);let o;if(this._data instanceof Dt){let c=this._data.getDataPlanes();if(c instanceof Promise&&(c=await c),!Array.isArray(c)||c.some(d=>!(d.data instanceof Uint8Array)||!Number.isInteger(d.stride)||d.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=c}else if(this._data instanceof Uint8Array)g(this._layout),g(this._layout.length===s.length),o=this._layout.map((c,d)=>{const u=Math.ceil(this.codedHeight/s[d].heightDivisor);return{data:this._data.subarray(c.offset,c.offset+c.stride*u),stride:c.stride}});else{const c=this._data.getContext("2d");g(c);const d=c.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:Z(d.data),stride:4*this.codedWidth}]}const n=[],l=s.length;for(let c=0;c<l;c++){const d=r.computedLayouts[c],u=o[c].stride,p=o[c].data;let h=d.sourceTop*u;h+=d.sourceLeftBytes;let m=d.destinationOffset;const f=d.sourceWidthBytes,y={offset:m,stride:d.destinationStride};for(let b=0;b<d.sourceHeight;b++){if(h+f>p.byteLength)throw new Error("Source buffer OOB read.");if(m+f>a.byteLength)throw new Error("Destination buffer OOB write.");const _=p.subarray(h,h+f);a.set(_,m),h+=u,m+=d.destinationStride}n.push(y)}if(e.format!==void 0){const c=this.format.startsWith("RGB")!==e.format.startsWith("RGB"),d=this.format.includes("X")&&e.format.includes("A");if(c||d)for(let u=0;u<r.allocationSize;u+=4){if(c){const p=a[u],h=a[u+2];a[u]=h,a[u+2]=p}d&&(a[u+3]=255)}}return n}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof Dt){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const t=this._data.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((o,n)=>o+n.data.byteLength,0),r=new Uint8Array(e);let a=0;const s=[];for(const o of t)r.set(o.data,a),s.push(a),a+=o.data.byteLength;return new VideoFrame(r,{format:this.format,layout:t.map((o,n)=>({offset:s[n],stride:o.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Gt(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,r,a,s,o,n,l,c){let d=0,u=0,p=this.displayWidth,h=this.displayHeight,m=0,f=0,y=this.displayWidth,b=this.displayHeight;if(o!==void 0?(d=e,u=r,p=a,h=s,m=o,f=n,l!==void 0?(y=l,b=c):(y=p,b=h)):(m=e,f=r,a!==void 0&&(y=a,b=s)),!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(f))throw new TypeError("dy must be a number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:p,sHeight:h}=this._rotateSourceRegion(d,u,p,h,this.rotation));const _=this.toCanvasImageSource();t.save();const T=m+y/2,S=f+b/2;t.translate(T,S),t.rotate(this.rotation*Math.PI/180);const A=this.rotation%180==0?1:y/b;t.scale(1/A,A),t.drawImage(_,d,u,p,h,-y/2,-b/2,y,b),t.restore()}drawWithFit(t,e){var _,T,S,A;if(!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||typeof e!="object")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(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");e.crop!==void 0&&Re(e.crop,"options.");const r=t.canvas.width,a=t.canvas.height,s=e.rotation??this.rotation,[o,n]=s%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let l,c,d,u,p=e.crop;p&&(p=sr(p,o,n));const{sx:h,sy:m,sWidth:f,sHeight:y}=this._rotateSourceRegion(((_=e.crop)==null?void 0:_.left)??0,((T=e.crop)==null?void 0:T.top)??0,((S=e.crop)==null?void 0:S.width)??o,((A=e.crop)==null?void 0:A.height)??n,s);if(e.fit==="fill")l=0,c=0,d=r,u=a;else{const[E,C]=e.crop?[e.crop.width,e.crop.height]:[o,n],I=e.fit==="contain"?Math.min(r/E,a/C):Math.max(r/E,a/C);d=E*I,u=C*I,l=(r-d)/2,c=(a-u)/2}t.save();const b=s%180==0?1:d/u;t.translate(r/2,a/2),t.rotate(s*Math.PI/180),t.scale(1/b,b),t.translate(-r/2,-a/2),t.drawImage(this.toCanvasImageSource(),h,m,f,y,l,c,d,u),t.restore()}_rotateSourceRegion(t,e,r,a,s){return s===90?[t,e,r,a]=[e,this.squarePixelHeight-t-r,a,r]:s===180?[t,e]=[this.squarePixelWidth-t-r,this.squarePixelHeight-e-a]:s===270&&([t,e,r,a]=[this.squarePixelWidth-e-a,t,a,r]),{sx:t,sy:e,sWidth:r,sHeight:a}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof Dt||this._data instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this._data}async transform(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&Re(t.crop,"options."),t.alpha!==void 0&&!["keep","discard"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const e=vi(this.rotation+(t.rotate??0)),[r,a]=e%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=t.crop;s&&(s=sr(s,r,a));const o=s?s.width:r,n=s?s.height:a,l=o/n;let c,d;t.width!==void 0&&t.height===void 0?(c=t.width,d=c/l):t.width===void 0&&t.height!==void 0?(d=t.height,c=d*l):t.width!==void 0&&t.height!==void 0?(c=t.width,d=t.height):(c=o,d=n),c=Ci(c,t.roundDimensionsTo??1),d=Ci(d,t.roundDimensionsTo??1);const u={width:c,height:d,fit:t.fit??"fill",rotation:e,crop:s??{left:0,top:0,width:r,height:a},alpha:t.alpha??"keep"};for(const f of ls){let y=f(this,u);if(y instanceof Promise&&(y=await y),y!==null)return y}let p=null,h=!1;for(const f of qt)if(f.canvas.width===u.width&&f.canvas.height===u.height){p=f.canvas,f.age=ar++;break}if(p===null){if(typeof OffscreenCanvas<"u")p=new OffscreenCanvas(u.width,u.height);else{if(typeof window>"u"||typeof document>"u")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().");p=document.createElement("canvas"),p.width=u.width,p.height=u.height}h=!0,qt.length>=hs&&qt.splice(((f,y)=>{let b=-1,_=1/0;for(let T=0;T<f.length;T++){const S=y(f[T]);S<_&&(_=S,b=T)}return b})(qt,f=>f.age),1),qt.push({canvas:p,age:ar++})}const m=p.getContext("2d",{alpha:!0});return g(m),u.alpha==="discard"?(m.fillStyle="black",m.fillRect(0,0,u.width,u.height)):h||m.clearRect(0,0,u.width,u.height),this.drawWithFit(m,{fit:u.fit,rotation:u.rotation,crop:u.crop}),new rt(p,{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}[Symbol.dispose](){this.close()}}const ls=[],hs=3,qt=[];let ar=0;class De{constructor(t){if(t!==void 0){if(!t||typeof t!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const e=Object.keys($t);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);const r=Object.keys(zt);if(t.transfer!=null&&!r.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);const a=Object.keys(Nt);if(t.matrix!=null&&!a.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${a.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=(t==null?void 0:t.primaries)??null,this.transfer=(t==null?void 0:t.transfer)??null,this.matrix=(t==null?void 0:t.matrix)??null,this.fullRange=(t==null?void 0:t.fullRange)??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Gt=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,sr=(i,t,e)=>{const r=Math.min(i.left,t),a=Math.min(i.top,e),s=Math.min(i.width,t-r),o=Math.min(i.height,e-a);return g(s>=0),g(o>=0),{left:r,top:a,width:s,height:o}},Re=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},or=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.colorSpace!==void 0&&!["display-p3","srgb"].includes(i.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(i.format!==void 0&&typeof i.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const t of i.layout){if(!t||typeof t!="object")throw new TypeError("Each entry in options.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(i.rect!==void 0){if(!i.rect||typeof i.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(i.rect.x!==void 0&&(!Number.isInteger(i.rect.x)||i.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(i.rect.y!==void 0&&(!Number.isInteger(i.rect.y)||i.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(i.rect.width!==void 0&&(!Number.isInteger(i.rect.width)||i.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(i.rect.height!==void 0&&(!Number.isInteger(i.rect.height)||i.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},us=(i,t,e)=>{const r=ce(i),a=[];let s=0;for(const o of r){const n=Math.ceil(t/o.widthDivisor),l=Math.ceil(e/o.heightDivisor),c=n*o.sampleBytes,d=c*l;a.push({offset:s,stride:c}),s+=d}return a},ce=i=>{const t=(e,r,a,s,o)=>{const n=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:a,heightDivisor:s},{sampleBytes:r,widthDivisor:a,heightDivisor:s}];return o&&n.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),n};switch(i){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(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:Vt(i),g(!1)}},nr=(i,t)=>{const e={left:0,top:0,width:i.codedWidth,height:i.codedHeight},r=t.rect,a=ps(e,r,i.codedWidth,i.codedHeight,i.format),s=t.layout;let o;if(t.format&&t.format!==i.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");o=t.format}else o=i.format;return fs(a,o,s)},ps=(i,t,e,r,a)=>{const s={...i};if(t!==void 0){if(t.width===0||t.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>e)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!ms(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},ms=(i,t)=>{if(i===null)return!0;const e=ce(i);for(let r=0;r<e.length;r++){const a=e[r],s=a.widthDivisor,o=a.heightDivisor;if((t.x||0)%s!==0||(t.y||0)%o!==0)return!1}return!0},fs=(i,t,e)=>{const r=ce(t),a=r.length;if(e!==void 0&&e.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const o=[],n=[];for(let l=0;l<a;l++){const c=r[l],d=c.sampleBytes,u=c.widthDivisor,p=c.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(i.y||0)/p),h.sourceHeight=Math.ceil(Math.trunc(i.height||0)/p),h.sourceLeftBytes=Math.floor(Math.trunc(i.x||0)/u)*d,h.sourceWidthBytes=Math.floor(Math.trunc(i.width||0)/u)*d,e!==void 0){const f=e[l];if(f.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${l} is too small.`);h.destinationOffset=f.offset,h.destinationStride=f.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const m=h.destinationStride*h.sourceHeight+h.destinationOffset;if(m>4294967295)throw new TypeError("Allocation size exceeds limit.");n.push(m),s=Math.max(s,m);for(let f=0;f<l;f++){const y=o[f];if(!(n[l]<=y.destinationOffset||n[f]<=h.destinationOffset))throw new TypeError("Planes overlap.")}o.push(h)}return{allocationSize:s,computedLayouts:o}},cr=new Map,dr=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");if(t.alpha!==void 0&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(t.bitrateMode!==void 0&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.latencyMode!==void 0&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&((e=t.fullCodecString).startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":e==="vp8"?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":e==="mp3"||e==="mp4a.69"||e==="mp4a.6B"||e==="mp4a.6b"||e==="mp4a.40.34"?"mp3":e.startsWith("mp4a.40.")||e==="mp4a.67"?"aac":e==="opus"?"opus":e==="vorbis"?"vorbis":e==="flac"?"flac":e==="ac-3"||e==="ac3"?"ac3":e==="ec-3"||e==="eac3"?"eac3":e==="ulaw"?"ulaw":e==="alaw"?"alaw":Oi.test(e)?e:e==="webvtt"?"webvtt":null)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`);var e;if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(t.contentHint!==void 0&&typeof t.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},lr=i=>{const t=i.bitrate instanceof Ve?i.bitrate._toVideoBitrate(i.codec,i.width,i.height):i.bitrate;return{codec:i.fullCodecString??Oa(i.codec,i.width,i.height,t),width:i.width,height:i.height,displayWidth:i.squarePixelWidth,displayHeight:i.squarePixelHeight,bitrate:t,bitrateMode:i.bitrateMode,alpha:i.alpha??"discard",framerate:i.framerate,latencyMode:i.latencyMode,hardwareAcceleration:i.hardwareAcceleration,scalabilityMode:i.scalabilityMode,contentHint:i.contentHint,...(e=i.codec,e==="avc"?{avc:{format:"avc"}}:e==="hevc"?{hevc:{format:"hevc"}}:{})};var e};class Ve{constructor(t){this._factor=t}_toVideoBitrate(t,e,r){const a=e*r,s=3e6*Math.pow(a/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[t]*this._factor;return 1e3*Math.ceil(s/1e3)}_toAudioBitrate(t){if(bt.includes(t)||t==="flac")return;const e={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[t];if(!e)throw new Error(`Unhandled codec: ${t}`);let r=e*this._factor;return t==="aac"?r=[96e3,128e3,16e4,192e3].reduce((a,s)=>Math.abs(s-r)<Math.abs(a-r)?s:a):t==="opus"||t==="vorbis"?r=Math.max(6e3,r):t==="mp3"&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,s)=>Math.abs(s-r)<Math.abs(a-r)?s:a)),1e3*Math.round(r/1e3)}}const gs=async(i,t={})=>{const{width:e=1280,height:r=720,bitrate:a=1e6,...s}=t;if(!nt.includes(i))return!1;if(!Number.isInteger(e)||e<=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(!(a instanceof Ve)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");dr(i,s);const o=lr({codec:i,width:e,height:r,bitrate:a,framerate:void 0,...s,alpha:"discard"}),n=JSON.stringify(o),l=cr.get(n);if(l)return l;const c=(async()=>hr.some(d=>d.supports(i,o))?!0:typeof VideoEncoder>"u"||(e%2==1||r%2==1)&&(i==="avc"||i==="hevc")?!1:!!(await VideoEncoder.isConfigSupported(o)).supported&&(!Bi()||new Promise(async d=>{try{const u=new VideoEncoder({output:()=>{},error:()=>d(!1)});u.configure(o);const p=new Uint8Array(e*r*4),h=new VideoFrame(p,{format:"RGBA",codedWidth:e,codedHeight:r,timestamp:0});u.encode(h),h.close(),await u.flush(),d(!0)}catch{d(!1)}})))();return cr.set(n,c),c},hr=[];class Rt{constructor(t,e,r,a,s){this.bytes=t,this.view=e,this.offset=r,this.start=a,this.end=s,this.bufferPos=a-r}static tempFromBytes(t){return new Rt(t,xi(t),0,0,t.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(t,e=this.end-t){if(t<this.start||t+e>this.end)throw new RangeError("Slicing outside of original slice.");return new Rt(this.bytes,this.view,this.offset,t,t+e)}}const ws=(i,t)=>{((r,a)=>{if(r.filePos<r.start||r.filePos+a>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+a}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)})(i,t);const e=i.bytes.subarray(i.bufferPos,i.bufferPos+t);return i.bufferPos+=t,e};class ur{constructor(t){this.mutex=new ki,this.trackTimestampInfo=new WeakMap,this.output=t}onTrackClose(t){}validateTimestamp(t,e,r){if(e<0)throw new Error(`Timestamps must be non-negative (got ${e}s).`);let a=this.trackTimestampInfo.get(t);if(a){if(r&&(a.maxTimestampBeforeLastKeyPacket=a.maxTimestamp),a.maxTimestampBeforeLastKeyPacket!==null&&e<a.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 ${a.maxTimestampBeforeLastKeyPacket}s.`);a.maxTimestamp=Math.max(a.maxTimestamp,e)}else{if(!r)throw new Error("First packet must be a key packet.");a={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,a)}}}const de=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ys=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,pr=i=>{const t=Math.floor(i/36e5),e=Math.floor(i%36e5/6e4),r=Math.floor(i%6e4/1e3),a=i%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};class le{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=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 s of t.children)s&&this.writeBox(s);const r=this.writer.getPos(),a=t.size??r-e;this.writer.seek(e),this.writeBoxHeader(t,a),this.writer.seek(r)}}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);g(e!==void 0);const r=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(r)}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 r of t.children)r&&(e+=this.measureBox(r));return e}}}const F=new Uint8Array(8),at=new DataView(F.buffer),N=i=>[(i%256+256)%256],P=i=>(at.setUint16(0,i,!1),[F[0],F[1]]),Le=i=>(at.setInt16(0,i,!1),[F[0],F[1]]),mr=i=>(at.setUint32(0,i,!1),[F[1],F[2],F[3]]),x=i=>(at.setUint32(0,i,!1),[F[0],F[1],F[2],F[3]]),xt=i=>(at.setInt32(0,i,!1),[F[0],F[1],F[2],F[3]]),ft=i=>(at.setUint32(0,Math.floor(i/2**32),!1),at.setUint32(4,i,!1),[F[0],F[1],F[2],F[3],F[4],F[5],F[6],F[7]]),bs=i=>(at.setInt32(0,Math.floor(i/2**32),!1),at.setUint32(4,i,!1),[F[0],F[1],F[2],F[3],F[4],F[5],F[6],F[7]]),fr=i=>(at.setInt16(0,256*i,!1),[F[0],F[1]]),ct=i=>(at.setInt32(0,65536*i,!1),[F[0],F[1],F[2],F[3]]),We=i=>(at.setInt32(0,2**30*i,!1),[F[0],F[1],F[2],F[3]]),Oe=(i,t)=>{const e=[];let r=i;do{let a=127&r;r>>=7,e.length>0&&(a|=128),e.push(a)}while(r>0||t);return e.reverse()},O=(i,t=!1)=>{const e=Array(i.length).fill(null).map((r,a)=>i.charCodeAt(a));return t&&e.push(0),e},gr=i=>{const t=i*(Math.PI/180),e=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[e,r,0,-r,e,0,0,0,1]},wr=gr(0),yr=i=>[ct(i[0]),ct(i[1]),We(i[2]),ct(i[3]),ct(i[4]),We(i[5]),ct(i[6]),ct(i[7]),We(i[8])],B=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),R=(i,t,e,r,a)=>B(i,[N(t),mr(e),r??[]],a),br=()=>B("styp",[O("iso5"),x(0),O("iso5"),O("iso6"),O("mp41"),O("cmfc"),O("dash")]),vr=(i,t)=>{let e=i.maxWrittenEndTimestamp-i.minWrittenTimestamp;return Number.isFinite(e)||(e=0),R("sidx",1,0,[x(1),x(lt),ft(z(i.minWrittenTimestamp,lt)),ft(0),P(0),P(1),x(2147483647&t),x(z(e,lt)),x(0)])},he=i=>({type:"mdat",largeSize:i}),Qt=i=>B("moov",void 0,[vs(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>xs(t,i.creationTime)),i.isFragmented?io(i.trackDatas):null,fo(i)]),vs=(i,t)=>{const e=Math.max(0,...t.map(o=>z(ue(o),lt)+z(o.startTimestampOffset??0,lt))),r=Math.max(0,...t.map(o=>o.track.id))+1,a=!Et(i)||!Et(e),s=a?ft:x;return R("mvhd",+a,0,[s(i),s(i),x(lt),s(e),ct(1),fr(1),Array(10).fill(0),yr(wr),Array(24).fill(0),x(r)])},ue=i=>{if(i.samples.length===0)return 0;let t=1/0,e=-1/0;for(let r=0;r<i.samples.length;r++){const a=i.samples[r];a.timestamp<t&&(t=a.timestamp),a.timestamp+a.duration>e&&(e=a.timestamp+a.duration)}return t===1/0?0:e-t},xs=(i,t)=>{const e=Co(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset>0;return B("trak",void 0,[_s(i,t),r?ks(i,i.startTimestampOffset):null,Ts(i,t),e.name!==void 0?B("udta",void 0,[B("name",[...J.encode(e.name)])]):null])},_s=(i,t)=>{var n;const e=z(ue(i),lt)+z(i.startTimestampOffset??0,lt),r=!Et(t)||!Et(e),a=r?ft:x;let s;if(i.type==="video"){const l=i.track.metadata.rotation;s=gr(l??0)}else s=wr;let o=2;return((n=i.track.metadata.disposition)==null?void 0:n.default)!==!1&&(o|=1),R("tkhd",+r,o,[a(t),a(t),x(i.track.id),x(0),a(e),Array(8).fill(0),P(0),P(i.track.id),fr(i.type==="audio"?1:0),P(0),yr(s),ct(i.type==="video"?i.info.width:0),ct(i.type==="video"?i.info.height:0)])},ks=(i,t)=>{const e=z(t,lt),r=z(ue(i),lt),a=!Et(e)||!Et(r),s=a?ft:x,o=a?bs:xt;return B("edts",void 0,[R("elst",a?1:0,0,[x(2),s(e),o(-1),ct(1),s(r),o(0),ct(1)])])},Ts=(i,t)=>B("mdia",void 0,[Cs(i,t),$e(!0,Es[i.type],Ss[i.type]),Bs(i)]),Cs=(i,t)=>{const e=z(ue(i),i.timescale),r=!Et(t)||!Et(e),a=r?ft:x;return R("mdhd",+r,0,[a(t),a(t),x(i.timescale),a(e),P(Sr(i.track.metadata.languageCode??"und")),P(0)])},Es={video:"vide",audio:"soun",subtitle:"text"},Ss={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},$e=(i,t,e,r="\0\0\0\0")=>R("hdlr",0,0,[i?O("mhlr"):x(0),O(t),O(r),x(0),x(0),O(e,!0)]),Bs=i=>B("minf",void 0,[Ps[i.type](),Ms(),Fs(i)]),Ps={video:()=>R("vmhd",0,1,[P(0),P(0),P(0),P(0)]),audio:()=>R("smhd",0,0,[P(0),P(0)]),subtitle:()=>R("nmhd",0,0)},Ms=()=>B("dinf",void 0,[Is()]),Is=()=>R("dref",0,0,[x(1)],[As()]),As=()=>R("url ",0,1),Fs=i=>{const t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return B("stbl",void 0,[Ds(i),Xs(i),t?to(i):null,t?eo(i):null,Ys(i),Js(i),Zs(i),Ks(i)])},Ds=i=>{let t;if(i.type==="video")t=Rs(bo(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){const e=Er(i.track.source._codec,i.muxer.isQuickTime);g(e),t=Ws(e,i)}else i.type==="subtitle"&&(t=Qs(_o[i.track.source._codec],i));return g(t),R("stsd",0,0,[x(1)],[t])},Rs=(i,t)=>B(i,[Array(6).fill(0),P(1),P(0),P(0),Array(12).fill(0),P(t.info.width),P(t.info.height),x(4718592),x(4718592),x(0),P(1),Array(32).fill(0),P(24),Le(65535)],[vo[t.track.source._codec](t),Vs(t),_i(t.info.decoderConfig.colorSpace)?Ls(t):null]),Vs=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:B("pasp",[x(i.info.pixelAspectRatio.num),x(i.info.pixelAspectRatio.den)]),Ls=i=>B("colr",[O("nclx"),P($t[i.info.decoderConfig.colorSpace.primaries]),P(zt[i.info.decoderConfig.colorSpace.transfer]),P(Nt[i.info.decoderConfig.colorSpace.matrix]),N((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),xr=i=>{var c,d,u,p;if(!i.info.decoderConfig)return null;const t=i.info.decoderConfig,e=t.codec.split("."),r=Number(e[1]),a=Number(e[2]),s=(Number(e[3])<<4)+((e[4]?Number(e[4]):1)<<1)+(e[8]?Number(e[8]):Number(((c=t.colorSpace)==null?void 0:c.fullRange)??0)),o=e[5]?Number(e[5]):(d=t.colorSpace)!=null&&d.primaries?$t[t.colorSpace.primaries]:2,n=e[6]?Number(e[6]):(u=t.colorSpace)!=null&&u.transfer?zt[t.colorSpace.transfer]:2,l=e[7]?Number(e[7]):(p=t.colorSpace)!=null&&p.matrix?Nt[t.colorSpace.matrix]:2;return R("vpcC",1,0,[N(r),N(a),N(s),N(o),N(n),N(l),P(0)])},Ws=(i,t)=>{var o;let e,r=0,a=16;const s=bt.includes(t.track.source._codec);if(s){const n=t.track.source._codec,{sampleSize:l}=At(n);a=8*l,a>16&&(r=1)}if(t.muxer.isQuickTime&&(r=1),r===0)e=[Array(6).fill(0),P(1),P(r),P(0),x(0),P(t.info.numberOfChannels),P(a),P(0),P(0),P(t.info.sampleRate<65536?t.info.sampleRate:0),P(0)];else{const n=s?0:-2;e=[Array(6).fill(0),P(1),P(r),P(0),x(0),P(t.info.numberOfChannels),P(Math.min(a,16)),Le(n),P(0),P(t.info.sampleRate<65536?t.info.sampleRate:0),P(0),s?[x(1),x(a/8),x(t.info.numberOfChannels*a/8)]:[x(0),x(0),x(0)],x(2)]}return B(i,e,[((o=xo(t.track.source._codec,t.muxer.isQuickTime))==null?void 0:o(t))??null])},Os=i=>{let t;switch(i.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let e=[...N(t),...N(21),...mr(0),...x(0),...x(0)];if(i.info.decoderConfig.description){const r=Z(i.info.decoderConfig.description);e=[...e,...N(5),...Oe(r.byteLength),...r]}return e=[...P(1),...N(0),...N(4),...Oe(e.length),...e,...N(6),...N(1),...N(2)],e=[...N(3),...Oe(e.length),...e],R("esds",0,0,e)},$s=i=>B("wave",void 0,[zs(i),Ns(i),B("\0\0\0\0")]),zs=i=>B("frma",[O(Er(i.track.source._codec,i.muxer.isQuickTime))]),Ns=i=>{const{littleEndian:t}=At(i.track.source._codec);return B("enda",[P(+t)])},Us=i=>{var l;let t=i.info.numberOfChannels,e=3840,r=i.info.sampleRate,a=0,s=0,o=new Uint8Array(0);const n=(l=i.info.decoderConfig)==null?void 0:l.description;if(n){g(n.byteLength>=18);const c=Z(n),d=Xi(c);t=d.outputChannelCount,e=d.preSkip,r=d.inputSampleRate,a=d.outputGain,s=d.channelMappingFamily,d.channelMappingTable&&(o=d.channelMappingTable)}return B("dOps",[N(0),N(t),P(e),x(r),Le(a),N(s),...o])},Hs=i=>{var r;const t=(r=i.info.decoderConfig)==null?void 0:r.description;g(t);const e=Z(t);return R("dfLa",0,0,[...e.subarray(4)])},js=i=>{const{littleEndian:t,sampleSize:e}=At(i.track.source._codec);return R("pcmC",0,0,[N(+t),N(8*e)])},qs=i=>{const t=(a=>{if(a.length<7||a[0]!==11||a[1]!==119)return null;const s=new G(a);s.skipBits(16),s.skipBits(16);const o=s.readBits(2);if(o===3)return null;const n=s.readBits(6),l=s.readBits(5);if(l>8)return null;const c=s.readBits(3),d=s.readBits(3);return 1&d&&d!==1&&s.skipBits(2),4&d&&s.skipBits(2),d===2&&s.skipBits(2),{fscod:o,bsid:l,bsmod:c,acmod:d,lfeon:s.readBits(1),bitRateCode:Math.floor(n/2)}})(i.info.firstPacket.data);if(!t)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 e=new Uint8Array(3),r=new G(e);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),B("dac3",[...e])},Gs=i=>{const t=(o=>{if(o.length<6||o[0]!==11||o[1]!==119)return null;const n=new G(o);n.skipBits(16);const l=n.readBits(2);if(n.skipBits(3),l!==0&&l!==2)return null;const c=n.readBits(11),d=n.readBits(2);let u,p=0;d===3?(p=n.readBits(2),u=3):u=n.readBits(2);const h=n.readBits(3),m=n.readBits(1),f=n.readBits(5);if(f<11||f>16)return null;const y=as[u];let b;return b=d<3?Ga[d]/1e3:Qa[p]/1e3,{dataRate:Math.round((c+1)*b/(16*y)),substreams:[{fscod:d,fscod2:p,bsid:f,bsmod:0,acmod:h,lfeon:m,numDepSub:0,chanLoc:0}]}})(i.info.firstPacket.data);if(!t)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 e=16;for(const o of t.substreams)e+=23,o.numDepSub>0?e+=9:e+=1;const r=Math.ceil(e/8),a=new Uint8Array(r),s=new G(a);s.writeBits(13,t.dataRate),s.writeBits(3,t.substreams.length-1);for(const o of t.substreams)s.writeBits(2,o.fscod),s.writeBits(5,o.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,o.bsmod),s.writeBits(3,o.acmod),s.writeBits(1,o.lfeon),s.writeBits(3,0),s.writeBits(4,o.numDepSub),o.numDepSub>0?s.writeBits(9,o.chanLoc):s.writeBits(1,0);return B("dec3",[...a])},Qs=(i,t)=>B(i,[Array(6).fill(0),P(1)],[ko[t.track.source._codec](t)]),Xs=i=>R("stts",0,0,[x(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[x(t.sampleCount),x(t.sampleDelta)])]),Ks=i=>{if(i.samples.every(e=>e.type==="key"))return null;const t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return R("stss",0,0,[x(t.length),t.map(([e])=>x(e+1))])},Ys=i=>R("stsc",0,0,[x(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[x(t.firstChunk),x(t.samplesPerChunk),x(1)])]),Js=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){const{sampleSize:t}=At(i.track.source._codec);return R("stsz",0,0,[x(t*i.info.numberOfChannels),x(i.samples.reduce((e,r)=>e+z(r.duration,i.timescale),0))])}return R("stsz",0,0,[x(0),x(i.samples.length),i.samples.map(t=>x(t.size))])},Zs=i=>i.finalizedChunks.length>0&&mt(i.finalizedChunks).offset>=2**32?R("co64",0,0,[x(i.finalizedChunks.length),i.finalizedChunks.map(t=>ft(t.offset))]):R("stco",0,0,[x(i.finalizedChunks.length),i.finalizedChunks.map(t=>x(t.offset))]),to=i=>R("ctts",1,0,[x(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[x(t.sampleCount),xt(t.sampleCompositionTimeOffset)])]),eo=i=>{let t=1/0,e=-1/0,r=1/0,a=-1/0;g(i.compositionTimeOffsetTable.length>0),g(i.samples.length>0);for(let o=0;o<i.compositionTimeOffsetTable.length;o++){const n=i.compositionTimeOffsetTable[o];t=Math.min(t,n.sampleCompositionTimeOffset),e=Math.max(e,n.sampleCompositionTimeOffset)}for(let o=0;o<i.samples.length;o++){const n=i.samples[o];r=Math.min(r,z(n.timestamp,i.timescale)),a=Math.max(a,z(n.timestamp+n.duration,i.timescale))}const s=Math.max(-t,0);return a>=2**31?null:R("cslg",0,0,[xt(s),xt(t),xt(e),xt(r),xt(a)])},io=i=>B("mvex",void 0,i.map(ro)),ro=i=>R("trex",0,0,[x(i.track.id),x(1),x(0),x(0),x(0)]),_r=(i,t)=>B("moof",void 0,[ao(i),...t.map(so)]),ao=i=>R("mfhd",0,0,[x(i)]),kr=i=>{let t=0,e=0;const r=i.type==="delta";return e|=+r,t|=r?1:2,t<<24|e<<16},so=i=>B("traf",void 0,[oo(i),no(i),co(i)]),oo=i=>{g(i.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const e=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:kr(e)};return R("tfhd",0,131128,[x(i.track.id),x(r.duration),x(r.size),x(r.flags)])},no=i=>(g(i.currentChunk),R("tfdt",1,0,[ft(z(i.currentChunk.startTimestamp,i.timescale))])),co=i=>{g(i.currentChunk);const t=i.currentChunk.samples.map(f=>f.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(f=>f.size),r=i.currentChunk.samples.map(kr),a=i.currentChunk.samples.map(f=>z(f.timestamp-f.decodeTimestamp,i.timescale)),s=new Set(t),o=new Set(e),n=new Set(r),l=new Set(a),c=n.size===2&&r[0]!==r[1],d=s.size>1,u=o.size>1,p=!c&&n.size>1,h=l.size>1||[...l].some(f=>f!==0);let m=0;return m|=1,m|=4*+c,m|=256*+d,m|=512*+u,m|=1024*+p,m|=2048*+h,R("trun",1,m,[x(i.currentChunk.samples.length),x(i.currentChunk.offset-i.currentChunk.moofOffset||0),c?x(r[0]):[],i.currentChunk.samples.map((f,y)=>[d?x(t[y]):[],u?x(e[y]):[],p?x(r[y]):[],h?xt(a[y]):[]])])},lo=(i,t)=>R("tfra",1,0,[x(i.track.id),x(63),x(i.finalizedChunks.length),i.finalizedChunks.map(e=>[ft(z(e.samples[0].timestamp,i.timescale)),ft(e.moofOffset),x(t+1),x(1),x(1)])]),ho=()=>R("mfro",0,0,[x(0)]),uo=()=>B("vtte"),po=(i,t,e,r,a)=>B("vttc",void 0,[a!==null?B("vsid",[xt(a)]):null,e!==null?B("iden",[...J.encode(e)]):null,t!==null?B("ctim",[...J.encode(pr(t))]):null,r!==null?B("sttg",[...J.encode(r)]):null,B("payl",[...J.encode(i)])]),mo=i=>B("vtta",[...J.encode(i)]),fo=i=>{const t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){const a=wo(r);a&&t.push(a)}else if(e==="mdta"){const a=yo(r);a&&t.push(a)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&go(t,i.output._metadataTags);return t.length===0?null:B("udta",void 0,t)},go=(i,t)=>{for(const{key:e,value:r}of Ee(t))switch(e){case"title":i.push(gt("©nam",r));break;case"description":i.push(gt("©des",r));break;case"artist":i.push(gt("©ART",r));break;case"album":i.push(gt("©alb",r));break;case"albumArtist":i.push(gt("albr",r));break;case"genre":i.push(gt("©gen",r));break;case"date":i.push(gt("©day",r.toISOString().slice(0,10)));break;case"comment":i.push(gt("©cmt",r));break;case"lyrics":i.push(gt("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Vt(e)}if(t.raw)for(const e in t.raw){const r=t.raw[e];r==null||e.length!==4||i.some(a=>a.type===e)||(typeof r=="string"?i.push(gt(e,r)):r instanceof Uint8Array&&i.push(B(e,Array.from(r))))}},gt=(i,t)=>{const e=J.encode(t);return B(i,[P(e.length),P(Sr("und")),Array.from(e)])},Tr={"image/jpeg":13,"image/png":14,"image/bmp":27},Cr=(i,t)=>{const e=[];for(const{key:r,value:a}of Ee(i))switch(r){case"title":e.push({key:t?"title":"©nam",value:dt(a)});break;case"description":e.push({key:t?"description":"©des",value:dt(a)});break;case"artist":e.push({key:t?"artist":"©ART",value:dt(a)});break;case"album":e.push({key:t?"album":"©alb",value:dt(a)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:dt(a)});break;case"comment":e.push({key:t?"comment":"©cmt",value:dt(a)});break;case"genre":e.push({key:t?"genre":"©gen",value:dt(a)});break;case"lyrics":e.push({key:t?"lyrics":"©lyr",value:dt(a)});break;case"date":e.push({key:t?"date":"©day",value:dt(a.toISOString().slice(0,10))});break;case"images":for(const s of a)s.kind==="coverFront"&&e.push({key:"covr",value:B("data",[x(Tr[s.mimeType]??0),x(0),Array.from(s.data)])});break;case"trackNumber":if(t){const s=i.tracksTotal!==void 0?`${a}/${i.tracksTotal}`:a.toString();e.push({key:"track",value:dt(s)})}else e.push({key:"trkn",value:B("data",[x(0),x(0),P(0),P(a),P(i.tracksTotal??0),P(0)])});break;case"discNumber":t||e.push({key:"disc",value:B("data",[x(0),x(0),P(0),P(a),P(i.discsTotal??0),P(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:Vt(r)}if(i.raw)for(const r in i.raw){const a=i.raw[r];a==null||!t&&r.length!==4||e.some(s=>s.key===r)||(typeof a=="string"?e.push({key:r,value:dt(a)}):a instanceof Uint8Array?e.push({key:r,value:B("data",[x(0),x(0),Array.from(a)])}):a instanceof Ai&&e.push({key:r,value:B("data",[x(Tr[a.mimeType]??0),x(0),Array.from(a.data)])}))}return e},wo=i=>{const t=Cr(i,!1);return t.length===0?null:R("meta",0,0,void 0,[$e(!1,"mdir","","appl"),B("ilst",void 0,t.map(e=>B(e.key,void 0,[e.value])))])},yo=i=>{const t=Cr(i,!0);return t.length===0?null:B("meta",void 0,[$e(!1,"mdta",""),R("keys",0,0,[x(t.length)],t.map(e=>B("mdta",[...J.encode(e.key)]))),B("ilst",void 0,t.map((e,r)=>{const a=String.fromCharCode(...x(r+1));return B(a,void 0,[e.value])}))])},dt=i=>B("data",[x(1),x(0),...J.encode(i)]),bo=(i,t)=>{switch(i){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},vo={avc:i=>i.info.decoderConfig&&B("avcC",[...Z(i.info.decoderConfig.description)]),hevc:i=>i.info.decoderConfig&&B("hvcC",[...Z(i.info.decoderConfig.description)]),vp8:xr,vp9:xr,av1:i=>B("av1C",Wi(i.info.decoderConfig.codec))},Er=(i,t)=>{switch(i){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(t)switch(i){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(i){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"}},xo=(i,t)=>{switch(i){case"aac":case"mp3":case"vorbis":return Os;case"opus":return Us;case"flac":return Hs;case"ac3":return qs;case"eac3":return Gs}if(t)switch(i){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 $s}else switch(i){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 js}return null},_o={webvtt:"wvtt"},ko={webvtt:i=>B("vttC",[...J.encode(i.info.config.description)])},Sr=i=>{g(i.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=i.charCodeAt(e)-96;return t};class ze{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t._setMonotonicity(e),t._writerAcquired=!0}start(){g(!this.started),this.target._start(),this.started=!0}write(t){g(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target._write(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return g(this.started&&!this.finalized),this.target._flush()}async finalize(){g(this.started&&!this.finalized),await this.target._finalize(),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 r=e+t.byteLength-this.trackedStart;let a=this.trackedWrites.byteLength;for(;a<r;)a*=2;if(a!==this.trackedWrites.byteLength){const s=new Uint8Array(a);s.set(this.trackedWrites,0),this.trackedWrites=s}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}}class _t extends Ii{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(t){this._monotonicity!==!1&&(this._monotonicity=t)}_dispatchWrite(t,e){var r;(r=this.onwrite)==null||r.call(this,t,e),this._emit("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 To(this,t)}}const Ne=65536,Br=2**32;class pe extends _t{constructor(t={}){if(super(),this.buffer=null,this._maxPos=0,!t||typeof t!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(t.onFinalize!==void 0&&typeof t.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=t,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(Ne,{maxByteLength:Br})}catch{this._buffer=new ArrayBuffer(Ne),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Ne);this._bytes=new Uint8Array(this._buffer)}_ensureSize(t){let e=this._buffer.byteLength;for(;e<t;)e*=2;if(e!==this._buffer.byteLength){if(e>Br)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this._supportsResize)this._buffer.resize(e);else{const r=new ArrayBuffer(e),a=new Uint8Array(r);a.set(this._bytes,0),this._buffer=r,this._bytes=a}}}_start(){}_write(t,e){this._ensureSize(e+t.byteLength),this._bytes.set(t,e),this._maxPos=Math.max(this._maxPos,e+t.byteLength),this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(t,e){return this._bytes.slice(t,e)}}class To extends _t{constructor(t,e){super(),this._baseTarget=t,this._offset=e}_start(){}_write(t,e){this._baseTarget._write(t,this._offset+e),this._dispatchWrite(e,e+t.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}}class Ue{constructor(t,e){if(this.rootPath=t,this.getTarget=e,typeof t!="string")throw new TypeError("rootPath must be a string.");if(typeof e!="function")throw new TypeError("getTarget must be a function.")}}const lt=57600,Co=i=>{const t={},e=i.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},z=(i,t,e=!0)=>{const r=i*t;return e?Math.round(r):r};class Eo extends ur{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new pe,this.auxWriter=new ze(this.auxTarget,!1),this.auxBoxWriter=new le(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=_e(),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 Dr,this.isCmaf=e instanceof Fr,this.minimumFragmentDuration=e._options.minimumFragmentDuration??(e instanceof Fr?1/0:1)}async start(){var r;const t=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(a=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":a instanceof pe),this.boxWriter=new le(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof pe&&"in-memory"),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const a=await this.output._getInitTarget(),s=new ze(a,!0);s.start(),this.initWriter=s,this.initBoxWriter=new le(s)}const e=this.output._tracks.some(a=>a.isVideoTrack()&&a.source._codec==="avc");{const a=this.initBoxWriter??this.boxWriter;if(g(a),this.format._options.onFtyp&&a.writer.startTrackingWrites(),a.writeBox((s=>s.isQuickTime?B("ftyp",[O("qt "),x(512),O("qt ")]):s.fragmented?s.cmaf?B("ftyp",[O("iso5"),x(512),O("iso5"),O("iso6"),O("mp41"),O("cmfc"),O("dash")]):B("ftyp",[O("iso5"),x(512),O("iso5"),O("iso6"),O("mp41")]):B("ftyp",[O("isom"),x(512),O("isom"),s.holdsAvc?O("avc1"):[],O("mp41")]))({isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){const{data:s,start:o}=a.writer.stopTrackingWrites();this.format._options.onFtyp(s,o)}this.ftypSize=a.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const a of this.output._tracks)if(a.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(g(this.writer),g(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=he(!0),this.boxWriter.writeBox(this.mdat));await((r=this.writer)==null?void 0:r.flush()),t()}allTracksAreKnown(){for(const t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(e=>e.type==="video"||e.type==="audio"?e.info.decoderConfig.codec:{webvtt:"wvtt"}[e.track.source._codec]);return(e=>{let r=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");return e.codecStrings.length>0&&(r+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`),r})({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type==="video"),hasAudio:this.trackDatas.some(e=>e.type==="audio"),codecStrings:t})}getVideoTrackData(t,e,r){const a=this.trackDatas.find(p=>p.track===t);if(a)return a;$i(r),g(r),g(r.decoderConfig);const s={...r.decoderConfig};g(s.codedWidth!==void 0),g(s.codedHeight!==void 0);let o=!1;if(t.source._codec!=="avc"||s.description){if(t.source._codec==="hevc"&&!s.description){const p=Ka(e.data);if(!p)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.");s.description=(h=>{const m=[];m.push(h.configurationVersion),m.push((3&h.generalProfileSpace)<<6|(1&h.generalTierFlag)<<5|31&h.generalProfileIdc),m.push(h.generalProfileCompatibilityFlags>>>24&255),m.push(h.generalProfileCompatibilityFlags>>>16&255),m.push(h.generalProfileCompatibilityFlags>>>8&255),m.push(255&h.generalProfileCompatibilityFlags),m.push(...h.generalConstraintIndicatorFlags),m.push(255&h.generalLevelIdc),m.push(240|h.minSpatialSegmentationIdc>>8&15),m.push(255&h.minSpatialSegmentationIdc),m.push(252|3&h.parallelismType),m.push(252|3&h.chromaFormatIdc),m.push(248|7&h.bitDepthLumaMinus8),m.push(248|7&h.bitDepthChromaMinus8),m.push(h.avgFrameRate>>8&255),m.push(255&h.avgFrameRate),m.push((3&h.constantFrameRate)<<6|(7&h.numTemporalLayers)<<3|(1&h.temporalIdNested)<<2|3&h.lengthSizeMinusOne),m.push(255&h.arrays.length);for(const f of h.arrays){m.push((1&f.arrayCompleteness)<<7|63&f.nalUnitType),m.push(f.nalUnits.length>>8&255),m.push(255&f.nalUnits.length);for(const y of f.nalUnits){m.push(y.length>>8&255),m.push(255&y.length);for(let b=0;b<y.length;b++)m.push(y[b])}}return new Uint8Array(m)})(p),o=!0}}else{const p=(h=>{try{const m=[],f=[],y=[];for(const S of Ht(h)){const A=h.subarray(S.offset,S.offset+S.length),E=Hi(A[0]);E===vt.SPS?m.push(A):E===vt.PPS?f.push(A):E===vt.SPS_EXT&&y.push(A)}if(m.length===0||f.length===0)return null;const b=m[0],_=Xa(b);g(_!==null);const T=_.profileIdc===100||_.profileIdc===110||_.profileIdc===122||_.profileIdc===144;return{configurationVersion:1,avcProfileIndication:_.profileIdc,profileCompatibility:_.constraintFlags,avcLevelIndication:_.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:m,pictureParameterSets:f,chromaFormat:T?_.chromaFormatIdc:null,bitDepthLumaMinus8:T?_.bitDepthLumaMinus8:null,bitDepthChromaMinus8:T?_.bitDepthChromaMinus8:null,sequenceParameterSetExt:T?y:null}}catch(m){return console.error("Error building AVC Decoder Configuration Record:",m),null}})(e.data);if(!p)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.");s.description=(h=>{const m=[];m.push(h.configurationVersion),m.push(h.avcProfileIndication),m.push(h.profileCompatibility),m.push(h.avcLevelIndication),m.push(252|3&h.lengthSizeMinusOne),m.push(224|31&h.sequenceParameterSets.length);for(const f of h.sequenceParameterSets){const y=f.byteLength;m.push(y>>8),m.push(255&y);for(let b=0;b<y;b++)m.push(f[b])}m.push(h.pictureParameterSets.length);for(const f of h.pictureParameterSets){const y=f.byteLength;m.push(y>>8),m.push(255&y);for(let b=0;b<y;b++)m.push(f[b])}if(h.avcProfileIndication===100||h.avcProfileIndication===110||h.avcProfileIndication===122||h.avcProfileIndication===144){g(h.chromaFormat!==null),g(h.bitDepthLumaMinus8!==null),g(h.bitDepthChromaMinus8!==null),g(h.sequenceParameterSetExt!==null),m.push(252|3&h.chromaFormat),m.push(248|7&h.bitDepthLumaMinus8),m.push(248|7&h.bitDepthChromaMinus8),m.push(h.sequenceParameterSetExt.length);for(const f of h.sequenceParameterSetExt){const y=f.byteLength;m.push(y>>8),m.push(255&y);for(let b=0;b<y;b++)m.push(f[b])}}return new Uint8Array(m)})(p),o=!0}const n=((p,h)=>{const m=p<0?-1:1;let f=0,y=1,b=1,_=0,T=p=Math.abs(p);for(;;){const S=Math.floor(T),A=S*b+f,E=S*_+y;if(E>h)return{num:m*b,den:_};if(f=b,y=_,b=A,_=E,T=1/(T-S),!isFinite(T))break}return{num:m*b,den:_}})(1/(t.metadata.frameRate??lt),1e6).den,l=s.displayAspectWidth,c=s.displayAspectHeight,d=l===void 0||c===void 0?{num:1,den:1}:Se({num:l*s.codedHeight,den:c*s.codedWidth}),u={muxer:this,track:t,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o},timescale:n,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(u),this.trackDatas.sort((p,h)=>p.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(t,e,r){const a=this.trackDatas.find(l=>l.track===t);if(a)return a;zi(r),g(r),g(r.decoderConfig);const s={...r.decoderConfig};let o=!1;if(t.source._codec==="aac"&&!s.description){const l=ne(Rt.tempFromBytes(e.data));if(!l)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 c=Be[l.samplingFrequencyIndex],d=Pe[l.channelConfiguration];if(c===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=Di({objectType:l.objectType,sampleRate:c,numberOfChannels:d}),o=!0}const n={muxer:this,track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&bt.includes(t.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,firstPacket:e},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(n),this.trackDatas.sort((l,c)=>l.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,e){const r=this.trackDatas.find(s=>s.track===t);if(r)return r;Ni(e),g(e),g(e.config);const a={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:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(t,e,r){const a=await this.mutex.acquire();try{const s=this.getVideoTrackData(t,e,r);let o=e.data;if(s.info.requiresAnnexBTransformation){const l=[...Ht(o)].map(c=>o.subarray(c.offset,c.offset+c.length));if(l.length===0)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.");o=((c,d)=>{const u=c.reduce((m,f)=>m+d+f.byteLength,0),p=new Uint8Array(u);let h=0;for(const m of c){const f=new DataView(p.buffer,p.byteOffset,p.byteLength);switch(d){case 1:f.setUint8(h,m.byteLength);break;case 2:f.setUint16(h,m.byteLength,!1);break;case 3:Ia(f,h,m.byteLength);break;case 4:f.setUint32(h,m.byteLength,!1)}h+=d,p.set(m,h),h+=m.byteLength}return p})(l,4)}this.validateTimestamp(s.track,e.timestamp,e.type==="key");const n=this.createSampleForTrack(s,o,e.timestamp,e.duration,e.type);await this.registerSample(s,n)}finally{a()}}async addEncodedAudioPacket(t,e,r){const a=await this.mutex.acquire();try{const s=this.getAudioTrackData(t,e,r);let o=e.data;if(s.info.requiresAdtsStripping){const d=ne(Rt.tempFromBytes(o));if(!d)throw new Error("Expected ADTS frame, didn't get one.");const u=d.crcCheck===null?7:9;o=o.subarray(u)}this.validateTimestamp(s.track,e.timestamp,e.type==="key");let n=e.timestamp,l=e.duration;if(s.info.requiresPcmTransformation){const d=At(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(l=o.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){const u=n-s.info.expectedNextPcmPacketTimestamp;if(u<.01)n=s.info.expectedNextPcmPacketTimestamp;else{const p=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,u);n=s.info.expectedNextPcmPacketTimestamp+p}}s.info.expectedNextPcmPacketTimestamp=n+l}const c=this.createSampleForTrack(s,o,n,l,e.type);await this.registerSample(s,c)}finally{a()}}async padWithSilence(t,e,r){const a=z(r,t.timescale);if(r=a/t.timescale,a>0){const{sampleSize:s,silentValue:o}=At(t.info.decoderConfig.codec),n=a*t.info.numberOfChannels,l=new Uint8Array(s*n).fill(o),c=this.createSampleForTrack(t,new Uint8Array(l.buffer),e,r,"key");await this.registerSample(t,c)}return r}async addSubtitleCue(t,e,r){const a=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(t,r);this.validateTimestamp(s.track,e.timestamp,!0),t.source._codec==="webvtt"&&(s.cueQueue.push(e),await this.processWebVTTCues(s,e.timestamp))}finally{a()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){const r=new Set([]);for(const c of t.cueQueue)g(c.timestamp<=e),g(t.lastCueEndTimestamp<=c.timestamp+c.duration),r.add(Math.max(c.timestamp,t.lastCueEndTimestamp)),r.add(c.timestamp+c.duration);const a=[...r].sort((c,d)=>c-d),s=a[0],o=a[1]??s;if(e<o)break;if(t.lastCueEndTimestamp<s){this.auxWriter.seek(0);const c=uo();this.auxBoxWriter.writeBox(c);const d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(t,d,t.lastCueEndTimestamp,s-t.lastCueEndTimestamp,"key");await this.registerSample(t,u),t.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let c=0;c<t.cueQueue.length;c++){const d=t.cueQueue[c];if(d.timestamp>=o)break;de.lastIndex=0;const u=de.test(d.text),p=d.timestamp+d.duration;let h=t.cueToSourceId.get(d);if(h===void 0&&o<p&&(h=t.nextSourceId++,t.cueToSourceId.set(d,h)),d.notes){const f=mo(d.notes);this.auxBoxWriter.writeBox(f)}const m=po(d.text,u?s:null,d.identifier??null,d.settings??null,h??null);this.auxBoxWriter.writeBox(m),p===o&&t.cueQueue.splice(c--,1)}const n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(t,n,s,o-s,"key");await this.registerSample(t,l),t.lastCueEndTimestamp=o}}createSampleForTrack(t,e,r,a,s){return{timestamp:r,decodeTimestamp:r,duration:a,data:e,size:e.byteLength,type:s,timescaleUnitsToNextSample:z(a,t.timescale)}}processTimestamps(t,e){if(t.timestampProcessingQueue.length===0)return;if(t.type==="audio"&&t.info.requiresPcmTransformation){this.isFragmented||(t.startTimestampOffset??(t.startTimestampOffset=t.timestampProcessingQueue[0].timestamp));let a=0;for(let s=0;s<t.timestampProcessingQueue.length;s++){const o=t.timestampProcessingQueue[s];a+=z(o.duration,t.timescale)}return t.timeToSampleTable.length===0?t.timeToSampleTable.push({sampleCount:a,sampleDelta:1}):mt(t.timeToSampleTable).sampleCount+=a,void(t.timestampProcessingQueue.length=0)}const r=t.timestampProcessingQueue.map(a=>a.timestamp).sort((a,s)=>a-s);this.isFragmented||(t.startTimestampOffset??(t.startTimestampOffset=r[0]));for(let a=0;a<t.timestampProcessingQueue.length;a++){const s=t.timestampProcessingQueue[a];s.decodeTimestamp=r[a];const o=z(s.timestamp-s.decodeTimestamp,t.timescale),n=z(s.duration,t.timescale);if(t.lastTimescaleUnits!==null){g(t.lastSample);const l=z(s.decodeTimestamp,t.timescale,!1),c=Math.round(l-t.lastTimescaleUnits);if(g(c>=0),t.lastTimescaleUnits+=c,t.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let d=mt(t.timeToSampleTable);if(g(d),d.sampleCount===1){d.sampleDelta=c;const p=t.timeToSampleTable[t.timeToSampleTable.length-2];p&&p.sampleDelta===c&&(p.sampleCount++,t.timeToSampleTable.pop(),d=p)}else d.sampleDelta!==c&&(d.sampleCount--,t.timeToSampleTable.push(d={sampleCount:1,sampleDelta:c}));d.sampleDelta===n?d.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:n});const u=mt(t.compositionTimeOffsetTable);g(u),u.sampleCompositionTimeOffset===o?u.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else t.lastTimescaleUnits=z(s.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:n}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));t.lastSample=s}if(t.timestampProcessingQueue.length=0,g(t.lastSample),g(t.lastTimescaleUnits!==null),e!==void 0&&t.lastSample.timescaleUnitsToNextSample===0){g(e.type==="key");const a=z(e.timestamp,t.timescale,!1),s=Math.round(a-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=s}}async registerSample(t,e){e.type==="key"&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),this.fastStart==="reserve")){const a=t.track.metadata.maximumPacketCount;if(g(a!==void 0),t.samples.length>a)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${a}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(t.currentChunk){t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,e.timestamp);const a=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(o=>{if(t===o)return e.type==="key";const n=o.sampleQueue[0];return n?n.type==="key":o.closed});a>=this.minimumFragmentDuration&&s&&e.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=a>=.5}else r=!0;r&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null}),g(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(g(!this.isFragmented),g(this.writer),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if(t.type==="audio"&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((r,a)=>r+z(a.duration,t.timescale),0)),t.compactlyCodedChunkTable.length!==0&&mt(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),this.fastStart!=="in-memory"){t.currentChunk.offset=this.writer.getPos();for(const r of t.currentChunk.samples)g(r.data),this.writer.write(r.data),r.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(g(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,r=1/0;for(const s of this.trackDatas){if(!t&&s.sampleQueue.length===0&&!s.closed)break t;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<r&&(e=s,r=s.sampleQueue[0].timestamp)}if(!e)break;const a=e.sampleQueue.shift();await this.addSampleToTrack(e,a)}}async finalizeFragment(t=!this.isCmaf){g(this.isFragmented);const e=this.nextFragmentNumber++;if(e===1){const h=this.initBoxWriter??this.boxWriter;g(h),this.format._options.onMoov&&h.writer.startTrackingWrites();const m=Qt(this);if(h.writeBox(m),this.format._options.onMoov){const{data:f,start:y}=h.writer.stopTrackingWrites();this.format._options.onMoov(f,y)}if(this.isCmaf){g(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new le(this.writer);const f=this.boxWriter.measureBox(br()),y=this.boxWriter.measureBox(vr(this,0));this.segmentHeaderSize=f+y,this.writer.seek(this.segmentHeaderSize)}}g(this.writer),g(this.boxWriter);const r=this.trackDatas.filter(h=>h.currentChunk),a=_r(e,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a);let n=o+8,l=1/0;for(const h of r){h.currentChunk.offset=n,h.currentChunk.moofOffset=s;for(const m of h.currentChunk.samples)n+=m.size;l=Math.min(l,h.currentChunk.startTimestamp)}const c=n-o,d=c>=2**32;if(d)for(const h of r)h.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const u=_r(e,r);if(this.boxWriter.writeBox(u),this.format._options.onMoof){const{data:h,start:m}=this.writer.stopTrackingWrites();this.format._options.onMoof(h,m,l)}g(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();const p=he(d);p.size=c,this.boxWriter.writeBox(p),this.writer.seek(o+(d?16:8));for(const h of r)for(const m of h.currentChunk.samples)this.writer.write(m.data),m.data=null;if(this.format._options.onMdat){const{data:h,start:m}=this.writer.stopTrackingWrites();this.format._options.onMdat(h,m)}for(const h of r)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){if(g(this.writer),g(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){const r=Qt(this),a=this.boxWriter.measureBox(r)+this.computeSampleTableSizeUpperBound()+4096;g(this.ftypSize!==null),this.writer.seek(this.ftypSize+a),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=he(!0),this.boxWriter.writeBox(this.mdat);for(const s of this.trackDatas){for(const o of s.sampleQueue)await this.addSampleToTrack(s,o);s.sampleQueue.length=0}}await this.addSampleToTrack(t,e)}else t.sampleQueue.push(e)}computeSampleTableSizeUpperBound(){g(this.fastStart==="reserve");let t=0;for(const e of this.trackDatas){const r=e.track.metadata.maximumPacketCount;g(r!==void 0),t+=8*Math.ceil(2/3*r),t+=4*r,t+=8*Math.ceil(2/3*r),t+=12*Math.ceil(2/3*r),t+=4*r,t+=8*r}return t}async onTrackClose(t){const e=await this.mutex.acquire(),r=this.trackDatas.find(a=>a.track===t);r&&(r.closed=!0,r.type==="subtitle"&&t.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const r of this.trackDatas){await this.finalizeCurrentChunk(r),g(r.startTimestampOffset!==null);for(let a=0;a<r.samples.length;a++){const s=r.samples[a];s.timestamp-=r.startTimestampOffset,s.decodeTimestamp-=r.startTimestampOffset}}if(g(this.writer),g(this.boxWriter),this.fastStart==="in-memory"){let r;this.mdat=he(!1);for(let s=0;s<2;s++){const o=Qt(this),n=this.boxWriter.measureBox(o);r=this.boxWriter.measureBox(this.mdat);let l=this.writer.getPos()+n+r;for(const c of this.finalizedChunks){c.offset=l;for(const{data:d}of c.samples)g(d),l+=d.byteLength,r+=d.byteLength}if(l<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const a=Qt(this);if(this.boxWriter.writeBox(a),this.format._options.onMoov){const{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(const s of this.finalizedChunks)for(const o of s.samples)g(o.data),this.writer.write(o.data),o.data=null;if(this.format._options.onMdat){const{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}}else if(this.isFragmented)if(this.isCmaf){const r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(br()),this.boxWriter.writeBox(vr(this,r))}else{const r=this.writer.getPos(),a=(e=this.trackDatas,B("mfra",void 0,[...e.map(lo),ho()]));this.boxWriter.writeBox(a);const s=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{g(this.mdat);const r=this.boxWriter.offsets.get(this.mdat);g(r!==void 0);const a=this.writer.getPos()-r;if(this.mdat.size=a,this.mdat.largeSize=a>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:o,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(o,n)}const s=Qt(this);if(this.fastStart==="reserve"){g(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);const o=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:o})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);if(this.format._options.onMoov){const{data:o,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(o,n)}}var e;t()}}const Pr="Mediabunny",So={video:1,audio:2,subtitle:17};class Bo extends ur{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=_e(),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=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._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new ss(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),t()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const t={id:v.EBML,data:[{id:v.EBMLVersion,data:1},{id:v.EBMLReadVersion,data:1},{id:v.EBMLMaxIDLength,data:4},{id:v.EBMLMaxSizeLength,data:8},{id:v.DocType,data:this.format instanceof fe?"webm":"matroska"},{id:v.DocTypeVersion,data:2},{id:v.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format._options.onEbmlHeader){const{data:e,start:r}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,r)}}maybeCreateSeekHead(t){if(this.format._options.appendOnly)return;const e=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),n={id:v.SeekHead,data:[{id:v.Seek,data:[{id:v.SeekID,data:e},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:v.Seek,data:[{id:v.SeekID,data:r},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:v.Seek,data:[{id:v.SeekID,data:a},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:v.Seek,data:[{id:v.SeekID,data:s},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:v.Seek,data:[{id:v.SeekID,data:o},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=n}createSegmentInfo(){const t={id:v.Duration,data:new Ae(0)};this.segmentDuration=t;const e={id:v.Info,data:[{id:v.TimestampScale,data:1e6},{id:v.MuxingApp,data:Pr},{id:v.WritingApp,data:Pr},this.format._options.appendOnly?null:t]};this.segmentInfo=e}createTracks(){var e,r,a,s,o,n;const t={id:v.Tracks,data:[]};this.tracksElement=t;for(const l of this.trackDatas){const c=os[l.track.source._codec];g(c);let d=0;if(l.type==="audio"&&l.track.source._codec==="opus"){d=8e7;const u=l.info.decoderConfig.description;if(u){const p=Z(u),h=Xi(p);d=Math.round(h.preSkip/48e3*1e9)}}t.data.push({id:v.TrackEntry,data:[{id:v.TrackNumber,data:l.track.id},{id:v.TrackUID,data:l.track.id},{id:v.TrackType,data:So[l.type]},((e=l.track.metadata.disposition)==null?void 0:e.default)===!1?{id:v.FlagDefault,data:0}:null,(r=l.track.metadata.disposition)!=null&&r.forced?{id:v.FlagForced,data:1}:null,(a=l.track.metadata.disposition)!=null&&a.hearingImpaired?{id:v.FlagHearingImpaired,data:1}:null,(s=l.track.metadata.disposition)!=null&&s.visuallyImpaired?{id:v.FlagVisualImpaired,data:1}:null,(o=l.track.metadata.disposition)!=null&&o.original?{id:v.FlagOriginal,data:1}:null,(n=l.track.metadata.disposition)!=null&&n.commentary?{id:v.FlagCommentary,data:1}:null,{id:v.FlagLacing,data:0},{id:v.Language,data:l.track.metadata.languageCode??"und"},{id:v.CodecID,data:c},{id:v.CodecDelay,data:0},{id:v.SeekPreRoll,data:d},l.track.metadata.name!==void 0?{id:v.Name,data:new St(l.track.metadata.name)}:null,l.type==="video"?this.videoSpecificTrackInfo(l):null,l.type==="audio"?this.audioSpecificTrackInfo(l):null,l.type==="subtitle"?this.subtitleSpecificTrackInfo(l):null]})}}videoSpecificTrackInfo(t){const{frameRate:e,rotation:r}=t.track.metadata,a=[t.info.decoderConfig.description?{id:v.CodecPrivate,data:Z(t.info.decoderConfig.description)}:null,e?{id:v.DefaultDuration,data:1e9/e}:null],s=r?vi(-r):0,o=!!t.info.aspectRatio&&t.info.aspectRatio.num*t.info.height!==t.info.aspectRatio.den*t.info.width,n=t.info.decoderConfig.colorSpace,l={id:v.Video,data:[{id:v.PixelWidth,data:t.info.width},{id:v.PixelHeight,data:t.info.height},o?{id:v.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:v.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:v.DisplayUnit,data:3}:null,t.info.alphaMode?{id:v.AlphaMode,data:1}:null,_i(n)?{id:v.Colour,data:[{id:v.MatrixCoefficients,data:Nt[n.matrix]},{id:v.TransferCharacteristics,data:zt[n.transfer]},{id:v.Primaries,data:$t[n.primaries]},{id:v.Range,data:n.fullRange?2:1}]}:null,s?{id:v.Projection,data:[{id:v.ProjectionType,data:0},{id:v.ProjectionPoseRoll,data:new Ie((s+180)%360-180)}]}:null]};return a.push(l),a}audioSpecificTrackInfo(t){const e=bt.includes(t.track.source._codec)?At(t.track.source._codec):null;return[t.info.decoderConfig.description?{id:v.CodecPrivate,data:Z(t.info.decoderConfig.description)}:null,{id:v.Audio,data:[{id:v.SamplingFrequency,data:new Ie(t.info.sampleRate)},{id:v.Channels,data:t.info.numberOfChannels},e?{id:v.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[{id:v.CodecPrivate,data:J.encode(t.info.config.description)}]}maybeCreateTags(){const t=[],e=(s,o)=>{t.push({id:v.SimpleTag,data:[{id:v.TagName,data:new St(s)},typeof o=="string"?{id:v.TagString,data:new St(o)}:{id:v.TagBinary,data:o}]})},r=this.output._metadataTags,a=new Set;for(const{key:s,value:o}of Ee(r))switch(s){case"title":e("TITLE",o),a.add("TITLE");break;case"description":e("DESCRIPTION",o),a.add("DESCRIPTION");break;case"artist":e("ARTIST",o),a.add("ARTIST");break;case"album":e("ALBUM",o),a.add("ALBUM");break;case"albumArtist":e("ALBUM_ARTIST",o),a.add("ALBUM_ARTIST");break;case"genre":e("GENRE",o),a.add("GENRE");break;case"comment":e("COMMENT",o),a.add("COMMENT");break;case"lyrics":e("LYRICS",o),a.add("LYRICS");break;case"date":e("DATE",o.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":e("PART_NUMBER",r.tracksTotal!==void 0?`${o}/${r.tracksTotal}`:o.toString()),a.add("PART_NUMBER");break;case"discNumber":e("DISC",r.discsTotal!==void 0?`${o}/${r.discsTotal}`:o.toString()),a.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:Vt(s)}if(r.raw)for(const s in r.raw){const o=r.raw[s];o==null||a.has(s)||(typeof o=="string"||o instanceof Uint8Array)&&e(s,o)}t.length!==0&&(this.tagsElement={id:v.Tags,data:[{id:v.Tag,data:[{id:v.Targets,data:[{id:v.TargetTypeValue,data:50},{id:v.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output._metadataTags,e=[],r=new Set,a=t.images??[];for(const s of a){let o,n=s.name;for(n===void 0&&(n=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(Va(s.mimeType)??""));;){o=0n;for(let l=0;l<8;l++)o<<=8n,o|=BigInt(Math.floor(256*Math.random()));if(o!==0n&&!r.has(o))break}r.add(o),e.push({id:v.AttachedFile,data:[s.description!==void 0?{id:v.FileDescription,data:new St(s.description)}:null,{id:v.FileName,data:new St(n)},{id:v.FileMediaType,data:s.mimeType},{id:v.FileData,data:s.data},{id:v.FileUID,data:o}]})}for(const[s,o]of Object.entries(t.raw??{}))o instanceof Fi&&/^\d+$/.test(s)&&(a.find(n=>n.mimeType===o.mimeType&&La(n.data,o.data))||e.push({id:v.AttachedFile,data:[o.description!==void 0?{id:v.FileDescription,data:new St(o.description)}:null,{id:v.FileName,data:new St(o.name??"")},{id:v.FileMediaType,data:o.mimeType??""},{id:v.FileData,data:o.data},{id:v.FileUID,data:BigInt(s)}]}));e.length!==0&&(this.attachmentsElement={id:v.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:v.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=t,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format._options.onSegmentHeader){const{data:e,start:r}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,r)}}createCues(){this.cues={id:v.Cues,data:[]}}get segmentDataOffset(){return g(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(e=>e.type==="video"||e.type==="audio"?e.info.decoderConfig.codec:{webvtt:"wvtt"}[e.track.source._codec]);return(e=>{let r=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");return e.codecStrings.length>0&&(r+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`),r})({isWebM:this.format instanceof fe,hasVideo:this.trackDatas.some(e=>e.type==="video"),hasAudio:this.trackDatas.some(e=>e.type==="audio"),codecStrings:t})}getVideoTrackData(t,e,r){const a=this.trackDatas.find(c=>c.track===t);if(a)return a;$i(r),g(r),g(r.decoderConfig),g(r.decoderConfig.codedWidth!==void 0),g(r.decoderConfig.codedHeight!==void 0);const s=r.decoderConfig.displayAspectWidth,o=r.decoderConfig.displayAspectHeight,n=s===void 0||o===void 0?null:Se({num:s,den:o}),l={track:t,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,aspectRatio:n,decoderConfig:r.decoderConfig,alphaMode:!!e.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return t.source._codec==="vp9"?l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array($a(l.info.decoderConfig.codec))}:t.source._codec==="av1"&&(l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array(Wi(l.info.decoderConfig.codec))}),this.trackDatas.push(l),this.trackDatas.sort((c,d)=>c.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(t,e,r){const a=this.trackDatas.find(l=>l.track===t);if(a)return a;zi(r),g(r),g(r.decoderConfig);const s={...r.decoderConfig};let o=!1;if(t.source._codec==="aac"&&!s.description){const l=ne(Rt.tempFromBytes(e.data));if(!l)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 c=Be[l.samplingFrequencyIndex],d=Pe[l.channelConfiguration];if(c===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=Di({objectType:l.objectType,sampleRate:c,numberOfChannels:d}),o=!0}const n={track:t,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(n),this.trackDatas.sort((l,c)=>l.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,e){const r=this.trackDatas.find(s=>s.track===t);if(r)return r;Ni(e),g(e),g(e.config);const a={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(t,e,r){const a=await this.mutex.acquire();try{const s=this.getVideoTrackData(t,e,r),o=e.type==="key";this.validateTimestamp(s.track,e.timestamp,o);let n=e.timestamp,l=e.duration;t.metadata.frameRate!==void 0&&(n=Ei(n,t.metadata.frameRate),l=Ei(l,t.metadata.frameRate));const c=s.info.alphaMode?e.sideData.alpha??null:null,d=this.createInternalChunk(e.data,n,l,e.type,c);t.source._codec==="vp9"&&this.fixVP9ColorSpace(s,d),s.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(t,e,r){const a=await this.mutex.acquire();try{const s=this.getAudioTrackData(t,e,r);let o=e.data;if(s.info.requiresAdtsStripping){const c=ne(Rt.tempFromBytes(o));if(!c)throw new Error("Expected ADTS frame, didn't get one.");const d=c.crcCheck===null?7:9;o=o.subarray(d)}const n=e.type==="key";this.validateTimestamp(s.track,e.timestamp,n);const l=this.createInternalChunk(o,e.timestamp,e.duration,e.type);s.chunkQueue.push(l),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(t,e,r){const a=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(t,r);this.validateTimestamp(s.track,e.timestamp,!0);let o=e.text;const n=Math.round(1e3*e.timestamp);de.lastIndex=0,o=o.replace(de,u=>{const p=(h=>{const m=ys.exec(h);if(!m)throw new Error("Expected match.");return 36e5*Number(m[1]||"0")+6e4*Number(m[2])+1e3*Number(m[3])+Number(m[4])})(u.slice(1,-1));return`<${pr(p-n)}>`});const l=J.encode(o),c=`${e.settings??""}
1
+ (function(et,K){typeof exports=="object"&&typeof module<"u"?K(exports):typeof define=="function"&&define.amd?define(["exports"],K):K((et=typeof globalThis<"u"?globalThis:et||self).TextmodeExport={})})(this,function(et){"use strict";var En=Object.defineProperty;var Sn=(et,K,ot)=>K in et?En(et,K,{enumerable:!0,configurable:!0,writable:!0,value:ot}):et[K]=ot;var w=(et,K,ot)=>Sn(et,typeof K!="symbol"?K+"":K,ot);class K{$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],a=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*a*100)/100}}}class ot{$downloadFile(t,e){try{const i=this._sanitizeFilename(e),a=URL.createObjectURL(t),s=document.createElement("a");s.href=a,s.download=i,s.style.display="none",s.rel="noopener",document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(a)}catch(i){console.error("[textmode-export] Failed to download file:",i)}}_sanitizeFilename(t){if(!t)return this._generateDefaultFilename();const e=t.trim();return e?e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,255)||this._generateDefaultFilename():this._generateDefaultFilename()}_generateDefaultFilename(){return`textmode-export-${new Date().toISOString().slice(0,19).replace(/:/g,"-")}`}}const or=new WeakMap;function ha(r){return Math.round(255*r[0])+(Math.round(255*r[1])<<8)}function be(r,t){let e=or.get(r);if(!e){e=new Map;for(const i of r.characters)e.set(ha(i.color),i);or.set(r,e)}return e.get(t)}function nr(r,t){const e=r==="base"?"Base layer":`Layer ${Number.parseInt(r.replace("layer-",""),10)}`;return t._visible===!1?`${e} (hidden)`:e}function cr(r){return[{id:"base",layer:r.layers.base},...r.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:nr(t,e),layer:e}))}function te(r,t){const e=t??r.layers.base,i=(function(n,l){if(l===n.layers.base)return"base";const c=n.layers.all.indexOf(l);if(c>=0)return`layer-${c+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")})(r,e),a=e.grid,s=e.font,o=e.drawFramebuffer;if(!a||!o)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:i,label:nr(i,e),layer:e,grid:a,font:s,drawFramebuffer:o}}function ee(r,t){return{r:r[t],g:r[t+1],b:r[t+2],a:r[t+3]}}class ua extends K{_calculateCellPosition(t,e,i){return{x:t,y:e,cellX:t*i.cellWidth,cellY:e*i.cellHeight}}$extractSVGCellData(t,e){const i=[];let a=0;for(let s=0;s<e.rows;s++)for(let o=0;o<e.cols;o++){const n=4*a,l=this.$getEncodedCharacterValue(t.characterPixels,n);let c=ee(t.primaryColorPixels,n),d=ee(t.secondaryColorPixels,n);const u=this.$extractCellTransform(t.characterPixels,n);if(u.isInverted){const h=c;c=d,d=h}const m=this._calculateCellPosition(o,s,e);i.push({encodedGlyphSlot:l,primaryColor:c,secondaryColor:d,transform:u,position:m}),a++}return i}}class ma{_createGlyphPath(t,e,i,a,s){const o=s/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:i+e.xMin*o,y1:a+-e.yMax*o,x2:i+e.xMax*o,y2:a+-e.yMin*o}),toSVG:()=>this._glyphToSVGPath(e,i,a,o)}}_glyphToSVGPath(t,e,i,a){if(!t||!t.xs)return"";const{xs:s,ys:o,endPts:n,flags:l}=t;if(!(s&&o&&n&&l))return"";let c="",d=0;for(let u=0;u<n.length;u++){const m=n[u];if(!(m<d)){if(m>=d){const h=e+s[d]*a,p=i-o[d]*a;c+=`M${h.toFixed(2)},${p.toFixed(2)}`;let f=d+1;for(;f<=m;)if(1&l[f]){const y=e+s[f]*a,b=i-o[f]*a;c+=`L${y.toFixed(2)},${b.toFixed(2)}`,f++}else{const y=e+s[f]*a,b=i-o[f]*a,_=f+1>m?d:f+1;if(1&l[_]){const T=e+s[_]*a,S=i-o[_]*a;c+=`Q${y.toFixed(2)},${b.toFixed(2)} ${T.toFixed(2)},${S.toFixed(2)}`,f=_+1}else{const T=(y+(e+s[_]*a))/2,S=(b+(i-o[_]*a))/2;c+=`Q${y.toFixed(2)},${b.toFixed(2)} ${T.toFixed(2)},${S.toFixed(2)}`,f=_}}c+="Z"}d=m+1}}return c}$generatePositionedCharacterPath(t,e,i,a,s,o,n,l){if(!l)return null;const c=e.font,d=n/c.head.unitsPerEm,u=i+(s-l.advanceWidth*d)/2,m=a+c.hhea.ascender*d;return this._createGlyphPath(c,l,u,m,n).toSVG()||null}}class pa{constructor(){w(this,"_pathGenerator");this._pathGenerator=new ma}$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>"}_generateTransformAttribute(t,e){const{transform:i,position:a}=t;if(!i.flipHorizontal&&!i.flipVertical&&!i.rotation)return"";const s=a.cellX+e.cellWidth/2,o=a.cellY+e.cellHeight/2,n=[];if(i.flipHorizontal||i.flipVertical){const l=i.flipHorizontal?-1:1,c=i.flipVertical?-1:1;n.push(`translate(${s} ${o})scale(${l} ${c})translate(${-s} ${-o})`)}return i.rotation&&n.push(`rotate(${i.rotation} ${s} ${o})`),` transform="${n.join(" ")}"`}_generateCellBackground(t,e,i){if(!i.includeBackgroundRectangles||t.secondaryColor.a===0)return"";const{position:a}=t,{r:s,g:o,b:n,a:l}=t.secondaryColor,c=`rgba(${s},${o},${n},${l/255})`;return i.drawMode==="stroke"?`<rect x="${a.cellX}" y="${a.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${c}" fill="none" stroke-width="${i.strokeWidth}"/>`:`<rect x="${a.cellX}" y="${a.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${c}"/>`}_generateCharacterPath(t,e,i,a){const s=be(i,t.encodedGlyphSlot);if(!s)return"";const o=this._pathGenerator.$generatePositionedCharacterPath(s.character,i,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,i.fontSize,s.glyphData);if(!o)return"";const{r:n,g:l,b:c,a:d}=t.primaryColor,u=`rgba(${n},${l},${c},${d/255})`;return a.drawMode==="stroke"?`<path d="${o}" stroke="${u}" stroke-width="${a.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${u}"/>`}$generateCellContent(t,e,i,a){const s=[],o=this._generateCellBackground(t,e,a);o&&s.push(o);const n=this._generateCharacterPath(t,e,i,a);if(n){const l=this._generateTransformAttribute(t,e);s.push(l?`<g${l}>${n}</g>`:n)}return s.join("")}$generateSVGContent(t,e,i,a){const s=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)s.push(this.$generateCellContent(o,e,i,a));return s.push(this.$generateSVGFooter()),s.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}}class dr{_applyDefaultOptions(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 ua,a=new pa,s=this._applyDefaultOptions(e),o=te(t,s.layer),n=i.$extractSVGCellData(i.$extractFramebufferData(o.drawFramebuffer),o.grid),l=a.$generateSVGContent(n,o.grid,o.font,s);return a.$optimizeSVGContent(l)}$saveSVG(t,e={}){new ot().$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename)}}const ve={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},fa=".png",ga=".jpg",wa=".webp";class lr{_applyDefaultOptions(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}_validateOptions(t){if(!(t.format in ve))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,a=document.createElement("canvas"),s=a.getContext("2d"),o=Math.round(i.width*e.scale),n=Math.round(i.height*e.scale);return a.width=o,a.height=n,s.imageSmoothingEnabled=!1,s.clearRect(0,0,o,n),s.drawImage(i,0,0,i.width,i.height,0,0,o,n),await new Promise((l,c)=>{a.toBlob(d=>{d?l(d):c(new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},ve[e.format])})}async $saveImage(t,e={}){const i=this._applyDefaultOptions(e);this._validateOptions(i);const a=await this.$generateImageBlob(t,i);new ot().$downloadFile(a,i.filename)}async $copyImageToClipboard(t,e={}){if(typeof navigator>"u"||!navigator.clipboard||typeof navigator.clipboard.write!="function")throw new Error("Clipboard API is not available in this environment");const i=this._applyDefaultOptions(e);this._validateOptions(i);const a=await this.$generateImageBlob(t,i),s=new ClipboardItem({[ve[i.format]]:a});await navigator.clipboard.write([s])}}class hr{_applyDefaultOptions(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}_createTXTContent(t,e){var l;const i=new K,a=te(t,e.layer),s=i.$extractFramebufferData(a.drawFramebuffer),o=[];let n=0;for(let c=0;c<a.grid.rows;c++){let d="";for(let u=0;u<a.grid.cols;u++){const m=4*n,h=i.$getEncodedCharacterValue(s.characterPixels,m);d+=((l=be(a.font,h))==null?void 0:l.character)||e.emptyCharacter,n++}e.preserveTrailingSpaces||(d=d.trimEnd()),o.push(d)}return o.join(`
2
+ `)}$generateTXT(t,e={}){return this._createTXTContent(t,this._applyDefaultOptions(e))}$saveTXT(t,e={}){const i=this._applyDefaultOptions(e),a=this._createTXTContent(t,i),s=new Blob([a],{type:"text/plain;charset=utf-8"});new ot().$downloadFile(s,i.filename)}}class ya{constructor(){w(this,"_canvas");w(this,"_ctx")}async $record(t,e,i,a){const s=Math.max(1,Math.round(e.frameRate)),o=Math.round(1e3/s),n=Math.max(1,Math.round(e.frameCount));return await new Promise((l,c)=>{const d=[];let u,m=0,h=!1;const p=()=>{u&&(u(),u=void 0)},f=b=>{h||(h=!0,p(),l(b))},y=()=>{if(m>=n)f(d);else try{const b=e.scale,_=Math.max(1,Math.round(t.width*b)),T=Math.max(1,Math.round(t.height*b));this._canvas||(this._canvas=document.createElement("canvas")),this._canvas.width===_&&this._canvas.height===T||(this._canvas.width=_,this._canvas.height=T),this._ctx||(this._ctx=this._canvas.getContext("2d"));const S=this._ctx;S.imageSmoothingEnabled=!1,S.clearRect(0,0,_,T),S.drawImage(t,0,0,t.width,t.height,0,0,_,T);const A={imageData:S.getImageData(0,0,_,T),width:_,height:T,delayMs:o};d.push(A),m+=1,a==null||a({state:"recording",frameIndex:m,totalFrames:n}),m>=n&&f(d)}catch(b){(_=>{if(h)return;h=!0,p();const T=_ instanceof Error?_.message:"GIF recording failed";a==null||a({state:"error",message:T}),c(_ instanceof Error?_:new Error(String(_)))})(b)}};u=i(()=>{y()}),a==null||a({state:"recording",frameIndex:0,totalFrames:n})})}}var ur,re,mr=Object.defineProperty,ba=(ur=r=>{function t(u,m,h){return .29889531*u+.58662247*m+.11448223*h}function e(u,m,h){return .59597799*u-.2741761*m-.32180189*h}function i(u,m,h){return .21147017*u-.52261711*m+.31114694*h}function a(u,m){let h=u[0]-m[0],p=u[1]-m[1],f=u[2]-m[2],y=s(u)-s(m);return h*h*.5053+p*p*.299+f*f*.1957+y*y}function s(u){return u[3]!=null?u[3]:255}function o(u,m){return Math.sqrt(a(u,m))}function n(u,m){let[h,p,f]=u,[y,b,_]=m,T=t(h,p,f)-t(y,b,_),S=e(h,p,f)-e(y,b,_),A=i(h,p,f)-i(y,b,_),E=s(u)-s(m);return T*T*.5053+S*S*.299+A*A*.1957+E*E}function l(u,m){return Math.sqrt(n(u,m))}function c(u,m){var h,p=0;for(h=0;h<u.length;h++){let f=u[h]-m[h];p+=f*f}return p}function d(u,m){return Math.sqrt(c(u,m))}mr(r,"__esModule",{value:!0}),((u,m)=>{for(var h in m)mr(u,h,{get:m[h],enumerable:!0})})(r,{colorDifferenceRGBToYIQ:()=>l,colorDifferenceRGBToYIQSquared:()=>n,colorDifferenceYIQ:()=>o,colorDifferenceYIQSquared:()=>a,euclideanDistance:()=>d,euclideanDistanceSquared:()=>c})},()=>(re||ur((re={exports:{}}).exports,re),re.exports)),va=59;function pr(r=256){let t=0,e=new Uint8Array(r);return{get buffer(){return e.buffer},reset(){t=0},bytesView:()=>e.subarray(0,t),bytes:()=>e.slice(0,t),writeByte(a){i(t+1),e[t]=a,t++},writeBytes(a,s=0,o=a.length){i(t+o);for(let n=0;n<o;n++)e[t++]=a[n+s]},writeBytesView(a,s=0,o=a.byteLength){i(t+o),e.set(a.subarray(s,s+o),t),t+=o}};function i(a){var s=e.length;if(s>=a)return;a=Math.max(a,s*(s<1048576?2:1.125)>>>0),s!=0&&(a=Math.max(a,256));let o=e;e=new Uint8Array(a),t>0&&e.set(o.subarray(0,t),0)}}var xa=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],_a=function(r,t,e,i,a,s,o,n){a=a||pr(512),s=s||new Uint8Array(256),o=o||new Int32Array(5003),n=n||new Int32Array(5003);let l=o.length,c=Math.max(2,i);s.fill(0),n.fill(0),I();let d=0,u=0,m=c+1,h=m,p=!1,f=h,y=L(f),b=1<<m-1,_=b+1,T=b+2,S=0,A=e[0],E=0;for(let M=l;M<65536;M*=2)++E;E=8-E,a.writeByte(c),$(b);for(let M=1;M<e.length;M++)D(e[M]);return $(A),$(_),a.writeByte(0),a.bytesView();function C(M){s[S++]=M,S>=254&&V()}function I(){o.fill(-1)}function D(M){let j=(M<<12)+A,W=M<<E^A;if(o[W]===j)A=n[W];else{if(o[W]>=0){let X=W===0?1:l-W;do if(W-=X,W<0&&(W+=l),o[W]===j)return void(A=n[W]);while(o[W]>=0)}$(A),A=M,T<4096?(n[W]=T++,o[W]=j):(I(),T=b+2,p=!0,$(b))}}function V(){S>0&&(a.writeByte(S),a.writeBytesView(s,0,S),S=0)}function L(M){return(1<<M)-1}function $(M){for(d&=xa[u],u>0?d|=M<<u:d=M,u+=f;u>=8;)C(255&d),d>>=8,u-=8;if((T>y||p)&&(p?(f=h,y=L(f),p=!1):(++f,y=f==12?4096:L(f))),M==_){for(;u>0;)C(255&d),d>>=8,u-=8;V()}}};function fr(r,t,e){return r<<8&63488|t<<2&992|e>>3&31}function gr(r,t,e,i){return r>>4|240&t|(240&e)<<4|(240&i)<<8}function wr(r,t,e){return r>>4<<8|t>>4<<4|e>>4}function ie(r,t,e){return r<t?t:r>e?e:r}function ae(r){return r*r}function yr(r,t,e){for(var i=0,a=1e100,s=r[t],o=s.cnt,n=(s.ac,s.rc),l=s.gc,c=s.bc,d=s.fw;d!=0;d=r[d].fw){var u=r[d].cnt,m=o*u/(o+u);if(!(m>=a)){var h=0;!((h+=m*ae(r[d].rc-n))>=a)&&!((h+=m*ae(r[d].gc-l))>=a)&&!((h+=m*ae(r[d].bc-c))>=a)&&(a=h,i=d)}}s.err=a,s.nn=i}function xe(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function ka(r,t,e){let{format:i="rgb565",clearAlpha:a=!0,clearAlphaColor:s=0,clearAlphaThreshold:o=0,oneBitAlpha:n=!1}=e||{},l=e.useSqrt!==!1,c=i==="rgba4444",d=(function(M,j){let W=new Array(j==="rgb444"?4096:65536),X=M.length;if(j==="rgba4444")for(let q=0;q<X;++q){let Y=M[q],U=Y>>24&255,tt=Y>>16&255,wt=Y>>8&255,st=255&Y,Q=gr(st,wt,tt,U),Tt=Q in W?W[Q]:W[Q]=xe();Tt.rc+=st,Tt.gc+=wt,Tt.bc+=tt,Tt.ac+=U,Tt.cnt++}else if(j==="rgb444")for(let q=0;q<X;++q){let Y=M[q],U=Y>>16&255,tt=Y>>8&255,wt=255&Y,st=wr(wt,tt,U),Q=st in W?W[st]:W[st]=xe();Q.rc+=wt,Q.gc+=tt,Q.bc+=U,Q.cnt++}else for(let q=0;q<X;++q){let Y=M[q],U=Y>>16&255,tt=Y>>8&255,wt=255&Y,st=fr(wt,tt,U),Q=st in W?W[st]:W[st]=xe();Q.rc+=wt,Q.gc+=tt,Q.bc+=U,Q.cnt++}return W})(r,i),u=d.length,m=u-1,h=new Uint32Array(u+1);for(var p=0,f=0;f<d.length;++f){let M=d[f];if(M!=null){var y=1/M.cnt;c&&(M.ac*=y),M.rc*=y,M.gc*=y,M.bc*=y,d[p++]=M}}for(ae(t)/p<.022&&(l=!1),f=0;f<p-1;++f)d[f].fw=f+1,d[f+1].bk=f,l&&(d[f].cnt=Math.sqrt(d[f].cnt));var b,_,T;for(l&&(d[f].cnt=Math.sqrt(d[f].cnt)),f=0;f<p;++f){yr(d,f);var S=d[f].err;for(_=++h[0];_>1&&!(d[b=h[T=_>>1]].err<=S);_=T)h[_]=b;h[_]=f}var A=p-t;for(f=0;f<A;){for(var E;;){var C=h[1];if((E=d[C]).tm>=E.mtm&&d[E.nn].mtm<=E.tm)break;for(E.mtm==m?C=h[1]=h[h[0]--]:(yr(d,C),E.tm=f),S=d[C].err,_=1;(T=_+_)<=h[0]&&(T<h[0]&&d[h[T]].err>d[h[T+1]].err&&T++,!(S<=d[b=h[T]].err));_=T)h[_]=b;h[_]=C}var I=d[E.nn],D=E.cnt,V=I.cnt;y=1/(D+V),c&&(E.ac=y*(D*E.ac+V*I.ac)),E.rc=y*(D*E.rc+V*I.rc),E.gc=y*(D*E.gc+V*I.gc),E.bc=y*(D*E.bc+V*I.bc),E.cnt+=I.cnt,E.mtm=++f,d[I.bk].fw=I.fw,d[I.fw].bk=I.bk,I.mtm=m}let L=[];var $=0;for(f=0;;++$){let M=ie(Math.round(d[f].rc),0,255),j=ie(Math.round(d[f].gc),0,255),W=ie(Math.round(d[f].bc),0,255),X=255;c&&(X=ie(Math.round(d[f].ac),0,255),n&&(X=X<=(typeof n=="number"?n:127)?0:255),a&&X<=o&&(M=j=W=s,X=0));let q=c?[M,j,W,X]:[M,j,W];if(Ta(L,q)||L.push(q),(f=d[f].fw)==0)break}return L}function Ta(r,t){for(let e=0;e<r.length;e++){let i=r[e],a=i[0]===t[0]&&i[1]===t[1]&&i[2]===t[2],s=!(i.length>=4&&t.length>=4)||i[3]===t[3];if(a&&s)return!0}return!1}function Ca(r,t,e){let i=(e=e||"rgb565")==="rgb444"?4096:65536,a=new Uint8Array(r.length),s=new Array(i);if(e==="rgba4444")for(let o=0;o<r.length;o++){let n,l=r[o],c=l>>24&255,d=l>>16&255,u=l>>8&255,m=255&l,h=gr(m,u,d,c);s[h]!=null?n=s[h]:(n=Ea(m,u,d,c,t),s[h]=n),a[o]=n}else for(let o=0;o<r.length;o++){let n,l=r[o],c=l>>16&255,d=l>>8&255,u=255&l,m=e==="rgb444"?wr(u,d,c):fr(u,d,c);s[m]!=null?n=s[m]:(n=Sa(u,d,c,t),s[m]=n),a[o]=n}return a}function Ea(r,t,e,i,a){let s=0,o=1e100;for(let n=0;n<a.length;n++){let l=a[n],c=l[0],d=l[1],u=l[2],m=Mt(l[3]-i);m>o||(m+=Mt(c-r),!(m>o)&&(m+=Mt(d-t),!(m>o)&&(m+=Mt(u-e),!(m>o)&&(o=m,s=n))))}return s}function Sa(r,t,e,i){let a=0,s=1e100;for(let o=0;o<i.length;o++){let n=i[o],l=n[0],c=n[1],d=n[2],u=Mt(l-r);u>s||(u+=Mt(c-t),!(u>s)&&(u+=Mt(d-e),!(u>s)&&(s=u,a=o)))}return a}function Mt(r){return r*r}function Ba(r={}){let{initialCapacity:t=4096,auto:e=!0}=r,i=pr(t),a=new Uint8Array(256),s=new Int32Array(5003),o=new Int32Array(5003),n=!1;return{reset(){i.reset(),n=!1},finish(){i.writeByte(va)},bytes:()=>i.bytes(),bytesView:()=>i.bytesView(),get buffer(){return i.buffer},get stream(){return i},writeHeader:l,writeFrame(c,d,u,m={}){let{transparent:h=!1,transparentIndex:p=0,delay:f=0,palette:y=null,repeat:b=0,colorDepth:_=8,dispose:T=-1}=m,S=!1;if(e?n||(S=!0,l(),n=!0):S=!!m.first,d=Math.max(0,Math.floor(d)),u=Math.max(0,Math.floor(u)),S){if(!y)throw new Error("First frame must include a { palette } option");(function(C,I,D,V,L=8){let $=1,M=0,j=_e(V.length)-1,W=$<<7|L-1<<4|M<<3|j;Ct(C,I),Ct(C,D),C.writeBytes([W,0,0])})(i,d,u,y,_),br(i,y),b>=0&&(function(C,I){C.writeByte(33),C.writeByte(255),C.writeByte(11),vr(C,"NETSCAPE2.0"),C.writeByte(3),C.writeByte(1),Ct(C,I),C.writeByte(0)})(i,b)}let A=Math.round(f/10);(function(C,I,D,V,L){var $,M;C.writeByte(33),C.writeByte(249),C.writeByte(4),L<0&&(L=0,V=!1),V?($=1,M=2):($=0,M=0),I>=0&&(M=7&I),M<<=2,C.writeByte(0|M|0|$),Ct(C,D),C.writeByte(L||0),C.writeByte(0)})(i,T,A,h,p);let E=!!y&&!S;(function(C,I,D,V){if(C.writeByte(44),Ct(C,0),Ct(C,0),Ct(C,I),Ct(C,D),V){let L=0,$=0,M=_e(V.length)-1;C.writeByte(128|L|$|M)}else C.writeByte(0)})(i,d,u,E?y:null),E&&br(i,y),(function(C,I,D,V,L=8,$,M,j){_a(D,V,I,L,C,$,M,j)})(i,c,d,u,_,a,s,o)}};function l(){vr(i,"GIF89a")}}function br(r,t){let e=1<<_e(t.length);for(let i=0;i<e;i++){let a=[0,0,0];i<t.length&&(a=t[i]),r.writeByte(a[0]),r.writeByte(a[1]),r.writeByte(a[2])}}function Ct(r,t){r.writeByte(255&t),r.writeByte(t>>8&255)}function vr(r,t){for(var e=0;e<t.length;e++)r.writeByte(t.charCodeAt(e))}function _e(r){return Math.max(Math.ceil(Math.log2(r)),1)}ba();class Pa{constructor(t,e){w(this,"_recorder");w(this,"_textmodifier");w(this,"_registerPostDrawHook");this._recorder=new ya,this._textmodifier=t,this._registerPostDrawHook=e}async $saveGIF(t={}){const e=this._textmodifier.canvas,i=this._applyDefaultOptions(t),a=t.onProgress;try{const s=await this._recorder.$record(e,i,this._registerPostDrawHook,a),o=Ba(),{repeat:n}=t;for(let d=0;d<s.length;d++){const u=s[d],{width:m,height:h,imageData:p,delayMs:f}=u,y=new Uint32Array(p.data.buffer),b=ka(y,256,{}),_=Ca(y,b);o.writeFrame(_,m,h,{palette:b,delay:f,repeat:d===0?n:-1}),d%2!=0&&d!==s.length-1||(a==null||a({state:"encoding",frameIndex:d+1,totalFrames:s.length}),await new Promise(T=>setTimeout(T,0)))}o.finish();const l=o.bytes(),c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);new ot().$downloadFile(new Blob([c],{type:"image/gif"}),i.filename),a==null||a({state:"completed",totalFrames:i.frameCount})}catch(s){throw a==null||a({state:"error",message:s instanceof Error?s.message:"GIF export failed"}),s}}_applyDefaultOptions(t){const e=Math.abs(Math.round(t.frameCount??300)),i=Math.abs(t.frameRate??60),a=Math.abs(t.scale??1),s=Math.max(-1,Math.round(t.repeat??0));return{filename:t.filename,frameCount:e,frameRate:i,scale:a,repeat:s}}}class Et extends Error{constructor(e,i,a){super(i);w(this,"code");w(this,"cause");this.name="VideoExportError",this.code=e,this.cause=a}}function Vt(){return new Et("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function se(r,t,e,i){return new Promise((a,s)=>{if(e!=null&&e.aborted)return void s(Vt());let o=!1;const n=setTimeout(()=>l(()=>s((function(d,u){return new Et("VIDEO_EXPORT_TIMEOUT",d,u)})(t))),i),l=d=>{o||(o=!0,clearTimeout(n),e==null||e.removeEventListener("abort",c),d())},c=()=>l(()=>s(Vt()));e==null||e.addEventListener("abort",c,{once:!0}),r.then(d=>l(()=>a(d)),d=>l(()=>s(d)))})}class Ma{constructor(t,e,i,a){w(this,"canvas");w(this,"_textmodifier");w(this,"_registerPostDrawHook");w(this,"_context");w(this,"_sourceCanvas");w(this,"_pendingFrame",null);w(this,"_syntheticFrameCount",0);w(this,"_syntheticMillis",0);this._textmodifier=t,this._registerPostDrawHook=e,this._sourceCanvas=t.canvas,this.canvas=this._createStagingCanvas(i,a);const s=this.canvas.getContext("2d");if(!s)throw new Error("Video export requires a 2D canvas context for staging frames.");s.imageSmoothingEnabled=!1,this._context=s}async $render(t){var p;const e=this._textmodifier,i=Math.max(1,Math.round(t.frameCount)),a=Math.max(1,Math.round(t.frameRate)),s=1e3/a,o=e.isLooping(),n=e.frameCount,l=e.millis,c="secs"in e,d=e.secs,u=this._captureMethodSnapshots(),m=this._capturePropertySnapshots(),h=this._registerPostDrawHook(()=>{this._capturePendingFrame()});try{e.noLoop(),this._syntheticFrameCount=n,this._syntheticMillis=l,this._shadowTimingProperties(c),this._shadowTimingMethods(a,s),this._shadowResizeCanvas();for(let f=0;f<i;f++)this._throwIfAborted(t.signal),this._syntheticFrameCount=n+f+1,this._syntheticMillis=1e3*f/a,await this._renderOneFrame(f,t.signal),this._throwIfAborted(t.signal),await t.onFrame({frameIndex:f,canvas:this.canvas})}finally{h(),(p=this._pendingFrame)==null||p.reject(new Error("Video export frame rendering was interrupted.")),this._pendingFrame=null,this._restoreProperties(m),this._restoreMethods(u),e.frameCount=n,e.millis=l,c&&d!==void 0&&(e.secs=d),o?e.loop():e.noLoop()}}_renderOneFrame(t,e){if(this._pendingFrame)throw new Error("A video export frame is already pending.");const i=this._textmodifier;return se(new Promise((a,s)=>{this._pendingFrame={frameIndex:t,resolve:a,reject:s};try{i.redraw(1)}catch(o){this._pendingFrame=null,s(o)}}),`Video export frame ${t+1} did not render within 30000ms.`,e,3e4).catch(a=>{var s;throw((s=this._pendingFrame)==null?void 0:s.frameIndex)===t&&(this._pendingFrame=null),a})}_capturePendingFrame(){const t=this._pendingFrame;if(t)try{this._context.clearRect(0,0,this.canvas.width,this.canvas.height),this._context.drawImage(this._sourceCanvas,0,0,this._sourceCanvas.width,this._sourceCanvas.height,0,0,this.canvas.width,this.canvas.height),this._pendingFrame=null,t.resolve()}catch(e){this._pendingFrame=null,t.reject(e)}}_createStagingCanvas(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}_captureMethodSnapshots(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._textmodifier,t),value:this._textmodifier[t]}))}_capturePropertySnapshots(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._textmodifier,t),descriptor:Object.getOwnPropertyDescriptor(this._textmodifier,t)}))}_shadowTimingProperties(t){Object.defineProperty(this._textmodifier,"frameCount",{configurable:!0,enumerable:!0,get:()=>this._syntheticFrameCount,set:e=>{this._syntheticFrameCount=e}}),Object.defineProperty(this._textmodifier,"millis",{configurable:!0,enumerable:!0,get:()=>this._syntheticMillis,set:e=>{this._syntheticMillis=e}}),t&&Object.defineProperty(this._textmodifier,"secs",{configurable:!0,enumerable:!0,get:()=>this._syntheticMillis/1e3,set:e=>{this._syntheticMillis=1e3*e}})}_shadowTimingMethods(t,e){const i=this._textmodifier,a=i.frameRate;i.deltaTime=()=>e,i.frameRate=function(s){return s===void 0?t:a.call(this,s)}}_shadowResizeCanvas(){this._textmodifier.resizeCanvas=()=>{}}_restoreMethods(t){const e=this._textmodifier;for(const i of t)i.hadOwnProperty?e[i.key]=i.value:delete e[i.key]}_restoreProperties(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this._textmodifier,e.key,e.descriptor):delete this._textmodifier[e.key]}_throwIfAborted(t){if(t!=null&&t.aborted)throw Vt()}}function g(r){if(!r)throw new Error("Assertion failed.")}const xr=r=>{const t=(r%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw new Error(`Invalid rotation ${r}.`)},pt=r=>r&&r[r.length-1],St=r=>r>=0&&r<2**32,k=r=>{let t=0;for(;r.readBits(1)===0&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+r.readBits(t)},yt=r=>{const t=k(r);return 1&t?t+1>>1:-(t>>1)},Z=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),_r=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),J=new TextEncoder,zt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Nt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Ut={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},kr=r=>!!(r&&r.primaries&&r.transfer&&r.matrix&&r.fullRange!==void 0),ke=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class Tr{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(a=>{let s=!1;t=()=>{s||(a(),this.pending--,s=!0)}}),i=this.currentPromise;return this.currentPromise=e,this.pending++,await i,t}}const Cr=(r,t,e)=>{let i=0,a=r.length-1,s=-1;for(;i<=a;){const o=i+(a-i+1)/2|0;e(r[o])<=t?(s=o,i=o+1):a=o-1}return s},Te=()=>{let r,t;return{promise:new Promise((e,i)=>{r=e,t=i}),resolve:r,reject:t}},Lt=r=>{throw new Error(`Unexpected value: ${r}`)},Ia=(r,t,e)=>r.getUint8(t)<<16|r.getUint8(t+1)<<8|r.getUint8(t+2),Aa=(r,t,e,i)=>{e>>>=0,e&=16777215,r.setUint8(t,e>>>16&255),r.setUint8(t+1,e>>>8&255),r.setUint8(t+2,255&e)},Er=(r,t)=>Math.round(r/t)*t,Sr=(r,t)=>Math.round(r*t)/t,Br=(r,t)=>Math.floor(r*t)/t,Fa=/^[a-z]{3}$/,Wt=1e6*(1+Number.EPSILON);class Da{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}}let Ce=null;const Pr=()=>{var r;return Ce!==null?Ce:Ce=typeof navigator<"u"&&((r=navigator.userAgent)==null?void 0:r.includes("Firefox"))};let Ee=null;const Ra=()=>{var r;return Ee!==null?Ee:Ee=!(typeof navigator>"u"||!((r=navigator.vendor)!=null&&r.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))};let Se=null;const Va=()=>{if(Se!==null)return Se;if(typeof navigator>"u")return null;const r=/\bChrome\/(\d+)/.exec(navigator.userAgent);return r?Se=Number(r[1]):null},Be=function*(r){for(const t in r){const e=r[t];e!==void 0&&(yield{key:t,value:e})}},La=r=>{switch(r.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}},Wa=(r,t)=>{if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==t[e])return!1;return!0},Pe=r=>{g(Number.isInteger(r.num)),g(Number.isInteger(r.den)),g(r.den!==0);let t=Math.abs(r.num),e=Math.abs(r.den);for(;e!==0;){const a=t%e;t=e,e=a}const i=t||1;return{num:r.num/i,den:r.den/i}},Mr=(r,t)=>{if(typeof r!="object"||!r)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},Ir=r=>Array.isArray(r)?r:[r];class Ar{constructor(){this._listeners=new Map}on(t,e,i){this._listeners.has(t)||this._listeners.set(t,new Set);const a={fn:e,once:(i==null?void 0:i.once)??!1};return this._listeners.get(t).add(a),()=>{var s;(s=this._listeners.get(t))==null||s.delete(a)}}_emit(...t){const[e,i]=t,a=this._listeners.get(e);if(a)for(const s of a){try{s.fn(i)}catch(o){console.error(o)}s.once&&a.delete(s)}}}const Oa=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(t=>typeof t=="string");class Fr{constructor(t,e){if(this.data=t,this.mimeType=e,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof e!="string")throw new TypeError("mimeType must be a string.")}}class Dr{constructor(t,e,i,a){if(this.data=t,this.mimeType=e,this.name=i,this.description=a,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!==void 0&&typeof e!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(a!==void 0&&typeof a!="string")throw new TypeError("description, when provided, must be a string.")}}class G{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),a=(e&1<<i)>>i;return this.pos++,a}readBits(t){if(t===1)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 a=this.pos;a<i;a++){const s=Math.floor(a/8);let o=this.bytes[s];const n=7-(7&a);o&=~(1<<n),o|=(e&1<<i-a-1)>>i-a-1<<n,this.bytes[s]=o}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 t=new G(this.bytes);return t.pos=this.pos,t}}const Me=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ie=[-1,1,2,3,4,5,6,8],Rr=r=>{let t=Me.indexOf(r.sampleRate),e=null;t===-1&&(t=15,e=r.sampleRate);const i=Ie.indexOf(r.numberOfChannels);if(i===-1)throw new TypeError(`Unsupported number of channels: ${r.numberOfChannels}`);let a=13;r.objectType>=32&&(a+=6),t===15&&(a+=24);const s=Math.ceil(a/8),o=new Uint8Array(s),n=new G(o);return r.objectType<32?n.writeBits(5,r.objectType):(n.writeBits(5,31),n.writeBits(6,r.objectType-32)),n.writeBits(4,t),t===15&&n.writeBits(24,e),n.writeBits(4,i),o},nt=["avc","hevc","vp9","av1","vp8"],bt=["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"],oe=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Ht=[...oe,...bt],It=["webvtt"],ne=[{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}],Vr=[{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}],Lr=[{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}],Wr=[{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}],$a=(r,t,e,i)=>{if(r==="avc"){const s=Math.ceil(t/16)*Math.ceil(e/16),o=ne.find(l=>s<=l.maxMacroblocks&&i<=l.maxBitrate)??pt(ne),n=o?o.level:0;return`avc1.${"64".padStart(2,"0")}00${n.toString(16).padStart(2,"0")}`}if(r==="hevc"){const n=t*e,l=Vr.find(d=>n<=d.maxPictureSize&&i<=d.maxBitrate)??pt(Vr);return`hev1.1.6.${l.tier}${l.level}.B0`}if(r==="vp8")return"vp8";if(r==="vp9"){const a=t*e;return`vp09.00.${(Lr.find(o=>a<=o.maxPictureSize&&i<=o.maxBitrate)??pt(Lr)).level.toString().padStart(2,"0")}.08`}if(r==="av1"){const s=t*e,o=Wr.find(l=>s<=l.maxPictureSize&&i<=l.maxBitrate)??pt(Wr);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}throw new TypeError(`Unhandled codec '${r}'.`)},za=r=>{const t=r.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},Or=r=>{const t=r.split("."),e=Number(t[1]),i=t[2];return[129,(e<<5)+Number(i.slice(0,-1)),((i.slice(-1)==="H"?1:0)<<7)+((Number(t[3])===8?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},$r=/^pcm-([usf])(\d+)(be)?$/,At=r=>{if(g(bt.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=$r.exec(r);let e;return g(t),e=t[1]==="u"?"unsigned":t[1]==="s"?"signed":"float",{dataType:e,sampleSize:Number(t[2])/8,littleEndian:t[3]!=="be",silentValue:r==="pcm-u8"?128:0}},Na=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Ua=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ha=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ja=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,qa=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,zr=r=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Na.some(t=>r.decoderConfig.codec.startsWith(t)))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(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!ke(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){const{colorSpace:t}=r.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const e=Object.keys(zt);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${e.join(", ")}.`);const i=Object.keys(Nt);if(t.transfer!=null&&!i.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const a=Object.keys(Ut);if(t.matrix!=null&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!Ua.test(r.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(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!Ha.test(r.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(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!ja.test(r.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(r.decoderConfig.codec.startsWith("av01")&&!qa.test(r.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/.')},Ga=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],Nr=r=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Ga.some(t=>r.decoderConfig.codec.startsWith(t)))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(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!ke(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.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(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.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(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.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(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.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(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!bt.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${bt.join(", ")}).`)},Ur=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")},Qa=[48e3,44100,32e3],Xa=[24e3,22050,16e3];var vt,rt;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(vt||(vt={})),(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(rt||(rt={}));const jt=function*(r){let t=0,e=-1;for(;t<r.length-2;){const i=r.indexOf(0,t);if(i===-1||i>=r.length-2)break;t=i;let a=0;t+3<r.length&&r[t+1]===0&&r[t+2]===0&&r[t+3]===1?a=4:r[t+1]===0&&r[t+2]===1&&(a=3),a!==0?(e!==-1&&t>e&&(yield{offset:e,length:t-e}),e=t+a,t=e):t++}e!==-1&&e<r.length&&(yield{offset:e,length:r.length-e})},Hr=function*(r,t){let e=0;const i=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;e+t<=r.length;){let a;t===1?a=i.getUint8(e):t===2?a=i.getUint16(e,!1):t===3?a=Ia(i,e):(g(t===4),a=i.getUint32(e,!1)),e+=t,yield{offset:e,length:a},e+=a}},jr=r=>31&r,ce=r=>{const t=[],e=r.length;for(let i=0;i<e;i++)i+2<e&&r[i]===0&&r[i+1]===0&&r[i+2]===3?(t.push(0,0),i+=2):t.push(r[i]);return new Uint8Array(t)},qr={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}},Ka=r=>{try{const t=new G(ce(r));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;const e=t.readAlignedByte(),i=t.readAlignedByte(),a=t.readAlignedByte();k(t);let s=1,o=0,n=0,l=0;if((e===100||e===110||e===122||e===244||e===44||e===83||e===86||e===118||e===128)&&(s=k(t),s===3&&(l=t.readBits(1)),o=k(t),n=k(t),t.skipBits(1),t.readBits(1))){for(let I=0;I<(s!==3?8:12);I++)if(t.readBits(1)){const D=I<6?16:64;let V=8,L=8;for(let $=0;$<D;$++)L!==0&&(L=(V+yt(t)+256)%256),V=L===0?V:L}}k(t);const c=k(t);if(c===0)k(t);else if(c===1){t.skipBits(1),yt(t),yt(t);const I=k(t);for(let D=0;D<I;D++)yt(t)}k(t),t.skipBits(1);const d=k(t),u=k(t),m=16*(d+1),h=16*(u+1);let p=m,f=h;const y=t.readBits(1);if(y||t.skipBits(1),t.skipBits(1),t.readBits(1)){const I=k(t),D=k(t),V=k(t),L=k(t);let $,M;(l===0?s:0)===0?($=1,M=2-y):($=s===3?1:2,M=(s===1?2:1)*(2-y)),p-=$*(I+D),f-=M*(V+L)}let b=2,_=2,T=2,S=0,A={num:1,den:1},E=null,C=null;if(t.readBits(1)){if(t.readBits(1)){const V=t.readBits(8);if(V===255)A={num:t.readBits(16),den:t.readBits(16)};else{const L=qr[V];L&&(A=L)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),S=t.readBits(1),t.readBits(1)&&(b=t.readBits(8),_=t.readBits(8),T=t.readBits(8))),t.readBits(1)&&(k(t),k(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const I=t.readBits(1);I&&Gr(t);const D=t.readBits(1);D&&Gr(t),(I||D)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),k(t),k(t),k(t),k(t),E=k(t),C=k(t))}if(E===null)if(g(C===null),e!==44&&e!==86&&e!==100&&e!==110&&e!==122&&e!==244||!(16&i)){const I=d+1,D=(2-y)*(u+1),V=ne.find($=>$.level>=a)??pt(ne),L=Math.min(Math.floor(V.maxDpbMbs/(I*D)),16);E=L,C=L}else E=0,C=0;return g(C!==null),{profileIdc:e,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:s,bitDepthLumaMinus8:o,bitDepthChromaMinus8:n,codedWidth:m,codedHeight:h,displayWidth:p,displayHeight:f,pixelAspectRatio:A,colourPrimaries:b,matrixCoefficients:T,transferCharacteristics:_,fullRangeFlag:S,numReorderFrames:E,maxDecFrameBuffering:C}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},Gr=r=>{const t=k(r);r.skipBits(4),r.skipBits(4);for(let e=0;e<=t;e++)k(r),k(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},Ae=r=>r>>1&63,Ya=r=>{try{const t=[],e=[],i=[],a=[];for(const l of jt(r)){const c=r.subarray(l.offset,l.offset+l.length),d=Ae(c[0]);d===rt.VPS_NUT?t.push(c):d===rt.SPS_NUT?e.push(c):d===rt.PPS_NUT?i.push(c):d!==rt.PREFIX_SEI_NUT&&d!==rt.SUFFIX_SEI_NUT||a.push(c)}if(e.length===0||i.length===0)return null;const s=(l=>{try{const c=new G(ce(l));c.skipBits(16),c.readBits(4);const d=c.readBits(3),u=c.readBits(1),{general_profile_space:m,general_tier_flag:h,general_profile_idc:p,general_profile_compatibility_flags:f,general_constraint_indicator_flags:y,general_level_idc:b}=Ja(c,d);k(c);const _=k(c);let T=0;_===3&&(T=c.readBits(1));const S=k(c),A=k(c);let E=S,C=A;if(c.readBits(1)){const U=k(c),tt=k(c),wt=k(c),st=k(c);let Q=1,Tt=1;const la=T===0?_:0;la===1?(Q=2,Tt=2):la===2&&(Q=2,Tt=1),E-=(U+tt)*Q,C-=(wt+st)*Tt}const I=k(c),D=k(c);k(c);const V=c.readBits(1);let L=0;for(let U=V?0:d;U<=d;U++)k(c),L=k(c),k(c);k(c),k(c),k(c),k(c),k(c),k(c),c.readBits(1)&&c.readBits(1)&&Za(c),c.skipBits(1),c.skipBits(1),c.readBits(1)&&(c.skipBits(4),c.skipBits(4),k(c),k(c),c.skipBits(1));const $=k(c);if(ts(c,$),c.readBits(1)){const U=k(c);for(let tt=0;tt<U;tt++)k(c),c.skipBits(1)}c.skipBits(1),c.skipBits(1);let M=2,j=2,W=2,X=0,q=0,Y={num:1,den:1};if(c.readBits(1)){const U=rs(c,d);Y=U.pixelAspectRatio,M=U.colourPrimaries,j=U.transferCharacteristics,W=U.matrixCoefficients,X=U.fullRangeFlag,q=U.minSpatialSegmentationIdc}return{displayWidth:E,displayHeight:C,pixelAspectRatio:Y,colourPrimaries:M,transferCharacteristics:j,matrixCoefficients:W,fullRangeFlag:X,maxDecFrameBuffering:L+1,spsMaxSubLayersMinus1:d,spsTemporalIdNestingFlag:u,generalProfileSpace:m,generalTierFlag:h,generalProfileIdc:p,generalProfileCompatibilityFlags:f,generalConstraintIndicatorFlags:y,generalLevelIdc:b,chromaFormatIdc:_,bitDepthLumaMinus8:I,bitDepthChromaMinus8:D,minSpatialSegmentationIdc:q}}catch(c){return console.error("Error parsing HEVC SPS:",c),null}})(e[0]);if(!s)return null;let o=0;if(i.length>0){const l=i[0],c=new G(ce(l));c.skipBits(16),k(c),k(c),c.skipBits(1),c.skipBits(1),c.skipBits(3),c.skipBits(1),c.skipBits(1),k(c),k(c),yt(c),c.skipBits(1),c.skipBits(1),c.readBits(1)&&k(c),yt(c),yt(c),c.skipBits(1),c.skipBits(1),c.skipBits(1),c.skipBits(1);const d=c.readBits(1),u=c.readBits(1);o=d||u?d&&!u?2:!d&&u?3:0:0}const n=[...t.length?[{arrayCompleteness:1,nalUnitType:rt.VPS_NUT,nalUnits:t}]:[],...e.length?[{arrayCompleteness:1,nalUnitType:rt.SPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:rt.PPS_NUT,nalUnits:i}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ae(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:n}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},Ja=(r,t)=>{const e=r.readBits(2),i=r.readBits(1),a=r.readBits(5);let s=0;for(let d=0;d<32;d++)s=s<<1|r.readBits(1);const o=new Uint8Array(6);for(let d=0;d<6;d++)o[d]=r.readBits(8);const n=r.readBits(8),l=[],c=[];for(let d=0;d<t;d++)l.push(r.readBits(1)),c.push(r.readBits(1));if(t>0)for(let d=t;d<8;d++)r.skipBits(2);for(let d=0;d<t;d++)l[d]&&r.skipBits(88),c[d]&&r.skipBits(8);return{general_profile_space:e,general_tier_flag:i,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:o,general_level_idc:n}},Za=r=>{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(r.readBits(1)){const i=Math.min(64,1<<4+(t<<1));t>1&&yt(r);for(let a=0;a<i;a++)yt(r)}else k(r)},ts=(r,t)=>{const e=[];for(let i=0;i<t;i++)e[i]=es(r,i,t,e)},es=(r,t,e,i)=>{let a=0,s=0,o=0;if(t!==0&&(s=r.readBits(1)),s){t===e?o=t-(k(r)+1):o=t-1,r.readBits(1),k(r);const n=i[o]??0;for(let l=0;l<=n;l++)r.readBits(1)||r.readBits(1);a=i[o]}else{const n=k(r),l=k(r);for(let c=0;c<n;c++)k(r),r.readBits(1);for(let c=0;c<l;c++)k(r),r.readBits(1);a=n+l}return a},rs=(r,t)=>{let e=2,i=2,a=2,s=0,o=0,n={num:1,den:1};if(r.readBits(1)){const l=r.readBits(8);if(l===255)n={num:r.readBits(16),den:r.readBits(16)};else{const c=qr[l];c&&(n=c)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),s=r.readBits(1),r.readBits(1)&&(e=r.readBits(8),i=r.readBits(8),a=r.readBits(8))),r.readBits(1)&&(k(r),k(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(k(r),k(r),k(r),k(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&k(r),r.readBits(1)&&is(r,!0,t)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),o=k(r),k(r),k(r),k(r),k(r)),{pixelAspectRatio:n,colourPrimaries:e,transferCharacteristics:i,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:o}},is=(r,t,e)=>{let i=!1,a=!1,s=!1;i=r.readBits(1)===1,a=r.readBits(1)===1,(i||a)&&(s=r.readBits(1)===1,s&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),s&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let o=0;o<=e;o++){let n=!0;r.readBits(1)===1||(n=r.readBits(1)===1);let l=!1;n?k(r):l=r.readBits(1)===1;let c=1;l||(c=k(r)+1),i&&Qr(r,c,s),a&&Qr(r,c,s)}},Qr=(r,t,e)=>{for(let i=0;i<t;i++)k(r),k(r),e&&(k(r),k(r)),r.readBits(1)};var Xr;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(Xr||(Xr={}));const Kr=r=>{const t=_r(r),e=t.getUint8(9),i=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),o=t.getUint8(18);let n=null;return o&&(n=r.subarray(19,21+e)),{outputChannelCount:e,preSkip:i,inputSampleRate:a,outputGain:s,channelMappingFamily:o,channelMappingTable:n}},as=(r,t,e)=>{switch(r){case"avc":for(const i of((a,s)=>{if(s.description){const o=3&Z(s.description)[4];return Hr(a,o+1)}return jt(a)})(e,t)){const a=e[i.offset],s=jr(a);if(s>=vt.NON_IDR_SLICE&&s<=vt.SLICE_DPC)return"delta";if(s===vt.IDR)return"key";if(s===vt.SEI&&(!Ra()||Va()>=144)){const o=e.subarray(i.offset,i.offset+i.length),n=ce(o);let l=1;do{let c=0;for(;;){const u=n[l++];if(u===void 0||(c+=u,u<255))break}let d=0;for(;;){const u=n[l++];if(u===void 0||(d+=u,u<255))break}if(c===6){const u=new G(n);u.pos=8*l;const m=k(u),h=u.readBits(1);if(m===0&&h===1)return"key"}l+=d}while(l<n.length-1)}}return"delta";case"hevc":for(const i of((a,s)=>{if(s.description){const o=3&Z(s.description)[21];return Hr(a,o+1)}return jt(a)})(e,t)){const a=Ae(e[i.offset]);if(a<rt.BLA_W_LP)return"delta";if(a<=rt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return(1&e[0])===0?"key":"delta";case"vp9":{const i=new G(e);if(i.readBits(2)!==2)return null;const a=i.readBits(1);return(i.readBits(1)<<1)+a===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:a,data:s}of(function*(o){const n=new G(o),l=()=>{let c=0;for(let d=0;d<8;d++){const u=n.readAlignedByte();if(c|=(127&u)<<7*d,!(128&u))break;if(d===7&&128&u)return null}return c>=2**32-1?null:c};for(;n.getBitsLeft()>=8;){n.skipBits(1);const c=n.readBits(4),d=n.readBits(1),u=n.readBits(1);let m;if(n.skipBits(1),d&&n.skipBits(8),u){const h=l();if(h===null)return;m=h}else m=Math.floor(n.getBitsLeft()/8);g(n.pos%8==0),yield{type:c,data:o.subarray(n.pos/8,n.pos/8+m)},n.skipBits(8*m)}})(e))if(a===1){const o=new G(s);o.skipBits(4),i=!!o.readBits(1)}else if(a===3||a===6||a===7){if(i)return"key";const o=new G(s);return o.readBits(1)?null:o.readBits(2)===0?"key":"delta"}return null}default:Lt(r),g(!1)}};var Yr;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Yr||(Yr={}));const ss=[1,2,3,6],Jr=new Uint8Array(0);class qt{constructor(t,e,i,a,s=-1,o,n){if(this.data=t,this.type=e,this.timestamp=i,this.duration=a,this.sequenceNumber=s,t===Jr&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!=="key"&&e!=="delta")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(a)||a<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))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(n!==void 0&&(typeof n!="object"||!n))throw new TypeError("sideData, when provided, must be an object.");if((n==null?void 0:n.alpha)!==void 0&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if((n==null?void 0:n.alphaByteLength)!==void 0&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=n??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Jr}get microsecondTimestamp(){return Math.trunc(Wt*this.timestamp)}get microsecondDuration(){return Math.trunc(Wt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")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(typeof EncodedVideoChunk>"u")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(typeof EncodedAudioChunk>"u")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(t,e){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(t.byteLength);return t.copyTo(i),new qt(i,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,e)}clone(t){if(t!==void 0&&(typeof t!="object"||t===null))throw new TypeError("options, when provided, must be an object.");if((t==null?void 0:t.data)!==void 0&&!(t.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if((t==null?void 0:t.type)!==void 0&&t.type!=="key"&&t.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if((t==null?void 0:t.timestamp)!==void 0&&!Number.isFinite(t.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if((t==null?void 0:t.duration)!==void 0&&!Number.isFinite(t.duration))throw new TypeError("options.duration, when provided, must be a number.");if((t==null?void 0:t.sequenceNumber)!==void 0&&!Number.isFinite(t.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if((t==null?void 0:t.sideData)!==void 0&&(typeof t.sideData!="object"||t.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new qt((t==null?void 0:t.data)??this.data,(t==null?void 0:t.type)??this.type,(t==null?void 0:t.timestamp)??this.timestamp,(t==null?void 0:t.duration)??this.duration,(t==null?void 0:t.sequenceNumber)??this.sequenceNumber,this.byteLength,(t==null?void 0:t.sideData)??this.sideData)}}class Fe{constructor(t){this.value=t}}class De{constructor(t){this.value=t}}class Zr{constructor(t){this.value=t}}class Bt{constructor(t){this.value=t}}var v;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(v||(v={}));const ti=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,ei=r=>r<256n?1:r<65536n?2:r<1n<<24n?3:r<1n<<32n?4:r<1n<<40n?5:r<1n<<48n?6:r<1n<<56n?7:8,ri=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-1048576&&r<1<<20?3:r>=-134217728&&r<1<<27?4:r>=-17179869184&&r<2**34?5:6;class os{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=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=ti(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=ei(t)){let i=0;for(let a=e-1;a>=0;a--)this.helperView.setUint8(i++,Number(t>>BigInt(8*a)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(t,e=ri(t)){t<0&&(t+=2**(8*e)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=(i=>{if(i<127)return 1;if(i<16383)return 2;if(i<2097151)return 3;if(i<268435455)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)})(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(e=>e.charCodeAt(0))))}writeEBML(t){if(t!==null)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=t.size===-1?1:t.size??4;t.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const a=this.writer.getPos();if(this.dataOffsets.set(t,a),this.writeEBML(t.data),t.size!==-1){const s=this.writer.getPos()-a,o=this.writer.getPos();this.writer.seek(e),this.writeVarInt(s,i),this.writer.seek(o)}}else if(typeof t.data=="number"){const e=t.size??ti(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if(typeof t.data=="bigint"){const e=t.size??ei(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if(typeof t.data=="string")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 Fe)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof De)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof Zr){const e=t.size??ri(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Bt){const e=J.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else Lt(t.data)}}const ns={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",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"},de=r=>{const t=r.filePos,e=ys(r,9),i=new G(e);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const a=i.readBits(1),s=i.readBits(2)+1,o=i.readBits(4);if(o===15)return null;i.skipBits(1);const n=i.readBits(3);if(n===0)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 l=i.readBits(13);i.skipBits(11);const c=i.readBits(2)+1;if(c!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let d=null;return a===1?r.filePos-=2:d=i.readBits(16),{objectType:s,samplingFrequencyIndex:o,channelConfiguration:n,frameLength:l,numberOfAacFrames:c,crcCheck:d,startPos:t}};var cs=function(r,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var i,a;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],e&&(a=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(s){return Promise.reject(s)}}),r.stack.push({value:t,dispose:i,async:e})}else e&&r.stack.push({async:!0});return t},ds=(function(r){return function(t){function e(s){t.error=t.hasError?new r(s,t.error,"An error was suppressed during disposal."):s,t.hasError=!0}var i,a=0;return(function s(){for(;i=t.stack.pop();)try{if(!i.async&&a===1)return a=0,t.stack.push(i),Promise.resolve().then(s);if(i.dispose){var o=i.dispose.call(i.value);if(i.async)return a|=2,Promise.resolve(o).then(s,function(n){return e(n),s()})}else a|=1}catch(n){e(n)}if(a===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error})()}})(typeof SuppressedError=="function"?SuppressedError:function(r,t,e){var i=new Error(e);return i.name="SuppressedError",i.error=r,i.suppressed=t,i});Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"));let ii=-1/0,ai=-1/0,Ft=null;typeof FinalizationRegistry<"u"&&(Ft=new FinalizationRegistry(r=>{const t=performance.now();r.type==="video"?(t-ii>=1e3&&(console.error("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."),ii=t),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(t-ai>=1e3&&(console.error("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."),ai=t),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class Dt{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Re=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ls=new Set(Re);class it{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(Wt*this.timestamp)}get microsecondDuration(){return Math.trunc(Wt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(t,e){var i,a,s,o,n,l,c,d;if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.format===void 0||!ls.has(e.format))throw new TypeError("init.format must be one of: "+Re.join(", "));if(!Number.isInteger(e.codedWidth)||e.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(e.codedHeight)||e.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.layout!==void 0){if(!Array.isArray(e.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const m of e.layout){if(!m||typeof m!="object"||Array.isArray(m))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(m.offset)||m.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(m.stride)||m.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(e.visibleRect!==void 0&&Mr(e.visibleRect,"init.visibleRect"),e.displayWidth!==void 0&&(!Number.isInteger(e.displayWidth)||e.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(e.displayHeight!==void 0&&(!Number.isInteger(e.displayHeight)||e.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(e.displayWidth!==void 0!=(e.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=Z(t).slice(),this._layout=e.layout??ms(e.format,e.codedWidth,e.codedHeight),this.format=e.format,this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0;let u=e.colorSpace??null;u===null&&(u=this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new Ve(u),this.visibleRect={left:((i=e.visibleRect)==null?void 0:i.left)??0,top:((a=e.visibleRect)==null?void 0:a.top)??0,width:((s=e.visibleRect)==null?void 0:s.width)??e.codedWidth,height:((o=e.visibleRect)==null?void 0:o.height)??e.codedHeight},e.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180==0?e.displayWidth:e.displayHeight,this.squarePixelHeight=this.rotation%180==0?e.displayHeight:e.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&t instanceof VideoFrame){if((e==null?void 0:e.rotation)!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if((e==null?void 0:e.timestamp)!==void 0&&!Number.isFinite(e==null?void 0:e.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if((e==null?void 0:e.duration)!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");(e==null?void 0:e.visibleRect)!==void 0&&Mr(e.visibleRect,"init.visibleRect"),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:((n=t.visibleRect)==null?void 0:n.x)??0,top:((l=t.visibleRect)==null?void 0:l.y)??0,width:((c=t.visibleRect)==null?void 0:c.width)??t.codedWidth,height:((d=t.visibleRect)==null?void 0:d.height)??t.codedHeight},this.rotation=(e==null?void 0:e.rotation)??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=(e==null?void 0:e.timestamp)??t.timestamp/1e6,this.duration=(e==null?void 0:e.duration)??(t.duration??0)/1e6,this.colorSpace=new Ve(t.colorSpace)}else if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof SVGImageElement<"u"&&t instanceof SVGImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new it(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*Wt),duration:Math.trunc((e.duration??0)*Wt)||void 0}),e);let u=0,m=0;if("naturalWidth"in t?(u=t.naturalWidth,m=t.naturalHeight):"videoWidth"in t?(u=t.videoWidth,m=t.videoHeight):"width"in t&&(u=Number(t.width),m=Number(t.height)),!u||!m)throw new TypeError("Could not determine dimensions.");const h=new OffscreenCanvas(u,m),p=h.getContext("2d",{alpha:Pr(),willReadFrequently:!0});g(p),p.drawImage(t,0,0),this._data=h,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:u,height:m},this.squarePixelWidth=u,this.squarePixelHeight=m,this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new Ve({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(t instanceof Dt))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!Re.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.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=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=e.rotation??0,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=t.getColorSpace()}this.pixelAspectRatio=Pe({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ft==null||Ft.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return g(this._data!==null),this._data instanceof Dt?new it(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):Qt(this._data)?new it(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(g(this._layout),new it(this._data,{format:this.format,layout:this._layout,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})):new it(this._data,{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})}close(){this._closed||(Ft==null||Ft.unregister(this),this._data instanceof Dt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Qt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(ni(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Qt(this._data)?this._data.allocationSize(t):ci(this,t).allocationSize}async copyTo(t,e={}){if(!ke(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ni(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(g(this._data!==null),Qt(this._data))return this._data.copyTo(t,e);if(e.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(e.format)){if(!(this._data instanceof Dt)){if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const c=this.toVideoFrame(),d=await c.copyTo(t,e);return c.close(),d}{const c={stack:[],error:void 0,hasError:!1};try{const d=cs(c,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},e.colorSpace??"srgb"),!1);if(!(d instanceof it))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(d.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${d.format}' instead.`);return await d.copyTo(t,e)}catch(d){c.error=d,c.hasError=!0}finally{ds(c)}}}const i=ci(this,e);g(this.format);const a=Z(t);if(a.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${a.byteLength}`);const s=le(this.format);let o;if(this._data instanceof Dt){let c=this._data.getDataPlanes();if(c instanceof Promise&&(c=await c),!Array.isArray(c)||c.some(d=>!(d.data instanceof Uint8Array)||!Number.isInteger(d.stride)||d.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=c}else if(this._data instanceof Uint8Array)g(this._layout),g(this._layout.length===s.length),o=this._layout.map((c,d)=>{const u=Math.ceil(this.codedHeight/s[d].heightDivisor);return{data:this._data.subarray(c.offset,c.offset+c.stride*u),stride:c.stride}});else{const c=this._data.getContext("2d");g(c);const d=c.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:Z(d.data),stride:4*this.codedWidth}]}const n=[],l=s.length;for(let c=0;c<l;c++){const d=i.computedLayouts[c],u=o[c].stride,m=o[c].data;let h=d.sourceTop*u;h+=d.sourceLeftBytes;let p=d.destinationOffset;const f=d.sourceWidthBytes,y={offset:p,stride:d.destinationStride};for(let b=0;b<d.sourceHeight;b++){if(h+f>m.byteLength)throw new Error("Source buffer OOB read.");if(p+f>a.byteLength)throw new Error("Destination buffer OOB write.");const _=m.subarray(h,h+f);a.set(_,p),h+=u,p+=d.destinationStride}n.push(y)}if(e.format!==void 0){const c=this.format.startsWith("RGB")!==e.format.startsWith("RGB"),d=this.format.includes("X")&&e.format.includes("A");if(c||d)for(let u=0;u<i.allocationSize;u+=4){if(c){const m=a[u],h=a[u+2];a[u]=h,a[u+2]=m}d&&(a[u+3]=255)}}return n}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof Dt){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const t=this._data.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((o,n)=>o+n.data.byteLength,0),i=new Uint8Array(e);let a=0;const s=[];for(const o of t)i.set(o.data,a),s.push(a),a+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:t.map((o,n)=>({offset:s[n],stride:o.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Qt(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,a,s,o,n,l,c){let d=0,u=0,m=this.displayWidth,h=this.displayHeight,p=0,f=0,y=this.displayWidth,b=this.displayHeight;if(o!==void 0?(d=e,u=i,m=a,h=s,p=o,f=n,l!==void 0?(y=l,b=c):(y=m,b=h)):(p=e,f=i,a!==void 0&&(y=a,b=s)),!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(f))throw new TypeError("dy must be a number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:u,sWidth:m,sHeight:h}=this._rotateSourceRegion(d,u,m,h,this.rotation));const _=this.toCanvasImageSource();t.save();const T=p+y/2,S=f+b/2;t.translate(T,S),t.rotate(this.rotation*Math.PI/180);const A=this.rotation%180==0?1:y/b;t.scale(1/A,A),t.drawImage(_,d,u,m,h,-y/2,-b/2,y,b),t.restore()}drawWithFit(t,e){var _,T,S,A;if(!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||typeof e!="object")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(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");e.crop!==void 0&&Le(e.crop,"options.");const i=t.canvas.width,a=t.canvas.height,s=e.rotation??this.rotation,[o,n]=s%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let l,c,d,u,m=e.crop;m&&(m=oi(m,o,n));const{sx:h,sy:p,sWidth:f,sHeight:y}=this._rotateSourceRegion(((_=e.crop)==null?void 0:_.left)??0,((T=e.crop)==null?void 0:T.top)??0,((S=e.crop)==null?void 0:S.width)??o,((A=e.crop)==null?void 0:A.height)??n,s);if(e.fit==="fill")l=0,c=0,d=i,u=a;else{const[E,C]=e.crop?[e.crop.width,e.crop.height]:[o,n],I=e.fit==="contain"?Math.min(i/E,a/C):Math.max(i/E,a/C);d=E*I,u=C*I,l=(i-d)/2,c=(a-u)/2}t.save();const b=s%180==0?1:d/u;t.translate(i/2,a/2),t.rotate(s*Math.PI/180),t.scale(1/b,b),t.translate(-i/2,-a/2),t.drawImage(this.toCanvasImageSource(),h,p,f,y,l,c,d,u),t.restore()}_rotateSourceRegion(t,e,i,a,s){return s===90?[t,e,i,a]=[e,this.squarePixelHeight-t-i,a,i]:s===180?[t,e]=[this.squarePixelWidth-t-i,this.squarePixelHeight-e-a]:s===270&&([t,e,i,a]=[this.squarePixelWidth-e-a,t,a,i]),{sx:t,sy:e,sWidth:i,sHeight:a}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(g(this._data!==null),this._data instanceof Dt||this._data instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this._data}async transform(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&Le(t.crop,"options."),t.alpha!==void 0&&!["keep","discard"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const e=xr(this.rotation+(t.rotate??0)),[i,a]=e%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let s=t.crop;s&&(s=oi(s,i,a));const o=s?s.width:i,n=s?s.height:a,l=o/n;let c,d;t.width!==void 0&&t.height===void 0?(c=t.width,d=c/l):t.width===void 0&&t.height!==void 0?(d=t.height,c=d*l):t.width!==void 0&&t.height!==void 0?(c=t.width,d=t.height):(c=o,d=n),c=Er(c,t.roundDimensionsTo??1),d=Er(d,t.roundDimensionsTo??1);const u={width:c,height:d,fit:t.fit??"fill",rotation:e,crop:s??{left:0,top:0,width:i,height:a},alpha:t.alpha??"keep"};for(const f of hs){let y=f(this,u);if(y instanceof Promise&&(y=await y),y!==null)return y}let m=null,h=!1;for(const f of Gt)if(f.canvas.width===u.width&&f.canvas.height===u.height){m=f.canvas,f.age=si++;break}if(m===null){if(typeof OffscreenCanvas<"u")m=new OffscreenCanvas(u.width,u.height);else{if(typeof window>"u"||typeof document>"u")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().");m=document.createElement("canvas"),m.width=u.width,m.height=u.height}h=!0,Gt.length>=us&&Gt.splice(((f,y)=>{let b=-1,_=1/0;for(let T=0;T<f.length;T++){const S=y(f[T]);S<_&&(_=S,b=T)}return b})(Gt,f=>f.age),1),Gt.push({canvas:m,age:si++})}const p=m.getContext("2d",{alpha:!0});return g(p),u.alpha==="discard"?(p.fillStyle="black",p.fillRect(0,0,u.width,u.height)):h||p.clearRect(0,0,u.width,u.height),this.drawWithFit(p,{fit:u.fit,rotation:u.rotation,crop:u.crop}),new it(m,{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}[Symbol.dispose](){this.close()}}const hs=[],us=3,Gt=[];let si=0;class Ve{constructor(t){if(t!==void 0){if(!t||typeof t!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const e=Object.keys(zt);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);const i=Object.keys(Nt);if(t.transfer!=null&&!i.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const a=Object.keys(Ut);if(t.matrix!=null&&!a.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${a.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=(t==null?void 0:t.primaries)??null,this.transfer=(t==null?void 0:t.transfer)??null,this.matrix=(t==null?void 0:t.matrix)??null,this.fullRange=(t==null?void 0:t.fullRange)??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Qt=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,oi=(r,t,e)=>{const i=Math.min(r.left,t),a=Math.min(r.top,e),s=Math.min(r.width,t-i),o=Math.min(r.height,e-a);return g(s>=0),g(o>=0),{left:i,top:a,width:s,height:o}},Le=(r,t)=>{if(!r||typeof r!="object")throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},ni=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const t of r.layout){if(!t||typeof t!="object")throw new TypeError("Each entry in options.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(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},ms=(r,t,e)=>{const i=le(r),a=[];let s=0;for(const o of i){const n=Math.ceil(t/o.widthDivisor),l=Math.ceil(e/o.heightDivisor),c=n*o.sampleBytes,d=c*l;a.push({offset:s,stride:c}),s+=d}return a},le=r=>{const t=(e,i,a,s,o)=>{const n=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:a,heightDivisor:s},{sampleBytes:i,widthDivisor:a,heightDivisor:s}];return o&&n.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),n};switch(r){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(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:Lt(r),g(!1)}},ci=(r,t)=>{const e={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=t.rect,a=ps(e,i,r.codedWidth,r.codedHeight,r.format),s=t.layout;let o;if(t.format&&t.format!==r.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");o=t.format}else o=r.format;return gs(a,o,s)},ps=(r,t,e,i,a)=>{const s={...r};if(t!==void 0){if(t.width===0||t.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>e)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!fs(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},fs=(r,t)=>{if(r===null)return!0;const e=le(r);for(let i=0;i<e.length;i++){const a=e[i],s=a.widthDivisor,o=a.heightDivisor;if((t.x||0)%s!==0||(t.y||0)%o!==0)return!1}return!0},gs=(r,t,e)=>{const i=le(t),a=i.length;if(e!==void 0&&e.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const o=[],n=[];for(let l=0;l<a;l++){const c=i[l],d=c.sampleBytes,u=c.widthDivisor,m=c.heightDivisor,h={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(h.sourceTop=Math.ceil(Math.trunc(r.y||0)/m),h.sourceHeight=Math.ceil(Math.trunc(r.height||0)/m),h.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/u)*d,h.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/u)*d,e!==void 0){const f=e[l];if(f.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${l} is too small.`);h.destinationOffset=f.offset,h.destinationStride=f.stride}else h.destinationOffset=s,h.destinationStride=h.sourceWidthBytes;const p=h.destinationStride*h.sourceHeight+h.destinationOffset;if(p>4294967295)throw new TypeError("Allocation size exceeds limit.");n.push(p),s=Math.max(s,p);for(let f=0;f<l;f++){const y=o[f];if(!(n[l]<=y.destinationOffset||n[f]<=h.destinationOffset))throw new TypeError("Planes overlap.")}o.push(h)}return{allocationSize:s,computedLayouts:o}},di=new Map,li=(r,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");if(t.alpha!==void 0&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(t.bitrateMode!==void 0&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.latencyMode!==void 0&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&((e=t.fullCodecString).startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":e==="vp8"?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":e==="mp3"||e==="mp4a.69"||e==="mp4a.6B"||e==="mp4a.6b"||e==="mp4a.40.34"?"mp3":e.startsWith("mp4a.40.")||e==="mp4a.67"?"aac":e==="opus"?"opus":e==="vorbis"?"vorbis":e==="flac"?"flac":e==="ac-3"||e==="ac3"?"ac3":e==="ec-3"||e==="eac3"?"eac3":e==="ulaw"?"ulaw":e==="alaw"?"alaw":$r.test(e)?e:e==="webvtt"?"webvtt":null)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);var e;if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(t.contentHint!==void 0&&typeof t.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},hi=r=>{const t=r.bitrate instanceof We?r.bitrate._toVideoBitrate(r.codec,r.width,r.height):r.bitrate;return{codec:r.fullCodecString??$a(r.codec,r.width,r.height,t),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:t,bitrateMode:r.bitrateMode,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...(e=r.codec,e==="avc"?{avc:{format:"avc"}}:e==="hevc"?{hevc:{format:"hevc"}}:{})};var e};class We{constructor(t){this._factor=t}_toVideoBitrate(t,e,i){const a=e*i,s=3e6*Math.pow(a/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[t]*this._factor;return 1e3*Math.ceil(s/1e3)}_toAudioBitrate(t){if(bt.includes(t)||t==="flac")return;const e={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[t];if(!e)throw new Error(`Unhandled codec: ${t}`);let i=e*this._factor;return t==="aac"?i=[96e3,128e3,16e4,192e3].reduce((a,s)=>Math.abs(s-i)<Math.abs(a-i)?s:a):t==="opus"||t==="vorbis"?i=Math.max(6e3,i):t==="mp3"&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,s)=>Math.abs(s-i)<Math.abs(a-i)?s:a)),1e3*Math.round(i/1e3)}}const ws=async(r,t={})=>{const{width:e=1280,height:i=720,bitrate:a=1e6,...s}=t;if(!nt.includes(r))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(a instanceof We)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");li(r,s);const o=hi({codec:r,width:e,height:i,bitrate:a,framerate:void 0,...s,alpha:"discard"}),n=JSON.stringify(o),l=di.get(n);if(l)return l;const c=(async()=>ui.some(d=>d.supports(r,o))?!0:typeof VideoEncoder>"u"||(e%2==1||i%2==1)&&(r==="avc"||r==="hevc")?!1:!!(await VideoEncoder.isConfigSupported(o)).supported&&(!Pr()||new Promise(async d=>{try{const u=new VideoEncoder({output:()=>{},error:()=>d(!1)});u.configure(o);const m=new Uint8Array(e*i*4),h=new VideoFrame(m,{format:"RGBA",codedWidth:e,codedHeight:i,timestamp:0});u.encode(h),h.close(),await u.flush(),d(!0)}catch{d(!1)}})))();return di.set(n,c),c},ui=[];class Rt{constructor(t,e,i,a,s){this.bytes=t,this.view=e,this.offset=i,this.start=a,this.end=s,this.bufferPos=a-i}static tempFromBytes(t){return new Rt(t,_r(t),0,0,t.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(t,e=this.end-t){if(t<this.start||t+e>this.end)throw new RangeError("Slicing outside of original slice.");return new Rt(this.bytes,this.view,this.offset,t,t+e)}}const ys=(r,t)=>{((i,a)=>{if(i.filePos<i.start||i.filePos+a>i.end)throw new RangeError(`Tried reading [${i.filePos}, ${i.filePos+a}), but slice is [${i.start}, ${i.end}). This is likely an internal error, please report it alongside the file that caused it.`)})(r,t);const e=r.bytes.subarray(r.bufferPos,r.bufferPos+t);return r.bufferPos+=t,e};class mi{constructor(t){this.mutex=new Tr,this.trackTimestampInfo=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 a=this.trackTimestampInfo.get(t);if(a){if(i&&(a.maxTimestampBeforeLastKeyPacket=a.maxTimestamp),a.maxTimestampBeforeLastKeyPacket!==null&&e<a.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 ${a.maxTimestampBeforeLastKeyPacket}s.`);a.maxTimestamp=Math.max(a.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");a={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,a)}}}const he=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,bs=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,pi=r=>{const t=Math.floor(r/36e5),e=Math.floor(r%36e5/6e4),i=Math.floor(r%6e4/1e3),a=r%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};class ue{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=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 s of t.children)s&&this.writeBox(s);const i=this.writer.getPos(),a=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,a),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);g(e!==void 0);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}}}const F=new Uint8Array(8),at=new DataView(F.buffer),N=r=>[(r%256+256)%256],P=r=>(at.setUint16(0,r,!1),[F[0],F[1]]),Oe=r=>(at.setInt16(0,r,!1),[F[0],F[1]]),fi=r=>(at.setUint32(0,r,!1),[F[1],F[2],F[3]]),x=r=>(at.setUint32(0,r,!1),[F[0],F[1],F[2],F[3]]),xt=r=>(at.setInt32(0,r,!1),[F[0],F[1],F[2],F[3]]),ft=r=>(at.setUint32(0,Math.floor(r/2**32),!1),at.setUint32(4,r,!1),[F[0],F[1],F[2],F[3],F[4],F[5],F[6],F[7]]),vs=r=>(at.setInt32(0,Math.floor(r/2**32),!1),at.setUint32(4,r,!1),[F[0],F[1],F[2],F[3],F[4],F[5],F[6],F[7]]),gi=r=>(at.setInt16(0,256*r,!1),[F[0],F[1]]),ct=r=>(at.setInt32(0,65536*r,!1),[F[0],F[1],F[2],F[3]]),$e=r=>(at.setInt32(0,2**30*r,!1),[F[0],F[1],F[2],F[3]]),ze=(r,t)=>{const e=[];let i=r;do{let a=127&i;i>>=7,e.length>0&&(a|=128),e.push(a)}while(i>0||t);return e.reverse()},O=(r,t=!1)=>{const e=Array(r.length).fill(null).map((i,a)=>r.charCodeAt(a));return t&&e.push(0),e},wi=r=>{const t=r*(Math.PI/180),e=Math.round(Math.cos(t)),i=Math.round(Math.sin(t));return[e,i,0,-i,e,0,0,0,1]},yi=wi(0),bi=r=>[ct(r[0]),ct(r[1]),$e(r[2]),ct(r[3]),ct(r[4]),$e(r[5]),ct(r[6]),ct(r[7]),$e(r[8])],B=(r,t,e)=>({type:r,contents:t&&new Uint8Array(t.flat(10)),children:e}),R=(r,t,e,i,a)=>B(r,[N(t),fi(e),i??[]],a),vi=()=>B("styp",[O("iso5"),x(0),O("iso5"),O("iso6"),O("mp41"),O("cmfc"),O("dash")]),xi=(r,t)=>{let e=r.maxWrittenEndTimestamp-r.minWrittenTimestamp;return Number.isFinite(e)||(e=0),R("sidx",1,0,[x(1),x(lt),ft(z(r.minWrittenTimestamp,lt)),ft(0),P(0),P(1),x(2147483647&t),x(z(e,lt)),x(0)])},me=r=>({type:"mdat",largeSize:r}),Xt=r=>B("moov",void 0,[xs(r.creationTime,r.trackDatas),...r.trackDatas.map(t=>_s(t,r.creationTime)),r.isFragmented?io(r.trackDatas):null,go(r)]),xs=(r,t)=>{const e=Math.max(0,...t.map(o=>z(pe(o),lt)+z(o.startTimestampOffset??0,lt))),i=Math.max(0,...t.map(o=>o.track.id))+1,a=!St(r)||!St(e),s=a?ft:x;return R("mvhd",+a,0,[s(r),s(r),x(lt),s(e),ct(1),gi(1),Array(10).fill(0),bi(yi),Array(24).fill(0),x(i)])},pe=r=>{if(r.samples.length===0)return 0;let t=1/0,e=-1/0;for(let i=0;i<r.samples.length;i++){const a=r.samples[i];a.timestamp<t&&(t=a.timestamp),a.timestamp+a.duration>e&&(e=a.timestamp+a.duration)}return t===1/0?0:e-t},_s=(r,t)=>{const e=Eo(r),i=r.startTimestampOffset!==null&&r.startTimestampOffset>0;return B("trak",void 0,[ks(r,t),i?Ts(r,r.startTimestampOffset):null,Cs(r,t),e.name!==void 0?B("udta",void 0,[B("name",[...J.encode(e.name)])]):null])},ks=(r,t)=>{var n;const e=z(pe(r),lt)+z(r.startTimestampOffset??0,lt),i=!St(t)||!St(e),a=i?ft:x;let s;if(r.type==="video"){const l=r.track.metadata.rotation;s=wi(l??0)}else s=yi;let o=2;return((n=r.track.metadata.disposition)==null?void 0:n.default)!==!1&&(o|=1),R("tkhd",+i,o,[a(t),a(t),x(r.track.id),x(0),a(e),Array(8).fill(0),P(0),P(r.track.id),gi(r.type==="audio"?1:0),P(0),bi(s),ct(r.type==="video"?r.info.width:0),ct(r.type==="video"?r.info.height:0)])},Ts=(r,t)=>{const e=z(t,lt),i=z(pe(r),lt),a=!St(e)||!St(i),s=a?ft:x,o=a?vs:xt;return B("edts",void 0,[R("elst",a?1:0,0,[x(2),s(e),o(-1),ct(1),s(i),o(0),ct(1)])])},Cs=(r,t)=>B("mdia",void 0,[Es(r,t),Ne(!0,Ss[r.type],Bs[r.type]),Ps(r)]),Es=(r,t)=>{const e=z(pe(r),r.timescale),i=!St(t)||!St(e),a=i?ft:x;return R("mdhd",+i,0,[a(t),a(t),x(r.timescale),a(e),P(Bi(r.track.metadata.languageCode??"und")),P(0)])},Ss={video:"vide",audio:"soun",subtitle:"text"},Bs={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Ne=(r,t,e,i="\0\0\0\0")=>R("hdlr",0,0,[r?O("mhlr"):x(0),O(t),O(i),x(0),x(0),O(e,!0)]),Ps=r=>B("minf",void 0,[Ms[r.type](),Is(),Ds(r)]),Ms={video:()=>R("vmhd",0,1,[P(0),P(0),P(0),P(0)]),audio:()=>R("smhd",0,0,[P(0),P(0)]),subtitle:()=>R("nmhd",0,0)},Is=()=>B("dinf",void 0,[As()]),As=()=>R("dref",0,0,[x(1)],[Fs()]),Fs=()=>R("url ",0,1),Ds=r=>{const t=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return B("stbl",void 0,[Rs(r),Ks(r),t?eo(r):null,t?ro(r):null,Js(r),Zs(r),to(r),Ys(r)])},Rs=r=>{let t;if(r.type==="video")t=Vs(vo(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const e=Si(r.track.source._codec,r.muxer.isQuickTime);g(e),t=Os(e,r)}else r.type==="subtitle"&&(t=Xs(ko[r.track.source._codec],r));return g(t),R("stsd",0,0,[x(1)],[t])},Vs=(r,t)=>B(r,[Array(6).fill(0),P(1),P(0),P(0),Array(12).fill(0),P(t.info.width),P(t.info.height),x(4718592),x(4718592),x(0),P(1),Array(32).fill(0),P(24),Oe(65535)],[xo[t.track.source._codec](t),Ls(t),kr(t.info.decoderConfig.colorSpace)?Ws(t):null]),Ls=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:B("pasp",[x(r.info.pixelAspectRatio.num),x(r.info.pixelAspectRatio.den)]),Ws=r=>B("colr",[O("nclx"),P(zt[r.info.decoderConfig.colorSpace.primaries]),P(Nt[r.info.decoderConfig.colorSpace.transfer]),P(Ut[r.info.decoderConfig.colorSpace.matrix]),N((r.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),_i=r=>{var c,d,u,m;if(!r.info.decoderConfig)return null;const t=r.info.decoderConfig,e=t.codec.split("."),i=Number(e[1]),a=Number(e[2]),s=(Number(e[3])<<4)+((e[4]?Number(e[4]):1)<<1)+(e[8]?Number(e[8]):Number(((c=t.colorSpace)==null?void 0:c.fullRange)??0)),o=e[5]?Number(e[5]):(d=t.colorSpace)!=null&&d.primaries?zt[t.colorSpace.primaries]:2,n=e[6]?Number(e[6]):(u=t.colorSpace)!=null&&u.transfer?Nt[t.colorSpace.transfer]:2,l=e[7]?Number(e[7]):(m=t.colorSpace)!=null&&m.matrix?Ut[t.colorSpace.matrix]:2;return R("vpcC",1,0,[N(i),N(a),N(s),N(o),N(n),N(l),P(0)])},Os=(r,t)=>{var o;let e,i=0,a=16;const s=bt.includes(t.track.source._codec);if(s){const n=t.track.source._codec,{sampleSize:l}=At(n);a=8*l,a>16&&(i=1)}if(t.muxer.isQuickTime&&(i=1),i===0)e=[Array(6).fill(0),P(1),P(i),P(0),x(0),P(t.info.numberOfChannels),P(a),P(0),P(0),P(t.info.sampleRate<65536?t.info.sampleRate:0),P(0)];else{const n=s?0:-2;e=[Array(6).fill(0),P(1),P(i),P(0),x(0),P(t.info.numberOfChannels),P(Math.min(a,16)),Oe(n),P(0),P(t.info.sampleRate<65536?t.info.sampleRate:0),P(0),s?[x(1),x(a/8),x(t.info.numberOfChannels*a/8)]:[x(0),x(0),x(0)],x(2)]}return B(r,e,[((o=_o(t.track.source._codec,t.muxer.isQuickTime))==null?void 0:o(t))??null])},$s=r=>{let t;switch(r.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${r.track.source._codec}`)}let e=[...N(t),...N(21),...fi(0),...x(0),...x(0)];if(r.info.decoderConfig.description){const i=Z(r.info.decoderConfig.description);e=[...e,...N(5),...ze(i.byteLength),...i]}return e=[...P(1),...N(0),...N(4),...ze(e.length),...e,...N(6),...N(1),...N(2)],e=[...N(3),...ze(e.length),...e],R("esds",0,0,e)},zs=r=>B("wave",void 0,[Ns(r),Us(r),B("\0\0\0\0")]),Ns=r=>B("frma",[O(Si(r.track.source._codec,r.muxer.isQuickTime))]),Us=r=>{const{littleEndian:t}=At(r.track.source._codec);return B("enda",[P(+t)])},Hs=r=>{var l;let t=r.info.numberOfChannels,e=3840,i=r.info.sampleRate,a=0,s=0,o=new Uint8Array(0);const n=(l=r.info.decoderConfig)==null?void 0:l.description;if(n){g(n.byteLength>=18);const c=Z(n),d=Kr(c);t=d.outputChannelCount,e=d.preSkip,i=d.inputSampleRate,a=d.outputGain,s=d.channelMappingFamily,d.channelMappingTable&&(o=d.channelMappingTable)}return B("dOps",[N(0),N(t),P(e),x(i),Oe(a),N(s),...o])},js=r=>{var i;const t=(i=r.info.decoderConfig)==null?void 0:i.description;g(t);const e=Z(t);return R("dfLa",0,0,[...e.subarray(4)])},qs=r=>{const{littleEndian:t,sampleSize:e}=At(r.track.source._codec);return R("pcmC",0,0,[N(+t),N(8*e)])},Gs=r=>{const t=(a=>{if(a.length<7||a[0]!==11||a[1]!==119)return null;const s=new G(a);s.skipBits(16),s.skipBits(16);const o=s.readBits(2);if(o===3)return null;const n=s.readBits(6),l=s.readBits(5);if(l>8)return null;const c=s.readBits(3),d=s.readBits(3);return 1&d&&d!==1&&s.skipBits(2),4&d&&s.skipBits(2),d===2&&s.skipBits(2),{fscod:o,bsid:l,bsmod:c,acmod:d,lfeon:s.readBits(1),bitRateCode:Math.floor(n/2)}})(r.info.firstPacket.data);if(!t)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 e=new Uint8Array(3),i=new G(e);return i.writeBits(2,t.fscod),i.writeBits(5,t.bsid),i.writeBits(3,t.bsmod),i.writeBits(3,t.acmod),i.writeBits(1,t.lfeon),i.writeBits(5,t.bitRateCode),i.writeBits(5,0),B("dac3",[...e])},Qs=r=>{const t=(o=>{if(o.length<6||o[0]!==11||o[1]!==119)return null;const n=new G(o);n.skipBits(16);const l=n.readBits(2);if(n.skipBits(3),l!==0&&l!==2)return null;const c=n.readBits(11),d=n.readBits(2);let u,m=0;d===3?(m=n.readBits(2),u=3):u=n.readBits(2);const h=n.readBits(3),p=n.readBits(1),f=n.readBits(5);if(f<11||f>16)return null;const y=ss[u];let b;return b=d<3?Qa[d]/1e3:Xa[m]/1e3,{dataRate:Math.round((c+1)*b/(16*y)),substreams:[{fscod:d,fscod2:m,bsid:f,bsmod:0,acmod:h,lfeon:p,numDepSub:0,chanLoc:0}]}})(r.info.firstPacket.data);if(!t)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 e=16;for(const o of t.substreams)e+=23,o.numDepSub>0?e+=9:e+=1;const i=Math.ceil(e/8),a=new Uint8Array(i),s=new G(a);s.writeBits(13,t.dataRate),s.writeBits(3,t.substreams.length-1);for(const o of t.substreams)s.writeBits(2,o.fscod),s.writeBits(5,o.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,o.bsmod),s.writeBits(3,o.acmod),s.writeBits(1,o.lfeon),s.writeBits(3,0),s.writeBits(4,o.numDepSub),o.numDepSub>0?s.writeBits(9,o.chanLoc):s.writeBits(1,0);return B("dec3",[...a])},Xs=(r,t)=>B(r,[Array(6).fill(0),P(1)],[To[t.track.source._codec](t)]),Ks=r=>R("stts",0,0,[x(r.timeToSampleTable.length),r.timeToSampleTable.map(t=>[x(t.sampleCount),x(t.sampleDelta)])]),Ys=r=>{if(r.samples.every(e=>e.type==="key"))return null;const t=[...r.samples.entries()].filter(([,e])=>e.type==="key");return R("stss",0,0,[x(t.length),t.map(([e])=>x(e+1))])},Js=r=>R("stsc",0,0,[x(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(t=>[x(t.firstChunk),x(t.samplesPerChunk),x(1)])]),Zs=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:t}=At(r.track.source._codec);return R("stsz",0,0,[x(t*r.info.numberOfChannels),x(r.samples.reduce((e,i)=>e+z(i.duration,r.timescale),0))])}return R("stsz",0,0,[x(0),x(r.samples.length),r.samples.map(t=>x(t.size))])},to=r=>r.finalizedChunks.length>0&&pt(r.finalizedChunks).offset>=2**32?R("co64",0,0,[x(r.finalizedChunks.length),r.finalizedChunks.map(t=>ft(t.offset))]):R("stco",0,0,[x(r.finalizedChunks.length),r.finalizedChunks.map(t=>x(t.offset))]),eo=r=>R("ctts",1,0,[x(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(t=>[x(t.sampleCount),xt(t.sampleCompositionTimeOffset)])]),ro=r=>{let t=1/0,e=-1/0,i=1/0,a=-1/0;g(r.compositionTimeOffsetTable.length>0),g(r.samples.length>0);for(let o=0;o<r.compositionTimeOffsetTable.length;o++){const n=r.compositionTimeOffsetTable[o];t=Math.min(t,n.sampleCompositionTimeOffset),e=Math.max(e,n.sampleCompositionTimeOffset)}for(let o=0;o<r.samples.length;o++){const n=r.samples[o];i=Math.min(i,z(n.timestamp,r.timescale)),a=Math.max(a,z(n.timestamp+n.duration,r.timescale))}const s=Math.max(-t,0);return a>=2**31?null:R("cslg",0,0,[xt(s),xt(t),xt(e),xt(i),xt(a)])},io=r=>B("mvex",void 0,r.map(ao)),ao=r=>R("trex",0,0,[x(r.track.id),x(1),x(0),x(0),x(0)]),ki=(r,t)=>B("moof",void 0,[so(r),...t.map(oo)]),so=r=>R("mfhd",0,0,[x(r)]),Ti=r=>{let t=0,e=0;const i=r.type==="delta";return e|=+i,t|=i?1:2,t<<24|e<<16},oo=r=>B("traf",void 0,[no(r),co(r),lo(r)]),no=r=>{g(r.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const e=r.currentChunk.samples[1]??r.currentChunk.samples[0],i={duration:e.timescaleUnitsToNextSample,size:e.size,flags:Ti(e)};return R("tfhd",0,131128,[x(r.track.id),x(i.duration),x(i.size),x(i.flags)])},co=r=>(g(r.currentChunk),R("tfdt",1,0,[ft(z(r.currentChunk.startTimestamp,r.timescale))])),lo=r=>{g(r.currentChunk);const t=r.currentChunk.samples.map(f=>f.timescaleUnitsToNextSample),e=r.currentChunk.samples.map(f=>f.size),i=r.currentChunk.samples.map(Ti),a=r.currentChunk.samples.map(f=>z(f.timestamp-f.decodeTimestamp,r.timescale)),s=new Set(t),o=new Set(e),n=new Set(i),l=new Set(a),c=n.size===2&&i[0]!==i[1],d=s.size>1,u=o.size>1,m=!c&&n.size>1,h=l.size>1||[...l].some(f=>f!==0);let p=0;return p|=1,p|=4*+c,p|=256*+d,p|=512*+u,p|=1024*+m,p|=2048*+h,R("trun",1,p,[x(r.currentChunk.samples.length),x(r.currentChunk.offset-r.currentChunk.moofOffset||0),c?x(i[0]):[],r.currentChunk.samples.map((f,y)=>[d?x(t[y]):[],u?x(e[y]):[],m?x(i[y]):[],h?xt(a[y]):[]])])},ho=(r,t)=>R("tfra",1,0,[x(r.track.id),x(63),x(r.finalizedChunks.length),r.finalizedChunks.map(e=>[ft(z(e.samples[0].timestamp,r.timescale)),ft(e.moofOffset),x(t+1),x(1),x(1)])]),uo=()=>R("mfro",0,0,[x(0)]),mo=()=>B("vtte"),po=(r,t,e,i,a)=>B("vttc",void 0,[a!==null?B("vsid",[xt(a)]):null,e!==null?B("iden",[...J.encode(e)]):null,t!==null?B("ctim",[...J.encode(pi(t))]):null,i!==null?B("sttg",[...J.encode(i)]):null,B("payl",[...J.encode(r)])]),fo=r=>B("vtta",[...J.encode(r)]),go=r=>{const t=[],e=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(e==="mdir"||e==="auto"&&!r.isQuickTime){const a=yo(i);a&&t.push(a)}else if(e==="mdta"){const a=bo(i);a&&t.push(a)}else(e==="udta"||e==="auto"&&r.isQuickTime)&&wo(t,r.output._metadataTags);return t.length===0?null:B("udta",void 0,t)},wo=(r,t)=>{for(const{key:e,value:i}of Be(t))switch(e){case"title":r.push(gt("©nam",i));break;case"description":r.push(gt("©des",i));break;case"artist":r.push(gt("©ART",i));break;case"album":r.push(gt("©alb",i));break;case"albumArtist":r.push(gt("albr",i));break;case"genre":r.push(gt("©gen",i));break;case"date":r.push(gt("©day",i.toISOString().slice(0,10)));break;case"comment":r.push(gt("©cmt",i));break;case"lyrics":r.push(gt("©lyr",i));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Lt(e)}if(t.raw)for(const e in t.raw){const i=t.raw[e];i==null||e.length!==4||r.some(a=>a.type===e)||(typeof i=="string"?r.push(gt(e,i)):i instanceof Uint8Array&&r.push(B(e,Array.from(i))))}},gt=(r,t)=>{const e=J.encode(t);return B(r,[P(e.length),P(Bi("und")),Array.from(e)])},Ci={"image/jpeg":13,"image/png":14,"image/bmp":27},Ei=(r,t)=>{const e=[];for(const{key:i,value:a}of Be(r))switch(i){case"title":e.push({key:t?"title":"©nam",value:dt(a)});break;case"description":e.push({key:t?"description":"©des",value:dt(a)});break;case"artist":e.push({key:t?"artist":"©ART",value:dt(a)});break;case"album":e.push({key:t?"album":"©alb",value:dt(a)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:dt(a)});break;case"comment":e.push({key:t?"comment":"©cmt",value:dt(a)});break;case"genre":e.push({key:t?"genre":"©gen",value:dt(a)});break;case"lyrics":e.push({key:t?"lyrics":"©lyr",value:dt(a)});break;case"date":e.push({key:t?"date":"©day",value:dt(a.toISOString().slice(0,10))});break;case"images":for(const s of a)s.kind==="coverFront"&&e.push({key:"covr",value:B("data",[x(Ci[s.mimeType]??0),x(0),Array.from(s.data)])});break;case"trackNumber":if(t){const s=r.tracksTotal!==void 0?`${a}/${r.tracksTotal}`:a.toString();e.push({key:"track",value:dt(s)})}else e.push({key:"trkn",value:B("data",[x(0),x(0),P(0),P(a),P(r.tracksTotal??0),P(0)])});break;case"discNumber":t||e.push({key:"disc",value:B("data",[x(0),x(0),P(0),P(a),P(r.discsTotal??0),P(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:Lt(i)}if(r.raw)for(const i in r.raw){const a=r.raw[i];a==null||!t&&i.length!==4||e.some(s=>s.key===i)||(typeof a=="string"?e.push({key:i,value:dt(a)}):a instanceof Uint8Array?e.push({key:i,value:B("data",[x(0),x(0),Array.from(a)])}):a instanceof Fr&&e.push({key:i,value:B("data",[x(Ci[a.mimeType]??0),x(0),Array.from(a.data)])}))}return e},yo=r=>{const t=Ei(r,!1);return t.length===0?null:R("meta",0,0,void 0,[Ne(!1,"mdir","","appl"),B("ilst",void 0,t.map(e=>B(e.key,void 0,[e.value])))])},bo=r=>{const t=Ei(r,!0);return t.length===0?null:B("meta",void 0,[Ne(!1,"mdta",""),R("keys",0,0,[x(t.length)],t.map(e=>B("mdta",[...J.encode(e.key)]))),B("ilst",void 0,t.map((e,i)=>{const a=String.fromCharCode(...x(i+1));return B(a,void 0,[e.value])}))])},dt=r=>B("data",[x(1),x(0),...J.encode(r)]),vo=(r,t)=>{switch(r){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},xo={avc:r=>r.info.decoderConfig&&B("avcC",[...Z(r.info.decoderConfig.description)]),hevc:r=>r.info.decoderConfig&&B("hvcC",[...Z(r.info.decoderConfig.description)]),vp8:_i,vp9:_i,av1:r=>B("av1C",Or(r.info.decoderConfig.codec))},Si=(r,t)=>{switch(r){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(t)switch(r){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(r){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"}},_o=(r,t)=>{switch(r){case"aac":case"mp3":case"vorbis":return $s;case"opus":return Hs;case"flac":return js;case"ac3":return Gs;case"eac3":return Qs}if(t)switch(r){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 zs}else switch(r){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 qs}return null},ko={webvtt:"wvtt"},To={webvtt:r=>B("vttC",[...J.encode(r.info.config.description)])},Bi=r=>{g(r.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=r.charCodeAt(e)-96;return t};class Ue{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t._setMonotonicity(e),t._writerAcquired=!0}start(){g(!this.started),this.target._start(),this.started=!0}write(t){g(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target._write(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return g(this.started&&!this.finalized),this.target._flush()}async finalize(){g(this.started&&!this.finalized),await this.target._finalize(),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 a=this.trackedWrites.byteLength;for(;a<i;)a*=2;if(a!==this.trackedWrites.byteLength){const s=new Uint8Array(a);s.set(this.trackedWrites,0),this.trackedWrites=s}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}}class _t extends Ar{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(t){this._monotonicity!==!1&&(this._monotonicity=t)}_dispatchWrite(t,e){var i;(i=this.onwrite)==null||i.call(this,t,e),this._emit("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 Co(this,t)}}const He=65536,Pi=2**32;class fe extends _t{constructor(t={}){if(super(),this.buffer=null,this._maxPos=0,!t||typeof t!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(t.onFinalize!==void 0&&typeof t.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=t,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(He,{maxByteLength:Pi})}catch{this._buffer=new ArrayBuffer(He),this._supportsResize=!1}else this._buffer=new ArrayBuffer(He);this._bytes=new Uint8Array(this._buffer)}_ensureSize(t){let e=this._buffer.byteLength;for(;e<t;)e*=2;if(e!==this._buffer.byteLength){if(e>Pi)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this._supportsResize)this._buffer.resize(e);else{const i=new ArrayBuffer(e),a=new Uint8Array(i);a.set(this._bytes,0),this._buffer=i,this._bytes=a}}}_start(){}_write(t,e){this._ensureSize(e+t.byteLength),this._bytes.set(t,e),this._maxPos=Math.max(this._maxPos,e+t.byteLength),this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(t,e){return this._bytes.slice(t,e)}}class Co extends _t{constructor(t,e){super(),this._baseTarget=t,this._offset=e}_start(){}_write(t,e){this._baseTarget._write(t,this._offset+e),this._dispatchWrite(e,e+t.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}}class je{constructor(t,e){if(this.rootPath=t,this.getTarget=e,typeof t!="string")throw new TypeError("rootPath must be a string.");if(typeof e!="function")throw new TypeError("getTarget must be a function.")}}const lt=57600,Eo=r=>{const t={},e=r.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},z=(r,t,e=!0)=>{const i=r*t;return e?Math.round(i):i};class So extends mi{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new fe,this.auxWriter=new Ue(this.auxTarget,!1),this.auxBoxWriter=new ue(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Te(),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 Ri,this.isCmaf=e instanceof Di,this.minimumFragmentDuration=e._options.minimumFragmentDuration??(e instanceof Di?1/0:1)}async start(){var i;const t=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(a=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":a instanceof fe),this.boxWriter=new ue(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof fe&&"in-memory"),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const a=await this.output._getInitTarget(),s=new Ue(a,!0);s.start(),this.initWriter=s,this.initBoxWriter=new ue(s)}const e=this.output._tracks.some(a=>a.isVideoTrack()&&a.source._codec==="avc");{const a=this.initBoxWriter??this.boxWriter;if(g(a),this.format._options.onFtyp&&a.writer.startTrackingWrites(),a.writeBox((s=>s.isQuickTime?B("ftyp",[O("qt "),x(512),O("qt ")]):s.fragmented?s.cmaf?B("ftyp",[O("iso5"),x(512),O("iso5"),O("iso6"),O("mp41"),O("cmfc"),O("dash")]):B("ftyp",[O("iso5"),x(512),O("iso5"),O("iso6"),O("mp41")]):B("ftyp",[O("isom"),x(512),O("isom"),s.holdsAvc?O("avc1"):[],O("mp41")]))({isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){const{data:s,start:o}=a.writer.stopTrackingWrites();this.format._options.onFtyp(s,o)}this.ftypSize=a.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const a of this.output._tracks)if(a.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(g(this.writer),g(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=me(!0),this.boxWriter.writeBox(this.mdat));await((i=this.writer)==null?void 0:i.flush()),t()}allTracksAreKnown(){for(const t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(e=>e.type==="video"||e.type==="audio"?e.info.decoderConfig.codec:{webvtt:"wvtt"}[e.track.source._codec]);return(e=>{let i=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");return e.codecStrings.length>0&&(i+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`),i})({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type==="video"),hasAudio:this.trackDatas.some(e=>e.type==="audio"),codecStrings:t})}getVideoTrackData(t,e,i){const a=this.trackDatas.find(m=>m.track===t);if(a)return a;zr(i),g(i),g(i.decoderConfig);const s={...i.decoderConfig};g(s.codedWidth!==void 0),g(s.codedHeight!==void 0);let o=!1;if(t.source._codec!=="avc"||s.description){if(t.source._codec==="hevc"&&!s.description){const m=Ya(e.data);if(!m)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.");s.description=(h=>{const p=[];p.push(h.configurationVersion),p.push((3&h.generalProfileSpace)<<6|(1&h.generalTierFlag)<<5|31&h.generalProfileIdc),p.push(h.generalProfileCompatibilityFlags>>>24&255),p.push(h.generalProfileCompatibilityFlags>>>16&255),p.push(h.generalProfileCompatibilityFlags>>>8&255),p.push(255&h.generalProfileCompatibilityFlags),p.push(...h.generalConstraintIndicatorFlags),p.push(255&h.generalLevelIdc),p.push(240|h.minSpatialSegmentationIdc>>8&15),p.push(255&h.minSpatialSegmentationIdc),p.push(252|3&h.parallelismType),p.push(252|3&h.chromaFormatIdc),p.push(248|7&h.bitDepthLumaMinus8),p.push(248|7&h.bitDepthChromaMinus8),p.push(h.avgFrameRate>>8&255),p.push(255&h.avgFrameRate),p.push((3&h.constantFrameRate)<<6|(7&h.numTemporalLayers)<<3|(1&h.temporalIdNested)<<2|3&h.lengthSizeMinusOne),p.push(255&h.arrays.length);for(const f of h.arrays){p.push((1&f.arrayCompleteness)<<7|63&f.nalUnitType),p.push(f.nalUnits.length>>8&255),p.push(255&f.nalUnits.length);for(const y of f.nalUnits){p.push(y.length>>8&255),p.push(255&y.length);for(let b=0;b<y.length;b++)p.push(y[b])}}return new Uint8Array(p)})(m),o=!0}}else{const m=(h=>{try{const p=[],f=[],y=[];for(const S of jt(h)){const A=h.subarray(S.offset,S.offset+S.length),E=jr(A[0]);E===vt.SPS?p.push(A):E===vt.PPS?f.push(A):E===vt.SPS_EXT&&y.push(A)}if(p.length===0||f.length===0)return null;const b=p[0],_=Ka(b);g(_!==null);const T=_.profileIdc===100||_.profileIdc===110||_.profileIdc===122||_.profileIdc===144;return{configurationVersion:1,avcProfileIndication:_.profileIdc,profileCompatibility:_.constraintFlags,avcLevelIndication:_.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:p,pictureParameterSets:f,chromaFormat:T?_.chromaFormatIdc:null,bitDepthLumaMinus8:T?_.bitDepthLumaMinus8:null,bitDepthChromaMinus8:T?_.bitDepthChromaMinus8:null,sequenceParameterSetExt:T?y:null}}catch(p){return console.error("Error building AVC Decoder Configuration Record:",p),null}})(e.data);if(!m)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.");s.description=(h=>{const p=[];p.push(h.configurationVersion),p.push(h.avcProfileIndication),p.push(h.profileCompatibility),p.push(h.avcLevelIndication),p.push(252|3&h.lengthSizeMinusOne),p.push(224|31&h.sequenceParameterSets.length);for(const f of h.sequenceParameterSets){const y=f.byteLength;p.push(y>>8),p.push(255&y);for(let b=0;b<y;b++)p.push(f[b])}p.push(h.pictureParameterSets.length);for(const f of h.pictureParameterSets){const y=f.byteLength;p.push(y>>8),p.push(255&y);for(let b=0;b<y;b++)p.push(f[b])}if(h.avcProfileIndication===100||h.avcProfileIndication===110||h.avcProfileIndication===122||h.avcProfileIndication===144){g(h.chromaFormat!==null),g(h.bitDepthLumaMinus8!==null),g(h.bitDepthChromaMinus8!==null),g(h.sequenceParameterSetExt!==null),p.push(252|3&h.chromaFormat),p.push(248|7&h.bitDepthLumaMinus8),p.push(248|7&h.bitDepthChromaMinus8),p.push(h.sequenceParameterSetExt.length);for(const f of h.sequenceParameterSetExt){const y=f.byteLength;p.push(y>>8),p.push(255&y);for(let b=0;b<y;b++)p.push(f[b])}}return new Uint8Array(p)})(m),o=!0}const n=((m,h)=>{const p=m<0?-1:1;let f=0,y=1,b=1,_=0,T=m=Math.abs(m);for(;;){const S=Math.floor(T),A=S*b+f,E=S*_+y;if(E>h)return{num:p*b,den:_};if(f=b,y=_,b=A,_=E,T=1/(T-S),!isFinite(T))break}return{num:p*b,den:_}})(1/(t.metadata.frameRate??lt),1e6).den,l=s.displayAspectWidth,c=s.displayAspectHeight,d=l===void 0||c===void 0?{num:1,den:1}:Pe({num:l*s.codedHeight,den:c*s.codedWidth}),u={muxer:this,track:t,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o},timescale:n,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(u),this.trackDatas.sort((m,h)=>m.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(t,e,i){const a=this.trackDatas.find(l=>l.track===t);if(a)return a;Nr(i),g(i),g(i.decoderConfig);const s={...i.decoderConfig};let o=!1;if(t.source._codec==="aac"&&!s.description){const l=de(Rt.tempFromBytes(e.data));if(!l)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 c=Me[l.samplingFrequencyIndex],d=Ie[l.channelConfiguration];if(c===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=Rr({objectType:l.objectType,sampleRate:c,numberOfChannels:d}),o=!0}const n={muxer:this,track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&bt.includes(t.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,firstPacket:e},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(n),this.trackDatas.sort((l,c)=>l.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,e){const i=this.trackDatas.find(s=>s.track===t);if(i)return i;Ur(e),g(e),g(e.config);const a={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:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(t,e,i){const a=await this.mutex.acquire();try{const s=this.getVideoTrackData(t,e,i);let o=e.data;if(s.info.requiresAnnexBTransformation){const l=[...jt(o)].map(c=>o.subarray(c.offset,c.offset+c.length));if(l.length===0)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.");o=((c,d)=>{const u=c.reduce((p,f)=>p+d+f.byteLength,0),m=new Uint8Array(u);let h=0;for(const p of c){const f=new DataView(m.buffer,m.byteOffset,m.byteLength);switch(d){case 1:f.setUint8(h,p.byteLength);break;case 2:f.setUint16(h,p.byteLength,!1);break;case 3:Aa(f,h,p.byteLength);break;case 4:f.setUint32(h,p.byteLength,!1)}h+=d,m.set(p,h),h+=p.byteLength}return m})(l,4)}this.validateTimestamp(s.track,e.timestamp,e.type==="key");const n=this.createSampleForTrack(s,o,e.timestamp,e.duration,e.type);await this.registerSample(s,n)}finally{a()}}async addEncodedAudioPacket(t,e,i){const a=await this.mutex.acquire();try{const s=this.getAudioTrackData(t,e,i);let o=e.data;if(s.info.requiresAdtsStripping){const d=de(Rt.tempFromBytes(o));if(!d)throw new Error("Expected ADTS frame, didn't get one.");const u=d.crcCheck===null?7:9;o=o.subarray(u)}this.validateTimestamp(s.track,e.timestamp,e.type==="key");let n=e.timestamp,l=e.duration;if(s.info.requiresPcmTransformation){const d=At(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(l=o.byteLength/d/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){const u=n-s.info.expectedNextPcmPacketTimestamp;if(u<.01)n=s.info.expectedNextPcmPacketTimestamp;else{const m=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,u);n=s.info.expectedNextPcmPacketTimestamp+m}}s.info.expectedNextPcmPacketTimestamp=n+l}const c=this.createSampleForTrack(s,o,n,l,e.type);await this.registerSample(s,c)}finally{a()}}async padWithSilence(t,e,i){const a=z(i,t.timescale);if(i=a/t.timescale,a>0){const{sampleSize:s,silentValue:o}=At(t.info.decoderConfig.codec),n=a*t.info.numberOfChannels,l=new Uint8Array(s*n).fill(o),c=this.createSampleForTrack(t,new Uint8Array(l.buffer),e,i,"key");await this.registerSample(t,c)}return i}async addSubtitleCue(t,e,i){const a=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(t,i);this.validateTimestamp(s.track,e.timestamp,!0),t.source._codec==="webvtt"&&(s.cueQueue.push(e),await this.processWebVTTCues(s,e.timestamp))}finally{a()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){const i=new Set([]);for(const c of t.cueQueue)g(c.timestamp<=e),g(t.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,t.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const a=[...i].sort((c,d)=>c-d),s=a[0],o=a[1]??s;if(e<o)break;if(t.lastCueEndTimestamp<s){this.auxWriter.seek(0);const c=mo();this.auxBoxWriter.writeBox(c);const d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(t,d,t.lastCueEndTimestamp,s-t.lastCueEndTimestamp,"key");await this.registerSample(t,u),t.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let c=0;c<t.cueQueue.length;c++){const d=t.cueQueue[c];if(d.timestamp>=o)break;he.lastIndex=0;const u=he.test(d.text),m=d.timestamp+d.duration;let h=t.cueToSourceId.get(d);if(h===void 0&&o<m&&(h=t.nextSourceId++,t.cueToSourceId.set(d,h)),d.notes){const f=fo(d.notes);this.auxBoxWriter.writeBox(f)}const p=po(d.text,u?s:null,d.identifier??null,d.settings??null,h??null);this.auxBoxWriter.writeBox(p),m===o&&t.cueQueue.splice(c--,1)}const n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(t,n,s,o-s,"key");await this.registerSample(t,l),t.lastCueEndTimestamp=o}}createSampleForTrack(t,e,i,a,s){return{timestamp:i,decodeTimestamp:i,duration:a,data:e,size:e.byteLength,type:s,timescaleUnitsToNextSample:z(a,t.timescale)}}processTimestamps(t,e){if(t.timestampProcessingQueue.length===0)return;if(t.type==="audio"&&t.info.requiresPcmTransformation){this.isFragmented||(t.startTimestampOffset??(t.startTimestampOffset=t.timestampProcessingQueue[0].timestamp));let a=0;for(let s=0;s<t.timestampProcessingQueue.length;s++){const o=t.timestampProcessingQueue[s];a+=z(o.duration,t.timescale)}return t.timeToSampleTable.length===0?t.timeToSampleTable.push({sampleCount:a,sampleDelta:1}):pt(t.timeToSampleTable).sampleCount+=a,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(a=>a.timestamp).sort((a,s)=>a-s);this.isFragmented||(t.startTimestampOffset??(t.startTimestampOffset=i[0]));for(let a=0;a<t.timestampProcessingQueue.length;a++){const s=t.timestampProcessingQueue[a];s.decodeTimestamp=i[a];const o=z(s.timestamp-s.decodeTimestamp,t.timescale),n=z(s.duration,t.timescale);if(t.lastTimescaleUnits!==null){g(t.lastSample);const l=z(s.decodeTimestamp,t.timescale,!1),c=Math.round(l-t.lastTimescaleUnits);if(g(c>=0),t.lastTimescaleUnits+=c,t.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let d=pt(t.timeToSampleTable);if(g(d),d.sampleCount===1){d.sampleDelta=c;const m=t.timeToSampleTable[t.timeToSampleTable.length-2];m&&m.sampleDelta===c&&(m.sampleCount++,t.timeToSampleTable.pop(),d=m)}else d.sampleDelta!==c&&(d.sampleCount--,t.timeToSampleTable.push(d={sampleCount:1,sampleDelta:c}));d.sampleDelta===n?d.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:n});const u=pt(t.compositionTimeOffsetTable);g(u),u.sampleCompositionTimeOffset===o?u.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else t.lastTimescaleUnits=z(s.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:n}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));t.lastSample=s}if(t.timestampProcessingQueue.length=0,g(t.lastSample),g(t.lastTimescaleUnits!==null),e!==void 0&&t.lastSample.timescaleUnitsToNextSample===0){g(e.type==="key");const a=z(e.timestamp,t.timescale,!1),s=Math.round(a-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=s}}async registerSample(t,e){e.type==="key"&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),this.fastStart==="reserve")){const a=t.track.metadata.maximumPacketCount;if(g(a!==void 0),t.samples.length>a)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${a}). 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 a=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const s=this.trackDatas.every(o=>{if(t===o)return e.type==="key";const n=o.sampleQueue[0];return n?n.type==="key":o.closed});a>=this.minimumFragmentDuration&&s&&e.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=a>=.5}else i=!0;i&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null}),g(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(g(!this.isFragmented),g(this.writer),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if(t.type==="audio"&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((i,a)=>i+z(a.duration,t.timescale),0)),t.compactlyCodedChunkTable.length!==0&&pt(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),this.fastStart!=="in-memory"){t.currentChunk.offset=this.writer.getPos();for(const i of t.currentChunk.samples)g(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(g(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,i=1/0;for(const s of this.trackDatas){if(!t&&s.sampleQueue.length===0&&!s.closed)break t;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<i&&(e=s,i=s.sampleQueue[0].timestamp)}if(!e)break;const a=e.sampleQueue.shift();await this.addSampleToTrack(e,a)}}async finalizeFragment(t=!this.isCmaf){g(this.isFragmented);const e=this.nextFragmentNumber++;if(e===1){const h=this.initBoxWriter??this.boxWriter;g(h),this.format._options.onMoov&&h.writer.startTrackingWrites();const p=Xt(this);if(h.writeBox(p),this.format._options.onMoov){const{data:f,start:y}=h.writer.stopTrackingWrites();this.format._options.onMoov(f,y)}if(this.isCmaf){g(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new ue(this.writer);const f=this.boxWriter.measureBox(vi()),y=this.boxWriter.measureBox(xi(this,0));this.segmentHeaderSize=f+y,this.writer.seek(this.segmentHeaderSize)}}g(this.writer),g(this.boxWriter);const i=this.trackDatas.filter(h=>h.currentChunk),a=ki(e,i),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a);let n=o+8,l=1/0;for(const h of i){h.currentChunk.offset=n,h.currentChunk.moofOffset=s;for(const p of h.currentChunk.samples)n+=p.size;l=Math.min(l,h.currentChunk.startTimestamp)}const c=n-o,d=c>=2**32;if(d)for(const h of i)h.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const u=ki(e,i);if(this.boxWriter.writeBox(u),this.format._options.onMoof){const{data:h,start:p}=this.writer.stopTrackingWrites();this.format._options.onMoof(h,p,l)}g(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();const m=me(d);m.size=c,this.boxWriter.writeBox(m),this.writer.seek(o+(d?16:8));for(const h of i)for(const p of h.currentChunk.samples)this.writer.write(p.data),p.data=null;if(this.format._options.onMdat){const{data:h,start:p}=this.writer.stopTrackingWrites();this.format._options.onMdat(h,p)}for(const h of i)h.finalizedChunks.push(h.currentChunk),this.finalizedChunks.push(h.currentChunk),h.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){if(g(this.writer),g(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){const i=Xt(this),a=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;g(this.ftypSize!==null),this.writer.seek(this.ftypSize+a),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=me(!0),this.boxWriter.writeBox(this.mdat);for(const s of this.trackDatas){for(const o of s.sampleQueue)await this.addSampleToTrack(s,o);s.sampleQueue.length=0}}await this.addSampleToTrack(t,e)}else t.sampleQueue.push(e)}computeSampleTableSizeUpperBound(){g(this.fastStart==="reserve");let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;g(i!==void 0),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(a=>a.track===t);i&&(i.closed=!0,i.type==="subtitle"&&t.source._codec==="webvtt"&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const i of this.trackDatas)i.closed=!0,i.type==="subtitle"&&i.track.source._codec==="webvtt"&&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),g(i.startTimestampOffset!==null);for(let a=0;a<i.samples.length;a++){const s=i.samples[a];s.timestamp-=i.startTimestampOffset,s.decodeTimestamp-=i.startTimestampOffset}}if(g(this.writer),g(this.boxWriter),this.fastStart==="in-memory"){let i;this.mdat=me(!1);for(let s=0;s<2;s++){const o=Xt(this),n=this.boxWriter.measureBox(o);i=this.boxWriter.measureBox(this.mdat);let l=this.writer.getPos()+n+i;for(const c of this.finalizedChunks){c.offset=l;for(const{data:d}of c.samples)g(d),l+=d.byteLength,i+=d.byteLength}if(l<2**32)break;i>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const a=Xt(this);if(this.boxWriter.writeBox(a),this.format._options.onMoov){const{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,o)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=i,this.boxWriter.writeBox(this.mdat);for(const s of this.finalizedChunks)for(const o of s.samples)g(o.data),this.writer.write(o.data),o.data=null;if(this.format._options.onMdat){const{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,o)}}else if(this.isFragmented)if(this.isCmaf){const i=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(vi()),this.boxWriter.writeBox(xi(this,i))}else{const i=this.writer.getPos(),a=(e=this.trackDatas,B("mfra",void 0,[...e.map(ho),uo()]));this.boxWriter.writeBox(a);const s=this.writer.getPos()-i;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{g(this.mdat);const i=this.boxWriter.offsets.get(this.mdat);g(i!==void 0);const a=this.writer.getPos()-i;if(this.mdat.size=a,this.mdat.largeSize=a>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:o,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(o,n)}const s=Xt(this);if(this.fastStart==="reserve"){g(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);const o=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:o})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);if(this.format._options.onMoov){const{data:o,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(o,n)}}var e;t()}}const Mi="Mediabunny",Bo={video:1,audio:2,subtitle:17};class Po extends mi{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=Te(),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=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._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new os(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),t()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const t={id:v.EBML,data:[{id:v.EBMLVersion,data:1},{id:v.EBMLReadVersion,data:1},{id:v.EBMLMaxIDLength,data:4},{id:v.EBMLMaxSizeLength,data:8},{id:v.DocType,data:this.format instanceof we?"webm":"matroska"},{id:v.DocTypeVersion,data:2},{id:v.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format._options.onEbmlHeader){const{data:e,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,i)}}maybeCreateSeekHead(t){if(this.format._options.appendOnly)return;const e=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),n={id:v.SeekHead,data:[{id:v.Seek,data:[{id:v.SeekID,data:e},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:v.Seek,data:[{id:v.SeekID,data:i},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:v.Seek,data:[{id:v.SeekID,data:a},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:v.Seek,data:[{id:v.SeekID,data:s},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:v.Seek,data:[{id:v.SeekID,data:o},{id:v.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=n}createSegmentInfo(){const t={id:v.Duration,data:new De(0)};this.segmentDuration=t;const e={id:v.Info,data:[{id:v.TimestampScale,data:1e6},{id:v.MuxingApp,data:Mi},{id:v.WritingApp,data:Mi},this.format._options.appendOnly?null:t]};this.segmentInfo=e}createTracks(){var e,i,a,s,o,n;const t={id:v.Tracks,data:[]};this.tracksElement=t;for(const l of this.trackDatas){const c=ns[l.track.source._codec];g(c);let d=0;if(l.type==="audio"&&l.track.source._codec==="opus"){d=8e7;const u=l.info.decoderConfig.description;if(u){const m=Z(u),h=Kr(m);d=Math.round(h.preSkip/48e3*1e9)}}t.data.push({id:v.TrackEntry,data:[{id:v.TrackNumber,data:l.track.id},{id:v.TrackUID,data:l.track.id},{id:v.TrackType,data:Bo[l.type]},((e=l.track.metadata.disposition)==null?void 0:e.default)===!1?{id:v.FlagDefault,data:0}:null,(i=l.track.metadata.disposition)!=null&&i.forced?{id:v.FlagForced,data:1}:null,(a=l.track.metadata.disposition)!=null&&a.hearingImpaired?{id:v.FlagHearingImpaired,data:1}:null,(s=l.track.metadata.disposition)!=null&&s.visuallyImpaired?{id:v.FlagVisualImpaired,data:1}:null,(o=l.track.metadata.disposition)!=null&&o.original?{id:v.FlagOriginal,data:1}:null,(n=l.track.metadata.disposition)!=null&&n.commentary?{id:v.FlagCommentary,data:1}:null,{id:v.FlagLacing,data:0},{id:v.Language,data:l.track.metadata.languageCode??"und"},{id:v.CodecID,data:c},{id:v.CodecDelay,data:0},{id:v.SeekPreRoll,data:d},l.track.metadata.name!==void 0?{id:v.Name,data:new Bt(l.track.metadata.name)}:null,l.type==="video"?this.videoSpecificTrackInfo(l):null,l.type==="audio"?this.audioSpecificTrackInfo(l):null,l.type==="subtitle"?this.subtitleSpecificTrackInfo(l):null]})}}videoSpecificTrackInfo(t){const{frameRate:e,rotation:i}=t.track.metadata,a=[t.info.decoderConfig.description?{id:v.CodecPrivate,data:Z(t.info.decoderConfig.description)}:null,e?{id:v.DefaultDuration,data:1e9/e}:null],s=i?xr(-i):0,o=!!t.info.aspectRatio&&t.info.aspectRatio.num*t.info.height!==t.info.aspectRatio.den*t.info.width,n=t.info.decoderConfig.colorSpace,l={id:v.Video,data:[{id:v.PixelWidth,data:t.info.width},{id:v.PixelHeight,data:t.info.height},o?{id:v.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:v.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:v.DisplayUnit,data:3}:null,t.info.alphaMode?{id:v.AlphaMode,data:1}:null,kr(n)?{id:v.Colour,data:[{id:v.MatrixCoefficients,data:Ut[n.matrix]},{id:v.TransferCharacteristics,data:Nt[n.transfer]},{id:v.Primaries,data:zt[n.primaries]},{id:v.Range,data:n.fullRange?2:1}]}:null,s?{id:v.Projection,data:[{id:v.ProjectionType,data:0},{id:v.ProjectionPoseRoll,data:new Fe((s+180)%360-180)}]}:null]};return a.push(l),a}audioSpecificTrackInfo(t){const e=bt.includes(t.track.source._codec)?At(t.track.source._codec):null;return[t.info.decoderConfig.description?{id:v.CodecPrivate,data:Z(t.info.decoderConfig.description)}:null,{id:v.Audio,data:[{id:v.SamplingFrequency,data:new Fe(t.info.sampleRate)},{id:v.Channels,data:t.info.numberOfChannels},e?{id:v.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[{id:v.CodecPrivate,data:J.encode(t.info.config.description)}]}maybeCreateTags(){const t=[],e=(s,o)=>{t.push({id:v.SimpleTag,data:[{id:v.TagName,data:new Bt(s)},typeof o=="string"?{id:v.TagString,data:new Bt(o)}:{id:v.TagBinary,data:o}]})},i=this.output._metadataTags,a=new Set;for(const{key:s,value:o}of Be(i))switch(s){case"title":e("TITLE",o),a.add("TITLE");break;case"description":e("DESCRIPTION",o),a.add("DESCRIPTION");break;case"artist":e("ARTIST",o),a.add("ARTIST");break;case"album":e("ALBUM",o),a.add("ALBUM");break;case"albumArtist":e("ALBUM_ARTIST",o),a.add("ALBUM_ARTIST");break;case"genre":e("GENRE",o),a.add("GENRE");break;case"comment":e("COMMENT",o),a.add("COMMENT");break;case"lyrics":e("LYRICS",o),a.add("LYRICS");break;case"date":e("DATE",o.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":e("PART_NUMBER",i.tracksTotal!==void 0?`${o}/${i.tracksTotal}`:o.toString()),a.add("PART_NUMBER");break;case"discNumber":e("DISC",i.discsTotal!==void 0?`${o}/${i.discsTotal}`:o.toString()),a.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:Lt(s)}if(i.raw)for(const s in i.raw){const o=i.raw[s];o==null||a.has(s)||(typeof o=="string"||o instanceof Uint8Array)&&e(s,o)}t.length!==0&&(this.tagsElement={id:v.Tags,data:[{id:v.Tag,data:[{id:v.Targets,data:[{id:v.TargetTypeValue,data:50},{id:v.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output._metadataTags,e=[],i=new Set,a=t.images??[];for(const s of a){let o,n=s.name;for(n===void 0&&(n=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(La(s.mimeType)??""));;){o=0n;for(let l=0;l<8;l++)o<<=8n,o|=BigInt(Math.floor(256*Math.random()));if(o!==0n&&!i.has(o))break}i.add(o),e.push({id:v.AttachedFile,data:[s.description!==void 0?{id:v.FileDescription,data:new Bt(s.description)}:null,{id:v.FileName,data:new Bt(n)},{id:v.FileMediaType,data:s.mimeType},{id:v.FileData,data:s.data},{id:v.FileUID,data:o}]})}for(const[s,o]of Object.entries(t.raw??{}))o instanceof Dr&&/^\d+$/.test(s)&&(a.find(n=>n.mimeType===o.mimeType&&Wa(n.data,o.data))||e.push({id:v.AttachedFile,data:[o.description!==void 0?{id:v.FileDescription,data:new Bt(o.description)}:null,{id:v.FileName,data:new Bt(o.name??"")},{id:v.FileMediaType,data:o.mimeType??""},{id:v.FileData,data:o.data},{id:v.FileUID,data:BigInt(s)}]}));e.length!==0&&(this.attachmentsElement={id:v.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:v.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=t,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format._options.onSegmentHeader){const{data:e,start:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,i)}}createCues(){this.cues={id:v.Cues,data:[]}}get segmentDataOffset(){return g(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output._tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(e=>e.type==="video"||e.type==="audio"?e.info.decoderConfig.codec:{webvtt:"wvtt"}[e.track.source._codec]);return(e=>{let i=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");return e.codecStrings.length>0&&(i+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`),i})({isWebM:this.format instanceof we,hasVideo:this.trackDatas.some(e=>e.type==="video"),hasAudio:this.trackDatas.some(e=>e.type==="audio"),codecStrings:t})}getVideoTrackData(t,e,i){const a=this.trackDatas.find(c=>c.track===t);if(a)return a;zr(i),g(i),g(i.decoderConfig),g(i.decoderConfig.codedWidth!==void 0),g(i.decoderConfig.codedHeight!==void 0);const s=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,n=s===void 0||o===void 0?null:Pe({num:s,den:o}),l={track:t,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:n,decoderConfig:i.decoderConfig,alphaMode:!!e.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return t.source._codec==="vp9"?l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array(za(l.info.decoderConfig.codec))}:t.source._codec==="av1"&&(l.info.decoderConfig={...l.info.decoderConfig,description:new Uint8Array(Or(l.info.decoderConfig.codec))}),this.trackDatas.push(l),this.trackDatas.sort((c,d)=>c.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(t,e,i){const a=this.trackDatas.find(l=>l.track===t);if(a)return a;Nr(i),g(i),g(i.decoderConfig);const s={...i.decoderConfig};let o=!1;if(t.source._codec==="aac"&&!s.description){const l=de(Rt.tempFromBytes(e.data));if(!l)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 c=Me[l.samplingFrequencyIndex],d=Ie[l.channelConfiguration];if(c===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=Rr({objectType:l.objectType,sampleRate:c,numberOfChannels:d}),o=!0}const n={track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(n),this.trackDatas.sort((l,c)=>l.track.id-c.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(t,e){const i=this.trackDatas.find(s=>s.track===t);if(i)return i;Ur(e),g(e),g(e.config);const a={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(t,e,i){const a=await this.mutex.acquire();try{const s=this.getVideoTrackData(t,e,i),o=e.type==="key";this.validateTimestamp(s.track,e.timestamp,o);let n=e.timestamp,l=e.duration;t.metadata.frameRate!==void 0&&(n=Sr(n,t.metadata.frameRate),l=Sr(l,t.metadata.frameRate));const c=s.info.alphaMode?e.sideData.alpha??null:null,d=this.createInternalChunk(e.data,n,l,e.type,c);t.source._codec==="vp9"&&this.fixVP9ColorSpace(s,d),s.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(t,e,i){const a=await this.mutex.acquire();try{const s=this.getAudioTrackData(t,e,i);let o=e.data;if(s.info.requiresAdtsStripping){const c=de(Rt.tempFromBytes(o));if(!c)throw new Error("Expected ADTS frame, didn't get one.");const d=c.crcCheck===null?7:9;o=o.subarray(d)}const n=e.type==="key";this.validateTimestamp(s.track,e.timestamp,n);const l=this.createInternalChunk(o,e.timestamp,e.duration,e.type);s.chunkQueue.push(l),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(t,e,i){const a=await this.mutex.acquire();try{const s=this.getSubtitleTrackData(t,i);this.validateTimestamp(s.track,e.timestamp,!0);let o=e.text;const n=Math.round(1e3*e.timestamp);he.lastIndex=0,o=o.replace(he,u=>{const m=(h=>{const p=bs.exec(h);if(!p)throw new Error("Expected match.");return 36e5*Number(p[1]||"0")+6e4*Number(p[2])+1e3*Number(p[3])+Number(p[4])})(u.slice(1,-1));return`<${pi(m-n)}>`});const l=J.encode(o),c=`${e.settings??""}
3
3
  ${e.identifier??""}
4
- ${e.notes??""}`,d=this.createInternalChunk(l,e.timestamp,e.duration,"key",c.trim()?J.encode(c):null);s.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async interleaveChunks(t=!1){if(t||this.allTracksAreKnown()){t:for(;;){let e=null,r=1/0;for(const s of this.trackDatas){if(!t&&s.chunkQueue.length===0&&!s.closed)break t;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<r&&(e=s,r=s.chunkQueue[0].timestamp)}if(!e)break;const a=e.chunkQueue.shift();this.writeBlock(e,a)}t||await this.writer.flush()}}fixVP9ColorSpace(t,e){if(e.type!=="key"||!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;const r=new G(e.data);r.skipBits(2);const a=r.readBits(1),s=(r.readBits(1)<<1)+a;if(s===3&&r.skipBits(1),r.readBits(1)||r.readBits(1)!==0||(r.skipBits(2),r.readBits(24)!==4817730))return;s>=2&&r.skipBits(1);const o={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];((n,l,c,d)=>{for(let u=l;u<c;u++){const p=Math.floor(u/8);let h=n[p];const m=7-(7&u);h&=~(1<<m),h|=(d&1<<c-u-1)>>c-u-1<<m,n[p]=h}})(e.data,r.pos,r.pos+3,o)}createInternalChunk(t,e,r,a,s=null){return{data:t,type:a,timestamp:e,duration:r,additions:s}}writeBlock(t,e){this.segment||this.createSegment();const r=Math.round(1e3*e.timestamp),a=this.trackDatas.every(d=>{if(t===d)return e.type==="key";const u=d.chunkQueue[0];return u?u.type==="key":d.closed});let s=!1;if(this.currentCluster){g(this.currentClusterStartMsTimestamp!==null),g(this.currentClusterMaxMsTimestamp!==null);const d=r-this.currentClusterStartMsTimestamp;s=a&&r>this.currentClusterMaxMsTimestamp&&d>=1e3*(this.format._options.minimumClusterDuration??1)||d>32767}else s=!0;s&&this.createNewCluster(r);const o=r-this.currentClusterStartMsTimestamp;if(o<-32768)return;const n=new Uint8Array(4),l=new DataView(n.buffer);l.setUint8(0,128|t.track.id),l.setInt16(1,o,!1);const c=Math.round(1e3*e.duration);if(e.additions){const d={id:v.BlockGroup,data:[{id:v.Block,data:[n,e.data]},e.type==="delta"?{id:v.ReferenceBlock,data:new Ji(t.lastWrittenMsTimestamp-r)}:null,e.additions?{id:v.BlockAdditions,data:[{id:v.BlockMore,data:[{id:v.BlockAddID,data:1},{id:v.BlockAdditional,data:e.additions}]}]}:null,c>0?{id:v.BlockDuration,data:c}:null]};this.ebmlWriter.writeEBML(d)}else{l.setUint8(3,+(e.type==="key")<<7);const d={id:v.SimpleBlock,data:[n,e.data]};this.ebmlWriter.writeEBML(d)}this.startTimestamp=Math.min(this.startTimestamp,r),this.endTimestamp=Math.max(this.endTimestamp,r+c),t.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(t){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:v.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:v.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(g(this.currentCluster),!this.format._options.appendOnly){const a=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(a,5),this.writer.seek(s)}if(this.format._options.onCluster){g(this.currentClusterStartMsTimestamp!==null);const{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=new Map;for(const[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)e.has(s)||e.set(s,[]),e.get(s).push(a);const r=[...e.entries()].sort((a,s)=>a[0]-s[0]);for(const[a,s]of r)g(this.cues),this.cues.data.push({id:v.CuePoint,data:[{id:v.CueTime,data:a},...s.map(o=>({id:v.CueTrackPositions,data:[{id:v.CueTrack,data:o.track.id},{id:v.CueClusterPosition,data:t}]}))]})}async onTrackClose(t){const e=await this.mutex.acquire(),r=this.trackDatas.find(a=>a.track===t);r&&(r.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(),g(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const e=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(e,6);const r=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Ae(r),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),g(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}}class He{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;const t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,t.output.state!=="finalizing"&&t.output.state!=="finalized"&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??(this._closingPromise=(async()=>{await this._flushAndClose(t),this._closed=!0})())}}class Mr extends He{constructor(t){if(super(),this._connectedTrack=null,!nt.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${nt.join(", ")}.`);this._codec=t}}const Ir=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Po{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 Fa,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(t,e,r){var s,o,n,l,c,d,u,p,h,m,f,y;const a=t;try{this.checkForEncoderError(),this.source._ensureValidAdd();const b=this.encodingConfig,_=b.sizeChangeBehavior??"deny";let T=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(T=!0,_==="deny"))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(((s=b.transform)==null?void 0:s.width)!==void 0||((o=b.transform)==null?void 0:o.height)!==void 0||((n=b.transform)==null?void 0:n.rotate)!==void 0||((l=b.transform)==null?void 0:l.crop)!==void 0||((c=b.transform)==null?void 0:c.force)===!0||T&&_!=="passThrough"){let E=(d=b.transform)==null?void 0:d.width,C=(u=b.transform)==null?void 0:u.height,I=((p=b.transform)==null?void 0:p.fit)??"fill";T&&_!=="passThrough"&&(g(this.outputWidth),g(this.outputHeight),g(_!=="deny"),E=this.outputWidth,C=this.outputHeight,I=_);const D=await t.transform({width:E,height:C,roundDimensionsTo:2,crop:(h=b.transform)==null?void 0:h.crop,rotate:(m=b.transform)==null?void 0:m.rotate,fit:I,alpha:b.alpha});this.outputWidth!==null&&this.outputHeight!==null||(this.outputWidth=D.displayWidth,this.outputHeight=D.displayHeight),e&&t.close(),t=D,e=!0}else this.outputWidth!==null&&this.outputHeight!==null||(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);const A=(f=b.transform)==null?void 0:f.frameRate;if(A!==void 0){const E=t.timestamp+t.duration,C=Si(t.timestamp,A);if(this.frameRateLastSample!==null){if(C<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=E);await this.padFrameRate(C,r)}t===a&&(t=t.clone(),e=!0),t.setTimestamp(C),t.setDuration(1/A),(y=this.frameRateLastSample)==null||y.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=C,this.frameRateLastEndTimestamp=E}await this.processAndEncode(t,r)}finally{e&&t.close()}}async processAndEncode(t,e){var s;const r=this.encodingConfig;let a;if((s=r.transform)!=null&&s.process){let o=r.transform.process(t);if(o instanceof Promise&&(o=await o),o===null)return;Array.isArray(o)||(o=[o]),a=o.map(n=>n instanceof rt?n:typeof VideoFrame<"u"&&n instanceof VideoFrame?new rt(n):new rt(n,{timestamp:t.timestamp,duration:t.duration}))}else a=[t];try{for(const o of a){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(o),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized);const n=this.encodingConfig.keyFrameInterval??2,l=Math.floor(o.timestamp/n),c={...e,keyFrame:(e==null?void 0:e.keyFrame)||n===0||l!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=l,this.customEncoder){this.customEncoderQueueSize++;const d=o.clone(),u=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(d,c)).then(()=>this.customEncoderQueueSize--).catch(p=>this.error??(this.error=p)).finally(()=>{d.close()});this.customEncoderQueueSize>=4&&await u}else{g(this.encoder);const d=o.toVideoFrame(),u=Ti(this.preciseTimings,d.timestamp,h=>h.microsecondTimestamp),p=u!==-1?this.preciseTimings[u]:null;if(p&&p.microsecondTimestamp===d.timestamp?(p.timestamp!==o.timestamp&&(p.timestampIsValid=!1),p.duration!==o.duration&&(p.durationIsValid=!1)):(this.preciseTimings.splice(u+1,0,{microsecondTimestamp:d.timestamp,timestamp:o.timestamp,duration:o.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(d.format&&!d.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(d,c),d.close();else{const h=d.displayWidth,m=d.displayHeight;this.splitter||(this.splitter=new me(h,m));const{colorFrame:f,alphaFrame:y}=await this.splitter.update(d);this.alphaFrameQueue.push(y),this.encoder.encode(f,c),f.close()}else this.encoder.encode(d,c),d.close();this.encoder.encodeQueueSize>=4&&await new Promise(h=>this.encoder.addEventListener("dequeue",h,{once:!0}))}await this.lastMuxerPromise}}finally{for(const o of a)o!==t&&o.close()}}async padFrameRate(t,e){const r=this.encodingConfig.transform.frameRate;g(this.frameRateLastSample);const a=Math.round((t-this.frameRateLastTimestamp)*r);for(let s=1;s<a;s++){const o=this.frameRateLastSample.clone();o.setTimestamp(this.frameRateLastTimestamp+s/r),o.setDuration(1/r),await this.processAndEncode(o,e),o.close()}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{var a,s,o;const e=lr({...this.encodingConfig,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:(a=this.source._connectedTrack)==null?void 0:a.metadata.frameRate});(o=(s=this.encodingConfig).onEncoderConfig)==null||o.call(s,e);const r=hr.find(n=>n.supports(this.encodingConfig.codec,e));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=e,this.customEncoder.onPacket=(n,l)=>{var c,d;if(!(n instanceof jt))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(l!==void 0&&(!l||typeof l!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Ir(this.source._connectedTrack,n),(d=(c=this.encodingConfig).onEncodedPacket)==null||d.call(c,n,l),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,l).catch(u=>{this.error??(this.error=u)})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(e.alpha="discard",this.encodingConfig.alpha==="keep"&&(e.latencyMode="quality"),(e.width%2==1||e.height%2==1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))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)throw new Error(`This specific encoder configuration (${e.codec}, ${e.bitrate} bps, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const n=[],l=[];let c=0,d=0;const u=(h,m,f)=>{var A,E;const y={};if(m){const C=new Uint8Array(m.byteLength);m.copyTo(C),y.alpha=C}let b=jt.fromEncodedChunk(h,y);const _=Ti(this.preciseTimings,h.timestamp,C=>C.microsecondTimestamp),T=_!==-1?this.preciseTimings[_]:null;let S=null;this.emittedEncoderPackets===0&&b.type==="delta"&&(f!=null&&f.decoderConfig)&&(S=rs(this.encodingConfig.codec,f.decoderConfig,b.data)),(T&&T.microsecondTimestamp===h.timestamp||S!==null)&&(b=b.clone({timestamp:T!=null&&T.timestampIsValid?T.timestamp:void 0,duration:T!=null&&T.durationIsValid?T.duration:void 0,type:S??void 0})),Ir(this.source._connectedTrack,b),(E=(A=this.encodingConfig).onEncodedPacket)==null||E.call(A,b,f),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,b,f).catch(C=>{this.error??(this.error=C)}),this.emittedEncoderPackets++},p=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,m)=>{if(!this.alphaEncoder)return void u(h,null,m);const f=this.alphaFrameQueue.shift();g(f!==void 0),f?(this.alphaEncoder.encode(f,{keyFrame:h.type==="key"}),d++,f.close(),n.push({chunk:h,meta:m})):d===0?u(h,null,m):(l.push(c+d),n.push({chunk:h,meta:m}))},error:h=>{h.stack=p,this.error??(this.error=h)}}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){const h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(m,f)=>{d--;const y=n.shift();for(g(y!==void 0),u(y.chunk,m,y.meta),c++;l.length>0&&l[0]===c;){l.shift();const b=n.shift();g(b!==void 0),u(b.chunk,null,b.meta)}},error:m=>{m.stack=h,this.error??(this.error=m)}}),this.alphaEncoder.configure(e)}}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(t){var e,r,a;if(t||this.checkForEncoderError(),!t&&this.frameRateLastSample){const s=this.encodingConfig.transform.frameRate,o=Si(this.frameRateLastEndTimestamp,s);await this.padFrameRate(o)}(e=this.frameRateLastSample)==null||e.close(),this.frameRateLastSample=null,this.customEncoder?(t||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(t||(await this.encoder.flush(),await((r=this.alphaEncoder)==null?void 0:r.flush())),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(s=>s==null?void 0:s.close()),(a=this.splitter)==null||a.close()),t||this.checkForEncoderError()}getQueueSize(){var t;return this.customEncoder?this.customEncoderQueueSize:((t=this.encoder)==null?void 0:t.encodeQueueSize)??0}checkForEncoderError(){if(this.error)throw this.error}}let Ar=!1;class me{constructor(t,e){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;const r=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!me.forceCpu&&r&&!Ar)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(t,e):(this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e);const a=this.canvas.getContext("webgl2",{alpha:!0});if(!a)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=a,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(a){this.gl=null,this.canvas=null,Ar=!0,console.warn("Falling back to CPU for color/alpha splitting.",a)}}async update(t){return this.gl?this.updateGpu(t):this.updateCpu(t)}updateGpu(t){g(this.gl),g(this.canvas),t.displayWidth===this.canvas.width&&t.displayHeight===this.canvas.height||(this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t);const e=this.runColorProgram(t),r=this.runAlphaProgram(t);return t.close(),{colorFrame:e,alphaFrame:r}}createVertexShader(){return g(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
4
+ ${e.notes??""}`,d=this.createInternalChunk(l,e.timestamp,e.duration,"key",c.trim()?J.encode(c):null);s.chunkQueue.push(d),await this.interleaveChunks()}finally{a()}}async interleaveChunks(t=!1){if(t||this.allTracksAreKnown()){t:for(;;){let e=null,i=1/0;for(const s of this.trackDatas){if(!t&&s.chunkQueue.length===0&&!s.closed)break t;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<i&&(e=s,i=s.chunkQueue[0].timestamp)}if(!e)break;const a=e.chunkQueue.shift();this.writeBlock(e,a)}t||await this.writer.flush()}}fixVP9ColorSpace(t,e){if(e.type!=="key"||!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;const i=new G(e.data);i.skipBits(2);const a=i.readBits(1),s=(i.readBits(1)<<1)+a;if(s===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;s>=2&&i.skipBits(1);const o={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];((n,l,c,d)=>{for(let u=l;u<c;u++){const m=Math.floor(u/8);let h=n[m];const p=7-(7&u);h&=~(1<<p),h|=(d&1<<c-u-1)>>c-u-1<<p,n[m]=h}})(e.data,i.pos,i.pos+3,o)}createInternalChunk(t,e,i,a,s=null){return{data:t,type:a,timestamp:e,duration:i,additions:s}}writeBlock(t,e){this.segment||this.createSegment();const i=Math.round(1e3*e.timestamp),a=this.trackDatas.every(d=>{if(t===d)return e.type==="key";const u=d.chunkQueue[0];return u?u.type==="key":d.closed});let s=!1;if(this.currentCluster){g(this.currentClusterStartMsTimestamp!==null),g(this.currentClusterMaxMsTimestamp!==null);const d=i-this.currentClusterStartMsTimestamp;s=a&&i>this.currentClusterMaxMsTimestamp&&d>=1e3*(this.format._options.minimumClusterDuration??1)||d>32767}else s=!0;s&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768)return;const n=new Uint8Array(4),l=new DataView(n.buffer);l.setUint8(0,128|t.track.id),l.setInt16(1,o,!1);const c=Math.round(1e3*e.duration);if(e.additions){const d={id:v.BlockGroup,data:[{id:v.Block,data:[n,e.data]},e.type==="delta"?{id:v.ReferenceBlock,data:new Zr(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:v.BlockAdditions,data:[{id:v.BlockMore,data:[{id:v.BlockAddID,data:1},{id:v.BlockAdditional,data:e.additions}]}]}:null,c>0?{id:v.BlockDuration,data:c}:null]};this.ebmlWriter.writeEBML(d)}else{l.setUint8(3,+(e.type==="key")<<7);const d={id:v.SimpleBlock,data:[n,e.data]};this.ebmlWriter.writeEBML(d)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+c),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._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:v.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:v.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(g(this.currentCluster),!this.format._options.appendOnly){const a=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(a,5),this.writer.seek(s)}if(this.format._options.onCluster){g(this.currentClusterStartMsTimestamp!==null);const{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=new Map;for(const[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)e.has(s)||e.set(s,[]),e.get(s).push(a);const i=[...e.entries()].sort((a,s)=>a[0]-s[0]);for(const[a,s]of i)g(this.cues),this.cues.data.push({id:v.CuePoint,data:[{id:v.CueTime,data:a},...s.map(o=>({id:v.CueTrackPositions,data:[{id:v.CueTrack,data:o.track.id},{id:v.CueClusterPosition,data:t}]}))]})}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(a=>a.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(),g(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const e=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(e,6);const i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new De(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),g(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}}class qe{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;const t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,t.output.state!=="finalizing"&&t.output.state!=="finalized"&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??(this._closingPromise=(async()=>{await this._flushAndClose(t),this._closed=!0})())}}class Ii extends qe{constructor(t){if(super(),this._connectedTrack=null,!nt.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${nt.join(", ")}.`);this._codec=t}}const Ai=(r,t)=>{if(r.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Mo{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 Da,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(t,e,i){var s,o,n,l,c,d,u,m,h,p,f,y;const a=t;try{this.checkForEncoderError(),this.source._ensureValidAdd();const b=this.encodingConfig,_=b.sizeChangeBehavior??"deny";let T=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(T=!0,_==="deny"))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(((s=b.transform)==null?void 0:s.width)!==void 0||((o=b.transform)==null?void 0:o.height)!==void 0||((n=b.transform)==null?void 0:n.rotate)!==void 0||((l=b.transform)==null?void 0:l.crop)!==void 0||((c=b.transform)==null?void 0:c.force)===!0||T&&_!=="passThrough"){let E=(d=b.transform)==null?void 0:d.width,C=(u=b.transform)==null?void 0:u.height,I=((m=b.transform)==null?void 0:m.fit)??"fill";T&&_!=="passThrough"&&(g(this.outputWidth),g(this.outputHeight),g(_!=="deny"),E=this.outputWidth,C=this.outputHeight,I=_);const D=await t.transform({width:E,height:C,roundDimensionsTo:2,crop:(h=b.transform)==null?void 0:h.crop,rotate:(p=b.transform)==null?void 0:p.rotate,fit:I,alpha:b.alpha});this.outputWidth!==null&&this.outputHeight!==null||(this.outputWidth=D.displayWidth,this.outputHeight=D.displayHeight),e&&t.close(),t=D,e=!0}else this.outputWidth!==null&&this.outputHeight!==null||(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);const A=(f=b.transform)==null?void 0:f.frameRate;if(A!==void 0){const E=t.timestamp+t.duration,C=Br(t.timestamp,A);if(this.frameRateLastSample!==null){if(C<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=E);await this.padFrameRate(C,i)}t===a&&(t=t.clone(),e=!0),t.setTimestamp(C),t.setDuration(1/A),(y=this.frameRateLastSample)==null||y.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=C,this.frameRateLastEndTimestamp=E}await this.processAndEncode(t,i)}finally{e&&t.close()}}async processAndEncode(t,e){var s;const i=this.encodingConfig;let a;if((s=i.transform)!=null&&s.process){let o=i.transform.process(t);if(o instanceof Promise&&(o=await o),o===null)return;Array.isArray(o)||(o=[o]),a=o.map(n=>n instanceof it?n:typeof VideoFrame<"u"&&n instanceof VideoFrame?new it(n):new it(n,{timestamp:t.timestamp,duration:t.duration}))}else a=[t];try{for(const o of a){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(o),this.encoderInitialized||await this.ensureEncoderPromise),g(this.encoderInitialized);const n=this.encodingConfig.keyFrameInterval??2,l=Math.floor(o.timestamp/n),c={...e,keyFrame:(e==null?void 0:e.keyFrame)||n===0||l!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=l,this.customEncoder){this.customEncoderQueueSize++;const d=o.clone(),u=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(d,c)).then(()=>this.customEncoderQueueSize--).catch(m=>this.error??(this.error=m)).finally(()=>{d.close()});this.customEncoderQueueSize>=4&&await u}else{g(this.encoder);const d=o.toVideoFrame(),u=Cr(this.preciseTimings,d.timestamp,h=>h.microsecondTimestamp),m=u!==-1?this.preciseTimings[u]:null;if(m&&m.microsecondTimestamp===d.timestamp?(m.timestamp!==o.timestamp&&(m.timestampIsValid=!1),m.duration!==o.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(u+1,0,{microsecondTimestamp:d.timestamp,timestamp:o.timestamp,duration:o.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(d.format&&!d.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(d,c),d.close();else{const h=d.displayWidth,p=d.displayHeight;this.splitter||(this.splitter=new ge(h,p));const{colorFrame:f,alphaFrame:y}=await this.splitter.update(d);this.alphaFrameQueue.push(y),this.encoder.encode(f,c),f.close()}else this.encoder.encode(d,c),d.close();this.encoder.encodeQueueSize>=4&&await new Promise(h=>this.encoder.addEventListener("dequeue",h,{once:!0}))}await this.lastMuxerPromise}}finally{for(const o of a)o!==t&&o.close()}}async padFrameRate(t,e){const i=this.encodingConfig.transform.frameRate;g(this.frameRateLastSample);const a=Math.round((t-this.frameRateLastTimestamp)*i);for(let s=1;s<a;s++){const o=this.frameRateLastSample.clone();o.setTimestamp(this.frameRateLastTimestamp+s/i),o.setDuration(1/i),await this.processAndEncode(o,e),o.close()}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{var a,s,o;const e=hi({...this.encodingConfig,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:(a=this.source._connectedTrack)==null?void 0:a.metadata.frameRate});(o=(s=this.encodingConfig).onEncoderConfig)==null||o.call(s,e);const i=ui.find(n=>n.supports(this.encodingConfig.codec,e));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=e,this.customEncoder.onPacket=(n,l)=>{var c,d;if(!(n instanceof qt))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(l!==void 0&&(!l||typeof l!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Ai(this.source._connectedTrack,n),(d=(c=this.encodingConfig).onEncodedPacket)==null||d.call(c,n,l),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,l).catch(u=>{this.error??(this.error=u)})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(e.alpha="discard",this.encodingConfig.alpha==="keep"&&(e.latencyMode="quality"),(e.width%2==1||e.height%2==1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))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)throw new Error(`This specific encoder configuration (${e.codec}, ${e.bitrate} bps, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const n=[],l=[];let c=0,d=0;const u=(h,p,f)=>{var A,E;const y={};if(p){const C=new Uint8Array(p.byteLength);p.copyTo(C),y.alpha=C}let b=qt.fromEncodedChunk(h,y);const _=Cr(this.preciseTimings,h.timestamp,C=>C.microsecondTimestamp),T=_!==-1?this.preciseTimings[_]:null;let S=null;this.emittedEncoderPackets===0&&b.type==="delta"&&(f!=null&&f.decoderConfig)&&(S=as(this.encodingConfig.codec,f.decoderConfig,b.data)),(T&&T.microsecondTimestamp===h.timestamp||S!==null)&&(b=b.clone({timestamp:T!=null&&T.timestampIsValid?T.timestamp:void 0,duration:T!=null&&T.durationIsValid?T.duration:void 0,type:S??void 0})),Ai(this.source._connectedTrack,b),(E=(A=this.encodingConfig).onEncodedPacket)==null||E.call(A,b,f),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,b,f).catch(C=>{this.error??(this.error=C)}),this.emittedEncoderPackets++},m=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(h,p)=>{if(!this.alphaEncoder)return void u(h,null,p);const f=this.alphaFrameQueue.shift();g(f!==void 0),f?(this.alphaEncoder.encode(f,{keyFrame:h.type==="key"}),d++,f.close(),n.push({chunk:h,meta:p})):d===0?u(h,null,p):(l.push(c+d),n.push({chunk:h,meta:p}))},error:h=>{h.stack=m,this.error??(this.error=h)}}),this.encoder.configure(e),this.encodingConfig.alpha==="keep"){const h=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(p,f)=>{d--;const y=n.shift();for(g(y!==void 0),u(y.chunk,p,y.meta),c++;l.length>0&&l[0]===c;){l.shift();const b=n.shift();g(b!==void 0),u(b.chunk,null,b.meta)}},error:p=>{p.stack=h,this.error??(this.error=p)}}),this.alphaEncoder.configure(e)}}g(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(t){var e,i,a;if(t||this.checkForEncoderError(),!t&&this.frameRateLastSample){const s=this.encodingConfig.transform.frameRate,o=Br(this.frameRateLastEndTimestamp,s);await this.padFrameRate(o)}(e=this.frameRateLastSample)==null||e.close(),this.frameRateLastSample=null,this.customEncoder?(t||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(t||(await this.encoder.flush(),await((i=this.alphaEncoder)==null?void 0:i.flush())),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(s=>s==null?void 0:s.close()),(a=this.splitter)==null||a.close()),t||this.checkForEncoderError()}getQueueSize(){var t;return this.customEncoder?this.customEncoderQueueSize:((t=this.encoder)==null?void 0:t.encodeQueueSize)??0}checkForEncoderError(){if(this.error)throw this.error}}let Fi=!1;class ge{constructor(t,e){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;const i=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!ge.forceCpu&&i&&!Fi)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(t,e):(this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=e);const a=this.canvas.getContext("webgl2",{alpha:!0});if(!a)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=a,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(a){this.gl=null,this.canvas=null,Fi=!0,console.warn("Falling back to CPU for color/alpha splitting.",a)}}async update(t){return this.gl?this.updateGpu(t):this.updateCpu(t)}updateGpu(t){g(this.gl),g(this.canvas),t.displayWidth===this.canvas.width&&t.displayHeight===this.canvas.height||(this.canvas.width=t.displayWidth,this.canvas.height=t.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t);const e=this.runColorProgram(t),i=this.runAlphaProgram(t);return t.close(),{colorFrame:e,alphaFrame:i}}createVertexShader(){return g(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
5
5
  in vec2 a_position;
6
6
  in vec2 a_texCoord;
7
7
  out vec2 v_texCoord;
@@ -21,7 +21,7 @@ ${e.notes??""}`,d=this.createInternalChunk(l,e.timestamp,e.duration,"key",c.trim
21
21
  vec4 source = texture(u_sourceTexture, v_texCoord);
22
22
  fragColor = vec4(source.rgb, 1.0);
23
23
  }
24
- `),r=this.gl.createProgram();return this.gl.attachShader(r,t),this.gl.attachShader(r,e),this.gl.linkProgram(r),r}createAlphaProgram(){g(this.gl);const t=this.createVertexShader(),e=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
24
+ `),i=this.gl.createProgram();return this.gl.attachShader(i,t),this.gl.attachShader(i,e),this.gl.linkProgram(i),i}createAlphaProgram(){g(this.gl);const t=this.createVertexShader(),e=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
25
25
  precision highp float;
26
26
 
27
27
  uniform sampler2D u_sourceTexture;
@@ -65,4 +65,4 @@ ${e.notes??""}`,d=this.createInternalChunk(l,e.timestamp,e.duration,"key",c.trim
65
65
 
66
66
  fragColor = result;
67
67
  }
68
- `),r=this.gl.createProgram();return this.gl.attachShader(r,t),this.gl.attachShader(r,e),this.gl.linkProgram(r),r}createShader(t,e){g(this.gl);const r=this.gl.createShader(t);return this.gl.shaderSource(r,e),this.gl.compileShader(r),this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(r)),r}createVAO(){g(this.gl),g(this.colorProgram);const t=this.gl.createVertexArray();this.gl.bindVertexArray(t);const e=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,e,this.gl.STATIC_DRAW);const a=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),t}createTexture(){g(this.gl);const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),t}runColorProgram(t){return g(this.gl),g(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:t.timestamp,duration:t.duration??void 0,alpha:"discard"})}runAlphaProgram(t){g(this.gl),g(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:e,height:r}=this.canvas,a=e*r+2*(Math.ceil(e/2)*Math.ceil(r/2)),s=Math.ceil(a/(4*e));let o=new Uint8Array(4*e*s);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,a),g(o[e*r]===128),g(o[o.length-1]===128);const n={format:"I420",codedWidth:e,codedHeight:r,timestamp:t.timestamp,duration:t.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,n)}updateCpu(t){if(!this.worker){const a=new Blob([`(${Mo.toString()})()`],{type:"application/javascript"}),s=URL.createObjectURL(a);this.worker=new Worker(s),URL.revokeObjectURL(s),this.worker.addEventListener("message",o=>{const n=o.data,l=this.pendingRequests.get(n.id);l&&(this.pendingRequests.delete(n.id),"error"in n?l.reject(new Error(n.error)):l.resolve({colorFrame:n.colorFrame,alphaFrame:n.alphaFrame}))}),this.worker.addEventListener("error",o=>{const n=new Error(o.message||"Color/alpha splitter worker error.");for(const l of this.pendingRequests.values())l.reject(n);this.pendingRequests.clear()})}const e=this.nextRequestId++,r=_e();return this.pendingRequests.set(e,r),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),r.promise}close(){var e,r,a;(r=(e=this.gl)==null?void 0:e.getExtension("WEBGL_lose_context"))==null||r.loseContext(),this.gl=null,this.canvas=null,(a=this.worker)==null||a.terminate(),this.worker=null;const t=new Error("Color/alpha splitter closed.");for(const s of this.pendingRequests.values())s.reject(t);this.pendingRequests.clear()}}me.forceCpu=!0;const Mo=()=>{let i=null,t=Promise.resolve();self.addEventListener("message",s=>{const{id:o,sourceFrame:n}=s.data;t=t.then(async()=>{try{const{colorFrame:l,alphaFrame:c}=await e(n);self.postMessage({id:o,colorFrame:l,alphaFrame:c},{transfer:[l,c]})}catch(l){self.postMessage({id:o,error:l.message})}finally{n.close()}})});const e=async s=>{const o=s.format;if(!o)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const n=s.codedWidth,l=s.codedHeight,c=s.allocationSize();if(i&&i.byteLength===c||(i=new Uint8Array(c)),await s.copyTo(i),o==="RGBA"||o==="BGRA")return r(i,n,l,o,s);if(o==="I420A"||o==="I420AP10"||o==="I420AP12"||o==="I422A"||o==="I422AP10"||o==="I422AP12"||o==="I444A"||o==="I444AP10"||o==="I444AP12")return a(i,n,l,o,s);throw new Error(`CPU color/alpha splitting does not support format '${o}'.`)},r=(s,o,n,l,c)=>{const d=o*n,u=Math.ceil(o/2),p=Math.ceil(n/2),h=new Uint8Array(d+u*p*2);for(let y=0,b=3;y<d;y++,b+=4)h[y]=s[b];h.fill(128,d);const m=new VideoFrame(s,{format:l==="RGBA"?"RGBX":"BGRX",codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0}),f={format:"I420",codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[h.buffer]};return{colorFrame:m,alphaFrame:new VideoFrame(h,f)}},a=(s,o,n,l,c)=>{const d=l.includes("P10"),u=l.includes("P12"),p=d||u?2:1;let h,m;l.startsWith("I420")?(h=Math.ceil(o/2),m=Math.ceil(n/2)):l.startsWith("I422")?(h=Math.ceil(o/2),m=n):(h=o,m=n);const f=o*n,y=f*p,b=f*p+2*(h*m*p),_=l.replace("A",""),T=Math.ceil(o/2)*Math.ceil(n/2),S=new Uint8Array(y+2*(T*p)),A=b;S.set(s.subarray(A,A+y),0);const E=y,C=d?512:u?2048:128;p===1?S.fill(C,E):new Uint16Array(S.buffer,E,2*T).fill(C);const I=d?"I420P10":u?"I420P12":"I420",D=new VideoFrame(s.subarray(0,b),{format:_,codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0}),V={format:I,codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[S.buffer]};return{colorFrame:D,alphaFrame:new VideoFrame(S,V)}}};class Io extends Mr{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");(r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!nt.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${nt.join(", ")}.`);if(!(r.bitrate instanceof Ve)&&(!Number.isInteger(r.bitrate)||r.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.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(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&Re(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");dr(r.codec,r)})(e),super(e.codec),this._encoder=new Po(this,e),this._canvas=t}add(t,e=0,r){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 a=new rt(this._canvas,{timestamp:t,duration:e});return this._encoder.add(a,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}}class Ao extends He{constructor(t){if(super(),this._connectedTrack=null,!Ut.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${Ut.join(", ")}.`);this._codec=t}}class Fo extends He{constructor(t){if(super(),this._connectedTrack=null,!It.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${It.join(", ")}.`);this._codec=t}}class je{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>nt.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>Ut.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>It.includes(t))}_codecUnsupportedHint(t){return""}}class qe extends je{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(t.minimumFragmentDuration!==void 0&&(!Number.isFinite(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(t.onFtyp!==void 0&&typeof t.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(t.onMoov!==void 0&&typeof t.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(t.onMdat!==void 0&&typeof t.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(t.onMoof!==void 0&&typeof t.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(t.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=t}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(t){return new Eo(t,this)}}class Ge extends qe{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...nt,...ae,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...It]}_codecUnsupportedHint(t){return new Dr().getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}}class Fr extends qe{constructor(t){super(t)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...nt,...ae,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...It]}}class Dr extends qe{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...nt,...Ut]}_codecUnsupportedHint(t){return new Ge().getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}}class Rr extends je{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.minimumClusterDuration!==void 0&&(!Number.isFinite(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(t.onEbmlHeader!==void 0&&typeof t.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(t.onSegmentHeader!==void 0&&typeof t.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(t.onCluster!==void 0&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Bo(t,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...nt,...ae,...bt.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...It]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class fe extends Rr{constructor(t){super(t)}getSupportedCodecs(){return[...nt.filter(t=>["vp8","vp9","av1"].includes(t)),...Ut.filter(t=>["opus","vorbis"].includes(t)),...It]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(t){return new Rr().getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}}const Do=["video","audio","subtitle"];class Xt{constructor(t,e,r,a,s){this.id=t,this.output=e,this.type=r,this.source=a,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(t){if(!(t instanceof Xt))throw new TypeError("other must be an OutputTrack.");if(this===t)return!1;const e=Mi(this.metadata.group),r=Mi(t.metadata.group);for(const a of e)if(this.type!==t.type&&r.some(s=>a===s)||r.some(s=>a._pairedGroups.has(s)))return!0;return!1}}class Ro extends Xt{constructor(t,e,r,a){super(t,e,"video",r,a)}}class Vo extends Xt{constructor(t,e,r,a){super(t,e,"audio",r,a)}}class Lo extends Xt{constructor(t,e,r,a){super(t,e,"subtitle",r,a)}}class Kt{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof Kt))throw new TypeError("other must be an OutputTrackGroup.");if(this===t)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(t),t._pairedGroups.add(this)}}const Qe=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&(t=i.languageCode,!Aa.test(t)))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");var t;if(i.name!==void 0&&typeof i.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(i.disposition!==void 0&&(e=>{if(!e||typeof e!="object")throw new TypeError("disposition must be an object.");if(e.default!==void 0&&typeof e.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(e.primary!==void 0&&typeof e.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(e.forced!==void 0&&typeof e.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(e.original!==void 0&&typeof e.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(e.commentary!==void 0&&typeof e.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(i.disposition),i.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(i.group!==void 0&&!(i.group instanceof Kt)&&(!Array.isArray(i.group)||i.group.some(e=>!(e instanceof Kt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class Wo extends Ii{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(t);const e=this._getRootTarget();if(e instanceof Promise)throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new Kt,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new ki,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.format instanceof je))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof _t||t.target instanceof Ue))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof _t&&this._rememberTarget(t.target),t.initTarget!==void 0&&!(t.initTarget instanceof _t)&&typeof t.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(t.onFinalize!==void 0&&typeof t.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this._target=t.target,this._onFinalize=t.onFinalize??null,this._initTarget=t.initTarget??null,this._initTarget instanceof _t&&this._rememberTarget(this._initTarget),this._muxer=t.format._createMuxer(this)}_getTargetValidated(t){g(this._target instanceof Ue);const e=this._target.getTarget(t),r=a=>{if(!(a instanceof _t))throw new TypeError("getTarget must return a Target.");return a};return e instanceof Promise?e.then(r):r(e)}async _getTarget(t){g(this._target instanceof Ue);const e=await this._getTargetValidated(t);return this._emit("target",{target:e,request:t,isRoot:t.isRoot}),this.state==="canceled"?await e._close():this._rememberTarget(e),e}_rememberTarget(t){this._unfinalizedTargets.add(t),t.on("finalized",()=>this._unfinalizedTargets.delete(t),{once:!0})}async _getInitTarget(){if(g(this._initTarget!==null),this._initTarget instanceof _t)return this._initTarget;const t=await this._initTarget();return this.state==="canceled"?await t._close():this._rememberTarget(t),t}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof _t)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const t={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},e=this._getTargetValidated(t),r=a=>(this.state==="canceled"?a._close():this._rememberTarget(a),this._emit("target",{target:a,request:t,isRoot:!0}),this._rootTarget=a,a);return e instanceof Promise?this._rootTargetPromise=e.then(r):r(e)}_getRootWriter(t){return this._rootWriterPromise??(this._rootWriterPromise=(async()=>{const e=await this._getRootTarget(),r=new ze(e,typeof t=="boolean"?t:t(e));return r.start(),r})())}addVideoTrack(t,e={}){if(!(t instanceof Mr))throw new TypeError("source must be a VideoSource.");if(Qe(e),e.rotation!==void 0&&![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._name} does not support video rotation metadata.`);if(e.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.frameRate}. Must be a positive number.`);const r={...e};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Ro(this._tracks.length+1,this,t,r))}addAudioTrack(t,e={}){if(!(t instanceof Ao))throw new TypeError("source must be an AudioSource.");Qe(e);const r={...e};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Vo(this._tracks.length+1,this,t,r))}addSubtitleTrack(t,e={}){if(!(t instanceof Fo))throw new TypeError("source must be a SubtitleSource.");Qe(e);const r={...e};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Lo(this._tracks.length+1,this,t,r))}setMetadataTags(t){if((e=>{if(!e||typeof e!="object")throw new TypeError("tags must be an object.");if(e.title!==void 0&&typeof e.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(e.description!==void 0&&typeof e.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(e.artist!==void 0&&typeof e.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(e.album!==void 0&&typeof e.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(e.albumArtist!==void 0&&typeof e.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(e.genre!==void 0&&typeof e.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(e.lyrics!==void 0&&typeof e.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(e.images!==void 0){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const r of e.images){if(!r||typeof r!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(r.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof r.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(r.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(e.comment!==void 0&&typeof e.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(e.raw!==void 0){if(!e.raw||typeof e.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const r of Object.values(e.raw))if(!(r===null||typeof r=="string"||r instanceof Uint8Array||r instanceof Ai||r instanceof Fi||Wa(r)))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}})(t),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=t}_addTrack(t){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t.source._connectedTrack)throw new Error("Source is already used for a track.");const e=this.format.getSupportedTrackCounts(),r=this._tracks.reduce((o,n)=>o+(n.type===t.type?1:0),0),a=e[t.type].max;if(r===a)throw new Error(a===0?`${this.format._name} does not support ${t.type} tracks.`:`${this.format._name} does not support more than ${a} ${t.type} track`+(a===1?"":"s")+".");const s=e.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks`+(s===1?"":"s")+" in total.");if(t.isVideoTrack()){const o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(n=>`'${n}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isAudioTrack()){const o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(n=>`'${n}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isSubtitleTrack()){const o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(n=>`'${n}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}return this._tracks.push(t),t.source._connectedTrack=t,t}async start(){const t=this.format.getSupportedTrackCounts();for(const r of Do){const a=this._tracks.reduce((o,n)=>o+(n.type===r?1:0),0),s=t[r].min;if(a<s)throw new Error(s===t[r].max?`${this.format._name} requires exactly ${s} ${r} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${r} track${s===1?"":"s"}.`)}const e=t.total.min;if(this._tracks.length<e)throw new Error(e===t.total.max?`${this.format._name} requires exactly ${e} track`+(e===1?"":"s")+".":`${this.format._name} requires at least ${e} track`+(e===1?"":"s")+".");if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const r=await this._mutex.acquire();try{await this._muxer.start();const a=this._tracks.map(s=>s.source._start());await Promise.all(a)}finally{r()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):this.state!=="finalizing"&&this.state!=="finalized"?this._cancelPromise=(async()=>{this.state="canceled";const t=await this._mutex.acquire();try{const e=this._tracks.map(r=>r.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(r=>r._close())),this._unfinalizedTargets.clear()}finally{t()}})():void(this.state==="finalized"&&console.warn("Output has already been finalized."))}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const t=await this._mutex.acquire();try{const e=this._tracks.map(r=>r.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){const r=await this._rootWriterPromise;r.finalized||(await r.flush(),await r.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{t()}})()}}const Oo=["vp9","vp8"],$o=["avc"];class zo{async $record(t,e,r){this._throwIfAborted(t.signal),this._assertWebCodecsAvailable();const a=await this._createEncodingPlan(t);this._log(t,"video export plan",a),this._emitProgress(r,"recording","probing",0,a.frameCount);const s=a.format==="mp4"?new Ge:new fe,o=new pe,n=new Wo({format:s,target:o}),l=new Io(e.canvas,{codec:a.codec,bitrate:a.bitrate,alpha:a.transparent?"keep":"discard",bitrateMode:a.bitrateMode,latencyMode:a.latencyMode,hardwareAcceleration:a.hardwareAcceleration,keyFrameInterval:a.keyFrameInterval,sizeChangeBehavior:"deny"});n.addVideoTrack(l);try{if(await n.start(),await e.$render({frameCount:a.frameCount,frameRate:a.frameRate,signal:t.signal,onFrame:async({frameIndex:c})=>{this._throwIfAborted(t.signal),await l.add(c/a.frameRate,1/a.frameRate),this._emitProgress(r,"recording","rendering",c+1,a.frameCount)}}),this._throwIfAborted(t.signal),this._emitProgress(r,"encoding","finalizing",a.frameCount,a.frameCount),await n.finalize(),this._emitProgress(r,"completed","finalizing",a.frameCount,a.frameCount),!o.buffer)throw new Mt("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:a.mimeType})}catch(c){const d=this._normalizeError(c);throw r==null||r({state:"error",message:d.message}),d}}async _createEncodingPlan(t){if(t.format==="mp4"&&t.transparent)throw new Mt("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const e=Math.max(1,Math.round(t.width)),r=Math.max(1,Math.round(t.height)),a=this._resolveBitrate(t.bitrate,e,r,t.frameRate),s=t.format==="mp4"?new Ge:new fe,o=t.format==="mp4"?$o:Oo,n=s.getSupportedVideoCodecs().filter(c=>o.includes(c)),l=await(async(c,d)=>{for(const u of c)if(await gs(u,d))return u;return null})(n,{width:e,height:r,bitrate:a});if(!l){const c=o.join(" or ");throw new Mt("VIDEO_CODEC_UNSUPPORTED",`This browser cannot encode ${c} at ${e}x${r}. Try a browser/device with native WebCodecs encoding support or reduce the export dimensions.`)}return{format:t.format,extension:t.format==="mp4"?".mp4":".webm",mimeType:s.mimeType,codec:l,bitrate:a,bitrateMode:t.bitrateMode,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,keyFrameInterval:t.keyFrameInterval,frameRate:t.frameRate,frameCount:t.frameCount,width:e,height:r,transparent:t.transparent}}_assertWebCodecsAvailable(){const t=globalThis;if(typeof t.VideoEncoder!="function"||typeof t.VideoFrame!="function")throw new Mt("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}_resolveBitrate(t,e,r,a){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.round(t);const s=typeof t=="string"?t:"medium",o=e*r,n=Math.max(.5,a/60),l=s==="high"?6:s==="low"?1.5:3;return Math.max(25e4,Math.round(o*n*l))}_throwIfAborted(t){if(t!=null&&t.aborted)throw bi()}_emitProgress(t,e,r,a,s){t==null||t({state:e,phase:r,frameIndex:a,frame:a,totalFrames:s,progress:s>0?a/s:0})}_normalizeError(t){return t instanceof Mt?t:new Mt("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}_log(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}}class No{constructor(t,e){w(this,"_recorder");w(this,"_textmodifier");w(this,"_registerPostDrawHook");this._recorder=new zo,this._textmodifier=t,this._registerPostDrawHook=e}async $saveVideo(t={}){await this._saveVideo(t.format??"mp4",t)}async _saveVideo(t,e){var s;const r=this._applyDefaultOptions(t,e),a=new Pa(this._textmodifier,this._registerPostDrawHook,r.width,r.height);try{const o=await this._recorder.$record(r,a,e.onProgress);new ot().$downloadFile(o,this._withExtension(r.filename,`.${t}`))}catch(o){throw(s=e.onProgress)==null||s.call(e,{state:"error",message:o instanceof Error?o.message:`${t.toUpperCase()} export failed`}),o}}_applyDefaultOptions(t,e){const r=this._positiveInteger(e.frameRate,60),a=this._positiveInteger(e.frameCount,300),s=this._positiveNumber(e.pixelDensity,1),o=this._currentPixelDensity(),n=Math.max(1,Math.round(this._textmodifier.canvas.width/o*s)),l=Math.max(1,Math.round(this._textmodifier.canvas.height/o*s));return{filename:e.filename,format:t,frameRate:r,frameCount:a,bitrate:this._bitrate(e.bitrate),bitrateMode:this._bitrateMode(e.bitrateMode),latencyMode:this._latencyMode(e.latencyMode),hardwareAcceleration:this._hardwareAcceleration(e.hardwareAcceleration),keyFrameInterval:this._keyFrameInterval(e.keyFrameInterval),pixelDensity:s,width:n,height:l,transparent:!!e.transparent,debugLogging:!!e.debugLogging,signal:e.signal}}_positiveInteger(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}_positiveNumber(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}_bitrate(t){return typeof t=="number"&&Number.isFinite(t)&&t>0||t==="low"||t==="medium"||t==="high"?t:"medium"}_bitrateMode(t){return t==="constant"||t==="variable"?t:"variable"}_latencyMode(t){return t==="quality"||t==="realtime"?t:"quality"}_hardwareAcceleration(t){return t==="prefer-hardware"||t==="prefer-software"||t==="no-preference"?t:"no-preference"}_keyFrameInterval(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}_currentPixelDensity(){var r;const t=this._textmodifier,e=(r=t.pixelDensity)==null?void 0:r.call(t);return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}_withExtension(t,e){if(!t)return;const r=t.trim();return r?r.toLowerCase().endsWith(e)?r:`${r}${e}`:void 0}}class Uo extends K{$extractCellData(t){var n;const e=this.$extractFramebufferData(t.drawFramebuffer),r=[],a=t.grid,s=t.font;let o=0;for(let l=0;l<a.rows;l++)for(let c=0;c<a.cols;c++){const d=4*o,u=this.$getEncodedCharacterValue(e.characterPixels,d),p=this.$extractCellTransform(e.characterPixels,d),h=((n=we(s,u))==null?void 0:n.character)??" ";r.push({x:c,y:l,character:h,foreground:te(e.primaryColorPixels,d),background:te(e.secondaryColorPixels,d),transform:{invert:p.isInverted,flipX:p.flipHorizontal,flipY:p.flipVertical,rotation:p.rotation}}),o++}return r}}const Vr="1.2.1",Lr="textmode.document",Wr="2.0.0";class Xe{_applyDefaultOptions(t){return{target:t.target??"selected",pretty:t.pretty??!0,colorMode:t.colorMode??"hex",includeMetadata:t.includeMetadata??!0,filename:t.filename,layer:t.layer}}_createMetadata(t){return t.includeMetadata?{createdAt:new Date().toISOString(),generator:{name:"textmode.export.js",version:Vr}}:void 0}_formatColor(t,e){return e==="rgba"?{...t}:`#${[t.r,t.g,t.b,t.a].map(r=>r.toString(16).padStart(2,"0")).join("")}`}_createObjectRowsCells(t,e,r,a){const s=[];for(let o=0;o<r;o++){const n=o*e,l=t.slice(n,n+e).map(c=>({x:c.x,y:c.y,character:c.character,foreground:this._formatColor(c.foreground,a),background:this._formatColor(c.background,a),transform:{...c.transform}}));s.push(l)}return{encoding:"object-rows-v1",rows:s}}_createLayerGrid(t){return{cols:t.grid.cols,rows:t.grid.rows,cellWidth:t.grid.cellWidth,cellHeight:t.grid.cellHeight}}_createLayerCells(t,e){const r=new Uo().$extractCellData(t);return this._createObjectRowsCells(r,t.grid.cols,t.grid.rows,e.colorMode)}_createStackLayer(t,e){return{id:t.id,visible:t.visible,opacity:t.opacity,blendMode:t.blendMode,offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this._createLayerGrid(t),cells:this._createLayerCells(t,e)}}$generateJSONData(t,e={}){const r=this._applyDefaultOptions(e),a=this._createMetadata(r);if(r.target==="all"){const o=(function(l){return[l.layers.base,...l.layers.all].map(c=>{const d=c;return{...Zt(l,c),visible:d._visible??!0,opacity:d._opacity??1,blendMode:d._blendMode??"normal",offsetX:d._offsetX??0,offsetY:d._offsetY??0,rotationZ:d._rotation??0}})})(t),n=o[0].grid;return{format:Lr,formatVersion:Wr,target:"all",...a?{metadata:a}:{},canvas:{width:n.width,height:n.height},layers:o.map(l=>this._createStackLayer(l,r))}}const s=Zt(t,r.layer);return{format:Lr,formatVersion:Wr,target:"selected",...a?{metadata:a}:{},canvas:{width:s.grid.width,height:s.grid.height},grid:this._createLayerGrid(s),layer:{id:s.id,cells:this._createLayerCells(s,r)}}}$generateJSONString(t,e={}){const r=this._applyDefaultOptions(e),a=this.$generateJSONData(t,r),s=typeof r.pretty=="number"?r.pretty:r.pretty?2:0;return JSON.stringify(a,null,s)}$saveJSON(t,e={}){const r=this._applyDefaultOptions(e);new ot().$downloadFile(new Blob([this.$generateJSONString(t,r)],{type:"application/json;charset=utf-8"}),r.filename)}}const Ho="textmode-export-overlay",ht="textmode-export-overlay__stack",Ke="textmode-export-overlay__stack--dense",Or="textmode-export-overlay__stack--compact",$r="textmode-export-overlay__section",jo="textmode-export-overlay__header",qo="textmode-export-overlay__header-title-row",Go="textmode-export-overlay__header-links",Qo="textmode-export-overlay__row",zr="textmode-export-overlay__label",Nr="textmode-export-overlay__field",Ur="textmode-export-overlay__field--compact",Hr="textmode-export-overlay__field--dense",jr="textmode-export-overlay__field--full",qr="textmode-export-overlay__field--channel",Gr="textmode-export-overlay__input",Xo="textmode-export-overlay__checkbox",Qr="textmode-export-overlay__muted",Ko="textmode-export-overlay__status",Yo="textmode-export-overlay__status--gif",Jo="textmode-export-overlay__status--video",Zo="textmode-export-overlay__status-title",tn="textmode-export-overlay__status-value",en="textmode-export-overlay__divider",rn="textmode-export-overlay__title",an="textmode-export-overlay__button",Ye="textmode-export-overlay__button--primary",Je="textmode-export-overlay__button--secondary",Xr="textmode-export-overlay__button--full",sn="textmode-export-overlay__support-link",on="textmode-export-overlay__support-icon",nn="textmode-export-overlay__link-icon";class ut{constructor(){w(this,"element");w(this,"mounted",!1);w(this,"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._onUnmount(),this.element.remove(),this.element=void 0,this.mounted=!1)}destroy(){this.destroyed||(this.unmount(),this._onDestroy(),this.destroyed=!0)}update(t){this.mounted&&this.onUpdate(t)}onMount(){}_onUnmount(){}_onDestroy(){}onUpdate(t){}get root(){if(!this.element)throw new Error("Component is not mounted yet");return this.element}isMounted(){return this.mounted}}const Ot=class Ot extends ut{render(){const t=document.createElement("div");t.classList.add(ht,Ke,jo);const e=document.createElement("div");e.classList.add(qo);const r=document.createElement("strong");r.textContent="textmode.export.js",r.classList.add(rn);const a=document.createElement("div");a.classList.add(Go);const s=this._createLink("https://github.com/humanbydefinition/textmode.export.js","View repository on GitHub",nn,[{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"}]),o=this._createLink("https://code.textmode.art/docs/support","Support textmode.export.js",on,[{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"}]);a.appendChild(s),a.appendChild(o),e.appendChild(r),e.appendChild(a);const n=document.createElement("div");return n.classList.add(en),t.appendChild(e),t.appendChild(n),t}_createLink(t,e,r,a){const s=document.createElement("a");return s.href=t,s.target="_blank",s.rel="noopener noreferrer",s.classList.add(sn),s.setAttribute("aria-label",e),s.appendChild(this._createIcon(r,a)),s}_createIcon(t,e){const r=document.createElementNS(Ot._iconNamespace,"svg");r.setAttribute("xmlns",Ot._iconNamespace),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(t);for(const a of e){const s=document.createElementNS(Ot._iconNamespace,"path");for(const[o,n]of Object.entries(a))s.setAttribute(o,n);r.appendChild(s)}return r}};w(Ot,"_iconNamespace","http://www.w3.org/2000/svg");let Ze=Ot;class H extends ut{constructor(e){super();w(this,"props");this.props=e}render(){const e=document.createElement("div");e.classList.add(Nr),this.applyVariant(e,this.props.variant);const r=document.createElement("label");if(r.classList.add(zr),r.textContent=this.props.label,this.props.labelFor&&(r.htmlFor=this.props.labelFor),e.appendChild(r),this.props.description){const a=document.createElement("span");a.classList.add(Qr),a.textContent=this.props.description,e.appendChild(a)}return e}attachControl(e){this.root.appendChild(e)}update(e){this.props=e,super.update(e)}onUpdate(e){const r=this.root;for(;r.firstChild;)r.removeChild(r.firstChild);this.props=e,r.classList.add(Nr),this.applyVariant(r,e.variant);const a=document.createElement("label");if(a.classList.add(zr),a.textContent=e.label,e.labelFor&&(a.htmlFor=e.labelFor),r.appendChild(a),e.description){const s=document.createElement("span");s.classList.add(Qr),s.textContent=e.description,r.appendChild(s)}}applyVariant(e,r){switch(e.classList.remove(Ur,Hr,jr,qr),r){case"compact":e.classList.add(Ur);break;case"dense":e.classList.add(Hr);break;case"full":e.classList.add(jr);break;case"channel":e.classList.add(qr)}}}class pt extends ut{constructor(e){super();w(this,"props");w(this,"select");w(this,"handleChange",()=>{this.props.defaultValue=this.select.value});this.props=e}render(){return this.select=document.createElement("select"),this.select.classList.add(Gr),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(e){this.select&&(this.select.value=e),this.props.defaultValue=e}_onUnmount(){this.select.removeEventListener("change",this.handleChange)}onUpdate(e){this.props=e,this.populateOptions(),e.defaultValue&&(this.select.value=e.defaultValue)}update(e){this.props={...this.props,...e},this.select&&(e.id&&(this.select.id=e.id),e.options&&this.populateOptions(),e.defaultValue!==void 0&&(this.select.value=e.defaultValue))}populateOptions(){if(this.select){this.select.innerHTML="";for(const e of this.props.options){const r=document.createElement("option");r.value=e.value,r.textContent=e.label,this.select.appendChild(r)}this.props.defaultValue&&(this.select.value=this.props.defaultValue)}}}class Kr extends ut{constructor(e){super();w(this,"props");w(this,"button");this.props=e}render(){return this.button=document.createElement("button"),this.button.type="button",this.button.textContent=this.props.label,this.button.classList.add(an),this.props.variant==="secondary"?this.button.classList.add(Je):this.button.classList.add(Ye),this.props.fullWidth&&this.button.classList.add(Xr),this.button.disabled=!!this.props.disabled,this.button}get buttonElement(){return this.button}setLabel(e){this.props.label=e,this.button.textContent=e}setDisabled(e){this.props.disabled=e,this.button.disabled=e}onUpdate(e){this.props=e,this.button.textContent=e.label,this.button.disabled=!!e.disabled,e.variant==="secondary"?(this.button.classList.add(Je),this.button.classList.remove(Ye)):(this.button.classList.add(Ye),this.button.classList.remove(Je)),this.button.classList.toggle(Xr,!!e.fullWidth)}}class cn{constructor(t){w(this,"api");this.api=t}async $copy(t,e){switch(t){case"txt":{const r=this.api.toString(e);await navigator.clipboard.writeText(r);break}case"json":{const r=this.api.toJSONString(e);await navigator.clipboard.writeText(r);break}case"svg":{const r=this.api.toSVG(e);await navigator.clipboard.writeText(r);break}case"image":await this.api.copyCanvas(e);break;default:throw new Error(`Clipboard not supported for ${t}`)}}}class dn{constructor(t,e){w(this,"api");w(this,"events");this.api=t,this.events=e}async $requestExport(t,e,r={}){this.events.$emit("export:request",{format:t});try{const a={onGIFProgress:r.onGIFProgress?s=>{var o;(o=r.onGIFProgress)==null||o.call(r,s),this.events.$emit("export:progress",{format:t,progress:s})}:t==="gif"?s=>this.events.$emit("export:progress",{format:t,progress:s}):void 0,onVideoProgress:r.onVideoProgress?s=>{var o;(o=r.onVideoProgress)==null||o.call(r,s),this.events.$emit("export:progress",{format:t,progress:s})}:t==="video"?s=>this.events.$emit("export:progress",{format:t,progress:s}):void 0};await this._execute(t,e,a),this.events.$emit("export:success",{format:t})}catch(a){throw this.events.$emit("export:error",{format:t,error:a}),a}}_execute(t,e,r){switch(t){case"txt":return Promise.resolve(this.api.saveStrings(e));case"json":return Promise.resolve(this.api.saveJSON(e));case"image":return this.api.saveCanvas(e);case"svg":return Promise.resolve(this.api.saveSVG(e));case"gif":{const a={...e,onProgress:r.onGIFProgress};return this.api.saveGIF(a)}case"video":{const a={...e,onProgress:r.onVideoProgress};return this.api.saveVideo(a)}}}}class ln{constructor(t,e){w(this,"modifier");w(this,"overlay");w(this,"animationFrameId",null);w(this,"handleUpdate");w(this,"bound",!1);this.modifier=t,this.overlay=e,this.handleUpdate=()=>this.scheduleUpdate()}scheduleUpdate(){this.animationFrameId!==null&&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())}update(){this.animationFrameId=null;const t=this.modifier.canvas.getBoundingClientRect();this.overlay.style.top=`${t.top+window.scrollY+8}px`,this.overlay.style.left=`${t.left+window.scrollX+8}px`}dispose(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.bound&&(window.removeEventListener("resize",this.handleUpdate),window.removeEventListener("scroll",this.handleUpdate,!0),this.bound=!1)}}const Yt="textmode-export-number-input",hn=`${Yt}__field`,un=`${Yt}__controls`,pn=`${Yt}__control`,Yr=`${Yt}__display`,ge=`${Yr}--visible`,Jr=i=>{const t=document.createElement("button");return t.type="button",t.className=pn,t.textContent=i>0?"▲":"▼",t};class kt extends ut{constructor(e){super();w(this,"props");w(this,"input");w(this,"display");w(this,"incrementButton");w(this,"decrementButton");w(this,"suppressClickAfterPointer",new WeakMap);w(this,"holdTimeoutId");w(this,"holdIntervalId");w(this,"activePointerId");w(this,"disabledObserver");this.props=e}render(){const e=document.createElement("div");e.className=Yt,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=hn,this.display=document.createElement("div"),this.display.className=Yr;const r=document.createElement("div");return r.className=un,this.incrementButton=Jr(1),this.decrementButton=Jr(-1),r.appendChild(this.incrementButton),r.appendChild(this.decrementButton),e.appendChild(this.input),e.appendChild(this.display),e.appendChild(r),this.bindStepControls(),this.bindHoldBehavior(),this.bindInputListeners(),this.observeDisabledState(e),this.updateDisplay(),e}get inputElement(){return this.input}get value(){return this.input.value}set value(e){this.input.value=e,this.updateDisplay()}refresh(){this.updateDisplay()}_onDestroy(){var e;this.clearHoldTimers(),(e=this.disabledObserver)==null||e.disconnect()}bindStepControls(){const e=o=>()=>{if(this.input.disabled)return;const n=this.input.value,l=this.input.getAttribute("step");if(l&&l!=="any")o>0?this.input.stepUp():this.input.stepDown();else{const d=o>0?1:-1,u=Number.parseFloat(this.input.value||"0"),p=Number.isFinite(u)?u+d:d;this.input.value=String(p)}var c;this.input.value!==n&&((c=this.input).dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0}))),this.updateDisplay(),this.input.focus({preventScroll:!0})},r=e(1),a=e(-1),s=(o,n)=>l=>{if(this.suppressClickAfterPointer.get(o))return this.suppressClickAfterPointer.set(o,!1),void l.preventDefault();n()};this.incrementButton.addEventListener("click",s(this.incrementButton,r)),this.decrementButton.addEventListener("click",s(this.decrementButton,a))}bindHoldBehavior(){const e=(r,a)=>{const s=a>0?()=>this.incrementButton.click():()=>this.decrementButton.click();r.addEventListener("pointerdown",l=>{if(l.button===0){l.preventDefault(),this.suppressClickAfterPointer.set(r,!0),this.activePointerId=l.pointerId;try{r.setPointerCapture(l.pointerId)}catch{}s(),this.holdTimeoutId=window.setTimeout(()=>{this.holdIntervalId=window.setInterval(s,80)},380)}});const o=()=>{if(this.activePointerId!==void 0){try{r.releasePointerCapture(this.activePointerId)}catch{}this.activePointerId=void 0}},n=()=>{this.clearHoldTimers(),o()};r.addEventListener("pointerup",n),r.addEventListener("pointerleave",n),r.addEventListener("pointercancel",n)};e(this.incrementButton,1),e(this.decrementButton,-1)}bindInputListeners(){const e=()=>{this.props.defaultValue=this.input.value,this.updateDisplay()};this.input.addEventListener("input",e),this.input.addEventListener("change",e)}observeDisabledState(e){const r=()=>{const a=this.input.disabled;this.incrementButton.disabled=a,this.decrementButton.disabled=a,e.classList.toggle("is-disabled",a),a?(this.display.classList.remove(ge),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor")):this.updateDisplay()};typeof MutationObserver<"u"&&(this.disabledObserver=new MutationObserver(r),this.disabledObserver.observe(this.input,{attributes:!0,attributeFilter:["disabled"]})),r()}updateDisplay(){const e=this.props.formatDisplay;if(!e)return this.display.textContent="",this.display.classList.remove(ge),this.input.style.removeProperty("color"),void this.input.style.removeProperty("caretColor");const r=this.input.value,a=Number.parseFloat(r),s=e(Number.isFinite(a)?a:Number.NaN,r,this.input);s?(this.display.textContent=s,this.display.classList.add(ge),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(ge),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor"))}clearHoldTimers(){this.holdTimeoutId!==void 0&&(window.clearTimeout(this.holdTimeoutId),this.holdTimeoutId=void 0),this.holdIntervalId!==void 0&&(window.clearInterval(this.holdIntervalId),this.holdIntervalId=void 0)}}class Bt extends ut{constructor(e="stack",r=[]){super();w(this,"variant");w(this,"additionalClasses");this.variant=e,this.additionalClasses=r}render(){const e=document.createElement("div"),r=[this.variant==="stack"?ht:void 0,this.variant==="stackDense"?Ke:void 0,this.variant==="stackCompact"?Or:void 0,this.variant==="row"?Qo:void 0,this.variant==="section"?$r:void 0,...this.additionalClasses].filter(Boolean);return e.classList.add(...r),e}}const Zr={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"};class ta extends ut{constructor(e){super();w(this,"props");w(this,"container");w(this,"messageElement");this.props=e}render(){this.container=document.createElement("div"),this.container.classList.add(Ko),this.props.context==="gif"?this.container.classList.add(Yo):this.props.context==="video"&&this.container.classList.add(Jo);const e=document.createElement("span");return e.classList.add(Zo),e.textContent=this.props.title,this.messageElement=document.createElement("span"),this.messageElement.classList.add(tn),this.messageElement.textContent=this.props.message,this.applyVariant(this.props.variant??"neutral"),this.container.appendChild(e),this.container.appendChild(this.messageElement),this.container}setMessage(e,r="neutral"){this.messageElement.textContent=e,this.applyVariant(r)}onUpdate(e){this.props=e,this.setMessage(e.message,e.variant??"neutral")}applyVariant(e){this.messageElement.classList.remove(...Object.values(Zr)),this.messageElement.classList.add(Zr[e])}}class Wt extends ut{constructor(e){super();w(this,"_config");w(this,"_managedComponents",new Set);this._config=e}_manageComponent(e){return this._managedComponents.add(e),e}_onUnmount(){for(const e of this._managedComponents)e.unmount()}_onDestroy(){for(const e of this._managedComponents)e.destroy();this._managedComponents.clear()}}const ea=300,ia=60,ra=1,mn=0;class ti extends Wt{constructor(e){super(e);w(this,"frameCountInput",this._manageComponent(new kt({defaultValue:String(ea),attributes:{min:"1",max:"600",step:"1"}})));w(this,"frameRateInput",this._manageComponent(new kt({defaultValue:String(ia),attributes:{min:"1",max:"60",step:"1"}})));w(this,"scaleInput",this._manageComponent(new kt({defaultValue:String(ra),attributes:{min:"0.1",max:"8",step:"0.1"}})));w(this,"repeatInput",this._manageComponent(new kt({defaultValue:"0",attributes:{min:"0",max:"50",step:"1"},formatDisplay:(e,r)=>Number.isFinite(e)?e===0?"∞":null:r.trim()===""?null:r})));w(this,"status",this._manageComponent(new ta({title:"status",message:"ready to record",variant:"neutral",context:"gif"})));w(this,"recordingState","idle")}render(){const e=document.createElement("div");e.classList.add(ht);const r=new Bt("row");r.mount(e);const a=new H({label:"number of frames",labelFor:"textmode-export-gif-frame-count",variant:"dense"});a.mount(r.root),this.frameCountInput.mount(a.root),this.frameCountInput.inputElement.id="textmode-export-gif-frame-count";const s=new H({label:"frame rate (fps)",labelFor:"textmode-export-gif-frame-rate",variant:"dense"});s.mount(r.root),this.frameRateInput.mount(s.root),this.frameRateInput.inputElement.id="textmode-export-gif-frame-rate";const o=new Bt("row");o.mount(e);const n=new H({label:"scale",labelFor:"textmode-export-gif-scale",variant:"dense"});n.mount(o.root),this.scaleInput.mount(n.root),this.scaleInput.inputElement.id="textmode-export-gif-scale";const l=new H({label:"loop count",labelFor:"textmode-export-gif-repeat",variant:"dense"});return l.mount(o.root),this.repeatInput.mount(l.root),this.repeatInput.inputElement.id="textmode-export-gif-repeat",this.status.mount(e),e}getOptions(){const e=this._config.defaultOptions??{};return{frameCount:this.safeParseInt(this.frameCountInput.value,e.frameCount??300),frameRate:this.safeParseInt(this.frameRateInput.value,e.frameRate??60),scale:this.safeParseFloat(this.scaleInput.value,e.scale??1),repeat:this.safeParseInt(this.repeatInput.value,e.repeat??0)}}reset(){this.recordingState="idle",this.applyDefaults(),this.setRecordingState("idle")}validate(){const e=Number.parseInt(this.frameCountInput.value,10),r=Number.parseInt(this.frameRateInput.value,10),a=Number.parseFloat(this.scaleInput.value);return Number.isFinite(e)&&e>0&&Number.isFinite(r)&&r>0&&Number.isFinite(a)&&a>0}isRecording(){return this.recordingState==="recording"||this.recordingState==="encoding"}setRecordingState(e,r){this.recordingState=e;const a=e==="recording"||e==="encoding";switch(this.frameCountInput.inputElement.disabled=a,this.frameRateInput.inputElement.disabled=a,this.scaleInput.inputElement.disabled=a,this.repeatInput.inputElement.disabled=a,e){case"recording":if(r!=null&&r.totalFrames){const s=r.frameIndex??0;this.status.setMessage(`recording ${s}/${r.totalFrames}`,"active")}else this.status.setMessage("recording…","active");break;case"encoding":if(r!=null&&r.totalFrames){const s=r.frameIndex??0;this.status.setMessage(`encoding ${s}/${r.totalFrames}`,"active")}else this.status.setMessage("encoding…","active");break;case"completed":this.status.setMessage("GIF saved successfully","active");break;case"error":this.status.setMessage((r==null?void 0:r.message)??"failed to export GIF","alert");break;default:this.status.setMessage("ready to record","neutral")}}handleProgress(e){if(e.state!=="recording"&&e.state!=="encoding"||!e.totalFrames)e.state==="completed"?this.status.setMessage("GIF saved successfully","active"):e.state==="error"&&this.status.setMessage(e.message??"failed to export GIF","alert");else{const r=e.state==="recording"?"recording":"encoding";this.status.setMessage(`${r} ${e.frameIndex??0}/${e.totalFrames}`,"active")}}applyDefaults(){const e=this._config.defaultOptions??{},r=e.frameCount??ea,a=e.frameRate??ia,s=e.scale??ra,o=e.repeat??mn;this.frameCountInput.value=String(r),this.frameRateInput.value=String(a),this.scaleInput.value=String(s),this.repeatInput.value=String(o),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.scaleInput.refresh(),this.repeatInput.refresh()}safeParseInt(e,r){const a=Number.parseInt(e,10);return Number.isFinite(a)?a:r}safeParseFloat(e,r){const a=Number.parseFloat(e);return Number.isFinite(a)?a:r}}class Jt extends ut{constructor(e){super();w(this,"props");w(this,"checkbox");w(this,"labelElement");w(this,"handleChange",()=>{this.props.defaultChecked=this.checkbox.checked});this.props=e}render(){this.labelElement=document.createElement("label"),this.labelElement.classList.add(Xo),this.checkbox=document.createElement("input"),this.checkbox.type="checkbox",this.props.id&&(this.checkbox.id=this.props.id),this.checkbox.checked=!!this.props.defaultChecked,this.checkbox.addEventListener("change",this.handleChange);const e=document.createElement("span");return e.textContent=this.props.label,this.labelElement.htmlFor=this.props.id??"",this.labelElement.appendChild(this.checkbox),this.labelElement.appendChild(e),this.labelElement}get inputElement(){return this.checkbox}get checked(){return this.checkbox.checked}set checked(e){this.checkbox.checked=e}_onUnmount(){this.checkbox.removeEventListener("change",this.handleChange)}onUpdate(e){this.props=e,e.id&&(this.checkbox.id=e.id,this.labelElement.htmlFor=e.id),this.checkbox.checked=!!e.defaultChecked,this.labelElement.lastElementChild&&(this.labelElement.lastElementChild.textContent=e.label)}}const aa="medium",sa="variable",oa="quality",na="no-preference";class ei extends Wt{constructor(e){super(e);w(this,"formatSelect",this._manageComponent(new pt({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"})));w(this,"bitrateSelect",this._manageComponent(new pt({id:"textmode-export-video-bitrate",options:[{value:"low",label:"low"},{value:"medium",label:"medium"},{value:"high",label:"high"}],defaultValue:aa})));w(this,"frameRateInput",this._manageComponent(new kt({defaultValue:String(60),attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:e=>Number.isFinite(e)?`${e} fps`:null})));w(this,"frameCountInput",this._manageComponent(new kt({defaultValue:String(480),attributes:{min:String(1),max:String(3600),step:"1"}})));w(this,"bitrateModeSelect",this._manageComponent(new pt({id:"textmode-export-video-bitrate-mode",options:[{value:"variable",label:"variable"},{value:"constant",label:"constant"}],defaultValue:sa})));w(this,"latencyModeSelect",this._manageComponent(new pt({id:"textmode-export-video-latency-mode",options:[{value:"quality",label:"quality"},{value:"realtime",label:"realtime"}],defaultValue:oa})));w(this,"hardwareAccelerationSelect",this._manageComponent(new pt({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:na})));w(this,"keyFrameIntervalInput",this._manageComponent(new kt({defaultValue:String(2),attributes:{min:"0",step:"0.25"},formatDisplay:e=>Number.isFinite(e)?`${e}s`:null})));w(this,"transparencyInput",this._manageComponent(new Jt({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1})));w(this,"status",this._manageComponent(new ta({title:"status",message:"ready to record",variant:"neutral",context:"video"})));w(this,"recordingState","idle");w(this,"handleFormatChange",()=>{this.syncTransparencyAvailability()})}render(){const e=document.createElement("div");e.classList.add(ht);const r=new Bt("row");r.mount(e);const a=new H({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});a.mount(r.root),this.formatSelect.mount(a.root);const s=new H({label:"bitrate preset",labelFor:"textmode-export-video-bitrate",variant:"compact"});s.mount(r.root),this.bitrateSelect.mount(s.root);const o=new Bt("row");o.mount(e);const n=new H({label:"number of frames",labelFor:"textmode-export-video-frame-count",variant:"compact"});n.mount(o.root),this.frameCountInput.mount(n.root),this.frameCountInput.inputElement.id="textmode-export-video-frame-count";const l=new H({label:"frame rate (fps)",labelFor:"textmode-export-video-frame-rate",variant:"compact"});l.mount(o.root),this.frameRateInput.mount(l.root),this.frameRateInput.inputElement.id="textmode-export-video-frame-rate";const c=new Bt("row");c.mount(e);const d=new H({label:"bitrate mode",labelFor:"textmode-export-video-bitrate-mode",variant:"compact"});d.mount(c.root),this.bitrateModeSelect.mount(d.root);const u=new H({label:"encoder mode",labelFor:"textmode-export-video-latency-mode",variant:"compact"});u.mount(c.root),this.latencyModeSelect.mount(u.root);const p=new Bt("row");p.mount(e);const h=new H({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(p.root),this.hardwareAccelerationSelect.mount(h.root);const m=new H({label:"keyframe interval",labelFor:"textmode-export-video-keyframe-interval",variant:"compact"});return m.mount(p.root),this.keyFrameIntervalInput.mount(m.root),this.keyFrameIntervalInput.inputElement.id="textmode-export-video-keyframe-interval",this.transparencyInput.mount(e),this.formatSelect.selectElement.addEventListener("change",this.handleFormatChange),this.syncTransparencyAvailability(),this.status.mount(e),e}getOptions(){const e=this._config.defaultOptions??{},r=Number.parseInt(this.frameCountInput.value,10),a=Number.parseFloat(this.frameRateInput.value),s=Number.parseFloat(this.keyFrameIntervalInput.value),o=this.formatSelect.value,n={format:o,bitrate:this.bitrateSelect.value,bitrateMode:this.bitrateModeSelect.value,latencyMode:this.latencyModeSelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.isFinite(s)?s:e.keyFrameInterval??2,frameCount:Number.isFinite(r)?r:e.frameCount??480,frameRate:Number.isFinite(a)?a:e.frameRate??60};return o==="webm"&&(n.transparent=this.transparencyInput.checked),n}reset(){this.recordingState="idle",this.applyDefaults(),this.status.setMessage("ready to record","neutral")}validate(){const e=Number.parseInt(this.frameCountInput.value,10),r=Number.parseFloat(this.frameRateInput.value),a=Number.parseFloat(this.keyFrameIntervalInput.value);return Number.isFinite(e)&&e>=1&&Number.isFinite(r)&&r>=1&&Number.isFinite(a)&&a>=0}isRecording(){return this.recordingState==="recording"||this.recordingState==="encoding"}setRecordingState(e,r){this.recordingState=e;const a=e==="recording"||e==="encoding";this.formatSelect.selectElement.disabled=a,this.bitrateSelect.selectElement.disabled=a,this.frameCountInput.inputElement.disabled=a,this.frameRateInput.inputElement.disabled=a,this.bitrateModeSelect.selectElement.disabled=a,this.latencyModeSelect.selectElement.disabled=a,this.hardwareAccelerationSelect.selectElement.disabled=a,this.keyFrameIntervalInput.inputElement.disabled=a,this.transparencyInput.inputElement.disabled=a||this.formatSelect.value!=="webm",this.syncStatus(e,r)}handleProgress(e){this.syncStatus(e.state,e)}syncStatus(e,r){switch(e){case"recording":{const a=(r==null?void 0:r.frameIndex)??0,s=(r==null?void 0:r.totalFrames)??this.resolvePlannedFrameCount();if(s){const o=Math.min(Math.max(0,Math.round(a)),s);this.status.setMessage(`recording ${o}/${s} frames`,"active")}else this.status.setMessage(`recording ${Math.max(0,Math.round(a))} frames`,"active");break}case"encoding":this.status.setMessage("finalizing video","active");break;case"completed":this.status.setMessage("saved to disk","active");break;case"error":this.status.setMessage(r!=null&&r.message?`error: ${r.message}`:"recording failed","alert");break;default:this.status.setMessage("ready to record","neutral")}}resolvePlannedFrameCount(){const e=Number.parseInt(this.frameCountInput.value,10);return Number.isFinite(e)&&e>0?Math.round(e):void 0}applyDefaults(){const e=this._config.defaultOptions??{},r=e.format??"mp4",a=e.frameCount??480,s=e.frameRate??60,o=e.keyFrameInterval??2;this.formatSelect.value=r,this.bitrateSelect.value=this.resolveBitratePreset(e.bitrate),this.frameCountInput.value=String(a),this.frameRateInput.value=String(s),this.bitrateModeSelect.value=e.bitrateMode??sa,this.latencyModeSelect.value=e.latencyMode??oa,this.hardwareAccelerationSelect.value=e.hardwareAcceleration??na,this.keyFrameIntervalInput.value=String(o),this.transparencyInput.checked=!!e.transparent,this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.keyFrameIntervalInput.refresh(),this.syncTransparencyAvailability()}resolveBitratePreset(e){return e==="low"||e==="medium"||e==="high"?e:aa}syncTransparencyAvailability(){if(!this.transparencyInput.isMounted())return;const e=this.formatSelect.value==="webm";this.transparencyInput.root.style.display=e?"":"none",this.transparencyInput.inputElement.disabled=!e||this.isRecording(),e||(this.transparencyInput.checked=!1)}}class fn{constructor(t,e,r,a,s){w(this,"_textmodifier");w(this,"_state");w(this,"_events");w(this,"_exportService");w(this,"_clipboardService");w(this,"_definitions");w(this,"_formats",new Map);w(this,"_eventUnsubscribers",[]);w(this,"_shadowHost");w(this,"_shadowRoot");w(this,"_overlayElement");w(this,"_optionsContainer");w(this,"_copyButtonContainer");w(this,"_positionService");w(this,"_header",new Ze);w(this,"_formatField",new H({label:"export format",labelFor:"textmode-export-format",variant:"full"}));w(this,"_formatSelect",new pt({id:"textmode-export-format",options:[]}));w(this,"_exportButton",new Kr({label:"download file",fullWidth:!0,variant:"primary"}));w(this,"_copyButton",new Kr({label:"copy to clipboard",fullWidth:!0,variant:"primary"}));w(this,"_currentFormat");w(this,"_currentBlade");w(this,"_handleFormatSelectChange",()=>{this._handleFormatChange(this._formatSelect.value)});w(this,"_handleExportClickSafe",()=>{this._handleExportClick().catch(t=>{console.error("[textmode-export] Export failed",t)})});w(this,"_handleCopyClickSafe",()=>{this._handleCopyClick().catch(t=>{console.error("[textmode-export] Copy failed",t)})});this._textmodifier=t,this._state=r,this._events=a,this._exportService=new dn(e,a),this._clipboardService=new cn(e),this._definitions=s,this._currentFormat=r.snapshot.format,this._initializeFormatMap(),this._registerEventHandlers()}$mount(){this._createOverlay(),this._renderStaticContent(),this._positionService=new ln(this._textmodifier,this._shadowHost),this._positionService.bind(),this._switchFormat(this._currentFormat)}show(){this._shadowHost&&(this.refreshLayerTargets(),this._shadowHost.style.display="")}hide(){this._shadowHost&&(this._shadowHost.style.display="none")}toggle(){this.isVisible()?this.hide():this.show()}isVisible(){return!!this._shadowHost&&this._shadowHost.style.display!=="none"}refreshLayerTargets(){this._currentBlade&&typeof this._currentBlade.blade.refreshLayerTargets=="function"&&this._currentBlade.blade.refreshLayerTargets()}$dispose(){var t,e;this._formatSelect.isMounted()&&this._formatSelect.selectElement.removeEventListener("change",this._handleFormatSelectChange),this._exportButton.isMounted()&&this._exportButton.buttonElement.removeEventListener("click",this._handleExportClickSafe),this._copyButton.isMounted()&&this._copyButton.buttonElement.removeEventListener("click",this._handleCopyClickSafe);for(const r of this._eventUnsubscribers)r();this._eventUnsubscribers.length=0,this._events.$clear();for(const r of this._formats.values())r.blade.destroy();this._formats.clear(),this._currentBlade=void 0,(t=this._shadowHost)!=null&&t.isConnected&&this._shadowHost.remove(),(e=this._positionService)==null||e.dispose()}_initializeFormatMap(){for(const t of this._definitions){const e=t.createBlade();this._formats.set(t.format,{definition:t,blade:e,initialized:!1})}}_createOverlay(){this._shadowHost=document.createElement("div"),this._shadowHost.dataset.plugin="textmode-export-overlay-host",this._shadowHost.style.cssText="position: absolute; top: 0; left: 0; pointer-events: none; z-index: 2147483647;",this._shadowRoot=this._shadowHost.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=`@layer textmode-export-overlay{.textmode-export-overlay{--overlay-bg: rgba(20, 20, 20, .8);--overlay-surface: rgba(40, 40, 40, .9);--overlay-border: rgba(255, 255, 255, .14);--overlay-border-strong: rgba(255, 255, 255, .2);--overlay-border-focus: rgba(160, 160, 160, .6);--overlay-focus-shadow: 0 0 0 1px rgba(140, 140, 140, .28);--overlay-text: #ffffff;--overlay-muted: rgba(200, 200, 200, .74);--overlay-radius: .75rem;--overlay-stack-gap: .55rem;position:absolute;top:0;left:0;display:flex;flex-direction:column;gap:var(--overlay-stack-gap);min-width:236px;max-width:236px;padding:.65rem .8rem;background:var(--overlay-bg);color:var(--overlay-text);border-radius:var(--overlay-radius);border:1px solid var(--overlay-border);box-shadow:0 12px 28px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:.82rem;line-height:1.35;pointer-events:auto;z-index:2147483647}.textmode-export-overlay *{box-sizing:border-box}.textmode-export-overlay__header{display:flex;flex-direction:column;gap:.4rem}.textmode-export-overlay__header-title-row{display:flex;align-items:center;justify-content:space-between;gap:.4rem}.textmode-export-overlay__header-links{display:inline-flex;align-items:center;gap:.3rem}.textmode-export-overlay__support-link{display:inline-flex;align-items:center;justify-content:center;padding:.2rem;border-radius:.45rem;border:1px solid transparent;color:#d7d7d7d1;background:transparent;text-decoration:none;line-height:0;transition:background .18s ease,color .18s ease,transform .18s ease,border-color .18s ease}.textmode-export-overlay__support-link:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__support-link:focus-visible{outline:none;border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow)}.textmode-export-overlay__support-icon,.textmode-export-overlay__link-icon{display:block;width:1rem;height:1rem}.textmode-export-overlay__stack{display:flex;flex-direction:column;gap:var(--overlay-stack-gap)}.textmode-export-overlay__stack--dense{gap:.3rem}.textmode-export-overlay__stack--compact{gap:.45rem}.textmode-export-overlay__section{display:flex;flex-direction:column;gap:.4rem}.textmode-export-overlay__title{font-size:.92rem;font-weight:600}.textmode-export-overlay__divider{width:100%;height:1px;background:#ffffff29;margin-top:.25rem}.textmode-export-overlay__label{font-weight:500;opacity:.9}.textmode-export-overlay__checkbox{display:flex;align-items:center;gap:.5rem}.textmode-export-overlay__checkbox input[type=checkbox]{width:1rem;height:1rem;accent-color:rgba(100,100,100,.9)}.textmode-export-overlay__row{display:flex;gap:.6rem;flex-wrap:wrap;align-items:flex-start;width:100%}.textmode-export-overlay__field{display:flex;flex-direction:column;gap:.3rem;flex:1 1 120px;min-width:120px}.textmode-export-overlay__field--compact{flex:1 1 100px;min-width:100px}.textmode-export-overlay__field--dense{flex:1 1 90px;min-width:90px}.textmode-export-overlay__field--channel{flex:1 1 0;min-width:0}.textmode-export-overlay__field--full{width:100%;flex:1 1 100%}.textmode-export-overlay__input,.textmode-export-overlay select.textmode-export-overlay__input,.textmode-export-overlay input.textmode-export-overlay__input{width:100%;padding:.35rem .5rem;border-radius:.4rem;border:1px solid var(--overlay-border-strong);background:var(--overlay-surface);color:var(--overlay-text);font:inherit;line-height:1.35;transition:border-color .18s ease,box-shadow .18s ease,background .18s ease}.textmode-export-overlay select.textmode-export-overlay__input{-webkit-appearance:none;-moz-appearance:none;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-repeat:no-repeat;background-position:right .5rem center;background-size:1rem;padding-right:2rem}.textmode-export-overlay__input:focus{outline:none;border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);background:#2d2f42eb}.textmode-export-overlay__input::placeholder{color:var(--overlay-muted);opacity:.7}.textmode-export-overlay__muted{font-size:.75rem;opacity:.7;display:block}.textmode-export-overlay__button{display:inline-flex;align-items:center;justify-content:center;gap:.35rem;border-radius:.45rem;border:none;font-weight:600;padding:.45rem .7rem;cursor:pointer;transition:background .2s ease,transform .2s ease,box-shadow .2s ease}.textmode-export-overlay__button--primary{background:#505050;color:#fff}.textmode-export-overlay__button--secondary{background:#606060;color:#fff}.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;transform:none;box-shadow:none}.textmode-export-overlay__status{display:flex;flex-direction:column;gap:.25rem;padding:.45rem .55rem;border-radius:.45rem;border:1px solid rgba(110,110,110,.22);background:#4646462e}.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{font-weight:600;font-size:.75rem;opacity:.85;text-transform:uppercase;letter-spacing:.04em}.textmode-export-overlay__status-value{font-size:.82rem;color:#dedede;transition:color .18s ease}.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{display:flex;align-items:stretch;width:100%;background:var(--overlay-surface);border:1px solid var(--overlay-border-strong);border-radius:.4rem;overflow:hidden;transition:border-color .18s ease,box-shadow .18s ease,background .18s ease;position:relative}.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{flex:1 1 auto;min-width:0;border:none;background:transparent;color:var(--overlay-text);font:inherit;padding:.35rem .5rem;-webkit-appearance:textfield;-moz-appearance:textfield;appearance:textfield}.textmode-export-number-input__field::-webkit-outer-spin-button,.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{display:flex;flex-direction:column;border-left:1px solid rgba(255,255,255,.12);min-width:1.6rem}.textmode-export-number-input__control{display:flex;align-items:center;justify-content:center;width:100%;flex:1;border:none;background:#32323299;color:#d0d0d0;font-size:.68rem;line-height:1;cursor:pointer;transition:background .15s ease,color .15s ease;padding:0}.textmode-export-number-input__control:hover:not(:disabled){background:#5a5a5ad9;color:#fff}.textmode-export-number-input__control:disabled{cursor:default;opacity:.4;background:#28282880;color:#c8c8c866}.textmode-export-number-input:focus-within .textmode-export-number-input__control{background:#3c3c3cbf;color:#e8e8e8}.textmode-export-number-input__display{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;padding:.4rem .55rem;pointer-events:none;color:#f8fafc;opacity:0;transition:opacity .14s ease}.textmode-export-number-input__display--visible{opacity:1}.textmode-export-range-input{position:relative;width:100%}.textmode-export-range-input.is-disabled{opacity:.55}.textmode-export-range-input__field{width:100%;height:1.4rem;padding:0;margin:0;background:transparent;cursor:pointer;-moz-appearance:none;appearance:none;-webkit-appearance:none}.textmode-export-range-input__field::-webkit-slider-thumb{width:12px;height:12px;margin-top:-3.5px;-webkit-appearance:none;border-radius:50%;background:#a0a0a0;border:2px solid #303030;box-shadow:0 0 0 2px #00000059}.textmode-export-range-input__field::-webkit-slider-runnable-track{height:5px;border-radius:999px;background:linear-gradient(90deg,#8c8c8cd9,#646464a6)}.textmode-export-range-input__field::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:#a0a0a0;border:2px solid #303030;margin-top:-3.5px}.textmode-export-range-input__field::-moz-range-track{height:5px;border-radius:999px;background:linear-gradient(90deg,#8c8c8cd9,#646464a6)}.textmode-export-range-input__tooltip{position:absolute;top:-1.5rem;left:0;transform:translate(-50%);padding:.2rem .35rem;border-radius:.35rem;background:#1e1e1ee0;color:#f8fafc;font-size:.68rem;line-height:1;white-space:nowrap;pointer-events:none;opacity:0;transition:opacity .15s ease}.textmode-export-range-input__tooltip--visible{opacity:1}}`,this._shadowRoot.appendChild(t),this._overlayElement=document.createElement("div"),this._overlayElement.dataset.plugin="textmode-export-overlay",this._overlayElement.classList.add(Ho,ht),this._shadowRoot.appendChild(this._overlayElement),document.body.appendChild(this._shadowHost)}_renderStaticContent(){this._header.mount(this._overlayElement);const t=document.createElement("div");t.classList.add($r),this._overlayElement.appendChild(t),this._formatField.mount(t),this._prepareFormatOptions(),this._formatSelect.mount(this._formatField.root),this._formatSelect.selectElement.addEventListener("change",this._handleFormatSelectChange),this._optionsContainer=document.createElement("div"),this._optionsContainer.classList.add(ht,Or),this._overlayElement.appendChild(this._optionsContainer),this._exportButton.mount(this._overlayElement),this._exportButton.buttonElement.addEventListener("click",this._handleExportClickSafe),this._copyButtonContainer=document.createElement("div"),this._copyButtonContainer.classList.add(ht,Ke),this._overlayElement.appendChild(this._copyButtonContainer),this._copyButton.mount(this._copyButtonContainer),this._copyButton.buttonElement.dataset.defaultLabel="copy to clipboard",this._copyButton.buttonElement.addEventListener("click",this._handleCopyClickSafe)}_prepareFormatOptions(){const t=this._definitions.map(e=>({value:e.format,label:e.label}));this._formatSelect.update({options:t,defaultValue:this._currentFormat})}_registerEventHandlers(){this._eventUnsubscribers.push(this._events.$on("export:request",({format:t})=>{t===this._currentFormat&&(this._state.$set({isBusy:!0,error:void 0}),this._updateExportButton())}),this._events.$on("export:success",({format:t})=>{if(t===this._currentFormat){const e={isBusy:!1};t==="gif"&&(e.gifProgress=void 0),t==="video"&&(e.videoProgress=void 0),this._state.$set(e),this._updateExportButton()}}),this._events.$on("export:error",({format:t,error:e})=>{t===this._currentFormat&&(this._state.$set({isBusy:!1,error:e}),this._updateExportButton())}),this._events.$on("export:progress",({format:t,progress:e})=>{var r,a;if(e){if(t==="gif"&&((r=this._currentBlade)==null?void 0:r.blade)instanceof ti){const s=e;this._state.$set({gifProgress:s}),this._currentBlade.blade.handleProgress(s)}else if(t==="video"&&((a=this._currentBlade)==null?void 0:a.blade)instanceof ei){const s=e;this._state.$set({videoProgress:s}),this._currentBlade.blade.handleProgress(s)}this._updateExportButton()}}))}_handleFormatChange(t){this._currentFormat=t,this._state.$set({format:t}),this._switchFormat(t),this._events.$emit("format:change",{format:t})}_switchFormat(t){var r;const e=this._formats.get(t);if(!e)throw new Error(`Unknown export format: ${t}`);this._currentBlade&&this._currentBlade.blade.unmount(),this._optionsContainer.innerHTML="",e.blade.mount(this._optionsContainer),e.initialized||(e.blade.reset(),e.initialized=!0),this._currentBlade=e,this._formatSelect.value=t,this.refreshLayerTargets(),this._updateCopyButtonState(),this._updateExportButton(),(r=this._positionService)==null||r.scheduleUpdate()}_updateCopyButtonState(){var e;const t=((e=this._currentBlade)==null?void 0:e.definition.supportsClipboard)??!1;this._copyButtonContainer.style.display=t?"flex":"none",this._copyButton.setDisabled(!t)}async _handleExportClick(){if(!this._currentBlade)return;const t=this._currentBlade.definition.format,e=this._currentBlade.blade.getOptions();if(this._currentBlade.blade.validate()){if(t==="gif"){const r=this._currentBlade.blade;if(r.isRecording())return;r.setRecordingState("recording");try{await this._exportService.$requestExport("gif",e,{onGIFProgress:a=>{r.setRecordingState(a.state,a)}})}catch(a){throw r.setRecordingState("error"),a}return void window.setTimeout(()=>{r.setRecordingState("idle"),this._updateExportButton()},1600)}if(t==="video"){const r=this._currentBlade.blade;if(r.isRecording())return;r.setRecordingState("recording");try{await this._exportService.$requestExport("video",e,{onVideoProgress:a=>{r.setRecordingState(a.state,a)}})}catch(a){throw r.setRecordingState("error"),a}return void window.setTimeout(()=>{r.setRecordingState("idle"),this._updateExportButton()},1600)}this._exportButton.setDisabled(!0),this._exportButton.setLabel("exporting…");try{await this._exportService.$requestExport(t,e)}finally{this._exportButton.setDisabled(!1),this._exportButton.setLabel("download file")}}else console.warn("[textmode-export] Export options failed validation")}async _handleCopyClick(){if(!this._currentBlade||!this._currentBlade.definition.supportsClipboard)return;const t=this._currentBlade.definition.format,e=this._currentBlade.blade.getOptions(),r=this._copyButton.buttonElement.dataset.defaultLabel??"copy to clipboard";this._copyButton.setDisabled(!0),this._copyButton.setLabel("copying…");try{switch(t){case"txt":await this._clipboardService.$copy("txt",e);break;case"json":await this._clipboardService.$copy("json",e);break;case"svg":await this._clipboardService.$copy("svg",e);break;case"image":await this._clipboardService.$copy("image",e);break;default:return}this._copyButton.setLabel("copied!")}catch(a){console.error("[textmode-export] Failed to copy to clipboard",a),this._copyButton.setLabel("copy failed!")}finally{window.setTimeout(()=>{this._copyButton.setLabel(r),this._copyButton.setDisabled(!1)},1200)}}_updateExportButton(){if(!this._currentBlade)return;const t=this._currentBlade.definition.format;if(t==="gif"&&this._currentBlade.blade instanceof ti){const r=this._currentBlade.blade,a=this._state.snapshot.gifProgress;if(r.isRecording())if(this._exportButton.setDisabled(!0),a==null?void 0:a.totalFrames){const s=a.frameIndex??0,o=a.state==="encoding"?"encoding":"recording";this._exportButton.setLabel(`${o} ${s}/${a.totalFrames}`)}else{const s=(a==null?void 0:a.state)==="encoding"?"encoding":"recording";this._exportButton.setLabel(`${s}…`)}else this._exportButton.setDisabled(!1),this._exportButton.setLabel("start recording");return}if(t==="video"&&this._currentBlade.blade instanceof ei){const r=this._currentBlade.blade,a=this._state.snapshot.videoProgress;if(r.isRecording())if(this._exportButton.setDisabled(!0),a==null?void 0:a.totalFrames){const s=a.frameIndex??0;this._exportButton.setLabel(`recording ${s}/${a.totalFrames} frames`)}else this._exportButton.setLabel("recording…");else this._exportButton.setDisabled(!1),this._exportButton.setLabel("start recording");return}const e=this._state.snapshot.isBusy;this._exportButton.setDisabled(e),this._exportButton.setLabel(e?"exporting…":"download file")}}class gn{constructor(){w(this,"_listeners",{})}_getPool(t){const e=this._listeners[t];if(e)return e;const r=new Set;return this._listeners[t]=r,r}$on(t,e){const r=this._getPool(t);return r.add(e),()=>{r.delete(e),r.size===0&&delete this._listeners[t]}}$emit(t,e){const r=this._listeners[t];if(r)for(const a of[...r])try{a(e)}catch(s){console.error("[textmode-export] Event handler failed",s)}}$clear(){for(const t of Object.keys(this._listeners))delete this._listeners[t]}}class wn{constructor(t){w(this,"_state");w(this,"_listeners",new Set);this._state=t}get snapshot(){return Object.freeze({...this._state})}$set(t){this._state=Object.assign({},this._state,t);const e=this.snapshot;for(const r of[...this._listeners])try{r(e)}catch(a){console.error("[textmode-export] State listener failed",a)}}$subscribe(t){return this._listeners.add(t),t(this.snapshot),()=>{this._listeners.delete(t)}}$reset(t){this._state=t;const e=this.snapshot;for(const r of[...this._listeners])r(e)}}class yn extends ut{constructor(e){super();w(this,"props");w(this,"input");w(this,"handleInput",()=>{this.props.defaultValue=this.input.value});this.props=e}render(){return this.input=document.createElement("input"),this.input.type="text",this.input.classList.add(Gr),this.props.id&&(this.input.id=this.props.id),this.props.maxLength!==void 0&&(this.input.maxLength=this.props.maxLength),this.props.defaultValue!==void 0&&(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(e){this.input.value=e}_onUnmount(){this.input.removeEventListener("input",this.handleInput)}onUpdate(e){this.props=e,e.id&&(this.input.id=e.id),e.maxLength!==void 0&&(this.input.maxLength=e.maxLength),e.defaultValue!==void 0&&(this.input.value=e.defaultValue)}}class ii extends ut{constructor(e){super();w(this,"provider");w(this,"field");w(this,"select");this.provider=e.provider,this.field=new H({label:"layer",labelFor:e.id,variant:"full"}),this.select=new pt({id:e.id,options:[],defaultValue:e.provider.getDefaultId()})}render(){const e=document.createElement("div");return this.field.mount(e),this.refresh(),this.select.mount(this.field.root),e}get layer(){const e=this.provider.getLayerById(this.select.value);if(e)return e;const r=this.provider.getDefaultId();return this.select.value=r,this.provider.getLayerById(r)}setDisabled(e){this.select.selectElement.disabled=e}refresh(){const e=this.provider.getOptions(),r=this.select.isMounted()?this.select.value:this.provider.getDefaultId(),a=e.some(s=>s.id===r)?r:this.provider.getDefaultId();this.select.update({options:e.map(s=>({value:s.id,label:s.label})),defaultValue:a}),this.select.value=a}_onUnmount(){this.select.unmount(),this.field.unmount()}_onDestroy(){this.select.destroy(),this.field.destroy()}}class bn extends Wt{constructor(e){super(e);w(this,"layerTarget");w(this,"trailingSpaces",this._manageComponent(new Jt({label:"preserve trailing spaces",defaultChecked:!1})));w(this,"emptyCharacter",this._manageComponent(new yn({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1})));e.layerTargetProvider&&(this.layerTarget=this._manageComponent(new ii({id:"textmode-export-txt-layer",provider:e.layerTargetProvider})))}render(){var a;const e=document.createElement("div");e.classList.add(ht),(a=this.layerTarget)==null||a.mount(e),this.trailingSpaces.mount(e);const r=new H({label:"empty character",labelFor:"textmode-export-empty-character",variant:"full"});return r.mount(e),this.emptyCharacter.mount(r.root),e}getOptions(){var a;const e=this._config.defaultOptions??{},r=this.emptyCharacter.value||e.emptyCharacter||" ";return{layer:(a=this.layerTarget)==null?void 0:a.layer,preserveTrailingSpaces:this.trailingSpaces.checked,emptyCharacter:r}}reset(){this.applyDefaults()}validate(){return this.emptyCharacter.value.length<=1}refreshLayerTargets(){var e;(e=this.layerTarget)==null||e.refresh()}applyDefaults(){const e=this._config.defaultOptions??{};this.trailingSpaces.checked=e.preserveTrailingSpaces??!1,this.emptyCharacter.value=e.emptyCharacter??" "}}class vn extends Wt{constructor(e){super(e);w(this,"layerTarget");w(this,"layerTargetContainer");w(this,"target",this._manageComponent(new pt({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"})));w(this,"prettyPrint",this._manageComponent(new Jt({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0})));w(this,"includeMetadata",this._manageComponent(new Jt({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0})));w(this,"colorMode",this._manageComponent(new pt({id:"textmode-export-json-color-mode",options:[{value:"hex",label:"hex"},{value:"rgba",label:"rgba"}],defaultValue:"hex"})));e.layerTargetProvider&&(this.layerTarget=this._manageComponent(new ii({id:"textmode-export-json-layer",provider:e.layerTargetProvider})))}render(){const e=document.createElement("div");e.classList.add(ht);const r=new H({label:"target",labelFor:"textmode-export-json-target",variant:"full"});r.mount(e),this.target.mount(r.root),this.target.selectElement.addEventListener("change",()=>this.updateLayerTargetVisibility()),this.layerTarget&&(this.layerTargetContainer=document.createElement("div"),this.layerTarget.mount(this.layerTargetContainer),e.appendChild(this.layerTargetContainer)),this.prettyPrint.mount(e),this.includeMetadata.mount(e);const a=new H({label:"color mode",labelFor:"textmode-export-json-color-mode",variant:"full"});return a.mount(e),this.colorMode.mount(a.root),this.updateLayerTargetVisibility(),e}getOptions(){var r;const e=this.target.value;return{target:e,layer:e==="selected"?(r=this.layerTarget)==null?void 0:r.layer:void 0,pretty:this.prettyPrint.checked,includeMetadata:this.includeMetadata.checked,colorMode:this.colorMode.value}}reset(){this.applyDefaults()}validate(){return!0}refreshLayerTargets(){var e;(e=this.layerTarget)==null||e.refresh()}applyDefaults(){const e=this._config.defaultOptions??{};this.target.value=e.target??"selected",this.prettyPrint.checked=typeof e.pretty=="number"?e.pretty>0:e.pretty??!0,this.includeMetadata.checked=e.includeMetadata??!0,this.colorMode.value=e.colorMode??"hex",this.updateLayerTargetVisibility()}updateLayerTargetVisibility(){var r;const e=this.target.value==="selected";this.layerTargetContainer&&(this.layerTargetContainer.style.display=e?"":"none"),(r=this.layerTarget)==null||r.setDisabled(!e)}}class xn extends Wt{constructor(e){super(e);w(this,"formatSelect",this._manageComponent(new pt({id:"textmode-export-image-format",options:[{value:"png",label:`PNG (${ma})`},{value:"jpg",label:`JPG (${fa})`},{value:"webp",label:`WEBP (${ga})`}],defaultValue:"png"})));w(this,"scaleInput",this._manageComponent(new kt({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}})))}render(){const e=document.createElement("div");e.classList.add(ht);const r=new Bt("row");r.mount(e);const a=new H({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});a.mount(r.root),this.formatSelect.mount(a.root);const s=new H({label:"scale",labelFor:"textmode-export-image-scale",variant:"dense"});return s.mount(r.root),this.scaleInput.mount(s.root),this.scaleInput.inputElement.id="textmode-export-image-scale",e}getOptions(){var r;const e=Number.parseFloat(this.scaleInput.value);return{format:this.formatSelect.value,scale:Number.isFinite(e)?e:((r=this._config.defaultOptions)==null?void 0:r.scale)??1}}reset(){this.applyDefaults(),this.scaleInput.refresh()}validate(){const e=Number.parseFloat(this.scaleInput.value);return Number.isFinite(e)&&e>0}applyDefaults(){const e=this._config.defaultOptions??{};this.formatSelect.value=e.format??"png";const r=e.scale??1;this.scaleInput.value=String(r)}}class _n extends Wt{constructor(e){super(e);w(this,"layerTarget");w(this,"includeBackground",this._manageComponent(new Jt({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0})));w(this,"drawMode",this._manageComponent(new pt({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"})));w(this,"strokeWidth",this._manageComponent(new kt({defaultValue:"1",attributes:{min:"0",step:"0.1"}})));e.layerTargetProvider&&(this.layerTarget=this._manageComponent(new ii({id:"textmode-export-svg-layer",provider:e.layerTargetProvider})))}render(){var o;const e=document.createElement("div");e.classList.add(ht),(o=this.layerTarget)==null||o.mount(e),this.includeBackground.mount(e);const r=new Bt("row");r.mount(e);const a=new H({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});a.mount(r.root),this.drawMode.mount(a.root);const s=new H({label:"stroke width",labelFor:"textmode-export-svg-stroke-width",variant:"compact"});return s.mount(r.root),this.strokeWidth.mount(s.root),this.strokeWidth.inputElement.id="textmode-export-svg-stroke-width",this.drawMode.selectElement.addEventListener("change",()=>this.updateStrokeControls()),this.updateStrokeControls(),e}getOptions(){var e;return{layer:(e=this.layerTarget)==null?void 0:e.layer,includeBackgroundRectangles:this.includeBackground.checked,drawMode:this.drawMode.value,strokeWidth:Number.parseFloat(this.strokeWidth.value)}}reset(){this.applyDefaults(),this.updateStrokeControls()}validate(){const e=Number.parseFloat(this.strokeWidth.value);return this.drawMode.value!=="stroke"||Number.isFinite(e)&&e>=0}refreshLayerTargets(){var e;(e=this.layerTarget)==null||e.refresh()}updateStrokeControls(){const e=this.drawMode.value==="stroke";this.strokeWidth.inputElement.disabled=!e,this.strokeWidth.refresh()}applyDefaults(){const e=this._config.defaultOptions??{};this.includeBackground.checked=e.includeBackgroundRectangles??!0,this.drawMode.value=e.drawMode??"fill";const r=e.strokeWidth??1;this.strokeWidth.value=String(r),this.strokeWidth.refresh()}}function kn(i,t,e){var l;const r=(function(c){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new bn({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:{preserveTrailingSpaces:!1,emptyCharacter:" "},layerTargetProvider:c})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new vn({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:{target:"selected",pretty:!0,includeMetadata:!0,colorMode:"hex"},layerTargetProvider:c})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new xn({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:{format:"png",scale:1}})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new _n({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:{includeBackgroundRectangles:!0,drawMode:"fill",strokeWidth:1},layerTargetProvider:c})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new ti({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:{frameCount:300,frameRate:60,scale:1,repeat:0}})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new ei({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:{format:"mp4",frameCount:480,frameRate:60,bitrate:"medium",bitrateMode:"variable",latencyMode:"quality",hardwareAcceleration:"no-preference",keyFrameInterval:2,transparent:!1}})}]})(e),a=(l=r[0])==null?void 0:l.format,s=new wn((c=>({format:c,isBusy:!1}))(a)),o=new gn,n=new fn(i,t,s,o,r);return n.$mount(),n}const ri={name:"textmode.export",version:Vr,async install(i,t){const e={saveCanvas:async(n={})=>new ci().$saveImage(i.canvas,n),copyCanvas:async(n={})=>new ci().$copyImageToClipboard(i.canvas,n),saveSVG:(n={})=>{new ni().$saveSVG(i,n)},saveStrings:(n={})=>{new di().$saveTXT(i,n)},toSVG:(n={})=>new ni().$generateSVG(i,n),toString:(n={})=>new di().$generateTXT(i,n),toJSON:(n={})=>new Xe().$generateJSONData(i,n),toJSONString:(n={})=>new Xe().$generateJSONString(i,n),saveJSON:(n={})=>{new Xe().$saveJSON(i,n)},saveGIF:async(n={})=>new Ba(i,t.registerPostDrawHook).$saveGIF(n),saveVideo:async(n={})=>new No(i,t.registerPostDrawHook).$saveVideo(n)},r=kn(i,e,(function(n){return{getOptions:()=>oi(n),getLayerById:l=>{var c;return(c=oi(n).find(d=>d.id===l))==null?void 0:c.layer},getDefaultId:()=>"base"}})(i));t.registerPostDrawHook(()=>{r.isVisible()&&r.refreshLayerTargets()});const a={show:()=>r.show(),hide:()=>r.hide(),toggle:()=>r.toggle(),isVisible:()=>r.isVisible()},s={...e,exportOverlay:a},o=i;Object.assign(o,s),o._exportOverlayController=r},async uninstall(i){const t=i,e=t._exportOverlayController;e==null||e.$dispose(),delete t._exportOverlayController;const r=["exportOverlay","saveCanvas","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","saveVideo"];for(const a of r)delete t[a]}},ca=(i={})=>{const t=i.overlay??!0,e={...ri},r=e.install;return e.install=async(a,s)=>{var n;const o=a;await r.call(e,o,s),t||((n=o.exportOverlay)==null||n.hide())},e};typeof window<"u"&&(window.ExportPlugin=ri,window.createTextmodeExportPlugin=ca),et.ExportPlugin=ri,et.createTextmodeExportPlugin=ca,Object.defineProperty(et,Symbol.toStringTag,{value:"Module"})});
68
+ `),i=this.gl.createProgram();return this.gl.attachShader(i,t),this.gl.attachShader(i,e),this.gl.linkProgram(i),i}createShader(t,e){g(this.gl);const i=this.gl.createShader(t);return this.gl.shaderSource(i,e),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){g(this.gl),g(this.colorProgram);const t=this.gl.createVertexArray();this.gl.bindVertexArray(t);const e=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,e,this.gl.STATIC_DRAW);const a=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),t}createTexture(){g(this.gl);const t=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,t),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),t}runColorProgram(t){return g(this.gl),g(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:t.timestamp,duration:t.duration??void 0,alpha:"discard"})}runAlphaProgram(t){g(this.gl),g(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:e,height:i}=this.canvas,a=e*i+2*(Math.ceil(e/2)*Math.ceil(i/2)),s=Math.ceil(a/(4*e));let o=new Uint8Array(4*e*s);this.gl.readPixels(0,0,e,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,a),g(o[e*i]===128),g(o[o.length-1]===128);const n={format:"I420",codedWidth:e,codedHeight:i,timestamp:t.timestamp,duration:t.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,n)}updateCpu(t){if(!this.worker){const a=new Blob([`(${Io.toString()})()`],{type:"application/javascript"}),s=URL.createObjectURL(a);this.worker=new Worker(s),URL.revokeObjectURL(s),this.worker.addEventListener("message",o=>{const n=o.data,l=this.pendingRequests.get(n.id);l&&(this.pendingRequests.delete(n.id),"error"in n?l.reject(new Error(n.error)):l.resolve({colorFrame:n.colorFrame,alphaFrame:n.alphaFrame}))}),this.worker.addEventListener("error",o=>{const n=new Error(o.message||"Color/alpha splitter worker error.");for(const l of this.pendingRequests.values())l.reject(n);this.pendingRequests.clear()})}const e=this.nextRequestId++,i=Te();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){var e,i,a;(i=(e=this.gl)==null?void 0:e.getExtension("WEBGL_lose_context"))==null||i.loseContext(),this.gl=null,this.canvas=null,(a=this.worker)==null||a.terminate(),this.worker=null;const t=new Error("Color/alpha splitter closed.");for(const s of this.pendingRequests.values())s.reject(t);this.pendingRequests.clear()}}ge.forceCpu=!0;const Io=()=>{let r=null,t=Promise.resolve();self.addEventListener("message",s=>{const{id:o,sourceFrame:n}=s.data;t=t.then(async()=>{try{const{colorFrame:l,alphaFrame:c}=await e(n);self.postMessage({id:o,colorFrame:l,alphaFrame:c},{transfer:[l,c]})}catch(l){self.postMessage({id:o,error:l.message})}finally{n.close()}})});const e=async s=>{const o=s.format;if(!o)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const n=s.codedWidth,l=s.codedHeight,c=s.allocationSize();if(r&&r.byteLength===c||(r=new Uint8Array(c)),await s.copyTo(r),o==="RGBA"||o==="BGRA")return i(r,n,l,o,s);if(o==="I420A"||o==="I420AP10"||o==="I420AP12"||o==="I422A"||o==="I422AP10"||o==="I422AP12"||o==="I444A"||o==="I444AP10"||o==="I444AP12")return a(r,n,l,o,s);throw new Error(`CPU color/alpha splitting does not support format '${o}'.`)},i=(s,o,n,l,c)=>{const d=o*n,u=Math.ceil(o/2),m=Math.ceil(n/2),h=new Uint8Array(d+u*m*2);for(let y=0,b=3;y<d;y++,b+=4)h[y]=s[b];h.fill(128,d);const p=new VideoFrame(s,{format:l==="RGBA"?"RGBX":"BGRX",codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0}),f={format:"I420",codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[h.buffer]};return{colorFrame:p,alphaFrame:new VideoFrame(h,f)}},a=(s,o,n,l,c)=>{const d=l.includes("P10"),u=l.includes("P12"),m=d||u?2:1;let h,p;l.startsWith("I420")?(h=Math.ceil(o/2),p=Math.ceil(n/2)):l.startsWith("I422")?(h=Math.ceil(o/2),p=n):(h=o,p=n);const f=o*n,y=f*m,b=f*m+2*(h*p*m),_=l.replace("A",""),T=Math.ceil(o/2)*Math.ceil(n/2),S=new Uint8Array(y+2*(T*m)),A=b;S.set(s.subarray(A,A+y),0);const E=y,C=d?512:u?2048:128;m===1?S.fill(C,E):new Uint16Array(S.buffer,E,2*T).fill(C);const I=d?"I420P10":u?"I420P12":"I420",D=new VideoFrame(s.subarray(0,b),{format:_,codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0}),V={format:I,codedWidth:o,codedHeight:n,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[S.buffer]};return{colorFrame:D,alphaFrame:new VideoFrame(S,V)}}};class Ao extends Ii{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");(i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!nt.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${nt.join(", ")}.`);if(!(i.bitrate instanceof We)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.width!==void 0&&(!Number.isInteger(i.transform.width)||i.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(i.transform.height!==void 0&&(!Number.isInteger(i.transform.height)||i.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(i.transform.fit!==void 0&&!["fill","contain","cover"].includes(i.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.transform.width!==void 0&&i.transform.height!==void 0&&i.transform.fit===void 0&&!["fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(i.transform.fit!==void 0&&["fill","contain","cover"].includes(i.sizeChangeBehavior)&&i.transform.fit!==i.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(i.transform.rotate!==void 0&&![0,90,180,270].includes(i.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(i.transform.crop!==void 0&&Le(i.transform.crop,"config.transform."),i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(i.transform.frameRate!==void 0&&(!Number.isFinite(i.transform.frameRate)||i.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(i.transform.force!==void 0&&typeof i.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");li(i.codec,i)})(e),super(e.codec),this._encoder=new Mo(this,e),this._canvas=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 a=new it(this._canvas,{timestamp:t,duration:e});return this._encoder.add(a,!0,i)}_flushAndClose(t){return this._encoder.flushAndClose(t)}}class Fo extends qe{constructor(t){if(super(),this._connectedTrack=null,!Ht.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${Ht.join(", ")}.`);this._codec=t}}class Do extends qe{constructor(t){if(super(),this._connectedTrack=null,!It.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${It.join(", ")}.`);this._codec=t}}class Ge{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>nt.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>Ht.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>It.includes(t))}_codecUnsupportedHint(t){return""}}class Qe extends Ge{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(t.minimumFragmentDuration!==void 0&&(!Number.isFinite(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(t.onFtyp!==void 0&&typeof t.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(t.onMoov!==void 0&&typeof t.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(t.onMdat!==void 0&&typeof t.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(t.onMoof!==void 0&&typeof t.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(t.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=t}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(t){return new So(t,this)}}class Xe extends Qe{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...nt,...oe,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...It]}_codecUnsupportedHint(t){return new Ri().getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}}class Di extends Qe{constructor(t){super(t)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...nt,...oe,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...It]}}class Ri extends Qe{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...nt,...Ht]}_codecUnsupportedHint(t){return new Xe().getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}}class Vi extends Ge{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.minimumClusterDuration!==void 0&&(!Number.isFinite(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(t.onEbmlHeader!==void 0&&typeof t.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(t.onSegmentHeader!==void 0&&typeof t.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(t.onCluster!==void 0&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Po(t,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...nt,...oe,...bt.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...It]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class we extends Vi{constructor(t){super(t)}getSupportedCodecs(){return[...nt.filter(t=>["vp8","vp9","av1"].includes(t)),...Ht.filter(t=>["opus","vorbis"].includes(t)),...It]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(t){return new Vi().getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}}const Ro=["video","audio","subtitle"];class Kt{constructor(t,e,i,a,s){this.id=t,this.output=e,this.type=i,this.source=a,this.metadata=s}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(t){if(!(t instanceof Kt))throw new TypeError("other must be an OutputTrack.");if(this===t)return!1;const e=Ir(this.metadata.group),i=Ir(t.metadata.group);for(const a of e)if(this.type!==t.type&&i.some(s=>a===s)||i.some(s=>a._pairedGroups.has(s)))return!0;return!1}}class Vo extends Kt{constructor(t,e,i,a){super(t,e,"video",i,a)}}class Lo extends Kt{constructor(t,e,i,a){super(t,e,"audio",i,a)}}class Wo extends Kt{constructor(t,e,i,a){super(t,e,"subtitle",i,a)}}class Yt{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof Yt))throw new TypeError("other must be an OutputTrackGroup.");if(this===t)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(t),t._pairedGroups.add(this)}}const Ke=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&(t=r.languageCode,!Fa.test(t)))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");var t;if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&(e=>{if(!e||typeof e!="object")throw new TypeError("disposition must be an object.");if(e.default!==void 0&&typeof e.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(e.primary!==void 0&&typeof e.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(e.forced!==void 0&&typeof e.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(e.original!==void 0&&typeof e.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(e.commentary!==void 0&&typeof e.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof Yt)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof Yt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class Oo extends Ar{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(t);const e=this._getRootTarget();if(e instanceof Promise)throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new Yt,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Tr,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.format instanceof Ge))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof _t||t.target instanceof je))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof _t&&this._rememberTarget(t.target),t.initTarget!==void 0&&!(t.initTarget instanceof _t)&&typeof t.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(t.onFinalize!==void 0&&typeof t.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this._target=t.target,this._onFinalize=t.onFinalize??null,this._initTarget=t.initTarget??null,this._initTarget instanceof _t&&this._rememberTarget(this._initTarget),this._muxer=t.format._createMuxer(this)}_getTargetValidated(t){g(this._target instanceof je);const e=this._target.getTarget(t),i=a=>{if(!(a instanceof _t))throw new TypeError("getTarget must return a Target.");return a};return e instanceof Promise?e.then(i):i(e)}async _getTarget(t){g(this._target instanceof je);const e=await this._getTargetValidated(t);return this._emit("target",{target:e,request:t,isRoot:t.isRoot}),this.state==="canceled"?await e._close():this._rememberTarget(e),e}_rememberTarget(t){this._unfinalizedTargets.add(t),t.on("finalized",()=>this._unfinalizedTargets.delete(t),{once:!0})}async _getInitTarget(){if(g(this._initTarget!==null),this._initTarget instanceof _t)return this._initTarget;const t=await this._initTarget();return this.state==="canceled"?await t._close():this._rememberTarget(t),t}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof _t)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const t={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},e=this._getTargetValidated(t),i=a=>(this.state==="canceled"?a._close():this._rememberTarget(a),this._emit("target",{target:a,request:t,isRoot:!0}),this._rootTarget=a,a);return e instanceof Promise?this._rootTargetPromise=e.then(i):i(e)}_getRootWriter(t){return this._rootWriterPromise??(this._rootWriterPromise=(async()=>{const e=await this._getRootTarget(),i=new Ue(e,typeof t=="boolean"?t:t(e));return i.start(),i})())}addVideoTrack(t,e={}){if(!(t instanceof Ii))throw new TypeError("source must be a VideoSource.");if(Ke(e),e.rotation!==void 0&&![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._name} does not support video rotation metadata.`);if(e.frameRate!==void 0&&(!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??(i.group=this.defaultTrackGroup),this._addTrack(new Vo(this._tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof Fo))throw new TypeError("source must be an AudioSource.");Ke(e);const i={...e};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new Lo(this._tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof Do))throw new TypeError("source must be a SubtitleSource.");Ke(e);const i={...e};return i.group??(i.group=this.defaultTrackGroup),this._addTrack(new Wo(this._tracks.length+1,this,t,i))}setMetadataTags(t){if((e=>{if(!e||typeof e!="object")throw new TypeError("tags must be an object.");if(e.title!==void 0&&typeof e.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(e.description!==void 0&&typeof e.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(e.artist!==void 0&&typeof e.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(e.album!==void 0&&typeof e.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(e.albumArtist!==void 0&&typeof e.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(e.genre!==void 0&&typeof e.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(e.lyrics!==void 0&&typeof e.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(e.images!==void 0){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const i of e.images){if(!i||typeof i!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(i.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof i.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(i.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(e.comment!==void 0&&typeof e.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(e.raw!==void 0){if(!e.raw||typeof e.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const i of Object.values(e.raw))if(!(i===null||typeof i=="string"||i instanceof Uint8Array||i instanceof Fr||i instanceof Dr||Oa(i)))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}})(t),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=t}_addTrack(t){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t.source._connectedTrack)throw new Error("Source is already used for a track.");const e=this.format.getSupportedTrackCounts(),i=this._tracks.reduce((o,n)=>o+(n.type===t.type?1:0),0),a=e[t.type].max;if(i===a)throw new Error(a===0?`${this.format._name} does not support ${t.type} tracks.`:`${this.format._name} does not support more than ${a} ${t.type} track`+(a===1?"":"s")+".");const s=e.total.max;if(this._tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks`+(s===1?"":"s")+" in total.");if(t.isVideoTrack()){const o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(n=>`'${n}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isAudioTrack()){const o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(n=>`'${n}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}else if(t.isSubtitleTrack()){const o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(t.source._codec));if(!o.includes(t.source._codec))throw new Error(`Codec '${t.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(n=>`'${n}'`).join(", ")}.`+this.format._codecUnsupportedHint(t.source._codec))}return this._tracks.push(t),t.source._connectedTrack=t,t}async start(){const t=this.format.getSupportedTrackCounts();for(const i of Ro){const a=this._tracks.reduce((o,n)=>o+(n.type===i?1:0),0),s=t[i].min;if(a<s)throw new Error(s===t[i].max?`${this.format._name} requires exactly ${s} ${i} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${i} track${s===1?"":"s"}.`)}const e=t.total.min;if(this._tracks.length<e)throw new Error(e===t.total.max?`${this.format._name} requires exactly ${e} track`+(e===1?"":"s")+".":`${this.format._name} requires at least ${e} track`+(e===1?"":"s")+".");if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const i=await this._mutex.acquire();try{await this._muxer.start();const a=this._tracks.map(s=>s.source._start());await Promise.all(a)}finally{i()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):this.state!=="finalizing"&&this.state!=="finalized"?this._cancelPromise=(async()=>{this.state="canceled";const t=await this._mutex.acquire();try{const e=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(i=>i._close())),this._unfinalizedTargets.clear()}finally{t()}})():void(this.state==="finalized"&&console.warn("Output has already been finalized."))}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const t=await this._mutex.acquire();try{const e=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){const i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{t()}})()}}const $o=["vp9","vp8"],zo=["avc"];class No{constructor(t,e,i){w(this,"_pending",[]);this._source=t,this._plan=e,this._timeoutMs=i}get pendingCount(){return this._pending.length}enqueue(t){let e;try{e=Promise.resolve(this._source.add(t/this._plan.frameRate,1/this._plan.frameRate))}catch(i){e=Promise.reject(i)}e.catch(()=>{}),this._pending.push(e)}async drainOne(t){if(this._pending.length===0)return;const e=await se(Promise.race(this._pending.map((i,a)=>i.then(()=>({index:a,error:null}),s=>({index:a,error:s})))),`Video encoder did not drain within ${this._timeoutMs}ms.`,t,this._timeoutMs);if(this._pending.splice(e.index,1),e.error)throw e.error}async drainAll(t,e){for(;this._pending.length>0;)await this.drainOne(t),e()}}class Uo{async $record(t,e,i){this._throwIfAborted(t.signal),this._assertWebCodecsAvailable();const a=await this._createEncodingPlan(t);this._log(t,"video export plan",a),this._emitProgress(i,"recording","probing",0,a.frameCount);const s=a.format==="mp4"?new Xe:new we,o=new fe,n=new Oo({format:s,target:o}),l=n,c=new Ao(e.canvas,{codec:a.codec,bitrate:a.bitrate,alpha:a.transparent?"keep":"discard",bitrateMode:a.bitrateMode,latencyMode:a.latencyMode,hardwareAcceleration:a.hardwareAcceleration,keyFrameInterval:a.keyFrameInterval,sizeChangeBehavior:"deny"}),d=new No(c,a,3e4);n.addVideoTrack(c);try{if(await se(n.start(),"Video output did not start within 30000ms.",t.signal,3e4),await e.$render({frameCount:a.frameCount,frameRate:a.frameRate,signal:t.signal,onFrame:async({frameIndex:u})=>{this._throwIfAborted(t.signal),d.enqueue(u),this._emitProgress(i,"recording","capturing",u+1,a.frameCount),await this._drainIfNeeded(d,i,a,u+1,t.signal),this._shouldYieldAfterCaptureFrame(u,a.frameCount)&&await this._yieldToBrowser(t.signal)}}),this._throwIfAborted(t.signal),await this._drainEncodes(d,i,a,t.signal),this._emitProgress(i,"encoding","finalizing",a.frameCount,a.frameCount),await se(n.finalize(),"Video output did not finalize within 30000ms.",t.signal,3e4),this._emitProgress(i,"completed","finalizing",a.frameCount,a.frameCount),!o.buffer)throw new Et("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:a.mimeType})}catch(u){try{await l.cancel()}catch{}const m=this._normalizeError(u);throw i==null||i({state:"error",message:m.message}),m}}async _drainIfNeeded(t,e,i,a,s){t.pendingCount<4||(await t.drainOne(s),this._emitProgress(e,"recording","draining",a,i.frameCount))}async _drainEncodes(t,e,i,a){await t.drainAll(a,()=>{this._throwIfAborted(a),this._emitProgress(e,"encoding","draining",i.frameCount,i.frameCount)})}_shouldYieldAfterCaptureFrame(t,e){const i=t+1;return i<e&&i%4==0}_yieldToBrowser(t){return new Promise((e,i)=>{if(t!=null&&t.aborted)return void i(Vt());let a=null,s=null,o=!1;const n=d=>{o||(o=!0,a!==null&&typeof globalThis.cancelAnimationFrame=="function"&&globalThis.cancelAnimationFrame(a),s!==null&&clearTimeout(s),t==null||t.removeEventListener("abort",l),d())},l=()=>n(()=>i(Vt())),c=()=>n(e);t==null||t.addEventListener("abort",l,{once:!0}),typeof globalThis.requestAnimationFrame!="function"?s=setTimeout(c,0):a=globalThis.requestAnimationFrame(()=>{a=null,s=setTimeout(c,0)})})}async _createEncodingPlan(t){if(t.format==="mp4"&&t.transparent)throw new Et("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const e=Math.max(1,Math.round(t.width)),i=Math.max(1,Math.round(t.height)),a=this._resolveBitrate(t.bitrate,e,i,t.frameRate),s=t.format==="mp4"?new Xe:new we,o=t.format==="mp4"?zo:$o,n=s.getSupportedVideoCodecs().filter(c=>o.includes(c)),l=await(async(c,d)=>{for(const u of c)if(await ws(u,d))return u;return null})(n,{width:e,height:i,bitrate:a});if(!l){const c=o.join(" or ");throw new Et("VIDEO_CODEC_UNSUPPORTED",`This browser cannot encode ${c} at ${e}x${i}. Try a browser/device with native WebCodecs encoding support or reduce the export dimensions.`)}return{format:t.format,extension:t.format==="mp4"?".mp4":".webm",mimeType:s.mimeType,codec:l,bitrate:a,bitrateMode:t.bitrateMode,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,keyFrameInterval:t.keyFrameInterval,frameRate:t.frameRate,frameCount:t.frameCount,width:e,height:i,transparent:t.transparent}}_assertWebCodecsAvailable(){const t=globalThis;if(typeof t.VideoEncoder!="function"||typeof t.VideoFrame!="function")throw new Et("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}_resolveBitrate(t,e,i,a){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.round(t);const s=typeof t=="string"?t:"medium",o=e*i,n=Math.max(.5,a/60),l=s==="high"?6:s==="low"?1.5:3;return Math.max(25e4,Math.round(o*n*l))}_throwIfAborted(t){if(t!=null&&t.aborted)throw Vt()}_emitProgress(t,e,i,a,s){t==null||t({state:e,phase:i,frameIndex:a,frame:a,totalFrames:s,progress:s>0?a/s:0})}_normalizeError(t){return t instanceof Et?t:new Et("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}_log(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}}class Ho{constructor(t,e){w(this,"_recorder");w(this,"_textmodifier");w(this,"_registerPostDrawHook");this._recorder=new Uo,this._textmodifier=t,this._registerPostDrawHook=e}async $saveVideo(t={}){await this._saveVideo(t.format??"mp4",t)}async _saveVideo(t,e){var s;const i=this._applyDefaultOptions(t,e),a=new Ma(this._textmodifier,this._registerPostDrawHook,i.width,i.height);try{const o=await this._recorder.$record(i,a,e.onProgress);new ot().$downloadFile(o,this._withExtension(i.filename,`.${t}`))}catch(o){throw(s=e.onProgress)==null||s.call(e,{state:"error",message:o instanceof Error?o.message:`${t.toUpperCase()} export failed`}),o}}_applyDefaultOptions(t,e){const i=this._positiveInteger(e.frameRate,60),a=this._positiveInteger(e.frameCount,300),s=this._positiveNumber(e.pixelDensity,1),o=this._currentPixelDensity(),n=Math.max(1,Math.round(this._textmodifier.canvas.width/o*s)),l=Math.max(1,Math.round(this._textmodifier.canvas.height/o*s));return{filename:e.filename,format:t,frameRate:i,frameCount:a,bitrate:this._bitrate(e.bitrate),bitrateMode:this._bitrateMode(e.bitrateMode),latencyMode:this._latencyMode(e.latencyMode),hardwareAcceleration:this._hardwareAcceleration(e.hardwareAcceleration),keyFrameInterval:this._keyFrameInterval(e.keyFrameInterval),pixelDensity:s,width:n,height:l,transparent:!!e.transparent,debugLogging:!!e.debugLogging,signal:e.signal}}_positiveInteger(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}_positiveNumber(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}_bitrate(t){return typeof t=="number"&&Number.isFinite(t)&&t>0||t==="low"||t==="medium"||t==="high"?t:"medium"}_bitrateMode(t){return t==="constant"||t==="variable"?t:"variable"}_latencyMode(t){return t==="quality"||t==="realtime"?t:"quality"}_hardwareAcceleration(t){return t==="prefer-hardware"||t==="prefer-software"||t==="no-preference"?t:"no-preference"}_keyFrameInterval(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}_currentPixelDensity(){var i;const t=this._textmodifier,e=(i=t.pixelDensity)==null?void 0:i.call(t);return typeof e=="number"&&Number.isFinite(e)&&e>0?e:1}_withExtension(t,e){if(!t)return;const i=t.trim();return i?i.toLowerCase().endsWith(e)?i:`${i}${e}`:void 0}}class jo extends K{$extractCellData(t){var n;const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],a=t.grid,s=t.font;let o=0;for(let l=0;l<a.rows;l++)for(let c=0;c<a.cols;c++){const d=4*o,u=this.$getEncodedCharacterValue(e.characterPixels,d),m=this.$extractCellTransform(e.characterPixels,d),h=((n=be(s,u))==null?void 0:n.character)??" ";i.push({x:c,y:l,character:h,foreground:ee(e.primaryColorPixels,d),background:ee(e.secondaryColorPixels,d),transform:{invert:m.isInverted,flipX:m.flipHorizontal,flipY:m.flipVertical,rotation:m.rotation}}),o++}return i}}const Li="1.2.1",Wi="textmode.document",Oi="2.0.0";class Ye{_applyDefaultOptions(t){return{target:t.target??"selected",pretty:t.pretty??!0,colorMode:t.colorMode??"hex",includeMetadata:t.includeMetadata??!0,filename:t.filename,layer:t.layer}}_createMetadata(t){return t.includeMetadata?{createdAt:new Date().toISOString(),generator:{name:"textmode.export.js",version:Li}}:void 0}_formatColor(t,e){return e==="rgba"?{...t}:`#${[t.r,t.g,t.b,t.a].map(i=>i.toString(16).padStart(2,"0")).join("")}`}_createObjectRowsCells(t,e,i,a){const s=[];for(let o=0;o<i;o++){const n=o*e,l=t.slice(n,n+e).map(c=>({x:c.x,y:c.y,character:c.character,foreground:this._formatColor(c.foreground,a),background:this._formatColor(c.background,a),transform:{...c.transform}}));s.push(l)}return{encoding:"object-rows-v1",rows:s}}_createLayerGrid(t){return{cols:t.grid.cols,rows:t.grid.rows,cellWidth:t.grid.cellWidth,cellHeight:t.grid.cellHeight}}_createLayerCells(t,e){const i=new jo().$extractCellData(t);return this._createObjectRowsCells(i,t.grid.cols,t.grid.rows,e.colorMode)}_createStackLayer(t,e){return{id:t.id,visible:t.visible,opacity:t.opacity,blendMode:t.blendMode,offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this._createLayerGrid(t),cells:this._createLayerCells(t,e)}}$generateJSONData(t,e={}){const i=this._applyDefaultOptions(e),a=this._createMetadata(i);if(i.target==="all"){const o=(function(l){return[l.layers.base,...l.layers.all].map(c=>{const d=c;return{...te(l,c),visible:d._visible??!0,opacity:d._opacity??1,blendMode:d._blendMode??"normal",offsetX:d._offsetX??0,offsetY:d._offsetY??0,rotationZ:d._rotation??0}})})(t),n=o[0].grid;return{format:Wi,formatVersion:Oi,target:"all",...a?{metadata:a}:{},canvas:{width:n.width,height:n.height},layers:o.map(l=>this._createStackLayer(l,i))}}const s=te(t,i.layer);return{format:Wi,formatVersion:Oi,target:"selected",...a?{metadata:a}:{},canvas:{width:s.grid.width,height:s.grid.height},grid:this._createLayerGrid(s),layer:{id:s.id,cells:this._createLayerCells(s,i)}}}$generateJSONString(t,e={}){const i=this._applyDefaultOptions(e),a=this.$generateJSONData(t,i),s=typeof i.pretty=="number"?i.pretty:i.pretty?2:0;return JSON.stringify(a,null,s)}$saveJSON(t,e={}){const i=this._applyDefaultOptions(e);new ot().$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename)}}const qo="textmode-export-overlay",ht="textmode-export-overlay__stack",Je="textmode-export-overlay__stack--dense",$i="textmode-export-overlay__stack--compact",zi="textmode-export-overlay__section",Go="textmode-export-overlay__header",Qo="textmode-export-overlay__header-title-row",Xo="textmode-export-overlay__header-links",Ko="textmode-export-overlay__row",Ni="textmode-export-overlay__label",Ui="textmode-export-overlay__field",Hi="textmode-export-overlay__field--compact",ji="textmode-export-overlay__field--dense",qi="textmode-export-overlay__field--full",Gi="textmode-export-overlay__field--channel",Qi="textmode-export-overlay__input",Yo="textmode-export-overlay__checkbox",Xi="textmode-export-overlay__muted",Jo="textmode-export-overlay__status",Zo="textmode-export-overlay__status--gif",tn="textmode-export-overlay__status--video",en="textmode-export-overlay__status-title",rn="textmode-export-overlay__status-value",an="textmode-export-overlay__divider",sn="textmode-export-overlay__title",on="textmode-export-overlay__button",Ze="textmode-export-overlay__button--primary",tr="textmode-export-overlay__button--secondary",Ki="textmode-export-overlay__button--full",nn="textmode-export-overlay__support-link",cn="textmode-export-overlay__support-icon",dn="textmode-export-overlay__link-icon";class ut{constructor(){w(this,"element");w(this,"mounted",!1);w(this,"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._onUnmount(),this.element.remove(),this.element=void 0,this.mounted=!1)}destroy(){this.destroyed||(this.unmount(),this._onDestroy(),this.destroyed=!0)}update(t){this.mounted&&this.onUpdate(t)}onMount(){}_onUnmount(){}_onDestroy(){}onUpdate(t){}get root(){if(!this.element)throw new Error("Component is not mounted yet");return this.element}isMounted(){return this.mounted}}const $t=class $t extends ut{render(){const t=document.createElement("div");t.classList.add(ht,Je,Go);const e=document.createElement("div");e.classList.add(Qo);const i=document.createElement("strong");i.textContent="textmode.export.js",i.classList.add(sn);const a=document.createElement("div");a.classList.add(Xo);const s=this._createLink("https://github.com/humanbydefinition/textmode.export.js","View repository on GitHub",dn,[{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"}]),o=this._createLink("https://code.textmode.art/docs/support","Support textmode.export.js",cn,[{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"}]);a.appendChild(s),a.appendChild(o),e.appendChild(i),e.appendChild(a);const n=document.createElement("div");return n.classList.add(an),t.appendChild(e),t.appendChild(n),t}_createLink(t,e,i,a){const s=document.createElement("a");return s.href=t,s.target="_blank",s.rel="noopener noreferrer",s.classList.add(nn),s.setAttribute("aria-label",e),s.appendChild(this._createIcon(i,a)),s}_createIcon(t,e){const i=document.createElementNS($t._iconNamespace,"svg");i.setAttribute("xmlns",$t._iconNamespace),i.setAttribute("width","18"),i.setAttribute("height","18"),i.setAttribute("viewBox","0 0 24 24"),i.setAttribute("fill","none"),i.setAttribute("stroke","currentColor"),i.setAttribute("stroke-width","2"),i.setAttribute("stroke-linecap","round"),i.setAttribute("stroke-linejoin","round"),i.classList.add(t);for(const a of e){const s=document.createElementNS($t._iconNamespace,"path");for(const[o,n]of Object.entries(a))s.setAttribute(o,n);i.appendChild(s)}return i}};w($t,"_iconNamespace","http://www.w3.org/2000/svg");let er=$t;class H extends ut{constructor(e){super();w(this,"props");this.props=e}render(){const e=document.createElement("div");e.classList.add(Ui),this.applyVariant(e,this.props.variant);const i=document.createElement("label");if(i.classList.add(Ni),i.textContent=this.props.label,this.props.labelFor&&(i.htmlFor=this.props.labelFor),e.appendChild(i),this.props.description){const a=document.createElement("span");a.classList.add(Xi),a.textContent=this.props.description,e.appendChild(a)}return e}attachControl(e){this.root.appendChild(e)}update(e){this.props=e,super.update(e)}onUpdate(e){const i=this.root;for(;i.firstChild;)i.removeChild(i.firstChild);this.props=e,i.classList.add(Ui),this.applyVariant(i,e.variant);const a=document.createElement("label");if(a.classList.add(Ni),a.textContent=e.label,e.labelFor&&(a.htmlFor=e.labelFor),i.appendChild(a),e.description){const s=document.createElement("span");s.classList.add(Xi),s.textContent=e.description,i.appendChild(s)}}applyVariant(e,i){switch(e.classList.remove(Hi,ji,qi,Gi),i){case"compact":e.classList.add(Hi);break;case"dense":e.classList.add(ji);break;case"full":e.classList.add(qi);break;case"channel":e.classList.add(Gi)}}}class mt extends ut{constructor(e){super();w(this,"props");w(this,"select");w(this,"handleChange",()=>{this.props.defaultValue=this.select.value});this.props=e}render(){return this.select=document.createElement("select"),this.select.classList.add(Qi),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(e){this.select&&(this.select.value=e),this.props.defaultValue=e}_onUnmount(){this.select.removeEventListener("change",this.handleChange)}onUpdate(e){this.props=e,this.populateOptions(),e.defaultValue&&(this.select.value=e.defaultValue)}update(e){this.props={...this.props,...e},this.select&&(e.id&&(this.select.id=e.id),e.options&&this.populateOptions(),e.defaultValue!==void 0&&(this.select.value=e.defaultValue))}populateOptions(){if(this.select){this.select.innerHTML="";for(const e of this.props.options){const i=document.createElement("option");i.value=e.value,i.textContent=e.label,this.select.appendChild(i)}this.props.defaultValue&&(this.select.value=this.props.defaultValue)}}}class Yi extends ut{constructor(e){super();w(this,"props");w(this,"button");this.props=e}render(){return this.button=document.createElement("button"),this.button.type="button",this.button.textContent=this.props.label,this.button.classList.add(on),this.props.variant==="secondary"?this.button.classList.add(tr):this.button.classList.add(Ze),this.props.fullWidth&&this.button.classList.add(Ki),this.button.disabled=!!this.props.disabled,this.button}get buttonElement(){return this.button}setLabel(e){this.props.label=e,this.button.textContent=e}setDisabled(e){this.props.disabled=e,this.button.disabled=e}onUpdate(e){this.props=e,this.button.textContent=e.label,this.button.disabled=!!e.disabled,e.variant==="secondary"?(this.button.classList.add(tr),this.button.classList.remove(Ze)):(this.button.classList.add(Ze),this.button.classList.remove(tr)),this.button.classList.toggle(Ki,!!e.fullWidth)}}class ln{constructor(t){w(this,"api");this.api=t}async $copy(t,e){switch(t){case"txt":{const i=this.api.toString(e);await navigator.clipboard.writeText(i);break}case"json":{const i=this.api.toJSONString(e);await navigator.clipboard.writeText(i);break}case"svg":{const i=this.api.toSVG(e);await navigator.clipboard.writeText(i);break}case"image":await this.api.copyCanvas(e);break;default:throw new Error(`Clipboard not supported for ${t}`)}}}class hn{constructor(t,e){w(this,"api");w(this,"events");this.api=t,this.events=e}async $requestExport(t,e,i={}){this.events.$emit("export:request",{format:t});try{const a={onGIFProgress:i.onGIFProgress?s=>{var o;(o=i.onGIFProgress)==null||o.call(i,s),this.events.$emit("export:progress",{format:t,progress:s})}:t==="gif"?s=>this.events.$emit("export:progress",{format:t,progress:s}):void 0,onVideoProgress:i.onVideoProgress?s=>{var o;(o=i.onVideoProgress)==null||o.call(i,s),this.events.$emit("export:progress",{format:t,progress:s})}:t==="video"?s=>this.events.$emit("export:progress",{format:t,progress:s}):void 0};await this._execute(t,e,a),this.events.$emit("export:success",{format:t})}catch(a){throw this.events.$emit("export:error",{format:t,error:a}),a}}_execute(t,e,i){switch(t){case"txt":return Promise.resolve(this.api.saveStrings(e));case"json":return Promise.resolve(this.api.saveJSON(e));case"image":return this.api.saveCanvas(e);case"svg":return Promise.resolve(this.api.saveSVG(e));case"gif":{const a={...e,onProgress:i.onGIFProgress};return this.api.saveGIF(a)}case"video":{const a={...e,onProgress:i.onVideoProgress};return this.api.saveVideo(a)}}}}class un{constructor(t,e){w(this,"modifier");w(this,"overlay");w(this,"animationFrameId",null);w(this,"handleUpdate");w(this,"bound",!1);this.modifier=t,this.overlay=e,this.handleUpdate=()=>this.scheduleUpdate()}scheduleUpdate(){this.animationFrameId!==null&&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())}update(){this.animationFrameId=null;const t=this.modifier.canvas.getBoundingClientRect();this.overlay.style.top=`${t.top+window.scrollY+8}px`,this.overlay.style.left=`${t.left+window.scrollX+8}px`}dispose(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.bound&&(window.removeEventListener("resize",this.handleUpdate),window.removeEventListener("scroll",this.handleUpdate,!0),this.bound=!1)}}const Jt="textmode-export-number-input",mn=`${Jt}__field`,pn=`${Jt}__controls`,fn=`${Jt}__control`,Ji=`${Jt}__display`,ye=`${Ji}--visible`,Zi=r=>{const t=document.createElement("button");return t.type="button",t.className=fn,t.textContent=r>0?"▲":"▼",t};class kt extends ut{constructor(e){super();w(this,"props");w(this,"input");w(this,"display");w(this,"incrementButton");w(this,"decrementButton");w(this,"suppressClickAfterPointer",new WeakMap);w(this,"holdTimeoutId");w(this,"holdIntervalId");w(this,"activePointerId");w(this,"disabledObserver");this.props=e}render(){const e=document.createElement("div");e.className=Jt,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=mn,this.display=document.createElement("div"),this.display.className=Ji;const i=document.createElement("div");return i.className=pn,this.incrementButton=Zi(1),this.decrementButton=Zi(-1),i.appendChild(this.incrementButton),i.appendChild(this.decrementButton),e.appendChild(this.input),e.appendChild(this.display),e.appendChild(i),this.bindStepControls(),this.bindHoldBehavior(),this.bindInputListeners(),this.observeDisabledState(e),this.updateDisplay(),e}get inputElement(){return this.input}get value(){return this.input.value}set value(e){this.input.value=e,this.updateDisplay()}refresh(){this.updateDisplay()}_onDestroy(){var e;this.clearHoldTimers(),(e=this.disabledObserver)==null||e.disconnect()}bindStepControls(){const e=o=>()=>{if(this.input.disabled)return;const n=this.input.value,l=this.input.getAttribute("step");if(l&&l!=="any")o>0?this.input.stepUp():this.input.stepDown();else{const d=o>0?1:-1,u=Number.parseFloat(this.input.value||"0"),m=Number.isFinite(u)?u+d:d;this.input.value=String(m)}var c;this.input.value!==n&&((c=this.input).dispatchEvent(new Event("input",{bubbles:!0})),c.dispatchEvent(new Event("change",{bubbles:!0}))),this.updateDisplay(),this.input.focus({preventScroll:!0})},i=e(1),a=e(-1),s=(o,n)=>l=>{if(this.suppressClickAfterPointer.get(o))return this.suppressClickAfterPointer.set(o,!1),void l.preventDefault();n()};this.incrementButton.addEventListener("click",s(this.incrementButton,i)),this.decrementButton.addEventListener("click",s(this.decrementButton,a))}bindHoldBehavior(){const e=(i,a)=>{const s=a>0?()=>this.incrementButton.click():()=>this.decrementButton.click();i.addEventListener("pointerdown",l=>{if(l.button===0){l.preventDefault(),this.suppressClickAfterPointer.set(i,!0),this.activePointerId=l.pointerId;try{i.setPointerCapture(l.pointerId)}catch{}s(),this.holdTimeoutId=window.setTimeout(()=>{this.holdIntervalId=window.setInterval(s,80)},380)}});const o=()=>{if(this.activePointerId!==void 0){try{i.releasePointerCapture(this.activePointerId)}catch{}this.activePointerId=void 0}},n=()=>{this.clearHoldTimers(),o()};i.addEventListener("pointerup",n),i.addEventListener("pointerleave",n),i.addEventListener("pointercancel",n)};e(this.incrementButton,1),e(this.decrementButton,-1)}bindInputListeners(){const e=()=>{this.props.defaultValue=this.input.value,this.updateDisplay()};this.input.addEventListener("input",e),this.input.addEventListener("change",e)}observeDisabledState(e){const i=()=>{const a=this.input.disabled;this.incrementButton.disabled=a,this.decrementButton.disabled=a,e.classList.toggle("is-disabled",a),a?(this.display.classList.remove(ye),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor")):this.updateDisplay()};typeof MutationObserver<"u"&&(this.disabledObserver=new MutationObserver(i),this.disabledObserver.observe(this.input,{attributes:!0,attributeFilter:["disabled"]})),i()}updateDisplay(){const e=this.props.formatDisplay;if(!e)return this.display.textContent="",this.display.classList.remove(ye),this.input.style.removeProperty("color"),void this.input.style.removeProperty("caretColor");const i=this.input.value,a=Number.parseFloat(i),s=e(Number.isFinite(a)?a:Number.NaN,i,this.input);s?(this.display.textContent=s,this.display.classList.add(ye),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(ye),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor"))}clearHoldTimers(){this.holdTimeoutId!==void 0&&(window.clearTimeout(this.holdTimeoutId),this.holdTimeoutId=void 0),this.holdIntervalId!==void 0&&(window.clearInterval(this.holdIntervalId),this.holdIntervalId=void 0)}}class Pt extends ut{constructor(e="stack",i=[]){super();w(this,"variant");w(this,"additionalClasses");this.variant=e,this.additionalClasses=i}render(){const e=document.createElement("div"),i=[this.variant==="stack"?ht:void 0,this.variant==="stackDense"?Je:void 0,this.variant==="stackCompact"?$i:void 0,this.variant==="row"?Ko:void 0,this.variant==="section"?zi:void 0,...this.additionalClasses].filter(Boolean);return e.classList.add(...i),e}}const ta={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"};class ea extends ut{constructor(e){super();w(this,"props");w(this,"container");w(this,"messageElement");this.props=e}render(){this.container=document.createElement("div"),this.container.classList.add(Jo),this.props.context==="gif"?this.container.classList.add(Zo):this.props.context==="video"&&this.container.classList.add(tn);const e=document.createElement("span");return e.classList.add(en),e.textContent=this.props.title,this.messageElement=document.createElement("span"),this.messageElement.classList.add(rn),this.messageElement.textContent=this.props.message,this.applyVariant(this.props.variant??"neutral"),this.container.appendChild(e),this.container.appendChild(this.messageElement),this.container}setMessage(e,i="neutral"){this.messageElement.textContent=e,this.applyVariant(i)}onUpdate(e){this.props=e,this.setMessage(e.message,e.variant??"neutral")}applyVariant(e){this.messageElement.classList.remove(...Object.values(ta)),this.messageElement.classList.add(ta[e])}}class Ot extends ut{constructor(e){super();w(this,"_config");w(this,"_managedComponents",new Set);this._config=e}_manageComponent(e){return this._managedComponents.add(e),e}_onUnmount(){for(const e of this._managedComponents)e.unmount()}_onDestroy(){for(const e of this._managedComponents)e.destroy();this._managedComponents.clear()}}const ra=300,ia=60,aa=1,gn=0;class rr extends Ot{constructor(e){super(e);w(this,"frameCountInput",this._manageComponent(new kt({defaultValue:String(ra),attributes:{min:"1",max:"600",step:"1"}})));w(this,"frameRateInput",this._manageComponent(new kt({defaultValue:String(ia),attributes:{min:"1",max:"60",step:"1"}})));w(this,"scaleInput",this._manageComponent(new kt({defaultValue:String(aa),attributes:{min:"0.1",max:"8",step:"0.1"}})));w(this,"repeatInput",this._manageComponent(new kt({defaultValue:"0",attributes:{min:"0",max:"50",step:"1"},formatDisplay:(e,i)=>Number.isFinite(e)?e===0?"∞":null:i.trim()===""?null:i})));w(this,"status",this._manageComponent(new ea({title:"status",message:"ready to record",variant:"neutral",context:"gif"})));w(this,"recordingState","idle")}render(){const e=document.createElement("div");e.classList.add(ht);const i=new Pt("row");i.mount(e);const a=new H({label:"number of frames",labelFor:"textmode-export-gif-frame-count",variant:"dense"});a.mount(i.root),this.frameCountInput.mount(a.root),this.frameCountInput.inputElement.id="textmode-export-gif-frame-count";const s=new H({label:"frame rate (fps)",labelFor:"textmode-export-gif-frame-rate",variant:"dense"});s.mount(i.root),this.frameRateInput.mount(s.root),this.frameRateInput.inputElement.id="textmode-export-gif-frame-rate";const o=new Pt("row");o.mount(e);const n=new H({label:"scale",labelFor:"textmode-export-gif-scale",variant:"dense"});n.mount(o.root),this.scaleInput.mount(n.root),this.scaleInput.inputElement.id="textmode-export-gif-scale";const l=new H({label:"loop count",labelFor:"textmode-export-gif-repeat",variant:"dense"});return l.mount(o.root),this.repeatInput.mount(l.root),this.repeatInput.inputElement.id="textmode-export-gif-repeat",this.status.mount(e),e}getOptions(){const e=this._config.defaultOptions??{};return{frameCount:this.safeParseInt(this.frameCountInput.value,e.frameCount??300),frameRate:this.safeParseInt(this.frameRateInput.value,e.frameRate??60),scale:this.safeParseFloat(this.scaleInput.value,e.scale??1),repeat:this.safeParseInt(this.repeatInput.value,e.repeat??0)}}reset(){this.recordingState="idle",this.applyDefaults(),this.setRecordingState("idle")}validate(){const e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseInt(this.frameRateInput.value,10),a=Number.parseFloat(this.scaleInput.value);return Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>0&&Number.isFinite(a)&&a>0}isRecording(){return this.recordingState==="recording"||this.recordingState==="encoding"}setRecordingState(e,i){this.recordingState=e;const a=e==="recording"||e==="encoding";switch(this.frameCountInput.inputElement.disabled=a,this.frameRateInput.inputElement.disabled=a,this.scaleInput.inputElement.disabled=a,this.repeatInput.inputElement.disabled=a,e){case"recording":if(i!=null&&i.totalFrames){const s=i.frameIndex??0;this.status.setMessage(`recording ${s}/${i.totalFrames}`,"active")}else this.status.setMessage("recording…","active");break;case"encoding":if(i!=null&&i.totalFrames){const s=i.frameIndex??0;this.status.setMessage(`encoding ${s}/${i.totalFrames}`,"active")}else this.status.setMessage("encoding…","active");break;case"completed":this.status.setMessage("GIF saved successfully","active");break;case"error":this.status.setMessage((i==null?void 0:i.message)??"failed to export GIF","alert");break;default:this.status.setMessage("ready to record","neutral")}}handleProgress(e){if(e.state!=="recording"&&e.state!=="encoding"||!e.totalFrames)e.state==="completed"?this.status.setMessage("GIF saved successfully","active"):e.state==="error"&&this.status.setMessage(e.message??"failed to export GIF","alert");else{const i=e.state==="recording"?"recording":"encoding";this.status.setMessage(`${i} ${e.frameIndex??0}/${e.totalFrames}`,"active")}}applyDefaults(){const e=this._config.defaultOptions??{},i=e.frameCount??ra,a=e.frameRate??ia,s=e.scale??aa,o=e.repeat??gn;this.frameCountInput.value=String(i),this.frameRateInput.value=String(a),this.scaleInput.value=String(s),this.repeatInput.value=String(o),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.scaleInput.refresh(),this.repeatInput.refresh()}safeParseInt(e,i){const a=Number.parseInt(e,10);return Number.isFinite(a)?a:i}safeParseFloat(e,i){const a=Number.parseFloat(e);return Number.isFinite(a)?a:i}}class Zt extends ut{constructor(e){super();w(this,"props");w(this,"checkbox");w(this,"labelElement");w(this,"handleChange",()=>{this.props.defaultChecked=this.checkbox.checked});this.props=e}render(){this.labelElement=document.createElement("label"),this.labelElement.classList.add(Yo),this.checkbox=document.createElement("input"),this.checkbox.type="checkbox",this.props.id&&(this.checkbox.id=this.props.id),this.checkbox.checked=!!this.props.defaultChecked,this.checkbox.addEventListener("change",this.handleChange);const e=document.createElement("span");return e.textContent=this.props.label,this.labelElement.htmlFor=this.props.id??"",this.labelElement.appendChild(this.checkbox),this.labelElement.appendChild(e),this.labelElement}get inputElement(){return this.checkbox}get checked(){return this.checkbox.checked}set checked(e){this.checkbox.checked=e}_onUnmount(){this.checkbox.removeEventListener("change",this.handleChange)}onUpdate(e){this.props=e,e.id&&(this.checkbox.id=e.id,this.labelElement.htmlFor=e.id),this.checkbox.checked=!!e.defaultChecked,this.labelElement.lastElementChild&&(this.labelElement.lastElementChild.textContent=e.label)}}const sa="medium",oa="variable",na="quality",ca="no-preference";class ir extends Ot{constructor(e){super(e);w(this,"formatSelect",this._manageComponent(new mt({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"})));w(this,"bitrateSelect",this._manageComponent(new mt({id:"textmode-export-video-bitrate",options:[{value:"low",label:"low"},{value:"medium",label:"medium"},{value:"high",label:"high"}],defaultValue:sa})));w(this,"frameRateInput",this._manageComponent(new kt({defaultValue:String(60),attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:e=>Number.isFinite(e)?`${e} fps`:null})));w(this,"frameCountInput",this._manageComponent(new kt({defaultValue:String(480),attributes:{min:String(1),max:String(3600),step:"1"}})));w(this,"bitrateModeSelect",this._manageComponent(new mt({id:"textmode-export-video-bitrate-mode",options:[{value:"variable",label:"variable"},{value:"constant",label:"constant"}],defaultValue:oa})));w(this,"latencyModeSelect",this._manageComponent(new mt({id:"textmode-export-video-latency-mode",options:[{value:"quality",label:"quality"},{value:"realtime",label:"realtime"}],defaultValue:na})));w(this,"hardwareAccelerationSelect",this._manageComponent(new mt({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:ca})));w(this,"keyFrameIntervalInput",this._manageComponent(new kt({defaultValue:String(2),attributes:{min:"0",step:"0.25"},formatDisplay:e=>Number.isFinite(e)?`${e}s`:null})));w(this,"transparencyInput",this._manageComponent(new Zt({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1})));w(this,"status",this._manageComponent(new ea({title:"status",message:"ready to record",variant:"neutral",context:"video"})));w(this,"recordingState","idle");w(this,"handleFormatChange",()=>{this.syncTransparencyAvailability()})}render(){const e=document.createElement("div");e.classList.add(ht);const i=new Pt("row");i.mount(e);const a=new H({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});a.mount(i.root),this.formatSelect.mount(a.root);const s=new H({label:"bitrate preset",labelFor:"textmode-export-video-bitrate",variant:"compact"});s.mount(i.root),this.bitrateSelect.mount(s.root);const o=new Pt("row");o.mount(e);const n=new H({label:"number of frames",labelFor:"textmode-export-video-frame-count",variant:"compact"});n.mount(o.root),this.frameCountInput.mount(n.root),this.frameCountInput.inputElement.id="textmode-export-video-frame-count";const l=new H({label:"frame rate (fps)",labelFor:"textmode-export-video-frame-rate",variant:"compact"});l.mount(o.root),this.frameRateInput.mount(l.root),this.frameRateInput.inputElement.id="textmode-export-video-frame-rate";const c=new Pt("row");c.mount(e);const d=new H({label:"bitrate mode",labelFor:"textmode-export-video-bitrate-mode",variant:"compact"});d.mount(c.root),this.bitrateModeSelect.mount(d.root);const u=new H({label:"encoder mode",labelFor:"textmode-export-video-latency-mode",variant:"compact"});u.mount(c.root),this.latencyModeSelect.mount(u.root);const m=new Pt("row");m.mount(e);const h=new H({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(m.root),this.hardwareAccelerationSelect.mount(h.root);const p=new H({label:"keyframe interval",labelFor:"textmode-export-video-keyframe-interval",variant:"compact"});return p.mount(m.root),this.keyFrameIntervalInput.mount(p.root),this.keyFrameIntervalInput.inputElement.id="textmode-export-video-keyframe-interval",this.transparencyInput.mount(e),this.formatSelect.selectElement.addEventListener("change",this.handleFormatChange),this.syncTransparencyAvailability(),this.status.mount(e),e}getOptions(){const e=this._config.defaultOptions??{},i=Number.parseInt(this.frameCountInput.value,10),a=Number.parseFloat(this.frameRateInput.value),s=Number.parseFloat(this.keyFrameIntervalInput.value),o=this.formatSelect.value,n={format:o,bitrate:this.bitrateSelect.value,bitrateMode:this.bitrateModeSelect.value,latencyMode:this.latencyModeSelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.isFinite(s)?s:e.keyFrameInterval??2,frameCount:Number.isFinite(i)?i:e.frameCount??480,frameRate:Number.isFinite(a)?a:e.frameRate??60};return o==="webm"&&(n.transparent=this.transparencyInput.checked),n}reset(){this.recordingState="idle",this.applyDefaults(),this.status.setMessage("ready to record","neutral")}validate(){const e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value),a=Number.parseFloat(this.keyFrameIntervalInput.value);return Number.isFinite(e)&&e>=1&&Number.isFinite(i)&&i>=1&&Number.isFinite(a)&&a>=0}isRecording(){return this.recordingState==="recording"||this.recordingState==="encoding"}setRecordingState(e,i){this.recordingState=e;const a=e==="recording"||e==="encoding";this.formatSelect.selectElement.disabled=a,this.bitrateSelect.selectElement.disabled=a,this.frameCountInput.inputElement.disabled=a,this.frameRateInput.inputElement.disabled=a,this.bitrateModeSelect.selectElement.disabled=a,this.latencyModeSelect.selectElement.disabled=a,this.hardwareAccelerationSelect.selectElement.disabled=a,this.keyFrameIntervalInput.inputElement.disabled=a,this.transparencyInput.inputElement.disabled=a||this.formatSelect.value!=="webm",this.syncStatus(e,i)}handleProgress(e){this.syncStatus(e.state,e)}syncStatus(e,i){switch(e){case"recording":{const a=(i==null?void 0:i.frameIndex)??0,s=(i==null?void 0:i.totalFrames)??this.resolvePlannedFrameCount();if(s){const o=Math.min(Math.max(0,Math.round(a)),s);this.status.setMessage(`recording ${o}/${s} frames`,"active")}else this.status.setMessage(`recording ${Math.max(0,Math.round(a))} frames`,"active");break}case"encoding":this.status.setMessage("finalizing video","active");break;case"completed":this.status.setMessage("saved to disk","active");break;case"error":this.status.setMessage(i!=null&&i.message?`error: ${i.message}`:"recording failed","alert");break;default:this.status.setMessage("ready to record","neutral")}}resolvePlannedFrameCount(){const e=Number.parseInt(this.frameCountInput.value,10);return Number.isFinite(e)&&e>0?Math.round(e):void 0}applyDefaults(){const e=this._config.defaultOptions??{},i=e.format??"mp4",a=e.frameCount??480,s=e.frameRate??60,o=e.keyFrameInterval??2;this.formatSelect.value=i,this.bitrateSelect.value=this.resolveBitratePreset(e.bitrate),this.frameCountInput.value=String(a),this.frameRateInput.value=String(s),this.bitrateModeSelect.value=e.bitrateMode??oa,this.latencyModeSelect.value=e.latencyMode??na,this.hardwareAccelerationSelect.value=e.hardwareAcceleration??ca,this.keyFrameIntervalInput.value=String(o),this.transparencyInput.checked=!!e.transparent,this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.keyFrameIntervalInput.refresh(),this.syncTransparencyAvailability()}resolveBitratePreset(e){return e==="low"||e==="medium"||e==="high"?e:sa}syncTransparencyAvailability(){if(!this.transparencyInput.isMounted())return;const e=this.formatSelect.value==="webm";this.transparencyInput.root.style.display=e?"":"none",this.transparencyInput.inputElement.disabled=!e||this.isRecording(),e||(this.transparencyInput.checked=!1)}}class wn{constructor(t,e,i,a,s){w(this,"_textmodifier");w(this,"_state");w(this,"_events");w(this,"_exportService");w(this,"_clipboardService");w(this,"_definitions");w(this,"_formats",new Map);w(this,"_eventUnsubscribers",[]);w(this,"_shadowHost");w(this,"_shadowRoot");w(this,"_overlayElement");w(this,"_optionsContainer");w(this,"_copyButtonContainer");w(this,"_positionService");w(this,"_header",new er);w(this,"_formatField",new H({label:"export format",labelFor:"textmode-export-format",variant:"full"}));w(this,"_formatSelect",new mt({id:"textmode-export-format",options:[]}));w(this,"_exportButton",new Yi({label:"download file",fullWidth:!0,variant:"primary"}));w(this,"_copyButton",new Yi({label:"copy to clipboard",fullWidth:!0,variant:"primary"}));w(this,"_currentFormat");w(this,"_currentBlade");w(this,"_handleFormatSelectChange",()=>{this._handleFormatChange(this._formatSelect.value)});w(this,"_handleExportClickSafe",()=>{this._handleExportClick().catch(t=>{console.error("[textmode-export] Export failed",t)})});w(this,"_handleCopyClickSafe",()=>{this._handleCopyClick().catch(t=>{console.error("[textmode-export] Copy failed",t)})});this._textmodifier=t,this._state=i,this._events=a,this._exportService=new hn(e,a),this._clipboardService=new ln(e),this._definitions=s,this._currentFormat=i.snapshot.format,this._initializeFormatMap(),this._registerEventHandlers()}$mount(){this._createOverlay(),this._renderStaticContent(),this._positionService=new un(this._textmodifier,this._shadowHost),this._positionService.bind(),this._switchFormat(this._currentFormat)}show(){this._shadowHost&&(this.refreshLayerTargets(),this._shadowHost.style.display="")}hide(){this._shadowHost&&(this._shadowHost.style.display="none")}toggle(){this.isVisible()?this.hide():this.show()}isVisible(){return!!this._shadowHost&&this._shadowHost.style.display!=="none"}refreshLayerTargets(){this._currentBlade&&typeof this._currentBlade.blade.refreshLayerTargets=="function"&&this._currentBlade.blade.refreshLayerTargets()}$dispose(){var t,e;this._formatSelect.isMounted()&&this._formatSelect.selectElement.removeEventListener("change",this._handleFormatSelectChange),this._exportButton.isMounted()&&this._exportButton.buttonElement.removeEventListener("click",this._handleExportClickSafe),this._copyButton.isMounted()&&this._copyButton.buttonElement.removeEventListener("click",this._handleCopyClickSafe);for(const i of this._eventUnsubscribers)i();this._eventUnsubscribers.length=0,this._events.$clear();for(const i of this._formats.values())i.blade.destroy();this._formats.clear(),this._currentBlade=void 0,(t=this._shadowHost)!=null&&t.isConnected&&this._shadowHost.remove(),(e=this._positionService)==null||e.dispose()}_initializeFormatMap(){for(const t of this._definitions){const e=t.createBlade();this._formats.set(t.format,{definition:t,blade:e,initialized:!1})}}_createOverlay(){this._shadowHost=document.createElement("div"),this._shadowHost.dataset.plugin="textmode-export-overlay-host",this._shadowHost.style.cssText="position: absolute; top: 0; left: 0; pointer-events: none; z-index: 2147483647;",this._shadowRoot=this._shadowHost.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=`@layer textmode-export-overlay{.textmode-export-overlay{--overlay-bg: rgba(20, 20, 20, .8);--overlay-surface: rgba(40, 40, 40, .9);--overlay-border: rgba(255, 255, 255, .14);--overlay-border-strong: rgba(255, 255, 255, .2);--overlay-border-focus: rgba(160, 160, 160, .6);--overlay-focus-shadow: 0 0 0 1px rgba(140, 140, 140, .28);--overlay-text: #ffffff;--overlay-muted: rgba(200, 200, 200, .74);--overlay-radius: .75rem;--overlay-stack-gap: .55rem;position:absolute;top:0;left:0;display:flex;flex-direction:column;gap:var(--overlay-stack-gap);min-width:236px;max-width:236px;padding:.65rem .8rem;background:var(--overlay-bg);color:var(--overlay-text);border-radius:var(--overlay-radius);border:1px solid var(--overlay-border);box-shadow:0 12px 28px #0000004d;-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:.82rem;line-height:1.35;pointer-events:auto;z-index:2147483647}.textmode-export-overlay *{box-sizing:border-box}.textmode-export-overlay__header{display:flex;flex-direction:column;gap:.4rem}.textmode-export-overlay__header-title-row{display:flex;align-items:center;justify-content:space-between;gap:.4rem}.textmode-export-overlay__header-links{display:inline-flex;align-items:center;gap:.3rem}.textmode-export-overlay__support-link{display:inline-flex;align-items:center;justify-content:center;padding:.2rem;border-radius:.45rem;border:1px solid transparent;color:#d7d7d7d1;background:transparent;text-decoration:none;line-height:0;transition:background .18s ease,color .18s ease,transform .18s ease,border-color .18s ease}.textmode-export-overlay__support-link:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__support-link:focus-visible{outline:none;border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow)}.textmode-export-overlay__support-icon,.textmode-export-overlay__link-icon{display:block;width:1rem;height:1rem}.textmode-export-overlay__stack{display:flex;flex-direction:column;gap:var(--overlay-stack-gap)}.textmode-export-overlay__stack--dense{gap:.3rem}.textmode-export-overlay__stack--compact{gap:.45rem}.textmode-export-overlay__section{display:flex;flex-direction:column;gap:.4rem}.textmode-export-overlay__title{font-size:.92rem;font-weight:600}.textmode-export-overlay__divider{width:100%;height:1px;background:#ffffff29;margin-top:.25rem}.textmode-export-overlay__label{font-weight:500;opacity:.9}.textmode-export-overlay__checkbox{display:flex;align-items:center;gap:.5rem}.textmode-export-overlay__checkbox input[type=checkbox]{width:1rem;height:1rem;accent-color:rgba(100,100,100,.9)}.textmode-export-overlay__row{display:flex;gap:.6rem;flex-wrap:wrap;align-items:flex-start;width:100%}.textmode-export-overlay__field{display:flex;flex-direction:column;gap:.3rem;flex:1 1 120px;min-width:120px}.textmode-export-overlay__field--compact{flex:1 1 100px;min-width:100px}.textmode-export-overlay__field--dense{flex:1 1 90px;min-width:90px}.textmode-export-overlay__field--channel{flex:1 1 0;min-width:0}.textmode-export-overlay__field--full{width:100%;flex:1 1 100%}.textmode-export-overlay__input,.textmode-export-overlay select.textmode-export-overlay__input,.textmode-export-overlay input.textmode-export-overlay__input{width:100%;padding:.35rem .5rem;border-radius:.4rem;border:1px solid var(--overlay-border-strong);background:var(--overlay-surface);color:var(--overlay-text);font:inherit;line-height:1.35;transition:border-color .18s ease,box-shadow .18s ease,background .18s ease}.textmode-export-overlay select.textmode-export-overlay__input{-webkit-appearance:none;-moz-appearance:none;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-repeat:no-repeat;background-position:right .5rem center;background-size:1rem;padding-right:2rem}.textmode-export-overlay__input:focus{outline:none;border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);background:#2d2f42eb}.textmode-export-overlay__input::placeholder{color:var(--overlay-muted);opacity:.7}.textmode-export-overlay__muted{font-size:.75rem;opacity:.7;display:block}.textmode-export-overlay__button{display:inline-flex;align-items:center;justify-content:center;gap:.35rem;border-radius:.45rem;border:none;font-weight:600;padding:.45rem .7rem;cursor:pointer;transition:background .2s ease,transform .2s ease,box-shadow .2s ease}.textmode-export-overlay__button--primary{background:#505050;color:#fff}.textmode-export-overlay__button--secondary{background:#606060;color:#fff}.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;transform:none;box-shadow:none}.textmode-export-overlay__status{display:flex;flex-direction:column;gap:.25rem;padding:.45rem .55rem;border-radius:.45rem;border:1px solid rgba(110,110,110,.22);background:#4646462e}.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{font-weight:600;font-size:.75rem;opacity:.85;text-transform:uppercase;letter-spacing:.04em}.textmode-export-overlay__status-value{font-size:.82rem;color:#dedede;transition:color .18s ease}.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{display:flex;align-items:stretch;width:100%;background:var(--overlay-surface);border:1px solid var(--overlay-border-strong);border-radius:.4rem;overflow:hidden;transition:border-color .18s ease,box-shadow .18s ease,background .18s ease;position:relative}.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{flex:1 1 auto;min-width:0;border:none;background:transparent;color:var(--overlay-text);font:inherit;padding:.35rem .5rem;-webkit-appearance:textfield;-moz-appearance:textfield;appearance:textfield}.textmode-export-number-input__field::-webkit-outer-spin-button,.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{display:flex;flex-direction:column;border-left:1px solid rgba(255,255,255,.12);min-width:1.6rem}.textmode-export-number-input__control{display:flex;align-items:center;justify-content:center;width:100%;flex:1;border:none;background:#32323299;color:#d0d0d0;font-size:.68rem;line-height:1;cursor:pointer;transition:background .15s ease,color .15s ease;padding:0}.textmode-export-number-input__control:hover:not(:disabled){background:#5a5a5ad9;color:#fff}.textmode-export-number-input__control:disabled{cursor:default;opacity:.4;background:#28282880;color:#c8c8c866}.textmode-export-number-input:focus-within .textmode-export-number-input__control{background:#3c3c3cbf;color:#e8e8e8}.textmode-export-number-input__display{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;padding:.4rem .55rem;pointer-events:none;color:#f8fafc;opacity:0;transition:opacity .14s ease}.textmode-export-number-input__display--visible{opacity:1}.textmode-export-range-input{position:relative;width:100%}.textmode-export-range-input.is-disabled{opacity:.55}.textmode-export-range-input__field{width:100%;height:1.4rem;padding:0;margin:0;background:transparent;cursor:pointer;-moz-appearance:none;appearance:none;-webkit-appearance:none}.textmode-export-range-input__field::-webkit-slider-thumb{width:12px;height:12px;margin-top:-3.5px;-webkit-appearance:none;border-radius:50%;background:#a0a0a0;border:2px solid #303030;box-shadow:0 0 0 2px #00000059}.textmode-export-range-input__field::-webkit-slider-runnable-track{height:5px;border-radius:999px;background:linear-gradient(90deg,#8c8c8cd9,#646464a6)}.textmode-export-range-input__field::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:#a0a0a0;border:2px solid #303030;margin-top:-3.5px}.textmode-export-range-input__field::-moz-range-track{height:5px;border-radius:999px;background:linear-gradient(90deg,#8c8c8cd9,#646464a6)}.textmode-export-range-input__tooltip{position:absolute;top:-1.5rem;left:0;transform:translate(-50%);padding:.2rem .35rem;border-radius:.35rem;background:#1e1e1ee0;color:#f8fafc;font-size:.68rem;line-height:1;white-space:nowrap;pointer-events:none;opacity:0;transition:opacity .15s ease}.textmode-export-range-input__tooltip--visible{opacity:1}}`,this._shadowRoot.appendChild(t),this._overlayElement=document.createElement("div"),this._overlayElement.dataset.plugin="textmode-export-overlay",this._overlayElement.classList.add(qo,ht),this._shadowRoot.appendChild(this._overlayElement),document.body.appendChild(this._shadowHost)}_renderStaticContent(){this._header.mount(this._overlayElement);const t=document.createElement("div");t.classList.add(zi),this._overlayElement.appendChild(t),this._formatField.mount(t),this._prepareFormatOptions(),this._formatSelect.mount(this._formatField.root),this._formatSelect.selectElement.addEventListener("change",this._handleFormatSelectChange),this._optionsContainer=document.createElement("div"),this._optionsContainer.classList.add(ht,$i),this._overlayElement.appendChild(this._optionsContainer),this._exportButton.mount(this._overlayElement),this._exportButton.buttonElement.addEventListener("click",this._handleExportClickSafe),this._copyButtonContainer=document.createElement("div"),this._copyButtonContainer.classList.add(ht,Je),this._overlayElement.appendChild(this._copyButtonContainer),this._copyButton.mount(this._copyButtonContainer),this._copyButton.buttonElement.dataset.defaultLabel="copy to clipboard",this._copyButton.buttonElement.addEventListener("click",this._handleCopyClickSafe)}_prepareFormatOptions(){const t=this._definitions.map(e=>({value:e.format,label:e.label}));this._formatSelect.update({options:t,defaultValue:this._currentFormat})}_registerEventHandlers(){this._eventUnsubscribers.push(this._events.$on("export:request",({format:t})=>{t===this._currentFormat&&(this._state.$set({isBusy:!0,error:void 0}),this._updateExportButton())}),this._events.$on("export:success",({format:t})=>{if(t===this._currentFormat){const e={isBusy:!1};t==="gif"&&(e.gifProgress=void 0),t==="video"&&(e.videoProgress=void 0),this._state.$set(e),this._updateExportButton()}}),this._events.$on("export:error",({format:t,error:e})=>{t===this._currentFormat&&(this._state.$set({isBusy:!1,error:e}),this._updateExportButton())}),this._events.$on("export:progress",({format:t,progress:e})=>{var i,a;if(e){if(t==="gif"&&((i=this._currentBlade)==null?void 0:i.blade)instanceof rr){const s=e;this._state.$set({gifProgress:s}),this._currentBlade.blade.handleProgress(s)}else if(t==="video"&&((a=this._currentBlade)==null?void 0:a.blade)instanceof ir){const s=e;this._state.$set({videoProgress:s}),this._currentBlade.blade.handleProgress(s)}this._updateExportButton()}}))}_handleFormatChange(t){this._currentFormat=t,this._state.$set({format:t}),this._switchFormat(t),this._events.$emit("format:change",{format:t})}_switchFormat(t){var i;const e=this._formats.get(t);if(!e)throw new Error(`Unknown export format: ${t}`);this._currentBlade&&this._currentBlade.blade.unmount(),this._optionsContainer.innerHTML="",e.blade.mount(this._optionsContainer),e.initialized||(e.blade.reset(),e.initialized=!0),this._currentBlade=e,this._formatSelect.value=t,this.refreshLayerTargets(),this._updateCopyButtonState(),this._updateExportButton(),(i=this._positionService)==null||i.scheduleUpdate()}_updateCopyButtonState(){var e;const t=((e=this._currentBlade)==null?void 0:e.definition.supportsClipboard)??!1;this._copyButtonContainer.style.display=t?"flex":"none",this._copyButton.setDisabled(!t)}async _handleExportClick(){if(!this._currentBlade)return;const t=this._currentBlade.definition.format,e=this._currentBlade.blade.getOptions();if(this._currentBlade.blade.validate()){if(t==="gif"){const i=this._currentBlade.blade;if(i.isRecording())return;i.setRecordingState("recording");try{await this._exportService.$requestExport("gif",e,{onGIFProgress:a=>{i.setRecordingState(a.state,a)}})}catch(a){throw i.setRecordingState("error"),a}return void window.setTimeout(()=>{i.setRecordingState("idle"),this._updateExportButton()},1600)}if(t==="video"){const i=this._currentBlade.blade;if(i.isRecording())return;i.setRecordingState("recording");try{await this._exportService.$requestExport("video",e,{onVideoProgress:a=>{i.setRecordingState(a.state,a)}})}catch(a){throw i.setRecordingState("error"),a}return void window.setTimeout(()=>{i.setRecordingState("idle"),this._updateExportButton()},1600)}this._exportButton.setDisabled(!0),this._exportButton.setLabel("exporting…");try{await this._exportService.$requestExport(t,e)}finally{this._exportButton.setDisabled(!1),this._exportButton.setLabel("download file")}}else console.warn("[textmode-export] Export options failed validation")}async _handleCopyClick(){if(!this._currentBlade||!this._currentBlade.definition.supportsClipboard)return;const t=this._currentBlade.definition.format,e=this._currentBlade.blade.getOptions(),i=this._copyButton.buttonElement.dataset.defaultLabel??"copy to clipboard";this._copyButton.setDisabled(!0),this._copyButton.setLabel("copying…");try{switch(t){case"txt":await this._clipboardService.$copy("txt",e);break;case"json":await this._clipboardService.$copy("json",e);break;case"svg":await this._clipboardService.$copy("svg",e);break;case"image":await this._clipboardService.$copy("image",e);break;default:return}this._copyButton.setLabel("copied!")}catch(a){console.error("[textmode-export] Failed to copy to clipboard",a),this._copyButton.setLabel("copy failed!")}finally{window.setTimeout(()=>{this._copyButton.setLabel(i),this._copyButton.setDisabled(!1)},1200)}}_updateExportButton(){if(!this._currentBlade)return;const t=this._currentBlade.definition.format;if(t==="gif"&&this._currentBlade.blade instanceof rr){const i=this._currentBlade.blade,a=this._state.snapshot.gifProgress;if(i.isRecording())if(this._exportButton.setDisabled(!0),a==null?void 0:a.totalFrames){const s=a.frameIndex??0,o=a.state==="encoding"?"encoding":"recording";this._exportButton.setLabel(`${o} ${s}/${a.totalFrames}`)}else{const s=(a==null?void 0:a.state)==="encoding"?"encoding":"recording";this._exportButton.setLabel(`${s}…`)}else this._exportButton.setDisabled(!1),this._exportButton.setLabel("start recording");return}if(t==="video"&&this._currentBlade.blade instanceof ir){const i=this._currentBlade.blade,a=this._state.snapshot.videoProgress;if(i.isRecording())if(this._exportButton.setDisabled(!0),a==null?void 0:a.totalFrames){const s=a.frameIndex??0;this._exportButton.setLabel(`recording ${s}/${a.totalFrames} frames`)}else this._exportButton.setLabel("recording…");else this._exportButton.setDisabled(!1),this._exportButton.setLabel("start recording");return}const e=this._state.snapshot.isBusy;this._exportButton.setDisabled(e),this._exportButton.setLabel(e?"exporting…":"download file")}}class yn{constructor(){w(this,"_listeners",{})}_getPool(t){const e=this._listeners[t];if(e)return e;const i=new Set;return this._listeners[t]=i,i}$on(t,e){const i=this._getPool(t);return i.add(e),()=>{i.delete(e),i.size===0&&delete this._listeners[t]}}$emit(t,e){const i=this._listeners[t];if(i)for(const a of[...i])try{a(e)}catch(s){console.error("[textmode-export] Event handler failed",s)}}$clear(){for(const t of Object.keys(this._listeners))delete this._listeners[t]}}class bn{constructor(t){w(this,"_state");w(this,"_listeners",new Set);this._state=t}get snapshot(){return Object.freeze({...this._state})}$set(t){this._state=Object.assign({},this._state,t);const e=this.snapshot;for(const i of[...this._listeners])try{i(e)}catch(a){console.error("[textmode-export] State listener failed",a)}}$subscribe(t){return this._listeners.add(t),t(this.snapshot),()=>{this._listeners.delete(t)}}$reset(t){this._state=t;const e=this.snapshot;for(const i of[...this._listeners])i(e)}}class vn extends ut{constructor(e){super();w(this,"props");w(this,"input");w(this,"handleInput",()=>{this.props.defaultValue=this.input.value});this.props=e}render(){return this.input=document.createElement("input"),this.input.type="text",this.input.classList.add(Qi),this.props.id&&(this.input.id=this.props.id),this.props.maxLength!==void 0&&(this.input.maxLength=this.props.maxLength),this.props.defaultValue!==void 0&&(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(e){this.input.value=e}_onUnmount(){this.input.removeEventListener("input",this.handleInput)}onUpdate(e){this.props=e,e.id&&(this.input.id=e.id),e.maxLength!==void 0&&(this.input.maxLength=e.maxLength),e.defaultValue!==void 0&&(this.input.value=e.defaultValue)}}class ar extends ut{constructor(e){super();w(this,"provider");w(this,"field");w(this,"select");this.provider=e.provider,this.field=new H({label:"layer",labelFor:e.id,variant:"full"}),this.select=new mt({id:e.id,options:[],defaultValue:e.provider.getDefaultId()})}render(){const e=document.createElement("div");return this.field.mount(e),this.refresh(),this.select.mount(this.field.root),e}get layer(){const e=this.provider.getLayerById(this.select.value);if(e)return e;const i=this.provider.getDefaultId();return this.select.value=i,this.provider.getLayerById(i)}setDisabled(e){this.select.selectElement.disabled=e}refresh(){const e=this.provider.getOptions(),i=this.select.isMounted()?this.select.value:this.provider.getDefaultId(),a=e.some(s=>s.id===i)?i:this.provider.getDefaultId();this.select.update({options:e.map(s=>({value:s.id,label:s.label})),defaultValue:a}),this.select.value=a}_onUnmount(){this.select.unmount(),this.field.unmount()}_onDestroy(){this.select.destroy(),this.field.destroy()}}class xn extends Ot{constructor(e){super(e);w(this,"layerTarget");w(this,"trailingSpaces",this._manageComponent(new Zt({label:"preserve trailing spaces",defaultChecked:!1})));w(this,"emptyCharacter",this._manageComponent(new vn({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1})));e.layerTargetProvider&&(this.layerTarget=this._manageComponent(new ar({id:"textmode-export-txt-layer",provider:e.layerTargetProvider})))}render(){var a;const e=document.createElement("div");e.classList.add(ht),(a=this.layerTarget)==null||a.mount(e),this.trailingSpaces.mount(e);const i=new H({label:"empty character",labelFor:"textmode-export-empty-character",variant:"full"});return i.mount(e),this.emptyCharacter.mount(i.root),e}getOptions(){var a;const e=this._config.defaultOptions??{},i=this.emptyCharacter.value||e.emptyCharacter||" ";return{layer:(a=this.layerTarget)==null?void 0:a.layer,preserveTrailingSpaces:this.trailingSpaces.checked,emptyCharacter:i}}reset(){this.applyDefaults()}validate(){return this.emptyCharacter.value.length<=1}refreshLayerTargets(){var e;(e=this.layerTarget)==null||e.refresh()}applyDefaults(){const e=this._config.defaultOptions??{};this.trailingSpaces.checked=e.preserveTrailingSpaces??!1,this.emptyCharacter.value=e.emptyCharacter??" "}}class _n extends Ot{constructor(e){super(e);w(this,"layerTarget");w(this,"layerTargetContainer");w(this,"target",this._manageComponent(new mt({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"})));w(this,"prettyPrint",this._manageComponent(new Zt({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0})));w(this,"includeMetadata",this._manageComponent(new Zt({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0})));w(this,"colorMode",this._manageComponent(new mt({id:"textmode-export-json-color-mode",options:[{value:"hex",label:"hex"},{value:"rgba",label:"rgba"}],defaultValue:"hex"})));e.layerTargetProvider&&(this.layerTarget=this._manageComponent(new ar({id:"textmode-export-json-layer",provider:e.layerTargetProvider})))}render(){const e=document.createElement("div");e.classList.add(ht);const i=new H({label:"target",labelFor:"textmode-export-json-target",variant:"full"});i.mount(e),this.target.mount(i.root),this.target.selectElement.addEventListener("change",()=>this.updateLayerTargetVisibility()),this.layerTarget&&(this.layerTargetContainer=document.createElement("div"),this.layerTarget.mount(this.layerTargetContainer),e.appendChild(this.layerTargetContainer)),this.prettyPrint.mount(e),this.includeMetadata.mount(e);const a=new H({label:"color mode",labelFor:"textmode-export-json-color-mode",variant:"full"});return a.mount(e),this.colorMode.mount(a.root),this.updateLayerTargetVisibility(),e}getOptions(){var i;const e=this.target.value;return{target:e,layer:e==="selected"?(i=this.layerTarget)==null?void 0:i.layer:void 0,pretty:this.prettyPrint.checked,includeMetadata:this.includeMetadata.checked,colorMode:this.colorMode.value}}reset(){this.applyDefaults()}validate(){return!0}refreshLayerTargets(){var e;(e=this.layerTarget)==null||e.refresh()}applyDefaults(){const e=this._config.defaultOptions??{};this.target.value=e.target??"selected",this.prettyPrint.checked=typeof e.pretty=="number"?e.pretty>0:e.pretty??!0,this.includeMetadata.checked=e.includeMetadata??!0,this.colorMode.value=e.colorMode??"hex",this.updateLayerTargetVisibility()}updateLayerTargetVisibility(){var i;const e=this.target.value==="selected";this.layerTargetContainer&&(this.layerTargetContainer.style.display=e?"":"none"),(i=this.layerTarget)==null||i.setDisabled(!e)}}class kn extends Ot{constructor(e){super(e);w(this,"formatSelect",this._manageComponent(new mt({id:"textmode-export-image-format",options:[{value:"png",label:`PNG (${fa})`},{value:"jpg",label:`JPG (${ga})`},{value:"webp",label:`WEBP (${wa})`}],defaultValue:"png"})));w(this,"scaleInput",this._manageComponent(new kt({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}})))}render(){const e=document.createElement("div");e.classList.add(ht);const i=new Pt("row");i.mount(e);const a=new H({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});a.mount(i.root),this.formatSelect.mount(a.root);const s=new H({label:"scale",labelFor:"textmode-export-image-scale",variant:"dense"});return s.mount(i.root),this.scaleInput.mount(s.root),this.scaleInput.inputElement.id="textmode-export-image-scale",e}getOptions(){var i;const e=Number.parseFloat(this.scaleInput.value);return{format:this.formatSelect.value,scale:Number.isFinite(e)?e:((i=this._config.defaultOptions)==null?void 0:i.scale)??1}}reset(){this.applyDefaults(),this.scaleInput.refresh()}validate(){const e=Number.parseFloat(this.scaleInput.value);return Number.isFinite(e)&&e>0}applyDefaults(){const e=this._config.defaultOptions??{};this.formatSelect.value=e.format??"png";const i=e.scale??1;this.scaleInput.value=String(i)}}class Tn extends Ot{constructor(e){super(e);w(this,"layerTarget");w(this,"includeBackground",this._manageComponent(new Zt({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0})));w(this,"drawMode",this._manageComponent(new mt({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"})));w(this,"strokeWidth",this._manageComponent(new kt({defaultValue:"1",attributes:{min:"0",step:"0.1"}})));e.layerTargetProvider&&(this.layerTarget=this._manageComponent(new ar({id:"textmode-export-svg-layer",provider:e.layerTargetProvider})))}render(){var o;const e=document.createElement("div");e.classList.add(ht),(o=this.layerTarget)==null||o.mount(e),this.includeBackground.mount(e);const i=new Pt("row");i.mount(e);const a=new H({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});a.mount(i.root),this.drawMode.mount(a.root);const s=new H({label:"stroke width",labelFor:"textmode-export-svg-stroke-width",variant:"compact"});return s.mount(i.root),this.strokeWidth.mount(s.root),this.strokeWidth.inputElement.id="textmode-export-svg-stroke-width",this.drawMode.selectElement.addEventListener("change",()=>this.updateStrokeControls()),this.updateStrokeControls(),e}getOptions(){var e;return{layer:(e=this.layerTarget)==null?void 0:e.layer,includeBackgroundRectangles:this.includeBackground.checked,drawMode:this.drawMode.value,strokeWidth:Number.parseFloat(this.strokeWidth.value)}}reset(){this.applyDefaults(),this.updateStrokeControls()}validate(){const e=Number.parseFloat(this.strokeWidth.value);return this.drawMode.value!=="stroke"||Number.isFinite(e)&&e>=0}refreshLayerTargets(){var e;(e=this.layerTarget)==null||e.refresh()}updateStrokeControls(){const e=this.drawMode.value==="stroke";this.strokeWidth.inputElement.disabled=!e,this.strokeWidth.refresh()}applyDefaults(){const e=this._config.defaultOptions??{};this.includeBackground.checked=e.includeBackgroundRectangles??!0,this.drawMode.value=e.drawMode??"fill";const i=e.strokeWidth??1;this.strokeWidth.value=String(i),this.strokeWidth.refresh()}}function Cn(r,t,e){var l;const i=(function(c){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new xn({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:{preserveTrailingSpaces:!1,emptyCharacter:" "},layerTargetProvider:c})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new _n({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:{target:"selected",pretty:!0,includeMetadata:!0,colorMode:"hex"},layerTargetProvider:c})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new kn({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:{format:"png",scale:1}})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Tn({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:{includeBackgroundRectangles:!0,drawMode:"fill",strokeWidth:1},layerTargetProvider:c})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new rr({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:{frameCount:300,frameRate:60,scale:1,repeat:0}})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new ir({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:{format:"mp4",frameCount:480,frameRate:60,bitrate:"medium",bitrateMode:"variable",latencyMode:"quality",hardwareAcceleration:"no-preference",keyFrameInterval:2,transparent:!1}})}]})(e),a=(l=i[0])==null?void 0:l.format,s=new bn((c=>({format:c,isBusy:!1}))(a)),o=new yn,n=new wn(r,t,s,o,i);return n.$mount(),n}const sr={name:"textmode.export",version:Li,async install(r,t){const e={saveCanvas:async(n={})=>new lr().$saveImage(r.canvas,n),copyCanvas:async(n={})=>new lr().$copyImageToClipboard(r.canvas,n),saveSVG:(n={})=>{new dr().$saveSVG(r,n)},saveStrings:(n={})=>{new hr().$saveTXT(r,n)},toSVG:(n={})=>new dr().$generateSVG(r,n),toString:(n={})=>new hr().$generateTXT(r,n),toJSON:(n={})=>new Ye().$generateJSONData(r,n),toJSONString:(n={})=>new Ye().$generateJSONString(r,n),saveJSON:(n={})=>{new Ye().$saveJSON(r,n)},saveGIF:async(n={})=>new Pa(r,t.registerPostDrawHook).$saveGIF(n),saveVideo:async(n={})=>new Ho(r,t.registerPostDrawHook).$saveVideo(n)},i=Cn(r,e,(function(n){return{getOptions:()=>cr(n),getLayerById:l=>{var c;return(c=cr(n).find(d=>d.id===l))==null?void 0:c.layer},getDefaultId:()=>"base"}})(r));t.registerPostDrawHook(()=>{i.isVisible()&&i.refreshLayerTargets()});const a={show:()=>i.show(),hide:()=>i.hide(),toggle:()=>i.toggle(),isVisible:()=>i.isVisible()},s={...e,exportOverlay:a},o=r;Object.assign(o,s),o._exportOverlayController=i},async uninstall(r){const t=r,e=t._exportOverlayController;e==null||e.$dispose(),delete t._exportOverlayController;const i=["exportOverlay","saveCanvas","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","saveVideo"];for(const a of i)delete t[a]}},da=(r={})=>{const t=r.overlay??!0,e={...sr},i=e.install;return e.install=async(a,s)=>{var n;const o=a;await i.call(e,o,s),t||((n=o.exportOverlay)==null||n.hide())},e};typeof window<"u"&&(window.ExportPlugin=sr,window.createTextmodeExportPlugin=da),et.ExportPlugin=sr,et.createTextmodeExportPlugin=da,Object.defineProperty(et,Symbol.toStringTag,{value:"Module"})});