textmode.export.js 1.9.0-beta.1 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/textmode.export.esm.js +1 -1
- package/dist/textmode.export.umd.js +1 -1
- package/dist/types/exporters/base/LayerTarget.d.ts +1 -3
- package/dist/types/exporters/gif/types.d.ts +0 -4
- package/dist/types/exporters/image/types.d.ts +0 -2
- package/dist/types/exporters/json/JSONExporter.d.ts +2 -1
- package/dist/types/exporters/json/index.d.ts +1 -2
- package/dist/types/exporters/json/types.d.ts +17 -202
- package/dist/types/exporters/svg/types.d.ts +1 -3
- package/dist/types/exporters/txt/types.d.ts +0 -2
- package/dist/types/exporters/video/types.d.ts +0 -20
- package/dist/types/exporters/zip/errors.d.ts +0 -1
- package/dist/types/exporters/zip/types.d.ts +0 -7
- package/dist/types/index.d.ts +1 -27
- package/dist/types/types.d.ts +7 -32
- package/package.json +11 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("textmode.js")):"function"==typeof define&&define.amd?define(["exports","textmode.js"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TextmodeExport={},t.textmode)}(this,function(t,e){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var i=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),r=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},n=new TextEncoder;function o(t,e){let i="",r=0;for(const o of t){const t=n.encode(o).byteLength;if(r+t>e)break;i+=o,r+=t}return i}var s=class{$resolve(t,e,i=new Date){const r=e.toLowerCase(),o=t?.trim(),s=o?.toLowerCase().endsWith(r)?o.slice(0,-r.length):o;return`${this.$sanitizeStem(s,i,255-n.encode(e).length)}${r}`}$sanitizeStem(t,e=new Date,i=255){const r=this.$defaultStem(e);return t?.trim()&&o(Array.from(t.normalize("NFC"),t=>{const e=t.codePointAt(0)??0;return e<32||127===e?"_":t}).join("").trim().replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/\.{2,}/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,""),i).replace(/[._]+$/g,"")||o(r,i)}$defaultStem(t=new Date){return`textmode-export-${t.toISOString().slice(0,19).replace(/:/g,"-")}`}},a=class{$downloadFile(t,e,i){const r=i?(new s).$resolve(e,i):(new s).$sanitizeStem(e),n=URL.createObjectURL(t),o=document.createElement("a");try{o.href=n,o.download=r,o.style.display="none",o.rel="noopener",document.body.appendChild(o),o.click()}finally{o.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}}},h=new WeakMap;function c(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function l(t,e){let i=h.get(t);if(!i){i=new Map;for(const e of t.characters)i.set(c(e.color),e);h.set(t,i)}return i.get(e)}function d(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function u(t){return[{id:"base",layer:t.layers.base},...t.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:d(t,e),layer:e}))}function f(t,e){const i=e??t.layers.base,r=function(t,e){if(e===t.layers.base)return"base";const i=t.layers.all.indexOf(e);if(i>=0)return`layer-${i+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")}(t,i),n=i.grid,o=i.font,s=i.drawFramebuffer;if(!n||!s)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:r,label:d(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}var p=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="FRAME_SEQUENCE_ABORTED"===t?"AbortError":"FrameSequenceError",this.code=t,this.cause=i}};function m(){return new p("FRAME_SEQUENCE_ABORTED","Frame-sequence capture was cancelled.")}function w(t){return t instanceof p&&"FRAME_SEQUENCE_ABORTED"===t.code||t instanceof DOMException&&"AbortError"===t.name}var v=class{m=!1;v=!1;acquire(){if(this.v)throw new p("FRAME_SEQUENCE_DISPOSED","The textmode export plugin has been disposed.");if(this.m)throw new p("FRAME_SEQUENCE_BUSY","Another deterministic frame capture is already active for this textmode instance.");this.m=!0;let t=!1;return()=>{t||(t=!0,this.m=!1)}}dispose(){this.v=!0}},b=1e6;function y(t,e){const i=Math.round(t*b/e),r=Math.max(i+1,Math.round((t+1)*b/e));return{startSeconds:i/b,centerSeconds:(i+Math.floor((r-i)/2))/b,endSeconds:r/b,durationSeconds:(r-i)/b}}var g=class{canvas;T;k;_;M;A=null;S=0;C=0;constructor(t,e,i){if(this.T=t,this.k=e,this.M=t.canvas,this.canvas=i?this.P(i):this.M,i){const t=this.canvas.getContext("2d");if(!t)throw new Error("Frame-sequence export requires a 2D canvas context for staging frames.");t.imageSmoothingEnabled=!1,this._=t}else this._=null}async $render(t){this.I(t.signal);const e=this.T,i=e.isLooping(),r=e.frameCount,n=e.millis,o="secs"in e,s=e.frameRate(),a=this.B(),h=this.F(),c=this.k(()=>this.O());try{e.noLoop(),this.S=r,this.C=n,this.R(o),this.$(t.frameRate,1e3/t.frameRate),this.D();for(let e=0;e<t.frameCount;e++){this.I(t.signal);const i=y(e,t.frameRate);this.S=r+e+1,this.C=1e3*i.startSeconds,await(t.prepareFrame?.({frameIndex:e,frameCount:t.frameCount,startSeconds:i.startSeconds,centerSeconds:i.centerSeconds,endSeconds:i.endSeconds,timeSeconds:i.startSeconds,frameRate:t.frameRate,signal:t.signal})),this.I(t.signal),await this.N(e,t.signal),this.I(t.signal),await t.onFrame({frameIndex:e,canvas:this.canvas}),this.I(t.signal)}}finally{try{c()}catch{}this.A?.reject(new Error("Frame-sequence rendering was interrupted.")),this.A=null,this.V(h),this.U(a),"number"==typeof s&&e.frameRate(s),i?e.loop():e.noLoop()}}N(t,e){if(this.A)throw new Error("A frame-sequence render is already pending.");return function(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(m());let s=!1;const a=t=>{s||(s=!0,clearTimeout(c),i?.removeEventListener("abort",h),t())},h=()=>a(()=>o(m())),c=setTimeout(()=>a(()=>o(function(t){return new p("FRAME_SEQUENCE_TIMEOUT",t,void 0)}(e))),r);i?.addEventListener("abort",h,{once:!0}),t.then(t=>a(()=>n(t)),t=>a(()=>o(t)))})}(new Promise((e,i)=>{this.A={frameIndex:t,resolve:e,reject:i};try{this.T.redraw(1)}catch(r){this.A=null,i(r)}}),`Frame ${t+1} did not render within 30000ms.`,e,3e4).catch(e=>{throw this.A?.frameIndex===t&&(this.A=null),e})}O(){const t=this.A;if(t)try{this._&&(this._.clearRect(0,0,this.canvas.width,this.canvas.height),this._.drawImage(this.M,0,0,this.M.width,this.M.height,0,0,this.canvas.width,this.canvas.height)),this.A=null,t.resolve()}catch(e){this.A=null,t.reject(e)}}P(t){const e=document.createElement("canvas");return e.width=Math.max(1,Math.round(t.width)),e.height=Math.max(1,Math.round(t.height)),e}B(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this.T,t),value:this.T[t]}))}F(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this.T,t),descriptor:Object.getOwnPropertyDescriptor(this.T,t)}))}R(t){Object.defineProperty(this.T,"frameCount",{configurable:!0,enumerable:!0,get:()=>this.S,set:t=>{this.S=t}}),Object.defineProperty(this.T,"millis",{configurable:!0,enumerable:!0,get:()=>this.C,set:t=>{this.C=t}}),t&&Object.defineProperty(this.T,"secs",{configurable:!0,enumerable:!0,get:()=>this.C/1e3,set:t=>{this.C=1e3*t}})}$(t,e){const i=this.T.frameRate;this.T.deltaTime=()=>e,this.T.frameRate=function(e){return void 0===e?t:i.call(this,e)}}D(){this.T.resizeCanvas=()=>{}}U(t){const e=this.T;for(const i of t)i.hadOwnProperty?e[i.key]=i.value:delete e[i.key]}V(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this.T,e.key,e.descriptor):delete this.T[e.key]}I(t){if(t?.aborted)throw m()}};function x(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var E=class extends r{j(t,e,i){return{x:t,y:e,cellX:t*i.cellWidth,cellY:e*i.cellHeight}}$extractSVGCellData(t,e){const i=[];let r=0;for(let n=0;n<e.rows;n++)for(let o=0;o<e.cols;o++){const s=4*r,a=this.$getEncodedCharacterValue(t.characterPixels,s);let h=x(t.primaryColorPixels,s),c=x(t.secondaryColorPixels,s);const l=this.$extractCellTransform(t.characterPixels,s);if(l.isInverted){const t=h;h=c,c=t}const d=this.j(o,n,e);i.push({encodedGlyphSlot:a,primaryColor:h,secondaryColor:c,transform:l,position:d}),r++}return i}},T=class{L(t,e,i,r,n){const o=n/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:i+e.xMin*o,y1:r+-e.yMax*o,x2:i+e.xMax*o,y2:r+-e.yMin*o}),toSVG:()=>this.q(e,i,r,o)}}q(t,e,i,r){if(!t||!t.xs)return"";const{xs:n,ys:o,endPts:s,flags:a}=t;if(!(n&&o&&s&&a))return"";let h="",c=0;for(let l=0;l<s.length;l++){const t=s[l];if(!(t<c)){if(t>=c){const s=e+n[c]*r,l=i-o[c]*r;h+=`M${s.toFixed(2)},${l.toFixed(2)}`;let d=c+1;for(;d<=t;)if(1&a[d]){const t=e+n[d]*r,s=i-o[d]*r;h+=`L${t.toFixed(2)},${s.toFixed(2)}`,d++}else{const s=e+n[d]*r,l=i-o[d]*r,u=d+1>t?c:d+1;if(1&a[u]){const t=e+n[u]*r,a=i-o[u]*r;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u+1}else{const t=(s+(e+n[u]*r))/2,a=(l+(i-o[u]*r))/2;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u}}h+="Z"}c=t+1}}return h}$generatePositionedCharacterPath(t,e,i,r,n,o,s,a){if(!a)return null;const h=e.font,c=s/h.head.unitsPerEm,l=i+(n-a.advanceWidth*c)/2,d=r+h.hhea.ascender*c;return this.L(h,a,l,d,s).toSVG()||null}},k=class{G;constructor(){this.G=new T}$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>"}H(t,e){const{transform:i,position:r}=t;if(!i.flipHorizontal&&!i.flipVertical&&!i.rotation)return"";const n=r.cellX+e.cellWidth/2,o=r.cellY+e.cellHeight/2,s=[];if(i.flipHorizontal||i.flipVertical){const t=i.flipHorizontal?-1:1,e=i.flipVertical?-1:1;s.push(`translate(${n} ${o})scale(${t} ${e})translate(${-n} ${-o})`)}return i.rotation&&s.push(`rotate(${i.rotation} ${n} ${o})`),` transform="${s.join(" ")}"`}W(t,e,i){if(!i.includeBackgroundRectangles||0===t.secondaryColor.a)return"";const{position:r}=t,{r:n,g:o,b:s,a}=t.secondaryColor,h=`rgba(${n},${o},${s},${a/255})`;return"stroke"===i.drawMode?`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${h}" fill="none" stroke-width="${i.strokeWidth}"/>`:`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${h}"/>`}X(t,e,i,r){const n=l(i,t.encodedGlyphSlot);if(!n)return"";const o=this.G.$generatePositionedCharacterPath(n.character,i,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,i.fontSize,n.glyphData);if(!o)return"";const{r:s,g:a,b:h,a:c}=t.primaryColor,d=`rgba(${s},${a},${h},${c/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.W(t,e,r);o&&n.push(o);const s=this.X(t,e,i,r);if(s){const i=this.H(t,e);n.push(i?`<g${i}>${s}</g>`:s)}return n.join("")}$generateSVGContent(t,e,i,r){const n=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)n.push(this.$generateCellContent(o,e,i,r));return n.push(this.$generateSVGFooter()),n.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}},_=class{Z(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 E,r=new k,n=this.Z(e),o=f(t,n.layer),s=i.$extractSVGCellData(i.$extractFramebufferData(o.drawFramebuffer),o.grid),a=r.$generateSVGContent(s,o.grid,o.font,n);return r.$optimizeSVGContent(a)}$saveSVG(t,e={}){(new a).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename,".svg")}},M={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},A=class{Z(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}Y(t){if(!(t.format in M))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},M[e.format])})}async $saveImage(t,e={}){const i=this.Z(e);this.Y(i);const r=await this.$toImageBlob(t,e);(new a).$downloadFile(r,i.filename,`.${i.format}`)}async $toImageBlob(t,e={}){const i=this.Z(e);return this.Y(i),this.$generateImageBlob(t,i)}async $copyImageToClipboard(t,e={}){if("undefined"==typeof navigator||!navigator.clipboard||"function"!=typeof navigator.clipboard.write)throw new Error("Clipboard API is not available in this environment");const i=this.Z(e);this.Y(i);const r=await this.$generateImageBlob(t,i),n=new ClipboardItem({[M[i.format]]:r});await navigator.clipboard.write([n])}},S=class{Z(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}J(t,e){const i=new r,n=f(t,e.layer),o=i.$extractFramebufferData(n.drawFramebuffer),s=[];let a=0;for(let r=0;r<n.grid.rows;r++){let t="";for(let r=0;r<n.grid.cols;r++){const r=4*a,s=i.$getEncodedCharacterValue(o.characterPixels,r);t+=l(n.font,s)?.character||e.emptyCharacter,a++}e.preserveTrailingSpaces||(t=t.trimEnd()),s.push(t)}return s.join("\n")}$generateTXT(t,e={}){return this.J(t,this.Z(e))}$saveTXT(t,e={}){const i=this.Z(e),r=this.J(t,i),n=new Blob([r],{type:"text/plain;charset=utf-8"});(new a).$downloadFile(n,i.filename,".txt")}},C=i(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>M,applyPalette:()=>b,default:()=>I,nearestColor:()=>_,nearestColorIndex:()=>T,nearestColorIndexWithDistance:()=>k,prequantize:()=>v,quantize:()=>f,snapColorsToPalette:()=>x});var i={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function r(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView:()=>i.subarray(0,e),bytes:()=>i.slice(0,e),writeByte(t){r(e+1),i[e]=t,e++},writeBytes(t,n=0,o=t.length){r(e+o);for(let r=0;r<o;r++)i[e++]=t[r+n]},writeBytesView(t,n=0,o=t.byteLength){r(e+o),i.set(t.subarray(n,n+o),e),e+=o}};function r(t){var r=i.length;if(r>=t)return;t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));const n=i;i=new Uint8Array(t),e>0&&i.set(n.subarray(0,e),0)}}var n=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],o=function(t,e,i,o,s=r(512),a=new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,v=m,b=(1<<v)-1;const y=1<<p-1,g=y+1;let x=y+2,E=0,T=i[0],k=0;for(let r=l;r<65536;r*=2)++k;k=8-k,s.writeByte(d),M(y);const _=i.length;for(let r=1;r<_;r++)t:{const t=i[r],e=(t<<12)+T;let n=t<<k^T;if(h[n]===e){T=c[n];break t}const o=0===n?1:l-n;for(;h[n]>=0;)if(n-=o,n<0&&(n+=l),h[n]===e){T=c[n];break t}M(T),T=t,x<4096?(c[n]=x++,h[n]=e):(h.fill(-1),x=y+2,w=!0,M(y))}return M(T),M(g),s.writeByte(0),s.bytesView();function M(t){for(u&=n[f],f>0?u|=t<<f:u=t,f+=v;f>=8;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;if((x>b||w)&&(w?(v=m,b=(1<<v)-1,w=!1):(++v,b=12===v?1<<v:(1<<v)-1)),t==g){for(;f>0;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;E>0&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0)}}};function s(t,e,i){return t<<8&63488|e<<2&992|i>>3}function a(t,e,i,r){return t>>4|240&e|(240&i)<<4|(240&r)<<8}function h(t,e,i){return t>>4<<8|240&e|i>>4}function c(t,e,i){return t<e?e:t>i?i:t}function l(t){return t*t}function d(t,e,i){var r=0,n=1e100;const o=t[e],s=o.cnt,a=o.ac,h=o.rc,c=o.gc,d=o.bc;for(var u=o.fw;0!=u;u=t[u].fw){const e=t[u],o=e.cnt,p=s*o/(s+o);if(!(p>=n)){var f=0;i&&(f+=p*l(e.ac-a))>=n||(f+=p*l(e.rc-h))>=n||(f+=p*l(e.gc-c))>=n||(f+=p*l(e.bc-d))>=n||(n=f,r=u)}}o.err=n,o.nn=r}function u(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function f(t,e,i={}){const{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:o=0,clearAlphaThreshold:f=0,oneBitAlpha:m=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");const w=new Uint32Array(t.buffer);let v=!1!==i.useSqrt;const b="rgba4444"===r,y=function(t,e){const i=new Array("rgb444"===e?4096:65536),r=t.length;if("rgba4444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>24&255,o=e>>16&255,s=e>>8&255,h=255&e,c=a(h,s,o,r);let l=c in i?i[c]:i[c]=u();l.rc+=h,l.gc+=s,l.bc+=o,l.ac+=r,l.cnt++}else if("rgb444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,s=255&e,a=h(s,o,r);let c=a in i?i[a]:i[a]=u();c.rc+=s,c.gc+=o,c.bc+=r,c.cnt++}else for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,a=255&e,h=s(a,o,r);let c=h in i?i[h]:i[h]=u();c.rc+=a,c.gc+=o,c.bc+=r,c.cnt++}return i}(w,r),g=y.length,x=g-1,E=new Uint32Array(g+1);for(var T=0,k=0;k<g;++k){const t=y[k];if(null!=t){var _=1/t.cnt;b&&(t.ac*=_),t.rc*=_,t.gc*=_,t.bc*=_,y[T++]=t}}var M,A,S;for(l(e)/T<.022&&(v=!1),k=0;k<T-1;++k)y[k].fw=k+1,y[k+1].bk=k,v&&(y[k].cnt=Math.sqrt(y[k].cnt));for(v&&(y[k].cnt=Math.sqrt(y[k].cnt)),k=0;k<T;++k){d(y,k,!1);var C=y[k].err;for(A=++E[0];A>1&&!(y[M=E[S=A>>1]].err<=C);A=S)E[A]=M;E[A]=k}var P=T-e;for(k=0;k<P;){for(var I;;){var B=E[1];if((I=y[B]).tm>=I.mtm&&y[I.nn].mtm<=I.tm)break;for(I.mtm==x?B=E[1]=E[E[0]--]:(d(y,B,!1),I.tm=k),C=y[B].err,A=1;(S=A+A)<=E[0]&&(S<E[0]&&y[E[S]].err>y[E[S+1]].err&&S++,!(C<=y[M=E[S]].err));A=S)E[A]=M;E[A]=B}var F=y[I.nn],O=I.cnt,R=F.cnt;_=1/(O+R),b&&(I.ac=_*(O*I.ac+R*F.ac)),I.rc=_*(O*I.rc+R*F.rc),I.gc=_*(O*I.gc+R*F.gc),I.bc=_*(O*I.bc+R*F.bc),I.cnt+=F.cnt,I.mtm=++k,y[F.bk].fw=F.fw,y[F.fw].bk=F.bk,F.mtm=x}let $=[];var D=0;for(k=0;;++D){let t=c(Math.round(y[k].rc),0,255),e=c(Math.round(y[k].gc),0,255),i=c(Math.round(y[k].bc),0,255),r=255;b&&(r=c(Math.round(y[k].ac),0,255),m&&(r=r<=("number"==typeof m?m:127)?0:255),n&&r<=f&&(t=e=i=o,r=0));const s=b?[t,e,i,r]:[t,e,i];if(p($,s)||$.push(s),0==(k=y[k].fw))break}return $}function p(t,e){for(let i=0;i<t.length;i++){const r=t[i];let n=r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2],o=!(r.length>=4&&e.length>=4)||r[3]===e[3];if(n&&o)return!0}return!1}function m(t,e){var i,r=0;for(i=0;i<t.length;i++){const n=t[i]-e[i];r+=n*n}return r}function w(t,e){return e>1?Math.round(t/e)*e:t}function v(t,{roundRGB:e=5,roundAlpha:i=10,oneBitAlpha:r=null}={}){const n=new Uint32Array(t.buffer);for(let o=0;o<n.length;o++){const t=n[o];let s=t>>24&255,a=t>>16&255,h=t>>8&255,c=255&t;s=w(s,i),r&&(s=s<=("number"==typeof r?r:127)?0:255),c=w(c,e),h=w(h,e),a=w(a,e),n[o]=s<<24|a<<16|h<<8|c}}function b(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");const r=new Uint32Array(t.buffer),n=r.length,o="rgb444"===i?4096:65536,c=new Uint8Array(n),l=new Array(o);if("rgba4444"===i)for(let s=0;s<n;s++){const t=r[s],i=t>>24&255,n=t>>16&255,o=t>>8&255,h=255&t,d=a(h,o,n,i);c[s]=d in l?l[d]:l[d]=y(h,o,n,i,e)}else{const t="rgb444"===i?h:s;for(let i=0;i<n;i++){const n=r[i],o=n>>16&255,s=n>>8&255,a=255&n,h=t(a,s,o);c[i]=h in l?l[h]:l[h]=g(a,s,o,e)}}return c}function y(t,e,i,r,n){let o=0,s=1e100;for(let a=0;a<n.length;a++){const h=n[a];let c=E(h[3]-r);c>s||(c+=E(h[0]-t),c>s||(c+=E(h[1]-e),c>s||(c+=E(h[2]-i),c>s||(s=c,o=a))))}return o}function g(t,e,i,r){let n=0,o=1e100;for(let s=0;s<r.length;s++){const a=r[s];let h=E(a[0]-t);h>o||(h+=E(a[1]-e),h>o||(h+=E(a[2]-i),h>o||(o=h,n=s)))}return n}function x(t,e,i=5){if(!t.length||!e.length)return;const r=t.map(t=>t.slice(0,3)),n=i*i,o=t[0].length;for(let s=0;s<e.length;s++){let i=e[s];i=i.length<o?[i[0],i[1],i[2],255]:i.length>o?i.slice(0,3):i.slice();const a=k(r,i.slice(0,3),m),h=a[0],c=a[1];c>0&&c<=n&&(t[h]=i)}}function E(t){return t*t}function T(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return n}function k(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return[n,r]}function _(t,e,i=m){return t[T(t,e,i)]}function M(t={}){const{initialCapacity:e=4096,auto:n=!0}=t,s=r(e),a=new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth:v=8,dispose:b=-1}=r;let y=!1;if(n?l||(y=!0,d(),l=!0):y=Boolean(r.first),e=Math.max(0,Math.floor(e)),i=Math.max(0,Math.floor(i)),y){if(!m)throw new Error("First frame must include a { palette } option");!function(t,e,i,r,n=8){const o=n-1<<4|128|P(r.length)-1;S(t,e),S(t,i),t.writeBytes([o,0,0])}(s,e,i,m,v),A(s,m),w>=0&&function(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),C(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),S(t,e),t.writeByte(0)}(s,w)}const g=Math.round(p/10);!function(t,e,i,r,n){var o,s;t.writeByte(33),t.writeByte(249),t.writeByte(4),n<0&&(n=0,r=!1),r?(o=1,s=2):(o=0,s=0),e>=0&&(s=7&e),s<<=2,t.writeByte(0|s|o),S(t,i),t.writeByte(n||0),t.writeByte(0)}(s,b,g,u,f);const x=Boolean(m)&&!y;!function(t,e,i,r){if(t.writeByte(44),S(t,0),S(t,0),S(t,e),S(t,i),r){const e=P(r.length)-1;t.writeByte(128|e)}else t.writeByte(0)}(s,e,i,x?m:null),x&&A(s,m),function(t,e,i,r,n=8,s,a,h){o(i,r,e,n,t,s,a,h)}(s,t,e,i,v,a,h,c)}};function d(){C(s,"GIF89a")}}function A(t,e){const i=1<<P(e.length);for(let r=0;r<i;r++){let i=[0,0,0];r<e.length&&(i=e[r]),t.writeByte(i[0]),t.writeByte(i[1]),t.writeByte(i[2])}}function S(t,e){t.writeByte(255&e),t.writeByte(e>>8&255)}function C(t,e){for(var i=0;i<e.length;i++)t.writeByte(e.charCodeAt(i))}function P(t){return Math.max(Math.ceil(Math.log2(t)),1)}var I=M}),P='(function() {\n\tvar r = ((t, r) => () => (r || (t((r = { exports: {} }).exports, r), t = null), r.exports))((t) => {\n\t\tvar r = Object.defineProperty;\n\t\tr(t, "__esModule", { value: !0 }), ((t, e) => {\n\t\t\tfor (var n in e) r(t, n, {\n\t\t\t\tget: e[n],\n\t\t\t\tenumerable: !0\n\t\t\t});\n\t\t})(t, {\n\t\t\tGIFEncoder: () => I,\n\t\t\tapplyPalette: () => b,\n\t\t\tdefault: () => x,\n\t\t\tnearestColor: () => C,\n\t\t\tnearestColorIndex: () => k,\n\t\t\tnearestColorIndexWithDistance: () => U,\n\t\t\tprequantize: () => A,\n\t\t\tquantize: () => y,\n\t\t\tsnapColorsToPalette: () => v\n\t\t});\n\t\tvar e = {\n\t\t\tsignature: "GIF",\n\t\t\tversion: "89a",\n\t\t\ttrailer: 59,\n\t\t\textensionIntroducer: 33,\n\t\t\tapplicationExtensionLabel: 255,\n\t\t\tgraphicControlExtensionLabel: 249,\n\t\t\timageSeparator: 44,\n\t\t\tsignatureSize: 3,\n\t\t\tversionSize: 3,\n\t\t\tglobalColorTableFlagMask: 128,\n\t\t\tcolorResolutionMask: 112,\n\t\t\tsortFlagMask: 8,\n\t\t\tglobalColorTableSizeMask: 7,\n\t\t\tapplicationIdentifierSize: 8,\n\t\t\tapplicationAuthCodeSize: 3,\n\t\t\tdisposalMethodMask: 28,\n\t\t\tuserInputFlagMask: 2,\n\t\t\ttransparentColorFlagMask: 1,\n\t\t\tlocalColorTableFlagMask: 128,\n\t\t\tinterlaceFlagMask: 64,\n\t\t\tidSortFlagMask: 32,\n\t\t\tlocalColorTableSizeMask: 7\n\t\t};\n\t\tfunction n(t = 256) {\n\t\t\tlet r = 0, e = new Uint8Array(t);\n\t\t\treturn {\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn e.buffer;\n\t\t\t\t},\n\t\t\t\treset() {\n\t\t\t\t\tr = 0;\n\t\t\t\t},\n\t\t\t\tbytesView: () => e.subarray(0, r),\n\t\t\t\tbytes: () => e.slice(0, r),\n\t\t\t\twriteByte(t) {\n\t\t\t\t\tn(r + 1), e[r] = t, r++;\n\t\t\t\t},\n\t\t\t\twriteBytes(t, o = 0, a = t.length) {\n\t\t\t\t\tn(r + a);\n\t\t\t\t\tfor (let n = 0; n < a; n++) e[r++] = t[n + o];\n\t\t\t\t},\n\t\t\t\twriteBytesView(t, o = 0, a = t.byteLength) {\n\t\t\t\t\tn(r + a), e.set(t.subarray(o, o + a), r), r += a;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction n(t) {\n\t\t\t\tvar n = e.length;\n\t\t\t\tif (n >= t) return;\n\t\t\t\tt = Math.max(t, n * (n < 1048576 ? 2 : 1.125) >>> 0), 0 != n && (t = Math.max(t, 256));\n\t\t\t\tconst o = e;\n\t\t\t\te = new Uint8Array(t), r > 0 && e.set(o.subarray(0, r), 0);\n\t\t\t}\n\t\t}\n\t\tvar o = [\n\t\t\t0,\n\t\t\t1,\n\t\t\t3,\n\t\t\t7,\n\t\t\t15,\n\t\t\t31,\n\t\t\t63,\n\t\t\t127,\n\t\t\t255,\n\t\t\t511,\n\t\t\t1023,\n\t\t\t2047,\n\t\t\t4095,\n\t\t\t8191,\n\t\t\t16383,\n\t\t\t32767,\n\t\t\t65535\n\t\t], a = function(t, r, e, a, i = n(512), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003)) {\n\t\t\tconst s = c.length, u = Math.max(2, a);\n\t\t\tl.fill(0), f.fill(0), c.fill(-1);\n\t\t\tlet p = 0, y = 0;\n\t\t\tconst h = u + 1, w = h;\n\t\t\tlet d = !1, A = w, b = (1 << A) - 1;\n\t\t\tconst M = 1 << h - 1, g = M + 1;\n\t\t\tlet v = M + 2, m = 0, k = e[0], U = 0;\n\t\t\tfor (let n = s; n < 65536; n *= 2) ++U;\n\t\t\tU = 8 - U, i.writeByte(u), I(M);\n\t\t\tconst C = e.length;\n\t\t\tfor (let n = 1; n < C; n++) t: {\n\t\t\t\tconst t = e[n], r = (t << 12) + k;\n\t\t\t\tlet o = t << U ^ k;\n\t\t\t\tif (c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tconst a = 0 === o ? 1 : s - o;\n\t\t\t\tfor (; c[o] >= 0;) if (o -= a, o < 0 && (o += s), c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tI(k), k = t, v < 4096 ? (f[o] = v++, c[o] = r) : (c.fill(-1), v = M + 2, d = !0, I(M));\n\t\t\t}\n\t\t\treturn I(k), I(g), i.writeByte(0), i.bytesView();\n\t\t\tfunction I(t) {\n\t\t\t\tfor (p &= o[y], y > 0 ? p |= t << y : p = t, y += A; y >= 8;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\tif ((v > b || d) && (d ? (A = w, b = (1 << A) - 1, d = !1) : (++A, b = 12 === A ? 1 << A : (1 << A) - 1)), t == g) {\n\t\t\t\t\tfor (; y > 0;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\t\tm > 0 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tfunction i(t, r, e) {\n\t\t\treturn t << 8 & 63488 | r << 2 & 992 | e >> 3;\n\t\t}\n\t\tfunction l(t, r, e, n) {\n\t\t\treturn t >> 4 | 240 & r | (240 & e) << 4 | (240 & n) << 8;\n\t\t}\n\t\tfunction c(t, r, e) {\n\t\t\treturn t >> 4 << 8 | 240 & r | e >> 4;\n\t\t}\n\t\tfunction f(t, r, e) {\n\t\t\treturn t < r ? r : t > e ? e : t;\n\t\t}\n\t\tfunction s(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction u(t, r, e) {\n\t\t\tvar n = 0, o = 1e100;\n\t\t\tconst a = t[r], i = a.cnt, l = a.ac, c = a.rc, f = a.gc, u = a.bc;\n\t\t\tfor (var p = a.fw; 0 != p; p = t[p].fw) {\n\t\t\t\tconst r = t[p], a = r.cnt, h = i * a / (i + a);\n\t\t\t\tif (!(h >= o)) {\n\t\t\t\t\tvar y = 0;\n\t\t\t\t\te && (y += h * s(r.ac - l)) >= o || (y += h * s(r.rc - c)) >= o || (y += h * s(r.gc - f)) >= o || (y += h * s(r.bc - u)) >= o || (o = y, n = p);\n\t\t\t\t}\n\t\t\t}\n\t\t\ta.err = o, a.nn = n;\n\t\t}\n\t\tfunction p() {\n\t\t\treturn {\n\t\t\t\tac: 0,\n\t\t\t\trc: 0,\n\t\t\t\tgc: 0,\n\t\t\t\tbc: 0,\n\t\t\t\tcnt: 0,\n\t\t\t\tnn: 0,\n\t\t\t\tfw: 0,\n\t\t\t\tbk: 0,\n\t\t\t\ttm: 0,\n\t\t\t\tmtm: 0,\n\t\t\t\terr: 0\n\t\t\t};\n\t\t}\n\t\tfunction y(t, r, e = {}) {\n\t\t\tconst { format: n = "rgb565", clearAlpha: o = !0, clearAlphaColor: a = 0, clearAlphaThreshold: y = 0, oneBitAlpha: w = !1 } = e;\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tconst d = new Uint32Array(t.buffer);\n\t\t\tlet A = !1 !== e.useSqrt;\n\t\t\tconst b = "rgba4444" === n, M = function(t, r) {\n\t\t\t\tconst e = new Array("rgb444" === r ? 4096 : 65536), n = t.length;\n\t\t\t\tif ("rgba4444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 24 & 255, a = r >> 16 & 255, i = r >> 8 & 255, c = 255 & r, f = l(c, i, a, n);\n\t\t\t\t\tlet s = f in e ? e[f] : e[f] = p();\n\t\t\t\t\ts.rc += c, s.gc += i, s.bc += a, s.ac += n, s.cnt++;\n\t\t\t\t}\n\t\t\t\telse if ("rgb444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, i = 255 & r, l = c(i, a, n);\n\t\t\t\t\tlet f = l in e ? e[l] : e[l] = p();\n\t\t\t\t\tf.rc += i, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\telse for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, l = 255 & r, c = i(l, a, n);\n\t\t\t\t\tlet f = c in e ? e[c] : e[c] = p();\n\t\t\t\t\tf.rc += l, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\treturn e;\n\t\t\t}(d, n), g = M.length, v = g - 1, m = new Uint32Array(g + 1);\n\t\t\tfor (var k = 0, U = 0; U < g; ++U) {\n\t\t\t\tconst t = M[U];\n\t\t\t\tif (null != t) {\n\t\t\t\t\tvar C = 1 / t.cnt;\n\t\t\t\t\tb && (t.ac *= C), t.rc *= C, t.gc *= C, t.bc *= C, M[k++] = t;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar I, F, z;\n\t\t\tfor (s(r) / k < .022 && (A = !1), U = 0; U < k - 1; ++U) M[U].fw = U + 1, M[U + 1].bk = U, A && (M[U].cnt = Math.sqrt(M[U].cnt));\n\t\t\tfor (A && (M[U].cnt = Math.sqrt(M[U].cnt)), U = 0; U < k; ++U) {\n\t\t\t\tu(M, U, !1);\n\t\t\t\tvar B = M[U].err;\n\t\t\t\tfor (F = ++m[0]; F > 1 && !(M[I = m[z = F >> 1]].err <= B); F = z) m[F] = I;\n\t\t\t\tm[F] = U;\n\t\t\t}\n\t\t\tvar E = k - r;\n\t\t\tfor (U = 0; U < E;) {\n\t\t\t\tfor (var x;;) {\n\t\t\t\t\tvar G = m[1];\n\t\t\t\t\tif ((x = M[G]).tm >= x.mtm && M[x.nn].mtm <= x.tm) break;\n\t\t\t\t\tfor (x.mtm == v ? G = m[1] = m[m[0]--] : (u(M, G, !1), x.tm = U), B = M[G].err, F = 1; (z = F + F) <= m[0] && (z < m[0] && M[m[z]].err > M[m[z + 1]].err && z++, !(B <= M[I = m[z]].err)); F = z) m[F] = I;\n\t\t\t\t\tm[F] = G;\n\t\t\t\t}\n\t\t\t\tvar S = M[x.nn], T = x.cnt, q = S.cnt;\n\t\t\t\tC = 1 / (T + q), b && (x.ac = C * (T * x.ac + q * S.ac)), x.rc = C * (T * x.rc + q * S.rc), x.gc = C * (T * x.gc + q * S.gc), x.bc = C * (T * x.bc + q * S.bc), x.cnt += S.cnt, x.mtm = ++U, M[S.bk].fw = S.fw, M[S.fw].bk = S.bk, S.mtm = v;\n\t\t\t}\n\t\t\tlet R = [];\n\t\t\tvar P = 0;\n\t\t\tfor (U = 0;; ++P) {\n\t\t\t\tlet t = f(Math.round(M[U].rc), 0, 255), r = f(Math.round(M[U].gc), 0, 255), e = f(Math.round(M[U].bc), 0, 255), n = 255;\n\t\t\t\tb && (n = f(Math.round(M[U].ac), 0, 255), w && (n = n <= ("number" == typeof w ? w : 127) ? 0 : 255), o && n <= y && (t = r = e = a, n = 0));\n\t\t\t\tconst i = b ? [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te,\n\t\t\t\t\tn\n\t\t\t\t] : [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te\n\t\t\t\t];\n\t\t\t\tif (h(R, i) || R.push(i), 0 == (U = M[U].fw)) break;\n\t\t\t}\n\t\t\treturn R;\n\t\t}\n\t\tfunction h(t, r) {\n\t\t\tfor (let e = 0; e < t.length; e++) {\n\t\t\t\tconst n = t[e];\n\t\t\t\tlet o = n[0] === r[0] && n[1] === r[1] && n[2] === r[2], a = !(n.length >= 4 && r.length >= 4) || n[3] === r[3];\n\t\t\t\tif (o && a) return !0;\n\t\t\t}\n\t\t\treturn !1;\n\t\t}\n\t\tfunction w(t, r) {\n\t\t\tvar e, n = 0;\n\t\t\tfor (e = 0; e < t.length; e++) {\n\t\t\t\tconst o = t[e] - r[e];\n\t\t\t\tn += o * o;\n\t\t\t}\n\t\t\treturn n;\n\t\t}\n\t\tfunction d(t, r) {\n\t\t\treturn r > 1 ? Math.round(t / r) * r : t;\n\t\t}\n\t\tfunction A(t, { roundRGB: r = 5, roundAlpha: e = 10, oneBitAlpha: n = null } = {}) {\n\t\t\tconst o = new Uint32Array(t.buffer);\n\t\t\tfor (let a = 0; a < o.length; a++) {\n\t\t\t\tconst t = o[a];\n\t\t\t\tlet i = t >> 24 & 255, l = t >> 16 & 255, c = t >> 8 & 255, f = 255 & t;\n\t\t\t\ti = d(i, e), n && (i = i <= ("number" == typeof n ? n : 127) ? 0 : 255), f = d(f, r), c = d(c, r), l = d(l, r), o[a] = i << 24 | l << 16 | c << 8 | f;\n\t\t\t}\n\t\t}\n\t\tfunction b(t, r, e = "rgb565") {\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (r.length > 256) throw new Error("applyPalette() only works with 256 colors or less");\n\t\t\tconst n = new Uint32Array(t.buffer), o = n.length, a = "rgb444" === e ? 4096 : 65536, f = new Uint8Array(o), s = new Array(a);\n\t\t\tif ("rgba4444" === e) for (let i = 0; i < o; i++) {\n\t\t\t\tconst t = n[i], e = t >> 24 & 255, o = t >> 16 & 255, a = t >> 8 & 255, c = 255 & t, u = l(c, a, o, e);\n\t\t\t\tf[i] = u in s ? s[u] : s[u] = M(c, a, o, e, r);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst t = "rgb444" === e ? c : i;\n\t\t\t\tfor (let e = 0; e < o; e++) {\n\t\t\t\t\tconst o = n[e], a = o >> 16 & 255, i = o >> 8 & 255, l = 255 & o, c = t(l, i, a);\n\t\t\t\t\tf[e] = c in s ? s[c] : s[c] = g(l, i, a, r);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn f;\n\t\t}\n\t\tfunction M(t, r, e, n, o) {\n\t\t\tlet a = 0, i = 1e100;\n\t\t\tfor (let l = 0; l < o.length; l++) {\n\t\t\t\tconst c = o[l];\n\t\t\t\tlet f = m(c[3] - n);\n\t\t\t\tf > i || (f += m(c[0] - t), f > i || (f += m(c[1] - r), f > i || (f += m(c[2] - e), f > i || (i = f, a = l))));\n\t\t\t}\n\t\t\treturn a;\n\t\t}\n\t\tfunction g(t, r, e, n) {\n\t\t\tlet o = 0, a = 1e100;\n\t\t\tfor (let i = 0; i < n.length; i++) {\n\t\t\t\tconst l = n[i];\n\t\t\t\tlet c = m(l[0] - t);\n\t\t\t\tc > a || (c += m(l[1] - r), c > a || (c += m(l[2] - e), c > a || (a = c, o = i)));\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction v(t, r, e = 5) {\n\t\t\tif (!t.length || !r.length) return;\n\t\t\tconst n = t.map((t) => t.slice(0, 3)), o = e * e, a = t[0].length;\n\t\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\t\tlet e = r[i];\n\t\t\t\te = e.length < a ? [\n\t\t\t\t\te[0],\n\t\t\t\t\te[1],\n\t\t\t\t\te[2],\n\t\t\t\t\t255\n\t\t\t\t] : e.length > a ? e.slice(0, 3) : e.slice();\n\t\t\t\tconst l = U(n, e.slice(0, 3), w), c = l[0], f = l[1];\n\t\t\t\tf > 0 && f <= o && (t[c] = e);\n\t\t\t}\n\t\t}\n\t\tfunction m(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction k(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction U(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn [o, n];\n\t\t}\n\t\tfunction C(t, r, e = w) {\n\t\t\treturn t[k(t, r, e)];\n\t\t}\n\t\tfunction I(t = {}) {\n\t\t\tconst { initialCapacity: r = 4096, auto: o = !0 } = t, i = n(r), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003);\n\t\t\tlet s = !1;\n\t\t\treturn {\n\t\t\t\treset() {\n\t\t\t\t\ti.reset(), s = !1;\n\t\t\t\t},\n\t\t\t\tfinish() {\n\t\t\t\t\ti.writeByte(e.trailer);\n\t\t\t\t},\n\t\t\t\tbytes: () => i.bytes(),\n\t\t\t\tbytesView: () => i.bytesView(),\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn i.buffer;\n\t\t\t\t},\n\t\t\t\tget stream() {\n\t\t\t\t\treturn i;\n\t\t\t\t},\n\t\t\t\twriteHeader: u,\n\t\t\t\twriteFrame(t, r, e, n = {}) {\n\t\t\t\t\tconst { transparent: p = !1, transparentIndex: y = 0, delay: h = 0, palette: w = null, repeat: d = 0, colorDepth: A = 8, dispose: b = -1 } = n;\n\t\t\t\t\tlet M = !1;\n\t\t\t\t\tif (o ? s || (M = !0, u(), s = !0) : M = Boolean(n.first), r = Math.max(0, Math.floor(r)), e = Math.max(0, Math.floor(e)), M) {\n\t\t\t\t\t\tif (!w) throw new Error("First frame must include a { palette } option");\n\t\t\t\t\t\t(function(t, r, e, n, o = 8) {\n\t\t\t\t\t\t\tconst a = o - 1 << 4 | 128 | E(n.length) - 1;\n\t\t\t\t\t\t\tz(t, r), z(t, e), t.writeBytes([\n\t\t\t\t\t\t\t\ta,\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t0\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t})(i, r, e, w, A), F(i, w), d >= 0 && function(t, r) {\n\t\t\t\t\t\t\tt.writeByte(33), t.writeByte(255), t.writeByte(11), B(t, "NETSCAPE2.0"), t.writeByte(3), t.writeByte(1), z(t, r), t.writeByte(0);\n\t\t\t\t\t\t}(i, d);\n\t\t\t\t\t}\n\t\t\t\t\tconst g = Math.round(h / 10);\n\t\t\t\t\t(function(t, r, e, n, o) {\n\t\t\t\t\t\tvar a, i;\n\t\t\t\t\t\tt.writeByte(33), t.writeByte(249), t.writeByte(4), o < 0 && (o = 0, n = !1), n ? (a = 1, i = 2) : (a = 0, i = 0), r >= 0 && (i = 7 & r), i <<= 2, t.writeByte(0 | i | a), z(t, e), t.writeByte(o || 0), t.writeByte(0);\n\t\t\t\t\t})(i, b, g, p, y);\n\t\t\t\t\tconst v = Boolean(w) && !M;\n\t\t\t\t\t(function(t, r, e, n) {\n\t\t\t\t\t\tif (t.writeByte(44), z(t, 0), z(t, 0), z(t, r), z(t, e), n) {\n\t\t\t\t\t\t\tconst r = E(n.length) - 1;\n\t\t\t\t\t\t\tt.writeByte(128 | r);\n\t\t\t\t\t\t} else t.writeByte(0);\n\t\t\t\t\t})(i, r, e, v ? w : null), v && F(i, w), function(t, r, e, n, o = 8, i, l, c) {\n\t\t\t\t\t\ta(e, n, r, o, t, i, l, c);\n\t\t\t\t\t}(i, t, r, e, A, l, c, f);\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction u() {\n\t\t\t\tB(i, "GIF89a");\n\t\t\t}\n\t\t}\n\t\tfunction F(t, r) {\n\t\t\tconst e = 1 << E(r.length);\n\t\t\tfor (let n = 0; n < e; n++) {\n\t\t\t\tlet e = [\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\t0\n\t\t\t\t];\n\t\t\t\tn < r.length && (e = r[n]), t.writeByte(e[0]), t.writeByte(e[1]), t.writeByte(e[2]);\n\t\t\t}\n\t\t}\n\t\tfunction z(t, r) {\n\t\t\tt.writeByte(255 & r), t.writeByte(r >> 8 & 255);\n\t\t}\n\t\tfunction B(t, r) {\n\t\t\tfor (var e = 0; e < r.length; e++) t.writeByte(r.charCodeAt(e));\n\t\t}\n\t\tfunction E(t) {\n\t\t\treturn Math.max(Math.ceil(Math.log2(t)), 1);\n\t\t}\n\t\tvar x = I;\n\t})();\n\tconst e = (0, r.GIFEncoder)();\n\tlet n = 1, o = 1, a = 16, i = 0;\n\tconst l = self;\n\tl.addEventListener("message", (t) => {\n\t\tconst c = t.data;\n\t\ttry {\n\t\t\tif ("init" === c.type) return n = c.width ?? n, o = c.height ?? o, a = c.delay ?? a, i = c.repeat ?? i, void l.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "ready"\n\t\t\t});\n\t\t\tif ("frame" === c.type && c.buffer) {\n\t\t\t\tconst t = new Uint8ClampedArray(c.buffer), f = (0, r.quantize)(t, 256, {}), s = (0, r.applyPalette)(t, f);\n\t\t\t\te.writeFrame(s, n, o, {\n\t\t\t\t\tpalette: f,\n\t\t\t\t\tdelay: a,\n\t\t\t\t\trepeat: 0 === c.frameIndex ? i : -1\n\t\t\t\t}), l.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "frame-complete"\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ("finish" === c.type) {\n\t\t\t\te.finish();\n\t\t\t\tconst t = e.bytes(), r = t.buffer.slice(t.byteOffset, t.byteOffset + t.byteLength);\n\t\t\t\tl.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "complete",\n\t\t\t\t\tbuffer: r\n\t\t\t\t}, [r]);\n\t\t\t}\n\t\t} catch (f) {\n\t\t\tl.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "error",\n\t\t\t\tmessage: f instanceof Error ? f.message : "GIF worker failed"\n\t\t\t});\n\t\t}\n\t});\n})();\n',I="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",P],{type:"text/javascript;charset=utf-8"});function B(t){let e;try{if(e=I&&(self.URL||self.webkitURL).createObjectURL(I),!e)throw"";const i=new Worker(e,{name:t?.name});return i.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),i}catch(i){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(P),{name:t?.name})}}var F=class{K;tt=new Map;et;it=0;v=!1;constructor(t,e,i,r,n){this.K=new B,this.K.addEventListener("message",this.rt),this.K.addEventListener("error",this.nt),n?.addEventListener("abort",this.dispose,{once:!0}),this.et=this.ot({type:"init",width:t,height:e,delay:Math.round(1e3/i),repeat:r})}async encodeFrame(t,e){await this.et,await this.ot({type:"frame",buffer:t,frameIndex:e},[t])}async finish(){await this.et;const t=await this.ot({type:"finish"});if(!t.buffer)throw new Error("GIF worker returned no encoded output.");return t.buffer}dispose=()=>{if(!this.v){this.v=!0,this.K.terminate();for(const t of this.tt.values())t.reject(new DOMException("GIF export was cancelled.","AbortError"));this.tt.clear()}};ot(t,e=[]){if(this.v)return Promise.reject(new DOMException("GIF export was cancelled.","AbortError"));const i=++this.it;return new Promise((r,n)=>{this.tt.set(i,{resolve:r,reject:n}),this.K.postMessage({...t,id:i},e)})}rt=t=>{const e=t.data,i=this.tt.get(e.id);i&&(this.tt.delete(e.id),"error"!==e.type?i.resolve(e):i.reject(new Error(e.message??"GIF worker failed")))};nt=t=>{const e=new Error(t.message||"GIF worker failed");for(const i of this.tt.values())i.reject(e);this.tt.clear()}},O=C(),R=class{T;k;constructor(t,e){this.T=t,this.k=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new a).$downloadFile(e,t.filename,".gif")}async $generateGIFBlob(t={}){const e=this.Z(t),i=this.T.canvas,r=Math.max(1,Math.round(i.width*e.scale)),n=Math.max(1,Math.round(i.height*e.scale)),o=new g(this.T,this.k,{width:r,height:n}),s=o.canvas.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("GIF export requires a 2D canvas context.");const a="undefined"==typeof Worker?(0,O.GIFEncoder)():null,h="undefined"==typeof Worker?null:new F(r,n,e.frameRate,e.repeat,e.signal);try{let i;if(this.I(e.signal),await o.$render({frameCount:e.frameCount,frameRate:e.frameRate,signal:e.signal,prepareFrame:e.prepareFrame,onFrame:async({frameIndex:i,canvas:r})=>{this.I(e.signal);const n=s.getImageData(0,0,r.width,r.height);if(h)await h.encodeFrame(n.data.buffer,i);else if(a){const t=n.data,o=(0,O.quantize)(t,256,{}),s=(0,O.applyPalette)(t,o);a.writeFrame(s,r.width,r.height,{palette:o,delay:Math.round(1e3/e.frameRate),repeat:0===i?e.repeat:-1})}t.onProgress?.({state:"encoding",frameIndex:i+1,totalFrames:e.frameCount}),(i+1)%2==0&&await this.st(e.signal)}}),this.I(e.signal),h)i=await h.finish();else{if(!a)throw new Error("No GIF encoder is available.");{a.finish();const t=a.bytes();i=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}return t.onProgress?.({state:"completed",totalFrames:e.frameCount}),new Blob([i],{type:"image/gif"})}catch(c){throw t.onProgress?.({state:"error",message:c instanceof Error?c.message:"GIF export failed"}),c}finally{h?.dispose()}}Z(t){return{filename:t.filename,frameCount:Math.max(1,Math.abs(Math.round(t.frameCount??300))),frameRate:Math.max(1,Math.abs(t.frameRate??60)),scale:Math.max(Number.EPSILON,Math.abs(t.scale??1)),repeat:Math.max(-1,Math.round(t.repeat??0)),signal:t.signal,prepareFrame:t.prepareFrame}}I(t){if(t?.aborted)throw new DOMException("GIF export was cancelled.","AbortError")}st(t){return new Promise((e,i)=>{t?.aborted?i(new DOMException("GIF export was cancelled.","AbortError")):setTimeout(e,0)})}},$=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function D(){return new $("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function N(t,e){return new $("VIDEO_EXPORT_TIMEOUT",t,e)}function V(t){return t instanceof $?t:w(t)?D():t instanceof p&&"FRAME_SEQUENCE_TIMEOUT"===t.code?N(t.message,t):new $("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}function U(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new $("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const i=Math.max(1,Math.round(t.width)),r=Math.max(1,Math.round(t.height));if("mp4"===t.format&&(i%2!=0||r%2!=0))throw new $("VIDEO_DIMENSIONS_UNSUPPORTED",`MP4/H.264 requires even dimensions; received ${i}x${r}. Increase pixel density or choose WebM.`);return{format:t.format,extension:"mp4"===t.format?".mp4":".webm",mimeType:"mp4"===t.format?"video/mp4":"video/webm",codec:e,quality:t.quality,hardwareAcceleration:t.hardwareAcceleration,keyFrameInterval:t.keyFrameInterval,frameRate:t.frameRate,frameCount:t.frameCount,width:i,height:r,transparent:t.transparent}}function z(t){if(!t)throw new Error("Assertion failed.")}var j,L=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},q=t=>t&&t[t.length-1],G=t=>t>=0&&t<2**32,H=t=>{let e=0;for(;0===t.readBits(1)&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},W=t=>{const e=H(t);return 1&e?e+1>>1:-(e>>1)},X=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Z=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Q=new TextEncoder,Y={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},J={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},K={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},tt=t=>!!(t&&t.primaries&&t.transfer&&t.matrix&&void 0!==t.fullRange),et=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),it=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(e=>{let i=!1;t=()=>{i||(e(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=e,this.pending++,await i,t}},rt=(t,e,i)=>{let r=0,n=t.length-1,o=-1;for(;r<=n;){const s=r+(n-r+1)/2|0;i(t[s])<=e?(o=s,r=s+1):n=s-1}return o},nt=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},ot=t=>{throw new Error(`Unexpected value: ${t}`)},st=(t,e,i)=>{const r=t.getUint8(e),n=t.getUint8(e+1),o=t.getUint8(e+2);return i?r|n<<8|o<<16:r<<16|n<<8|o},at=(t,e,i)=>Math.max(e,Math.min(i,t)),ht=(t,e)=>Math.round(t/e)*e,ct=(t,e)=>Math.round(t*e)/e,lt=(t,e)=>Math.floor(t*e)/e,dt=t=>{let e=0;for(;0!==t;)t&=t-1,e++;return e},ut=/^[a-z]{3}$/,ft=1e6*(1+Number.EPSILON),pt=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},mt=null,wt=()=>null!==mt?mt:mt=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),vt=null,bt=()=>null!==vt?vt:vt="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),yt=null,gt=()=>null!==yt?yt:yt=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),xt=null,Et=()=>{if(null!==xt)return xt;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?xt=Number(t[1]):null},Tt=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},kt=t=>{switch(t.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},_t=(t,e)=>{if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0},Mt=t=>{z(Number.isInteger(t.num)),z(Number.isInteger(t.den)),z(0!==t.den);let e=Math.abs(t.num),i=Math.abs(t.den);for(;0!==i;){const t=e%i;e=i,i=t}const r=e||1;return{num:t.num/r,den:t.den/r}},At=(t,e)=>{if("object"!=typeof t||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},St=t=>Array.isArray(t)?t:[t],Ct=class{constructor(){this.ht=new Map}on(t,e,i){this.ht.has(t)||this.ht.set(t,new Set);const r={fn:e,once:i?.once??!1};return this.ht.get(t).add(r),()=>{this.ht.get(t)?.delete(r)}}ct(...t){const[e,i]=t,r=this.ht.get(e);if(r)for(const o of r){try{o.fn(i)}catch(n){console.error(n)}o.once&&r.delete(o)}}},Pt=t=>null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(t=>"string"==typeof t);!function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"}(j||(j={}));var It=class t{constructor(){}static get level(){return t.lt}static set level(e){if(e!==j.Silent&&e!==j.Errors&&e!==j.Warnings&&e!==j.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");t.lt=e}static get dt(){return t.ut??=new Ct}static on(e,i,r){return t.dt.on(e,i,r)}static ft(...e){t.dt.ct("error",e),t.lt>=j.Errors&&console.error(...e)}static wt(...e){t.dt.ct("warn",e),t.lt>=j.Warnings&&console.warn(...e)}static vt(...e){t.dt.ct("info",e),t.lt>=j.Info&&console.info(...e)}};It.lt=j.Info,It.ut=null;var Bt,Ft,Ot=class{constructor(t,e){if(this.data=t,this.mimeType=e,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof e)throw new TypeError("mimeType must be a string.")}},Rt=class{constructor(t,e,i,r){if(this.data=t,this.mimeType=e,this.name=i,this.description=r,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==e&&"string"!=typeof e)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}},$t=class t{constructor(t){this.bytes=t,this.pos=0}seekToByte(t){this.pos=8*t}readBit(){const t=Math.floor(this.pos/8),e=this.bytes[t]??0,i=7-(7&this.pos),r=(e&1<<i)>>i;return this.pos++,r}readBits(t){if(1===t)return this.readBit();let e=0;for(let i=0;i<t;i++)e<<=1,e|=this.readBit();return e}writeBits(t,e){const i=this.pos+t;for(let r=this.pos;r<i;r++){const t=Math.floor(r/8);let n=this.bytes[t];const o=7-(7&r);n&=~(1<<o),n|=(e&1<<i-r-1)>>i-r-1<<o,this.bytes[t]=n}this.pos=i}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new t(this.bytes);return e.pos=this.pos,e}},Dt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Nt=[-1,1,2,3,4,5,6,8],Vt=t=>{let e=Dt.indexOf(t.sampleRate),i=null;-1===e&&(e=15,i=t.sampleRate);const r=Nt.indexOf(t.numberOfChannels);if(-1===r)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),15===e&&(n+=24);const o=Math.ceil(n/8),s=new Uint8Array(o),a=new $t(s);return t.objectType<32?a.writeBits(5,t.objectType):(a.writeBits(5,31),a.writeBits(6,t.objectType-32)),a.writeBits(4,e),15===e&&a.writeBits(24,i),a.writeBits(4,r),s},Ut=["avc","hevc","vp9","av1","vp8","prores"],zt=["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"],jt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Lt=[...jt,...zt],qt=["webvtt"],Gt=[{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}],Ht=[{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}],Wt=[{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}],Xt=[{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}],Zt=["ap4x","ap4h","apch","apcn","apcs","apco"],Qt=["dtsc","dtsh","dtsl","dtse"],Yt=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],Jt=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=Gt.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??q(Gt),s=o?o.level:0;return`avc1.${t.toString(16).padStart(2,"0")}00${s.toString(16).padStart(2,"0")}`}if("hevc"===t){const t="",n=1,o="6",s=e*i,a=Ht.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??q(Ht);return`hev1.${t}${n}.${o}.${a.tier}${a.level}.B0`}if("vp8"===t)return"vp8";if("vp9"===t){const t=e*i;return`vp09.00.${(Wt.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??q(Wt)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=Xt.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??q(Xt);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Yt.filter(t=>t.alpha===n);let s=o[0].fourCc,a=1/0;for(const{fourCc:e,bitrate:i}of o){const n=Math.abs(i*t-r);n<a&&(a=n,s=e)}return s}throw ot(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Kt=t=>{const e=t.split("."),i=Number(e[1]),r=e[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(e[3])?0:1)<<6)+0+((e[4]?Number(e[4]):0)<<4)+((e[5]?Number(e[5][0]):1)<<3)+((e[5]?Number(e[5][1]):1)<<2)+(e[5]?Number(e[5][2]):0),0]},te=/^pcm-([usf])(\d+)(be)?$/,ee=t=>{if(z(zt.includes(t)),"ulaw"===t)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===t)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=te.exec(t);let i;return z(e),i="u"===e[1]?"unsigned":"s"===e[1]?"signed":"float",{dataType:i,sampleSize:Number(e[2])/8,littleEndian:"be"!==e[3],silentValue:"pcm-u8"===t?128:0}},ie=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":"vp8"===t?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":Zt.includes(t)?"prores":"mp3"===t||"mp4a.69"===t||"mp4a.6B"===t||"mp4a.6b"===t||"mp4a.40.34"===t?"mp3":t.startsWith("mp4a.40.")||"mp4a.67"===t?"aac":"opus"===t?"opus":"vorbis"===t?"vorbis":"flac"===t?"flac":"ac-3"===t||"ac3"===t?"ac3":"ec-3"===t||"eac3"===t?"eac3":Qt.includes(t)?"dts":"ulaw"===t?"ulaw":"alaw"===t?"alaw":te.test(t)?t:"webvtt"===t?"webvtt":null,re=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Zt],ne=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,oe=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,se=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ae=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,he=(t,e)=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!re.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==t.decoderConfig.displayAspectWidth&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectHeight&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectWidth!=(void 0!==t.decoderConfig.displayAspectHeight))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(void 0!==t.decoderConfig.description&&!et(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==t.decoderConfig.colorSpace){const{colorSpace:e}=t.decoderConfig;if("object"!=typeof e)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(Y);if(null!=e.primaries&&!i.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(J);if(null!=e.transfer&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const n=Object.keys(K);if(null!=e.matrix&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!ne.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!oe.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if("vp8"!==t.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!se.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")){if(!ae.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Zt.some(e=>t.decoderConfig.codec.startsWith(e))&&!Zt.some(e=>t.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Zt.join(", ")}.`);if(null!==e&&ie(t.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},ce=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],le=(t,e)=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!ce.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==t.decoderConfig.description&&!et(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==t.decoderConfig.codec&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if("opus"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if("flac"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if("ac-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if("ec-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(t.decoderConfig.codec.startsWith("dts")){if(!Qt.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Qt.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!zt.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${zt.join(", ")}).`);if(null!==e&&ie(t.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},de=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof t)throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof t.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof t.config.description)throw new TypeError("Subtitle metadata config description must be a string.")},ue=[48e3,44100,32e3],fe=[24e3,22050,16e3];!function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"}(Bt||(Bt={})),function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(Ft||(Ft={}));var pe,me=function*(t){let e=0,i=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(-1===r||r>=t.length-2)break;e=r;let n=0;e+3<t.length&&0===t[e+1]&&0===t[e+2]&&1===t[e+3]?n=4:0===t[e+1]&&1===t[e+2]&&(n=3),0!==n?(-1!==i&&e>i&&(yield{offset:i,length:e-i}),i=e+n,e=i):e++}-1!==i&&i<t.length&&(yield{offset:i,length:t.length-i})},we=function*(t,e){let i=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let t;1===e?t=r.getUint8(i):2===e?t=r.getUint16(i,!1):3===e?t=st(r,i,!1):(z(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},ve=t=>31&t,be=t=>{const e=[],i=t.length;for(let r=0;r<i;r++)r+2<i&&0===t[r]&&0===t[r+1]&&3===t[r+2]?(e.push(0,0),r+=2):e.push(t[r]);return new Uint8Array(e)},ye=(new Uint8Array([0,0,0,1]),{1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}}),ge=t=>{const e=H(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)H(t),H(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},xe=t=>t>>1&63,Ee=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},Te=t=>{for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBits(1)){const i=Math.min(64,1<<4+(e<<1));e>1&&W(t);for(let e=0;e<i;e++)W(t)}else H(t)},ke=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=_e(t,r,e,i)},_e=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(H(t)+1):e-1,t.readBits(1),H(t);const o=r[s]??0;for(let e=0;e<=o;e++)t.readBits(1)||t.readBits(1);n=r[s]}else{const e=H(t),i=H(t);for(let r=0;r<e;r++)H(t),t.readBits(1);for(let r=0;r<i;r++)H(t),t.readBits(1);n=e+i}return n},Me=(t,e)=>{let i=2,r=2,n=2,o=0,s=0,a={num:1,den:1};if(t.readBits(1)){const e=t.readBits(8);if(255===e)a={num:t.readBits(16),den:t.readBits(16)};else{const t=ye[e];t&&(a=t)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),o=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(H(t),H(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(H(t),H(t),H(t),H(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&H(t),t.readBits(1)&&Ae(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=H(t),H(t),H(t),H(t),H(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},Ae=(t,e,i)=>{let r=!1,n=!1,o=!1;e&&(r=1===t.readBits(1),n=1===t.readBits(1),(r||n)&&(o=1===t.readBits(1),o&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),o&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let s=0;s<=i;s++){let e=!0;1===t.readBits(1)||(e=1===t.readBits(1));let i=!1;e?H(t):i=1===t.readBits(1);let s=1;i||(s=H(t)+1),r&&Se(t,s,o),n&&Se(t,s,o)}},Se=(t,e,i)=>{for(let r=0;r<e;r++)H(t),H(t),i&&(H(t),H(t)),t.readBits(1)};!function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"}(pe||(pe={}));var Ce,Pe=t=>{const e=Z(t),i=e.getUint8(9),r=e.getUint16(10,!0),n=e.getUint32(12,!0),o=e.getInt16(16,!0),s=e.getUint8(18);let a=null;return s&&(a=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:o,channelMappingFamily:s,channelMappingTable:a}};!function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"}(Ce||(Ce={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var Ie,Be=[1,2,3,6],Fe=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Oe=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Re=[16,16,20,20,0,24,24,0],$e=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],De=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Ne=[32e3,44100,48e3,0],Ve=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ue=[512,1024,2048,4096],ze=t=>{if(t.length<10)return null;if(100!==t[0]||88!==t[1]||32!==t[2]||37!==t[3])return null;const e=new $t(t);e.skipBits(32),e.skipBits(8);const i=e.readBits(2),r=e.readBits(1),n=8+4*r,o=16+4*r;e.skipBits(n);const s=e.readBits(o)+1,a={frameSize:s,asset:null};if(!e.readBits(1))return a;const h=Ne[e.readBits(2)],c=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const l=e.readBits(3)+1,d=e.readBits(3)+1,u=[];for(let v=0;v<l;v++)u.push(e.readBits(i+1));for(const v of u)e.skipBits(8*dt(v));if(e.readBits(1)){e.skipBits(2);const t=e.readBits(2)+1<<2,i=e.readBits(2)+1;e.skipBits(i*t)}for(let v=0;v<d;v++)e.skipBits(o);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const f=e.readBits(5)+1,p=Ve[e.readBits(4)],m=e.readBits(8)+1;let w=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const t=e.readBits(2)+1<<2;w=e.readBits(t)}return 0===h||e.getBitsLeft()<0?a:{frameSize:s,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(c*p/h),channelLayout:w,pcmResolution:f}}},je=t=>{const e=new Uint8Array(20),i=Z(e);i.setUint32(0,t.sampleRate),i.setUint32(4,t.bitRate),i.setUint32(8,t.bitRate),e[12]=t.pcmResolution;const r=t.core&&!t.hasExtensions?1:0,n=new $t(e);return n.seekToByte(13),n.writeBits(2,Math.max(Ue.indexOf(t.sampleCount),0)),n.writeBits(5,r),n.writeBits(1,t.core?.lfePresent?1:0),n.writeBits(6,t.core?.amode??0),n.writeBits(14,t.core?t.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,t.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e},Le=new Uint8Array(0),qe=class t{constructor(t,e,i,r,n=-1,o,s){if(this.data=t,this.type=e,this.timestamp=i,this.duration=r,this.sequenceNumber=n,t===Le&&void 0===o)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===o&&(o=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==e&&"delta"!==e)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==s&&("object"!=typeof s||!s))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==s?.alpha&&!(s.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==s?.alphaByteLength&&(!Number.isInteger(s.alphaByteLength)||s.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=s??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Le}get microsecondTimestamp(){return Math.trunc(ft*this.timestamp)}get microsecondDuration(){return Math.trunc(ft*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,i){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new t(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,i)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!=typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}},Ge=class{constructor(t){this.value=t}},He=class{constructor(t){this.value=t}},We=class{constructor(t){this.value=t}},Xe=class{constructor(t){this.value=t}};!function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"}(Ie||(Ie={})),Ie.EBML,Ie.Segment,Ie.SeekHead,Ie.Info,Ie.Cluster,Ie.Tracks,Ie.Cues,Ie.Attachments,Ie.Chapters,Ie.Tags;var Ze=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,Qe=t=>t<256n?1:t<65536n?2:t<1n<<24n?3:t<1n<<32n?4:t<1n<<40n?5:t<1n<<48n?6:t<1n<<56n?7:8,Ye=t=>t>=-64&&t<64?1:t>=-8192&&t<8192?2:t>=-1048576&&t<1<<20?3:t>=-134217728&&t<1<<27?4:t>=-(2**34)&&t<2**34?5:6,Je=class{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=Ze(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=Qe(t)){let i=0;for(let r=e-1;r>=0;r--)this.helperView.setUint8(i++,Number(t>>BigInt(8*r)&255n));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(t,e=Ye(t)){t<0&&(t+=2**(8*e)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=(t=>{if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML varint size not supported "+t)})(t)){let i=0;switch(e){case 1:this.helperView.setUint8(i++,128|t);break;case 2:this.helperView.setUint8(i++,64|t>>8),this.helperView.setUint8(i++,t);break;case 3:this.helperView.setUint8(i++,32|t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 4:this.helperView.setUint8(i++,16|t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 5:this.helperView.setUint8(i++,8|t/2**32&7),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 6:this.helperView.setUint8(i++,4|t/2**40&3),this.helperView.setUint8(i++,t/2**32|0),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(t=>t.charCodeAt(0))))}writeEBML(t){if(null!==t)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(const e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data)){const e=this.writer.getPos(),i=-1===t.size?1:t.size??4;-1===t.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const r=this.writer.getPos();if(this.dataOffsets.set(t,r),this.writeEBML(t.data),-1!==t.size){const t=this.writer.getPos()-r,n=this.writer.getPos();this.writer.seek(e),this.writeVarInt(t,i),this.writer.seek(n)}}else if("number"==typeof t.data){const e=t.size??Ze(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??Qe(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if("string"==typeof t.data)this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof Ge)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof He)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof We){const e=t.size??Ye(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Xe){const e=Q.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else ot(t.data)}},Ke={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS","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"},ti=t=>{const e=t.filePos,i=new $t(Ni(t,9));if(4095!==i.readBits(12))return null;if(i.skipBits(1),0!==i.readBits(2))return null;const r=i.readBits(1),n=i.readBits(2)+1,o=i.readBits(4);if(15===o)return null;i.skipBits(1);const s=i.readBits(3);if(0===s)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const a=i.readBits(13);i.skipBits(11);const h=i.readBits(2)+1;if(1!==h)throw new Error("ADTS frames with more than one AAC frame are not supported.");let c=null;return 1===r?t.filePos-=2:c=i.readBits(16),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s,frameLength:a,numberOfAacFrames:h,crcCheck:c,startPos:e}},ei=i((t,e)=>{e.exports={}}),ii=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});Symbol.dispose??=Symbol("Symbol.dispose");var ri=-1/0,ni=-1/0,oi=null;"undefined"!=typeof FinalizationRegistry&&(oi=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-ri>=1e3&&(It.ft("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."),ri=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-ni>=1e3&&(It.ft("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."),ni=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var si=class{constructor(){this.bt=0,this.yt=null}},ai=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],hi=new Set(ai),ci=class t{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(ft*this.timestamp)}get microsecondDuration(){return Math.trunc(ft*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,i){if(this.gt=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0===i.format||!hi.has(i.format))throw new TypeError("init.format must be one of: "+ai.join(", "));if(!Number.isInteger(i.codedWidth)||i.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(i.codedHeight)||i.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==i.layout){if(!Array.isArray(i.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const t of i.layout){if(!t||"object"!=typeof t||Array.isArray(t))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==i.visibleRect&&At(i.visibleRect,"init.visibleRect"),void 0!==i.displayWidth&&(!Number.isInteger(i.displayWidth)||i.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==i.displayHeight&&(!Number.isInteger(i.displayHeight)||i.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==i.displayWidth!=(void 0!==i.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=i.format,this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0;const t=i.layout??yi(i.format,i.codedWidth,i.codedHeight);let r=i.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},void 0!==i.displayWidth?(this.squarePixelWidth=this.rotation%180==0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180==0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this.xt=i.Et?X(e):X(e).slice(),this.Tt=t,this.colorSpace=new pi(r)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==i?.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==i?.timestamp&&!Number.isFinite(i?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==i?.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==i?.visibleRect&&At(i.visibleRect,"init.visibleRect"),this.xt=e,this.Tt=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=i?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=i?.timestamp??e.timestamp/1e6,this.duration=i?.duration??(e.duration??0)/1e6,this.colorSpace=new pi(e.colorSpace)}else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==i.visibleRect&&At(i.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*ft),duration:Math.trunc((i.duration??0)*ft)||void 0,visibleRect:i.visibleRect&&{x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height}}),i);let r=0,n=0;if("naturalWidth"in e?(r=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,n=e.videoHeight):"width"in e&&(r=Number(e.width),n=Number(e.height)),!r||!n)throw new TypeError("Could not determine dimensions.");const o=i.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(o.width,o.height),a=s.getContext("2d",{alpha:bt(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-o.left,-o.top),this.xt=s,this.Tt=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:o.width,height:o.height},this.squarePixelWidth=o.width,this.squarePixelHeight=o.height,this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=new pi({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof si))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this.xt=e,e.bt++,this.format=e.getFormat(),null!==this.format&&!ai.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=i?.encodeOptions??{},this.pixelAspectRatio=Mt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),oi?.register(this,{type:"video",data:this.xt},this)}clone(){if(this.gt)throw new Error("VideoSample is closed.");return z(null!==this.xt),this.xt instanceof si?new t(this.xt,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):mi(this.xt)?new t(this.xt.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this.xt instanceof Uint8Array?(z(this.Tt),new t(this.xt,{format:this.format,layout:this.Tt,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,Et:!0})):new t(this.xt,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this.gt||(oi?.unregister(this),this.xt instanceof si?(this.xt.bt--,0===this.xt.bt&&this.xt.close()):mi(this.xt)?this.xt.close():this.xt=null,this.gt=!0)}allocationSize(t={}){if(bi(t),this.gt)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot get allocation size when format is null.");return mi(this.xt)?this.xt.allocationSize(t):xi(this,t).allocationSize}async copyTo(e,i={}){if(!et(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(bi(i),this.gt)throw new Error("VideoSample is closed.");if(null==(i.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(z(null!==this.xt),mi(this.xt))return this.xt.copyTo(e,i);if(i.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(i.format)){if(!(this.xt instanceof si)){if("undefined"==typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const t=this.toVideoFrame(),r=await t.copyTo(e,i);return t.close(),r}{const r={stack:[],error:void 0,hasError:!1};try{const n=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e}(r,await this.xt.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},i.colorSpace??"srgb"),!1);if(!(n instanceof t))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return await n.copyTo(e,i)}catch(c){r.error=c,r.hasError=!0}finally{ii(r)}}}const r=xi(this,i);z(this.format);const n=X(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=gi(this.format);let s;if(this.xt instanceof si){let t=this.xt.getDataPlanes();if(t instanceof Promise&&(t=await t),!Array.isArray(t)||t.some(t=>!(t.data instanceof Uint8Array)||!Number.isInteger(t.stride)||t.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=t}else if(this.xt instanceof Uint8Array)z(this.Tt),z(this.Tt.length===o.length),s=this.Tt.map((t,e)=>{const i=Math.ceil(this.codedHeight/o[e].heightDivisor);return{data:this.xt.subarray(t.offset,t.offset+t.stride*i),stride:t.stride}});else{const t=this.xt.getContext("2d");z(t),s=[{data:X(t.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const a=[],h=o.length;for(let t=0;t<h;t++){const e=r.computedLayouts[t],i=s[t].stride,o=s[t].data;let h=e.sourceTop*i;h+=e.sourceLeftBytes;let c=e.destinationOffset;const l=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let t=0;t<e.sourceHeight;t++){if(h+l>o.byteLength)throw new Error("Source buffer OOB read.");if(c+l>n.byteLength)throw new Error("Destination buffer OOB write.");const t=o.subarray(h,h+l);n.set(t,c),h+=i,c+=e.destinationStride}a.push(d)}if(void 0!==i.format){const t=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),e=this.format.includes("X")&&i.format.includes("A");if(t||e)for(let i=0;i<r.allocationSize;i+=4){if(t){const t=n[i];n[i]=n[i+2],n[i+2]=t}e&&(n[i+3]=255)}}return a}toVideoFrame(){if(this.gt)throw new Error("VideoSample is closed.");if(z(null!==this.xt),this.xt instanceof si){if(null===this.format)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const t=this.xt.getDataPlanes();if(t instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const e=t.reduce((t,e)=>t+e.data.byteLength,0),i=new Uint8Array(e);let r=0;const n=[];for(const o of t)i.set(o.data,r),n.push(r),r+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:t.map((t,e)=>({offset:n[e],stride:t.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return mi(this.xt)?new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.xt instanceof Uint8Array?(z(this.Tt),new VideoFrame(this.xt,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this.Tt,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,r,n,o,s,a,h){let c=0,l=0,d=this.displayWidth,u=this.displayHeight,f=0,p=0,m=this.displayWidth,w=this.displayHeight;if(void 0!==o?(c=e,l=i,d=r,u=n,f=o,p=s,void 0!==a?(m=a,w=h):(m=d,w=u)):(f=e,p=i,void 0!==r&&(m=r,w=n)),!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this.gt)throw new Error("VideoSample is closed.");({sx:c,sy:l,sWidth:d,sHeight:u}=this.kt(c,l,d,u,this.rotation));const v=this.toCanvasImageSource();t.save();const b=f+m/2,y=p+w/2;t.translate(b,y),t.rotate(this.rotation*Math.PI/180);const g=this.rotation%180==0?1:m/w;t.scale(1/g,g),t.drawImage(v,c,l,d,u,-m/2,-w/2,m,w),t.restore()}drawWithFit(t,e){if(!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==e.crop&&vi(e.crop,"options.");const i=t.canvas.width,r=t.canvas.height,n=e.rotation??this.rotation,[o,s]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a,h,c,l,d=e.crop;d&&(d=wi(d,o,s));const{sx:u,sy:f,sWidth:p,sHeight:m}=this.kt(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??s,n);if("fill"===e.fit)a=0,h=0,c=i,l=r;else{const[t,n]=e.crop?[e.crop.width,e.crop.height]:[o,s],d="contain"===e.fit?Math.min(i/t,r/n):Math.max(i/t,r/n);c=t*d,l=n*d,a=(i-c)/2,h=(r-l)/2}t.save();const w=n%180==0?1:c/l;t.translate(i/2,r/2),t.rotate(n*Math.PI/180),t.scale(1/w,w),t.translate(-i/2,-r/2),t.drawImage(this.toCanvasImageSource(),u,f,p,m,a,h,c,l),t.restore()}kt(t,e,i,r,n){return 90===n?[t,e,i,r]=[e,this.squarePixelHeight-t-i,r,i]:180===n?[t,e]=[this.squarePixelWidth-t-i,this.squarePixelHeight-e-r]:270===n&&([t,e,i,r]=[this.squarePixelWidth-e-r,t,r,i]),{sx:t,sy:e,sWidth:i,sHeight:r}}_t(t,e,i){const r=t.width,n=t.height,[o,s]=i.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],a=i.crop?i.crop.width:o,h=i.crop?i.crop.height:s;let c=0;2*r<a&&2*n<h&&(c=Math.floor(Math.log2(Math.min(a/r,h/n))));const l=r*2**c,d=n*2**c,{canvas:u,context:f,isNew:p}=c>0?fi(l,d):{canvas:t,context:e,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,l,d)):p||f.clearRect(0,0,l,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let m=c;m>1;m--){const t=r*2**m,e=n*2**m;f.drawImage(u,0,0,t,e,0,0,t/2,e/2)}f.globalCompositeOperation="source-over",c>0&&(e.imageSmoothingQuality="high",e.globalCompositeOperation="copy",e.drawImage(u,0,0,2*r,2*n,0,0,r,n),e.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this.gt)throw new Error("VideoSample is closed.");if(z(null!==this.xt),this.xt instanceof si||this.xt instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this.xt}async transform(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&vi(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const i=L(this.rotation+(e.rotate??0)),[r,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=wi(o,r,n));const s=o?o.width:r,a=o?o.height:n,h=s/a;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/h):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*h):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=a),c=ht(c,e.roundDimensionsTo??1),l=ht(l,e.roundDimensionsTo??1);const d={width:c,height:l,fit:e.fit??"fill",rotation:i,crop:o??{left:0,top:0,width:r,height:n},alpha:e.alpha??"keep"};for(const t of li){let e=t(this,d);if(e instanceof Promise&&(e=await e),null!==e)return e}const{canvas:u,context:f,isNew:p}=fi(d.width,d.height);return this._t(u,f,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:p,fillBlack:"discard"===d.alpha}),new t(u,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||"object"!=typeof t)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},li=[],di=[],ui=0,fi=(t,e)=>{for(const n of di)if(n.canvas.width===t&&n.canvas.height===e)return n.age=ui++,{canvas:n.canvas,context:n.context,isNew:!1};let i;if("undefined"!=typeof OffscreenCanvas)i=new OffscreenCanvas(t,e);else{if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=t,i.height=e}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return di.length>=3&&di.splice(((t,e)=>{let i=-1,r=1/0;for(let n=0;n<t.length;n++){const o=e(t[n]);o<r&&(r=o,i=n)}return i})(di,t=>t.age),1),di.push({canvas:i,context:r,age:ui++}),{canvas:i,context:r,isNew:!0}},pi=class{constructor(t){if(void 0!==t){if(!t||"object"!=typeof t)throw new TypeError("init.colorSpace, when provided, must be an object.");const e=Object.keys(Y);if(null!=t.primaries&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);const i=Object.keys(J);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(K);if(null!=t.matrix&&!r.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},mi=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,wi=(t,e,i)=>{const r=Math.min(t.left,e),n=Math.min(t.top,i),o=Math.min(t.width,e-r),s=Math.min(t.height,i-n);return z(o>=0),z(s>=0),{left:r,top:n,width:o,height:s}},vi=(t,e)=>{if(!t||"object"!=typeof t)throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},bi=t=>{if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.colorSpace&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==t.format&&"string"!=typeof t.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!=typeof e)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.rect){if(!t.rect||"object"!=typeof t.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==t.rect.x&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==t.rect.y&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==t.rect.width&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==t.rect.height&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},yi=(t,e,i)=>{const r=gi(t),n=[];let o=0;for(const s of r){const t=Math.ceil(e/s.widthDivisor),r=Math.ceil(i/s.heightDivisor),a=t*s.sampleBytes,h=a*r;n.push({offset:o,stride:a}),o+=h}return n},gi=t=>{const e=(t,e,i,r,n)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:e,widthDivisor:i,heightDivisor:r},{sampleBytes:e,widthDivisor:i,heightDivisor:r}];return n&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:ot(t),z(!1)}},xi=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=Ei(i,r,t.codedWidth,t.codedHeight,t.format),o=e.layout;let s;if(e.format&&e.format!==t.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(e.format))throw new Error("NotSupportedError: Invalid destination format.");s=e.format}else s=t.format;return ki(n,s,o)},Ei=(t,e,i,r,n)=>{const o={...t};if(void 0!==e){if(0===e.width||0===e.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");o.x=e.x||0,o.y=e.y||0,o.width=e.width||0,o.height=e.height||0}if(!Ti(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},Ti=(t,e)=>{if(null===t)return!0;const i=gi(t);for(let r=0;r<i.length;r++){const t=i[r],n=t.widthDivisor,o=t.heightDivisor;if((e.x||0)%n!==0)return!1;if((e.y||0)%o!==0)return!1}return!0},ki=(t,e,i)=>{const r=gi(e),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let o=0;const s=[],a=[];for(let h=0;h<n;h++){const e=r[h],n=e.sampleBytes,c=e.widthDivisor,l=e.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(t.y||0)/l),d.sourceHeight=Math.ceil(Math.trunc(t.height||0)/l),d.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/c)*n,d.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/c)*n,void 0!==i){const t=i[h];if(t.stride<d.sourceWidthBytes)throw new TypeError(`Stride for plane ${h} is too small.`);d.destinationOffset=t.offset,d.destinationStride=t.stride}else d.destinationOffset=o,d.destinationStride=d.sourceWidthBytes;const u=d.destinationStride*d.sourceHeight+d.destinationOffset;if(u>4294967295)throw new TypeError("Allocation size exceeds limit.");a.push(u),o=Math.max(o,u);for(let t=0;t<h;t++){const e=s[t];if(!(a[h]<=e.destinationOffset||a[t]<=d.destinationOffset))throw new TypeError("Planes overlap.")}s.push(d)}return{allocationSize:o,computedLayouts:s}},_i=new Map,Mi=(t,e)=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding options must be an object.");if(void 0!==e.alpha&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const i=e.bitrateMode;if(void 0!==i&&!["constant","variable"].includes(i))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==e.latencyMode&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==e.fullCodecString&&"string"!=typeof e.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==e.fullCodecString&&ie(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==e.contentHint&&"string"!=typeof e.contentHint)throw new TypeError("contentHint, when provided, must be a string.")},Ai=t=>{const e=t.bitrateMode,i=t.quality.Mt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Jt(t.codec,t.width,t.height,r,"keep"===t.alpha),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:e,bitrateMode:i,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...(n=t.codec,"avc"===n?{avc:{format:"avc"}}:"hevc"===n?{hevc:{format:"hevc"}}:{})};var n},n=[];return null!==i.quantizer&&n.push({config:r(void 0,"quantizer",i.bitrate),quantizer:i.quantizer}),"quantizer"!==i.bitrateMode&&n.push({config:r(i.bitrate,i.bitrateMode,i.bitrate),quantizer:null}),z(n.length>0),n},Si=class{constructor(t){if("number"!=typeof t&&"string"!=typeof t||(t={quality:t}),!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if("string"==typeof t.quality?!(t.quality in Ci):"number"!=typeof t.quality||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(void 0!==t.preferBitrate&&"boolean"!=typeof t.preferBitrate)throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this.At="string"==typeof t.quality?Ci[t.quality]:t.quality,this.St=t.preferBitrate??!1,this.Ct=void 0,this.Pt=void 0}else{if(void 0!==t.bitrate&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(void 0!==t.quantizer&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(void 0===t.bitrate&&void 0===t.quantizer)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this.At=void 0,this.St=!1,this.Ct=t.bitrate,this.Pt=t.quantizer}this.It=t.bitrateMode}Mt(t,e,i,r){const n=Pi[t];let o=null,s=this.It??r??"variable";if(void 0!==this.Pt){if(n)if(this.Pt<n.min||this.Pt>n.max){if(void 0===this.Ct)throw new Error(`Quantizer ${this.Pt} is out of range for codec '${t}'; must be between ${n.min} and ${n.max}.`)}else o=this.Pt,void 0===this.Ct&&(s="quantizer");else if(void 0===this.Ct)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else void 0===this.Ct&&n&&!this.St&&(z(void 0!==this.At),o=at(Math.round((a=n.worst)+(n.best-a)*this.At),n.min,n.max));var a;let h;if(void 0!==this.Ct)h=this.Ct;else{let r=this.At;void 0===r&&(z(null!==o&&n),r=at((o-n.worst)/(n.best-n.worst),0,1)),h=Bi(t,e,i,Ii(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}Bt(t,e,i){return void 0!==this.Ct?this.Ct:(z(void 0!==this.At),Bi(t,e,i,Ii(this.At)))}Ft(t){if(zt.includes(t)||"flac"===t)return;if(void 0!==this.Ct)return this.Ct;if(void 0===this.At)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const e=Ii(this.At),i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!i)throw new Error(`Unhandled codec: ${t}`);let r=i*e;return"aac"===t?r=[96e3,128e3,16e4,192e3].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t):"opus"===t||"vorbis"===t?r=Math.max(6e3,r):"mp3"===t&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t)),1e3*Math.round(r/1e3)}},Ci={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Pi={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:{min:0,max:63,worst:52,best:20},av1:{min:0,max:255,worst:208,best:80}},Ii=t=>.3*Math.exp(2.5538*t),Bi=(t,e,i,r)=>{const n=e*i,o=3e6*Math.pow(n/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:73.33333333333333}[t]*r;return 1e3*Math.ceil(o/1e3)},Fi=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void z(!1),Oi=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,...s}=e;if(!Ut.includes(t))return!1;if(!Number.isInteger(i)||i<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(void 0!==n&&!(n instanceof Si))throw new TypeError("quality, when provided, must be a Quality.");if(void 0!==n&&void 0!==o)throw new TypeError("quality and bitrate cannot both be provided.");if(void 0!==o&&!(o instanceof Si)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Mi(t,s);const a=Ri(n,o)??new Si("medium");let h;try{h=Ai({codec:t,width:i,height:r,quality:a,framerate:void 0,...s,alpha:"discard"})}catch{return!1}const c=JSON.stringify(h),l=_i.get(c);if(l)return l;const d=(async()=>{for(const{config:e}of h)if($i.some(i=>i.supports(t,e)))return!0;if("undefined"==typeof VideoEncoder)return!1;if(!(i%2!=1&&r%2!=1||"avc"!==t&&"hevc"!==t))return!1;for(const{config:e,quantizer:n}of h){try{if(!(await VideoEncoder.isConfigSupported(e)).supported)continue}catch{continue}if(!bt())return!0;if(await new Promise(async o=>{try{const s=new VideoEncoder({output:()=>{},error:()=>o(!1)});s.configure(e);const a=new Uint8Array(i*r*4),h=new VideoFrame(a,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});s.encode(h,null!==n?Fi(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return _i.set(c,d),d},Ri=(t,e)=>void 0!==t?t:void 0!==e?e instanceof Si?e:new Si({bitrate:e}):void 0,$i=[],Di=class t{constructor(t,e,i,r,n){this.bytes=t,this.view=e,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new t(e,Z(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(e,i=this.end-e){if(e<this.start||e+i>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+i)}},Ni=(t,e)=>{((t,e)=>{if(t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)})(t,e);const i=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,i},Vi=class{constructor(t){this.mutex=new it,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 r=this.trackTimestampInfo.get(t);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,r)}}},Ui=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,zi=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,ji=t=>{const e=Math.floor(t/36e5),i=Math.floor(t%36e5/6e4),r=Math.floor(t%6e4/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")},Li=class{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 n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);z(void 0!==e);const i=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(i)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(const i of t.children)i&&(e+=this.measureBox(i));return e}}},qi=new Uint8Array(8),Gi=new DataView(qi.buffer),Hi=t=>[(t%256+256)%256],Wi=t=>(Gi.setUint16(0,t,!1),[qi[0],qi[1]]),Xi=t=>(Gi.setInt16(0,t,!1),[qi[0],qi[1]]),Zi=t=>(Gi.setUint32(0,t,!1),[qi[1],qi[2],qi[3]]),Qi=t=>(Gi.setUint32(0,t,!1),[qi[0],qi[1],qi[2],qi[3]]),Yi=t=>(Gi.setInt32(0,t,!1),[qi[0],qi[1],qi[2],qi[3]]),Ji=t=>(Gi.setUint32(0,Math.floor(t/2**32),!1),Gi.setUint32(4,t,!1),[qi[0],qi[1],qi[2],qi[3],qi[4],qi[5],qi[6],qi[7]]),Ki=t=>(Gi.setInt32(0,Math.floor(t/2**32),!1),Gi.setUint32(4,t,!1),[qi[0],qi[1],qi[2],qi[3],qi[4],qi[5],qi[6],qi[7]]),tr=t=>(Gi.setInt16(0,256*t,!1),[qi[0],qi[1]]),er=t=>(Gi.setInt32(0,65536*t,!1),[qi[0],qi[1],qi[2],qi[3]]),ir=t=>(Gi.setInt32(0,2**30*t,!1),[qi[0],qi[1],qi[2],qi[3]]),rr=(t,e)=>{const i=[];let r=t;do{let t=127&r;r>>=7,i.length>0&&(t|=128),i.push(t),void 0!==e&&e--}while(r>0||e);return i.reverse()},nr=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},or=t=>{const e=t*(Math.PI/180),i=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[i,r,0,-r,i,0,0,0,1]},sr=or(0),ar=t=>[er(t[0]),er(t[1]),ir(t[2]),er(t[3]),er(t[4]),ir(t[5]),er(t[6]),er(t[7]),ir(t[8])],hr=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),cr=(t,e,i,r,n)=>hr(t,[Hi(e),Zi(i),r??[]],n),lr=()=>hr("styp",[nr("iso5"),Qi(0),nr("iso5"),nr("iso6"),nr("mp41"),nr("cmfc"),nr("dash")]),dr=(t,e)=>{let i=t.maxWrittenEndTimestamp-t.minWrittenTimestamp;return Number.isFinite(i)||(i=0),cr("sidx",1,0,[Qi(1),Qi(Dn),Ji(Vn(t.minWrittenTimestamp,Dn)),Ji(0),Wi(0),Wi(1),Qi(2147483647&e),Qi(Vn(i,Dn)),Qi(0)])},ur=t=>({type:"mdat",largeSize:t}),fr=t=>hr("moov",void 0,[pr(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>wr(e,t.creationTime)),t.isFragmented?tn(t.trackDatas):null,pn(t)]),pr=(t,e)=>{const i=Math.max(0,...e.map(t=>Vn(mr(t),Dn)+Vn(t.startTimestampOffset??0,Dn))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!G(t)||!G(i),o=n?Ji:Qi;return cr("mvhd",+n,0,[o(t),o(t),Qi(Dn),o(i),er(1),tr(1),Array(10).fill(0),ar(sr),Array(24).fill(0),Qi(r)])},mr=t=>{if(0===t.samples.length)return 0;let e=1/0,i=-1/0;for(let r=0;r<t.samples.length;r++){const n=t.samples[r];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>i&&(i=n.timestamp+n.duration)}return e===1/0?0:i-e},wr=(t,e)=>{const i=Nn(t),r=null!==t.startTimestampOffset&&t.startTimestampOffset>0;return hr("trak",void 0,[vr(t,e),r?br(t,t.startTimestampOffset):null,yr(t,e),void 0!==i.name?hr("udta",void 0,[hr("name",[...Q.encode(i.name)])]):null])},vr=(t,e)=>{const i=Vn(mr(t),Dn)+Vn(t.startTimestampOffset??0,Dn),r=!G(e)||!G(i),n=r?Ji:Qi;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=or(e??0)}else o=sr;let s=2;!1!==t.track.metadata.disposition?.default&&(s|=1);const a="video"===t.type?0:"audio"===t.type?1:"subtitle"===t.type?2:ot(t);return cr("tkhd",+r,s,[n(e),n(e),Qi(t.track.id),Qi(0),n(i),Array(8).fill(0),Wi(0),Wi(a),tr("audio"===t.type?1:0),Wi(0),ar(o),er("video"===t.type?t.info.width:0),er("video"===t.type?t.info.height:0)])},br=(t,e)=>{const i=Vn(e,Dn),r=Vn(mr(t),Dn),n=!G(i)||!G(r),o=n?Ji:Qi,s=n?Ki:Yi;return hr("edts",void 0,[cr("elst",n?1:0,0,[Qi(2),o(i),s(-1),er(1),o(r),s(0),er(1)])])},yr=(t,e)=>hr("mdia",void 0,[gr(t,e),Tr(!0,xr[t.type],Er[t.type]),kr(t)]),gr=(t,e)=>{const i=Vn(mr(t),t.timescale),r=!G(e)||!G(i),n=r?Ji:Qi;return cr("mdhd",+r,0,[n(e),n(e),Qi(t.timescale),n(i),Wi(Sn(t.track.metadata.languageCode??"und")),Wi(0)])},xr={video:"vide",audio:"soun",subtitle:"text"},Er={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Tr=(t,e,i,r="\0\0\0\0")=>cr("hdlr",0,0,[t?nr("mhlr"):Qi(0),nr(e),nr(r),Qi(0),Qi(0),nr(i,!0)]),kr=t=>hr("minf",void 0,[_r[t.type](),Mr(),Cr(t)]),_r={video:()=>cr("vmhd",0,1,[Wi(0),Wi(0),Wi(0),Wi(0)]),audio:()=>cr("smhd",0,0,[Wi(0),Wi(0)]),subtitle:()=>cr("nmhd",0,0)},Mr=()=>hr("dinf",void 0,[Ar()]),Ar=()=>cr("dref",0,0,[Qi(1)],[Sr()]),Sr=()=>cr("url ",0,1),Cr=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return hr("stbl",void 0,[Pr(t),Wr(t),e?Jr(t):null,e?Kr(t):null,Zr(t),Qr(t),Yr(t),Xr(t)])},Pr=t=>{let e;if("video"===t.type)e=Ir(En(t.track.source.Ot,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=kn(t.track.source.Ot,t.info.decoderConfig.codec,t.muxer.isQuickTime);z(i),e=Rr(i,t)}else"subtitle"===t.type&&(e=Hr(Mn[t.track.source.Ot],t));return z(e),cr("stsd",0,0,[Qi(1)],[e])},Ir=(t,e)=>hr(t,[Array(6).fill(0),Wi(1),Wi(0),Wi(0),Array(12).fill(0),Wi(e.info.width),Wi(e.info.height),Qi(4718592),Qi(4718592),Qi(0),Wi(1),Hi(10),nr("Mediabunny"),Array(21).fill(0),Wi(e.info.hasAlphaChannel?32:24),Xi(65535)],[Tn[e.track.source.Ot]?.(e)??null,Br(e),tt(e.info.decoderConfig.colorSpace)?Fr(e):null]),Br=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:hr("pasp",[Qi(t.info.pixelAspectRatio.num),Qi(t.info.pixelAspectRatio.den)]),Fr=t=>hr("colr",[nr(t.muxer.isQuickTime?"nclc":"nclx"),Wi(Y[t.info.decoderConfig.colorSpace.primaries]),Wi(J[t.info.decoderConfig.colorSpace.transfer]),Wi(K[t.info.decoderConfig.colorSpace.matrix]),t.muxer.isQuickTime?[]:Hi((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Or=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,i=e.codec.split("."),r=Number(i[1]),n=Number(i[2]),o=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(e.colorSpace?.fullRange??0)),s=i[5]?Number(i[5]):e.colorSpace?.primaries?Y[e.colorSpace.primaries]:2,a=i[6]?Number(i[6]):e.colorSpace?.transfer?J[e.colorSpace.transfer]:2,h=i[7]?Number(i[7]):e.colorSpace?.matrix?K[e.colorSpace.matrix]:2;return cr("vpcC",1,0,[Hi(r),Hi(n),Hi(o),Hi(s),Hi(a),Hi(h),Wi(0)])},Rr=(t,e)=>{let i,r=0,n=16;const o=zt.includes(e.track.source.Ot);if(o){const t=e.track.source.Ot,{sampleSize:i}=ee(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),Wi(1),Wi(r),Wi(0),Qi(0),Wi(e.info.numberOfChannels),Wi(n),Wi(0),Wi(0),Wi(e.info.sampleRate<65536?e.info.sampleRate:0),Wi(0)];else{const t=o?0:-2;i=[Array(6).fill(0),Wi(1),Wi(r),Wi(0),Qi(0),Wi(e.info.numberOfChannels),Wi(Math.min(n,16)),Xi(t),Wi(0),Wi(e.info.sampleRate<65536?e.info.sampleRate:0),Wi(0),o?[Qi(1),Qi(n/8),Qi(e.info.numberOfChannels*n/8)]:[Qi(0),Qi(0),Qi(0)],Qi(2)]}return hr(t,i,[_n(e.track.source.Ot,e.muxer.isQuickTime)?.(e)??null])},$r=t=>{let e;switch(t.track.source.Ot){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source.Ot}`)}let i=[...Hi(e),...Hi(21),...Zi(0),...Qi(0),...Qi(0)];if(t.info.decoderConfig.description){const e=X(t.info.decoderConfig.description);i=[...i,...Hi(5),...rr(e.byteLength),...e]}return i=[...Wi(1),...Hi(0),...Hi(4),...rr(i.length),...i,...Hi(6),...Hi(1),...Hi(2)],i=[...Hi(3),...rr(i.length),...i],cr("esds",0,0,i)},Dr=t=>hr("wave",void 0,[Nr(t),Vr(t),hr("\0\0\0\0")]),Nr=t=>hr("frma",[nr(kn(t.track.source.Ot,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),Vr=t=>{const{littleEndian:e}=ee(t.track.source.Ot);return hr("enda",[Wi(+e)])},Ur=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){z(a.byteLength>=18);const t=Pe(X(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return hr("dOps",[Hi(0),Hi(e),Wi(i),Qi(r),Xi(n),Hi(o),...s])},zr=t=>{const e=t.info.decoderConfig?.description;z(e);const i=X(e);return cr("dfLa",0,0,[...i.subarray(4)])},jr=t=>{const{littleEndian:e,sampleSize:i}=ee(t.track.source.Ot);return cr("pcmC",0,0,[Hi(+e),Hi(8*i)])},Lr=t=>{z(t.info.primingPacket);const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new $t(t);e.skipBits(16),e.skipBits(16);const i=e.readBits(2);if(3===i)return null;const r=e.readBits(6),n=e.readBits(5);if(n>8)return null;const o=e.readBits(3),s=e.readBits(3);return 1&s&&1!==s&&e.skipBits(2),4&s&&e.skipBits(2),2===s&&e.skipBits(2),{fscod:i,bsid:n,bsmod:o,acmod:s,lfeon:e.readBits(1),bitRateCode:Math.floor(r/2)}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const i=new Uint8Array(3),r=new $t(i);return r.writeBits(2,e.fscod),r.writeBits(5,e.bsid),r.writeBits(3,e.bsmod),r.writeBits(3,e.acmod),r.writeBits(1,e.lfeon),r.writeBits(5,e.bitRateCode),r.writeBits(5,0),hr("dac3",[...i])},qr=t=>{z(t.info.primingPacket);const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new $t(t);e.skipBits(16);const i=e.readBits(2);if(e.skipBits(3),0!==i&&2!==i)return null;const r=e.readBits(11),n=e.readBits(2);let o,s=0;3===n?(s=e.readBits(2),o=3):o=e.readBits(2);const a=e.readBits(3),h=e.readBits(1),c=e.readBits(5);if(c<11||c>16)return null;const l=Be[o];let d;return d=n<3?ue[n]/1e3:fe[s]/1e3,{dataRate:Math.round((r+1)*d/(16*l)),substreams:[{fscod:n,fscod2:s,bsid:c,bsmod:0,acmod:a,lfeon:h,numDepSub:0,chanLoc:0}]}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let i=16;for(const s of e.substreams)i+=23,s.numDepSub>0?i+=9:i+=1;const r=Math.ceil(i/8),n=new Uint8Array(r),o=new $t(n);o.writeBits(13,e.dataRate),o.writeBits(3,e.substreams.length-1);for(const s of e.substreams)o.writeBits(2,s.fscod),o.writeBits(5,s.bsid),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(3,s.bsmod),o.writeBits(3,s.acmod),o.writeBits(1,s.lfeon),o.writeBits(3,0),o.writeBits(4,s.numDepSub),s.numDepSub>0?o.writeBits(9,s.chanLoc):o.writeBits(1,0);return hr("dec3",[...n])},Gr=t=>{z(t.info.primingPacket);const e=(t=>{const e=(t=>{if(t.length<18)return null;if(127!==t[0]||254!==t[1]||128!==t[2]||1!==t[3])return null;const e=new $t(t);if(e.skipBits(32),e.skipBits(1),31!==e.readBits(5))return null;const i=e.readBits(1),r=e.readBits(7)+1;if(r%8!=0)return null;const n=e.readBits(14)+1;if(n<96)return null;const o=e.readBits(6);if(o>=$e.length)return null;const s=Fe[e.readBits(4)];if(0===s)return null;const a=Oe[e.readBits(5)];if(0!==e.readBits(1))return null;e.skipBits(4),e.skipBits(5);const h=e.readBits(2);if(3===h)return null;e.skipBits(1),i&&e.skipBits(16),e.skipBits(7);const c=Re[e.readBits(3)];if(0===c)return null;const l=0!==h;return{frameSize:n,sampleRate:s,numberOfChannels:$e[o]+(l?1:0),sampleCount:32*r,channelLayout:De[o]|(l?8:0),amode:o,lfePresent:l,bitRate:a,pcmResolution:c}})(t),i=Z(t);let r=e?4*Math.ceil(e.frameSize/4):0,n=null;for(;r+4<=t.length&&1683496997===i.getUint32(r);){const e=ze(t.subarray(r));if(!e)break;n??=e,r+=e.frameSize}if(e)return{frameSize:n?r:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:null!==n};if(!n?.asset)return null;const{asset:o}=n;return{frameSize:r,sampleRate:o.sampleRate,numberOfChannels:o.numberOfChannels,sampleCount:o.sampleCount,channelLayout:o.channelLayout,pcmResolution:o.pcmResolution,bitRate:0,core:null,hasExtensions:!0}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return hr("ddts",[...je(e)])},Hr=(t,e)=>hr(t,[Array(6).fill(0),Wi(1)],[An[e.track.source.Ot](e)]),Wr=t=>cr("stts",0,0,[Qi(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[Qi(t.sampleCount),Qi(t.sampleDelta)])]),Xr=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return cr("stss",0,0,[Qi(e.length),e.map(([t])=>Qi(t+1))])},Zr=t=>cr("stsc",0,0,[Qi(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[Qi(t.firstChunk),Qi(t.samplesPerChunk),Qi(1)])]),Qr=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=ee(t.track.source.Ot);return cr("stsz",0,0,[Qi(e*t.info.numberOfChannels),Qi(t.samples.reduce((e,i)=>e+Vn(i.duration,t.timescale),0))])}return cr("stsz",0,0,[Qi(0),Qi(t.samples.length),t.samples.map(t=>Qi(t.size))])},Yr=t=>t.finalizedChunks.length>0&&q(t.finalizedChunks).offset>=2**32?cr("co64",0,0,[Qi(t.finalizedChunks.length),t.finalizedChunks.map(t=>Ji(t.offset))]):cr("stco",0,0,[Qi(t.finalizedChunks.length),t.finalizedChunks.map(t=>Qi(t.offset))]),Jr=t=>cr("ctts",1,0,[Qi(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[Qi(t.sampleCount),Yi(t.sampleCompositionTimeOffset)])]),Kr=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;z(t.compositionTimeOffsetTable.length>0),z(t.samples.length>0);for(let s=0;s<t.compositionTimeOffsetTable.length;s++){const r=t.compositionTimeOffsetTable[s];e=Math.min(e,r.sampleCompositionTimeOffset),i=Math.max(i,r.sampleCompositionTimeOffset)}for(let s=0;s<t.samples.length;s++){const e=t.samples[s];r=Math.min(r,Vn(e.timestamp,t.timescale)),n=Math.max(n,Vn(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:cr("cslg",0,0,[Yi(o),Yi(e),Yi(i),Yi(r),Yi(n)])},tn=t=>hr("mvex",void 0,t.map(en)),en=t=>cr("trex",0,0,[Qi(t.track.id),Qi(1),Qi(0),Qi(0),Qi(0)]),rn=(t,e)=>hr("moof",void 0,[nn(t),...e.map(sn)]),nn=t=>cr("mfhd",0,0,[Qi(t)]),on=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},sn=t=>hr("traf",void 0,[an(t),hn(t),cn(t)]),an=t=>{z(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:on(i)};return cr("tfhd",0,131128,[Qi(t.track.id),Qi(r.duration),Qi(r.size),Qi(r.flags)])},hn=t=>(z(t.currentChunk),cr("tfdt",1,0,[Ji(Vn(t.currentChunk.startTimestamp,t.timescale))])),cn=t=>{z(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(on),n=t.currentChunk.samples.map(e=>Vn(e.timestamp-e.decodeTimestamp,t.timescale)),o=new Set(e),s=new Set(i),a=new Set(r),h=new Set(n),c=2===a.size&&r[0]!==r[1],l=o.size>1,d=s.size>1,u=!c&&a.size>1,f=h.size>1||[...h].some(t=>0!==t);let p=0;return p|=1,p|=4*+c,p|=256*+l,p|=512*+d,p|=1024*+u,p|=2048*+f,cr("trun",1,p,[Qi(t.currentChunk.samples.length),Qi(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?Qi(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?Qi(e[o]):[],d?Qi(i[o]):[],u?Qi(r[o]):[],f?Yi(n[o]):[]])])},ln=t=>cr("tfra",1,0,[Qi(t.track.id),Qi(63),Qi(t.finalizedChunks.length),t.finalizedChunks.map(e=>[Ji(Vn(e.samples[0].timestamp,t.timescale)),Ji(e.moofOffset),Qi(e.trafIndex+1),Qi(1),Qi(1)])]),dn=()=>hr("vtte"),un=(t,e,i,r,n)=>hr("vttc",void 0,[null!==n?hr("vsid",[Yi(n)]):null,null!==i?hr("iden",[...Q.encode(i)]):null,null!==e?hr("ctim",[...Q.encode(ji(e))]):null,null!==r?hr("sttg",[...Q.encode(r)]):null,hr("payl",[...Q.encode(t)])]),fn=t=>hr("vtta",[...Q.encode(t)]),pn=t=>{const e=[],i=t.format.Rt.metadataFormat??"auto",r=t.output.$t;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=yn(r);t&&e.push(t)}else if("mdta"===i){const t=gn(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&mn(e,t.output.$t);return 0===e.length?null:hr("udta",void 0,e)},mn=(t,e)=>{for(const{key:i,value:r}of Tt(e))switch(i){case"title":t.push(wn("©nam",r));break;case"description":t.push(wn("©des",r));break;case"artist":t.push(wn("©ART",r));break;case"album":t.push(wn("©alb",r));break;case"albumArtist":t.push(wn("albr",r));break;case"genre":t.push(wn("©gen",r));break;case"date":t.push(wn("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(wn("©cmt",r));break;case"lyrics":t.push(wn("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ot(i)}if(e.raw)for(const i in e.raw){const r=e.raw[i];null==r||4!==i.length||t.some(t=>t.type===i)||("string"==typeof r?t.push(wn(i,r)):r instanceof Uint8Array&&t.push(hr(i,Array.from(r))))}},wn=(t,e)=>{const i=Q.encode(e);return hr(t,[Wi(i.length),Wi(Sn("und")),Array.from(i)])},vn={"image/jpeg":13,"image/png":14,"image/bmp":27},bn=(t,e)=>{const i=[];for(const{key:r,value:n}of Tt(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:xn(n)});break;case"description":i.push({key:e?"description":"©des",value:xn(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:xn(n)});break;case"album":i.push({key:e?"album":"©alb",value:xn(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:xn(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:xn(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:xn(n)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:xn(n)});break;case"date":i.push({key:e?"date":"©day",value:xn(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:hr("data",[Qi(vn[t.mimeType]??0),Qi(0),Array.from(t.data)])});break;case"trackNumber":if(e){const e=void 0!==t.tracksTotal?`${n}/${t.tracksTotal}`:n.toString();i.push({key:"track",value:xn(e)})}else i.push({key:"trkn",value:hr("data",[Qi(0),Qi(0),Wi(0),Wi(n),Wi(t.tracksTotal??0),Wi(0)])});break;case"discNumber":e||i.push({key:"disc",value:hr("data",[Qi(0),Qi(0),Wi(0),Wi(n),Wi(t.discsTotal??0),Wi(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:ot(r)}if(t.raw)for(const r in t.raw){const n=t.raw[r];null==n||!e&&4!==r.length||i.some(t=>t.key===r)||("string"==typeof n?i.push({key:r,value:xn(n)}):n instanceof Uint8Array?i.push({key:r,value:hr("data",[Qi(0),Qi(0),Array.from(n)])}):n instanceof Ot&&i.push({key:r,value:hr("data",[Qi(vn[n.mimeType]??0),Qi(0),Array.from(n.data)])}))}return i},yn=t=>{const e=bn(t,!1);return 0===e.length?null:cr("meta",0,0,void 0,[Tr(!1,"mdir","","appl"),hr("ilst",void 0,e.map(t=>hr(t.key,void 0,[t.value])))])},gn=t=>{const e=bn(t,!0);return 0===e.length?null:hr("meta",void 0,[Tr(!1,"mdta",""),cr("keys",0,0,[Qi(e.length)],e.map(t=>hr("mdta",[...Q.encode(t.key)]))),hr("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...Qi(e+1));return hr(i,void 0,[t.value])}))])},xn=t=>hr("data",[Qi(1),Qi(0),...Q.encode(t)]),En=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Tn={avc:t=>t.info.decoderConfig&&hr("avcC",[...X(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&hr("hvcC",[...X(t.info.decoderConfig.description)]),vp8:Or,vp9:Or,av1:t=>hr("av1C",Kt(t.info.decoderConfig.codec)),prores:null},kn=(t,e,i)=>{switch(t){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e}if(i)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},_n=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return $r;case"opus":return Ur;case"flac":return zr;case"ac3":return Lr;case"eac3":return qr;case"dts":return Gr}if(e)switch(t){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Dr}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return jr}return null},Mn={webvtt:"wvtt"},An={webvtt:t=>hr("vttC",[...Q.encode(t.info.config.description)])},Sn=t=>{z(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},Cn=class{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t.Dt)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t.Nt(e),t.Dt=!0}start(){z(!this.started),this.target.Vt(),this.started=!0}write(t){z(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target.Ut(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return z(this.started&&!this.finalized),this.target.zt()}async finalize(){z(this.started&&!this.finalized),await this.target.jt(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=0}const i=e+t.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const t=new Uint8Array(r);t.set(this.trackedWrites,0),this.trackedWrites=t}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},Pn=(ei(),class extends Ct{constructor(){super(...arguments),this.Dt=!1,this.Lt=null,this.onwrite=null}Nt(t){!1!==this.Lt&&(this.Lt=t)}qt(t,e){this.onwrite?.(t,e),this.ct("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 Rn(this,t)}}),In=65536,Bn=2**32,Fn=class extends Pn{constructor(t={}){if(super(),this.buffer=null,this.Gt=0,!t||"object"!=typeof t)throw new TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");if(this.Rt=t,this.Ht="resize"in new ArrayBuffer(0),this.Ht)try{this.Wt=new ArrayBuffer(In,{maxByteLength:Bn})}catch{this.Wt=new ArrayBuffer(In),this.Ht=!1}else this.Wt=new ArrayBuffer(In);this.Xt=new Uint8Array(this.Wt)}Zt(t){let e=this.Wt.byteLength;for(;e<t;)e*=2;if(e!==this.Wt.byteLength){if(e>Bn)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.Ht)this.Wt.resize(e);else{const t=new ArrayBuffer(e),i=new Uint8Array(t);i.set(this.Xt,0),this.Wt=t,this.Xt=i}}}Vt(){}Ut(t,e){this.Zt(e+t.byteLength),this.Xt.set(t,e),this.Gt=Math.max(this.Gt,e+t.byteLength),this.qt(e,e+t.byteLength)}async zt(){}async jt(){this.buffer=this.Wt.slice(0,this.Gt),this.Rt.onFinalize&&await this.Rt.onFinalize(this.buffer),this.ct("finalized")}async Qt(){}Yt(t,e){return this.Xt.slice(t,e)}},On=class extends Pn{constructor(t,e={}){if(super(),this.Jt=[],this.Kt=0,this.te=0,this.ee=null,this.ie=null,this.re=[],!(t instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=e&&"object"!=typeof e)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==e.chunked&&"boolean"!=typeof e.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==e.chunkSize&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this.ne=t,this.Rt=e,this.oe=e.chunked??!1,this.se=e.chunkSize??16777216}Vt(){this.ee=this.ne.getWriter()}Ut(t,e){if(e>this.Kt){const t=e-this.Kt;this.Ut(new Uint8Array(t),this.Kt)}this.Jt.push({data:t.slice(),start:e}),this.Kt=Math.max(this.Kt,e+t.byteLength),this.qt(e,e+t.byteLength)}async zt(){if(null!==this.ie)throw this.ie;if(z(this.ee),0===this.Jt.length)return;const t=[],e=[...this.Jt].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){const r=t[t.length-1],n=e[i];n.start<=r.start+r.size?r.size=Math.max(r.size,n.start+n.data.byteLength-r.start):t.push({start:n.start,size:n.data.byteLength})}for(const i of t){i.data=new Uint8Array(i.size);for(const t of this.Jt)i.start<=t.start&&t.start<i.start+i.size&&i.data.set(t.data,t.start-i.start);if(null!==this.ee.desiredSize&&this.ee.desiredSize<=0&&await this.ee.ready,this.oe)this.ae(i.data,i.start),this.he();else{if(!0===this.Lt&&i.start!==this.te)throw new Error("Internal error: Monotonicity violation.");this.ee.write({type:"write",data:i.data,position:i.start}).catch(t=>{this.ie??=t}),this.te=i.start+i.data.byteLength}}this.Jt.length=0}ae(t,e){let i=this.re.findIndex(t=>t.start<=e&&e<t.start+this.se);-1===i&&(i=this.ce(e));const r=this.re[i],n=e-r.start,o=t.subarray(0,Math.min(this.se-n,t.byteLength));r.data.set(o,n);const s={start:n,end:n+o.byteLength};if(this.le(r,s),0===r.written[0].start&&r.written[0].end===this.se&&(r.shouldFlush=!0),this.re.length>2){for(let t=0;t<this.re.length-1;t++)this.re[t].shouldFlush=!0;this.he()}o.byteLength<t.byteLength&&this.ae(t.subarray(o.byteLength),e+o.byteLength)}le(t,e){let i=0,r=t.written.length-1,n=-1;for(;i<=r;){const o=Math.floor(i+(r-i+1)/2);t.written[o].start<=e.start?(i=o+1,n=o):r=o-1}for(t.written.splice(n+1,0,e),(-1===n||t.written[n].end<e.start)&&n++;n<t.written.length-1&&t.written[n].end>=t.written[n+1].start;)t.written[n].end=Math.max(t.written[n].end,t.written[n+1].end),t.written.splice(n+1,1)}ce(t){const e={start:Math.floor(t/this.se)*this.se,data:new Uint8Array(this.se),written:[],shouldFlush:!1};return this.re.push(e),this.re.sort((t,e)=>t.start-e.start),this.re.indexOf(e)}he(t=!1){z(this.ee);for(let e=0;e<this.re.length;e++){const i=this.re[e];if(i.shouldFlush||t){for(const t of i.written){const e=i.start+t.start;if(!0===this.Lt&&e!==this.te)throw new Error("Internal error: Monotonicity violation.");let r;r=0===t.start&&t.end===i.data.byteLength||!wt()?i.data.subarray(t.start,t.end):i.data.slice(t.start,t.end),this.ee.write({type:"write",data:r,position:e}).catch(t=>{this.ie??=t}),this.te=i.start+t.end}this.re.splice(e--,1)}}}async jt(){if(this.oe&&this.he(!0),null!==this.ie)throw this.ie;z(this.ee),await this.ee.ready,await this.ee.close(),this.ct("finalized")}async Qt(){return this.ee?.close()}},Rn=class extends Pn{constructor(t,e){super(),this.de=t,this.ue=e}Vt(){}Ut(t,e){this.de.Ut(t,this.ue+e),this.qt(e,e+t.byteLength)}zt(){return this.de.zt()}async jt(){this.ct("finalized")}async Qt(){}Nt(t){super.Nt(t),this.de.Nt(t)}},$n=class{constructor(t,e){if(this.rootPath=t,this.getTarget=e,"string"!=typeof t)throw new TypeError("rootPath must be a string.");if("function"!=typeof e)throw new TypeError("getTarget must be a function.")}},Dn=57600,Nn=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},Vn=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},Un=class extends Vi{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Fn,this.auxWriter=new Cn(this.auxTarget,!1),this.auxBoxWriter=new Li(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=nt(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=e,this.formatOptions={...e.Rt},this.isQuickTime=e instanceof so,this.isCmaf=e instanceof oo,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(e instanceof oo?1/0:1),this.auxWriter.start()}async start(){const t=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output.fe(t=>void 0!==this.formatOptions.fastStart?"fragmented"===this.formatOptions.fastStart:t instanceof Fn),this.boxWriter=new Li(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Fn&&"in-memory"),this.isFragmented="fragmented"===this.fastStart),this.isCmaf){if(!this.output.pe())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const t=new Cn(await this.output.me(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new Li(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.Ot);{const t=this.initBoxWriter??this.boxWriter;if(z(t),this.formatOptions.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return hr("ftyp",t.isQuickTime?[nr("qt "),Qi(e),nr("qt ")]:t.fragmented?t.cmaf?[nr("iso5"),Qi(e),nr("iso5"),nr("iso6"),nr("mp41"),nr("cmfc"),nr("dash")]:[nr("iso5"),Qi(e),nr("iso5"),nr("iso6"),nr("mp41")]:[nr("isom"),Qi(e),nr("isom"),t.holdsAvc?nr("avc1"):[],nr("mp41")])})({isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onFtyp(e,i)}this.ftypSize=t.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const i of this.output.tracks)if(void 0===i.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(z(this.writer),z(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=ur(!0),this.boxWriter.writeBox(this.mdat));await(this.writer?.flush());for(const i of this.output.tracks)i.isVideoTrack()&&i.metadata.decoderConfig?this.getVideoTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig}):i.isAudioTrack()&&i.metadata.decoderConfig&&this.getAudioTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig});t()}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.gt&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.Ot]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings)].join(", ")}"`),e})({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;he(i,t.source.Ot),z(i),z(i.decoderConfig);const n={...i.decoderConfig};z(void 0!==n.codedWidth),z(void 0!==n.codedHeight);let o=!1;if("avc"!==t.source.Ot||n.description){if("hevc"===t.source.Ot&&!n.description){if(!e)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const t=(t=>{try{const e=[],i=[],r=[],n=[];for(const h of me(t)){const o=t.subarray(h.offset,h.offset+h.length),s=xe(o[0]);s===Ft.VPS_NUT?e.push(o):s===Ft.SPS_NUT?i.push(o):s===Ft.PPS_NUT?r.push(o):s!==Ft.PREFIX_SEI_NUT&&s!==Ft.SUFFIX_SEI_NUT||n.push(o)}if(0===i.length||0===r.length)return null;const o=(t=>{try{const e=new $t(be(t));e.skipBits(16),e.readBits(4);const i=e.readBits(3),r=e.readBits(1),{general_profile_space:n,general_tier_flag:o,general_profile_idc:s,general_profile_compatibility_flags:a,general_constraint_indicator_flags:h,general_level_idc:c}=Ee(e,i);H(e);const l=H(e);let d=0;3===l&&(d=e.readBits(1));const u=H(e),f=H(e);let p=u,m=f;if(e.readBits(1)){const t=H(e),i=H(e),r=H(e),n=H(e);let o=1,s=1;const a=0===d?l:0;1===a?(o=2,s=2):2===a&&(o=2,s=1),p-=(t+i)*o,m-=(r+n)*s}const w=H(e),v=H(e);H(e);const b=e.readBits(1)?0:i;let y=0;for(let t=b;t<=i;t++)H(e),y=H(e),H(e);H(e),H(e),H(e),H(e),H(e),H(e),e.readBits(1)&&e.readBits(1)&&Te(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),H(e),H(e),e.skipBits(1));const g=H(e);if(ke(e,g),e.readBits(1)){const t=H(e);for(let i=0;i<t;i++)H(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,E=2,T=2,k=0,_=0,M={num:1,den:1};if(e.readBits(1)){const t=Me(e,i);M=t.pixelAspectRatio,x=t.colourPrimaries,E=t.transferCharacteristics,T=t.matrixCoefficients,k=t.fullRangeFlag,_=t.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:M,colourPrimaries:x,transferCharacteristics:E,matrixCoefficients:T,fullRangeFlag:k,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:h,generalLevelIdc:c,chromaFormatIdc:l,bitDepthLumaMinus8:w,bitDepthChromaMinus8:v,minSpatialSegmentationIdc:_}}catch(e){return It.ft("Error parsing HEVC SPS:",e),null}})(i[0]);if(!o)return null;let s=0;if(r.length>0){const t=r[0],e=new $t(be(t));e.skipBits(16),H(e),H(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),H(e),H(e),W(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&H(e),W(e),W(e),e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const i=e.readBits(1),n=e.readBits(1);s=i||n?i&&!n?2:!i&&n?3:0:0}const a=[...e.length?[{arrayCompleteness:1,nalUnitType:Ft.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ft.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ft.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:xe(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:s,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:a}}catch(e){return It.ft("Error building HEVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push((3&t.generalProfileSpace)<<6|(1&t.generalTierFlag)<<5|31&t.generalProfileIdc),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(255&t.generalProfileCompatibilityFlags),e.push(...t.generalConstraintIndicatorFlags),e.push(255&t.generalLevelIdc),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(255&t.minSpatialSegmentationIdc),e.push(252|3&t.parallelismType),e.push(252|3&t.chromaFormatIdc),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.avgFrameRate>>8&255),e.push(255&t.avgFrameRate),e.push((3&t.constantFrameRate)<<6|(7&t.numTemporalLayers)<<3|(1&t.temporalIdNested)<<2|3&t.lengthSizeMinusOne),e.push(255&t.arrays.length);for(const i of t.arrays){e.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),e.push(i.nalUnits.length>>8&255),e.push(255&i.nalUnits.length);for(const t of i.nalUnits){e.push(t.length>>8&255),e.push(255&t.length);for(let i=0;i<t.length;i++)e.push(t[i])}}return new Uint8Array(e)})(t),o=!0}}else{if(!e)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const t=(t=>{try{const e=[],i=[],r=[];for(const s of me(t)){const n=t.subarray(s.offset,s.offset+s.length),o=ve(n[0]);o===Bt.SPS?e.push(n):o===Bt.PPS?i.push(n):o===Bt.SPS_EXT&&r.push(n)}if(0===e.length)return null;if(0===i.length)return null;const n=(t=>{try{const e=new $t(be(t));if(e.skipBits(1),e.skipBits(2),7!==e.readBits(5))return null;const i=e.readAlignedByte(),r=e.readAlignedByte(),n=e.readAlignedByte();H(e);let o=1,s=0,a=0,h=0;if((100===i||110===i||122===i||244===i||44===i||83===i||86===i||118===i||128===i)&&(o=H(e),3===o&&(h=e.readBits(1)),s=H(e),a=H(e),e.skipBits(1),e.readBits(1)))for(let t=0;t<(3!==o?8:12);t++)if(e.readBits(1)){const i=t<6?16:64;let r=8,n=8;for(let t=0;t<i;t++)0!==n&&(n=(r+W(e)+256)%256),r=0===n?r:n}H(e);const c=H(e);if(0===c)H(e);else if(1===c){e.skipBits(1),W(e),W(e);const t=H(e);for(let i=0;i<t;i++)W(e)}H(e),e.skipBits(1);const l=H(e),d=H(e),u=16*(l+1),f=16*(d+1);let p=u,m=f;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const t=H(e),i=H(e),r=H(e),n=H(e);let s,a;0===(0===h?o:0)?(s=1,a=2-w):(s=3===o?1:2,a=(1===o?2:1)*(2-w)),p-=s*(t+i),m-=a*(r+n)}let v=2,b=2,y=2,g=0,x={num:1,den:1},E=null,T=null;if(e.readBits(1)){if(e.readBits(1)){const t=e.readBits(8);if(255===t)x={num:e.readBits(16),den:e.readBits(16)};else{const e=ye[t];e&&(x=e)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),g=e.readBits(1),e.readBits(1)&&(v=e.readBits(8),b=e.readBits(8),y=e.readBits(8))),e.readBits(1)&&(H(e),H(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const t=e.readBits(1);t&&ge(e);const i=e.readBits(1);i&&ge(e),(t||i)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),H(e),H(e),H(e),H(e),E=H(e),T=H(e))}if(null===E)if(z(null===T),(44===i||86===i||100===i||110===i||122===i||244===i)&&16&r)E=0,T=0;else{const t=l+1,e=(2-w)*(d+1),i=Gt.find(t=>t.level>=n)??q(Gt),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);E=r,T=r}return z(null!==T),{profileIdc:i,constraintFlags:r,levelIdc:n,frameMbsOnlyFlag:w,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:a,codedWidth:u,codedHeight:f,displayWidth:p,displayHeight:m,pixelAspectRatio:x,colourPrimaries:v,matrixCoefficients:y,transferCharacteristics:b,fullRangeFlag:g,numReorderFrames:E,maxDecFrameBuffering:T}}catch(e){return It.ft("Error parsing AVC SPS:",e),null}})(e[0]);z(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:i,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return It.ft("Error building AVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|3&t.lengthSizeMinusOne),e.push(224|31&t.sequenceParameterSets.length);for(const i of t.sequenceParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}e.push(t.pictureParameterSets.length);for(const i of t.pictureParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}if(100===t.avcProfileIndication||110===t.avcProfileIndication||122===t.avcProfileIndication||144===t.avcProfileIndication){z(null!==t.chromaFormat),z(null!==t.bitDepthLumaMinus8),z(null!==t.bitDepthChromaMinus8),z(null!==t.sequenceParameterSetExt),e.push(252|3&t.chromaFormat),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.sequenceParameterSetExt.length);for(const i of t.sequenceParameterSetExt){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}}return new Uint8Array(e)})(t),o=!0}const s=(t=>{const e=t<0?-1:1;let i=0,r=1,n=1,o=0,s=t=Math.abs(t);for(;;){const t=Math.floor(s),a=t*n+i,h=t*o+r;if(h>1e6)return{num:e*n,den:o};if(i=n,r=o,n=a,o=h,s=1/(s-t),!isFinite(s))break}return{num:e*n,den:o}})(1/(t.metadata.frameRate??57600)).den,a=n.displayAspectWidth,h=n.displayAspectHeight,c=void 0===a||void 0===h?{num:1,den:1}:Mt({num:a*n.codedHeight,den:h*n.codedWidth}),l="ap4h"===n.codec||"ap4x"===n.codec,d={muxer:this,track:t,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:c,decoderConfig:n,requiresAnnexBTransformation:o,hasAlphaChannel:l},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;le(i,t.source.Ot),z(i),z(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ot&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=ti(Di.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Dt[t.samplingFrequencyIndex],r=Nt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Vt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}if(!e){if("ac3"===t.source.Ot||"eac3"===t.source.Ot)throw new Error("AC-3/E-AC-3 require a priming packet.");if("dts"===t.source.Ot)throw new Error("DTS requires a priming packet.")}const s={muxer:this,track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&zt.includes(t.source.Ot),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:e},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;de(e),z(e),z(e.config);const r={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...me(n)].map(t=>n.subarray(t.offset,t.offset+t.length));if(0===t.length)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");n=(t=>{const e=t.reduce((t,e)=>t+4+e.byteLength,0),i=new Uint8Array(e);let r=0;for(const n of t){const t=new DataView(i.buffer,i.byteOffset,i.byteLength);t.setUint32(r,n.byteLength,!1),r+=4,i.set(n,r),r+=n.byteLength}return i})(t)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);const o=this.createSampleForTrack(r,n,e.timestamp,e.duration,e.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=ti(Di.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);let o=e.timestamp,s=e.duration;if(r.info.requiresPcmTransformation){const t=ee(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(s=n.byteLength/t/r.info.sampleRate,null!==r.info.expectedNextPcmPacketTimestamp){const t=o-r.info.expectedNextPcmPacketTimestamp;if(t<.01)o=r.info.expectedNextPcmPacketTimestamp;else{const e=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,t);o=r.info.expectedNextPcmPacketTimestamp+e}}r.info.expectedNextPcmPacketTimestamp=o+s}const a=this.createSampleForTrack(r,n,o,s,e.type);await this.registerSample(r,a)}finally{r()}}async padWithSilence(t,e,i){const r=Vn(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=ee(t.info.decoderConfig.codec),s=r*t.info.numberOfChannels,a=new Uint8Array(n*s).fill(o),h=this.createSampleForTrack(t,new Uint8Array(a.buffer),e,i,"key");await this.registerSample(t,h)}return i}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0),"webvtt"===t.source.Ot&&(r.cueQueue.push(e),await this.processWebVTTCues(r,e.timestamp))}finally{r()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){const i=new Set([]);for(const h of t.cueQueue)z(h.timestamp<=e),z(t.lastCueEndTimestamp<=h.timestamp+h.duration),i.add(Math.max(h.timestamp,t.lastCueEndTimestamp)),i.add(h.timestamp+h.duration);const r=[...i].sort((t,e)=>t-e),n=r[0],o=r[1]??n;if(e<o)break;if(t.lastCueEndTimestamp<n){this.auxWriter.seek(0);const e=dn();this.auxBoxWriter.writeBox(e);const i=this.auxTarget.Yt(0,this.auxWriter.getPos()),r=this.createSampleForTrack(t,i,t.lastCueEndTimestamp,n-t.lastCueEndTimestamp,"key");await this.registerSample(t,r),t.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let e=0;e<t.cueQueue.length;e++){const i=t.cueQueue[e];if(i.timestamp>=o)break;Ui.lastIndex=0;const r=Ui.test(i.text),s=i.timestamp+i.duration;let a=t.cueToSourceId.get(i);if(void 0===a&&o<s&&(a=t.nextSourceId++,t.cueToSourceId.set(i,a)),i.notes){const t=fn(i.notes);this.auxBoxWriter.writeBox(t)}const h=un(i.text,r?n:null,i.identifier??null,i.settings??null,a??null);this.auxBoxWriter.writeBox(h),s===o&&t.cueQueue.splice(e--,1)}const s=this.auxTarget.Yt(0,this.auxWriter.getPos()),a=this.createSampleForTrack(t,s,n,o-n,"key");await this.registerSample(t,a),t.lastCueEndTimestamp=o}}createSampleForTrack(t,e,i,r,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:e,size:e.byteLength,type:n,timescaleUnitsToNextSample:Vn(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){this.isFragmented||(t.startTimestampOffset??=t.timestampProcessingQueue[0].timestamp);let e=0;for(let i=0;i<t.timestampProcessingQueue.length;i++){const r=t.timestampProcessingQueue[i];e+=Vn(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):q(t.timeToSampleTable).sampleCount+=e,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(t=>t.timestamp).sort((t,e)=>t-e);this.isFragmented||(t.startTimestampOffset??=i[0]);for(let r=0;r<t.timestampProcessingQueue.length;r++){const e=t.timestampProcessingQueue[r];e.decodeTimestamp=i[r];const n=Vn(e.timestamp-e.decodeTimestamp,t.timescale),o=Vn(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){z(t.lastSample);const i=Vn(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(z(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=q(t.timeToSampleTable);if(z(e),1===e.sampleCount){e.sampleDelta=r;const i=t.timeToSampleTable[t.timeToSampleTable.length-2];i&&i.sampleDelta===r&&(i.sampleCount++,t.timeToSampleTable.pop(),e=i)}else e.sampleDelta!==r&&(e.sampleCount--,t.timeToSampleTable.push(e={sampleCount:1,sampleDelta:r}));e.sampleDelta===o?e.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const i=q(t.compositionTimeOffsetTable);z(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=Vn(e.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));t.lastSample=e}if(t.timestampProcessingQueue.length=0,z(t.lastSample),z(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){z("key"===e.type);const i=Vn(e.timestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=r}}async registerSample(t,e){"key"===e.type&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),"reserve"===this.fastStart)){const e=t.track.metadata.maximumPacketCount;if(z(void 0!==e),t.samples.length>e)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${e}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(t.currentChunk){t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,e.timestamp);const r=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.closed});r>=this.minimumFragmentDuration&&n&&e.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),z(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(z(!this.isFragmented),z(this.writer),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if("audio"===t.type&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((e,i)=>e+Vn(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&q(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),"in-memory"!==this.fastStart){t.currentChunk.offset=this.writer.getPos();for(const e of t.currentChunk.samples)z(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(z(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.sampleQueue.length&&!n.closed)break t;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(e=n,i=n.sampleQueue[0].timestamp)}if(!e)break;const r=e.sampleQueue.shift();await this.addSampleToTrack(e,r)}}async finalizeFragment(t=!this.isCmaf){if(z(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const t=this.initBoxWriter??this.boxWriter;z(t),this.formatOptions.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=fr(this);if(t.writeBox(e),this.formatOptions.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onMoov(e,i)}if(this.isCmaf){z(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.fe(!0),this.boxWriter=new Li(this.writer);const t=this.boxWriter.measureBox(lr()),e=this.boxWriter.measureBox(dr(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}z(this.writer),z(this.boxWriter);const e=this.trackDatas.filter(t=>t.currentChunk);if(0===e.length)return void(t&&await this.writer.flush());const i=this.nextFragmentNumber++,r=rn(i,e),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let s=o+8,a=1/0;for(let u=0;u<e.length;u++){const t=e[u];t.currentChunk.offset=s,t.currentChunk.moofOffset=n,t.currentChunk.trafIndex=u;for(const e of t.currentChunk.samples)s+=e.size;a=Math.min(a,t.currentChunk.startTimestamp)}const h=s-o,c=h>=2**32;if(c)for(const u of e)u.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const l=rn(i,e);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(t,e,a)}z(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const d=ur(c);d.size=h,this.boxWriter.writeBox(d),this.writer.seek(o+(c?16:8));for(const u of e)for(const t of u.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}for(const u of e)u.finalizedChunks.push(u.currentChunk),this.finalizedChunks.push(u.currentChunk),u.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(t,e)):t.sampleQueue.push(e)}async createFastStartReserveMdat(){z(this.writer),z(this.boxWriter),this.ensureOneEnabledTrack();const t=fr(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;z(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=ur(!0),this.boxWriter.writeBox(this.mdat);for(const i of this.trackDatas){for(const t of i.sampleQueue)await this.addSampleToTrack(i,t);i.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){z("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;z(void 0!==i),t+=8*Math.ceil(2/3*i),t+=4*i,t+=8*Math.ceil(2/3*i),t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i}return t}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0,"subtitle"===i.type&&"webvtt"===t.source.Ot&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}ensureOneEnabledTrack(){for(const t of["video","audio","subtitle"]){const e=this.trackDatas.filter(e=>e.type===t);if(0!==e.length&&!e.some(t=>!1!==t.track.metadata.disposition?.default)){const t=e[0];t.track.metadata.disposition={...t.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){z(this.isFragmented);const t=await this.mutex.acquire();try{for(const t of this.trackDatas)"subtitle"===t.type&&"webvtt"===t.track.source.Ot&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{t()}}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),this.mdat||"reserve"!==this.fastStart||await this.createFastStartReserveMdat();for(const i of this.trackDatas)i.closed=!0,"subtitle"===i.type&&"webvtt"===i.track.source.Ot&&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)if(await this.finalizeCurrentChunk(i),null!==i.startTimestampOffset)for(let t=0;t<i.samples.length;t++){const e=i.samples[t];e.timestamp-=i.startTimestampOffset,e.decodeTimestamp-=i.startTimestampOffset}if(z(this.writer),z(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=ur(!1);for(let i=0;i<2;i++){const e=fr(this),i=this.boxWriter.measureBox(e);t=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+t;for(const n of this.finalizedChunks){n.offset=r;for(const{data:e}of n.samples)z(e),r+=e.byteLength,t+=e.byteLength}if(r<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const e=fr(this);if(this.boxWriter.writeBox(e),this.formatOptions.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(t,e)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const t of i.samples)z(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}}else if(this.isFragmented)if(this.isCmaf){const t=null!==this.segmentHeaderSize?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(lr()),this.boxWriter.writeBox(dr(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,hr("mfra",void 0,[...e.map(ln),cr("mfro",0,0,[Qi(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{z(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);z(void 0!==t);const e=this.writer.getPos()-t;if(this.mdat.size=e,this.mdat.largeSize=e>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}const i=fr(this);if("reserve"===this.fastStart){z(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const t=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:t})}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.formatOptions.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(t,e)}}var e;t()}},zn="Mediabunny",jn={video:1,audio:2,subtitle:17},Ln=class extends Vi{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=nt(),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.fe(!!this.format.Rt.appendOnly),this.ebmlWriter=new Je(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(const e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});t()}writeEBMLHeader(){this.format.Rt.onEbmlHeader&&this.writer.startTrackingWrites();const t={id:Ie.EBML,data:[{id:Ie.EBMLVersion,data:1},{id:Ie.EBMLReadVersion,data:1},{id:Ie.EBMLMaxIDLength,data:4},{id:Ie.EBMLMaxSizeLength,data:8},{id:Ie.DocType,data:this.format instanceof ho?"webm":"matroska"},{id:Ie.DocTypeVersion,data:2},{id:Ie.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format.Rt.onEbmlHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.Rt.onEbmlHeader(t,e)}}maybeCreateSeekHead(t){if(this.format.Rt.appendOnly)return;const e=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),s={id:Ie.SeekHead,data:[{id:Ie.Seek,data:[{id:Ie.SeekID,data:e},{id:Ie.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:Ie.Seek,data:[{id:Ie.SeekID,data:i},{id:Ie.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:Ie.Seek,data:[{id:Ie.SeekID,data:r},{id:Ie.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:Ie.Seek,data:[{id:Ie.SeekID,data:n},{id:Ie.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:Ie.Seek,data:[{id:Ie.SeekID,data:o},{id:Ie.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const t={id:Ie.Duration,data:new He(0)};this.segmentDuration=t;const e={id:Ie.Info,data:[{id:Ie.TimestampScale,data:1e6},{id:Ie.MuxingApp,data:zn},{id:Ie.WritingApp,data:zn},this.format.Rt.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:Ie.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){let i=Ke[e.track.source.Ot];z(i),"audio"===e.type&&"dts"===e.track.source.Ot&&("dtse"===e.info.decoderConfig.codec?i="A_DTS/EXPRESS":"dtsl"===e.info.decoderConfig.codec&&(i="A_DTS/LOSSLESS"));let r=0;if("audio"===e.type&&"opus"===e.track.source.Ot){r=8e7;const t=e.info.decoderConfig.description;if(t){const e=Pe(X(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:Ie.TrackEntry,data:[{id:Ie.TrackNumber,data:e.track.id},{id:Ie.TrackUID,data:e.track.id},{id:Ie.TrackType,data:jn[e.type]},!1===e.track.metadata.disposition?.default?{id:Ie.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:Ie.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:Ie.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:Ie.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:Ie.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:Ie.FlagCommentary,data:1}:null,{id:Ie.FlagLacing,data:0},{id:Ie.Language,data:e.track.metadata.languageCode??"und"},{id:Ie.CodecID,data:i},e.codecPrivate?{id:Ie.CodecPrivate,data:X(e.codecPrivate)}:null,{id:Ie.CodecDelay,data:0},{id:Ie.SeekPreRoll,data:r},void 0!==e.track.metadata.name?{id:Ie.Name,data:new Xe(e.track.metadata.name)}:null,"video"===e.type?this.videoSpecificTrackInfo(e):null,"audio"===e.type?this.audioSpecificTrackInfo(e):null,"subtitle"===e.type?this.subtitleSpecificTrackInfo(e):null]})}}videoSpecificTrackInfo(t){const{frameRate:e,rotation:i}=t.track.metadata,r=[e?{id:Ie.DefaultDuration,data:1e9/e}:null],n=i?L(-i):0,o=!!t.info.aspectRatio&&t.info.aspectRatio.num*t.info.height!==t.info.aspectRatio.den*t.info.width,s=t.info.decoderConfig.colorSpace,a={id:Ie.Video,data:[{id:Ie.PixelWidth,data:t.info.width},{id:Ie.PixelHeight,data:t.info.height},o?{id:Ie.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:Ie.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:Ie.DisplayUnit,data:3}:null,t.info.alphaMode?{id:Ie.AlphaMode,data:1}:null,tt(s)?{id:Ie.Colour,data:[{id:Ie.MatrixCoefficients,data:K[s.matrix]},{id:Ie.TransferCharacteristics,data:J[s.transfer]},{id:Ie.Primaries,data:Y[s.primaries]},{id:Ie.Range,data:s.fullRange?2:1}]}:null,n?{id:Ie.Projection,data:[{id:Ie.ProjectionType,data:0},{id:Ie.ProjectionPoseRoll,data:new Ge((n+180)%360-180)}]}:null]};return r.push(a),r}audioSpecificTrackInfo(t){const e=zt.includes(t.track.source.Ot)?ee(t.track.source.Ot):null;return[{id:Ie.Audio,data:[{id:Ie.SamplingFrequency,data:new Ge(t.info.sampleRate)},{id:Ie.Channels,data:t.info.numberOfChannels},e?{id:Ie.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:Ie.SimpleTag,data:[{id:Ie.TagName,data:new Xe(e)},"string"==typeof i?{id:Ie.TagString,data:new Xe(i)}:{id:Ie.TagBinary,data:i}]})},i=this.output.$t,r=new Set;for(const{key:n,value:o}of Tt(i))switch(n){case"title":e("TITLE",o),r.add("TITLE");break;case"description":e("DESCRIPTION",o),r.add("DESCRIPTION");break;case"artist":e("ARTIST",o),r.add("ARTIST");break;case"album":e("ALBUM",o),r.add("ALBUM");break;case"albumArtist":e("ALBUM_ARTIST",o),r.add("ALBUM_ARTIST");break;case"genre":e("GENRE",o),r.add("GENRE");break;case"comment":e("COMMENT",o),r.add("COMMENT");break;case"lyrics":e("LYRICS",o),r.add("LYRICS");break;case"date":e("DATE",o.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":e("PART_NUMBER",void 0!==i.tracksTotal?`${o}/${i.tracksTotal}`:o.toString()),r.add("PART_NUMBER");break;case"discNumber":e("DISC",void 0!==i.discsTotal?`${o}/${i.discsTotal}`:o.toString()),r.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:ot(n)}if(i.raw)for(const n in i.raw){const t=i.raw[n];null==t||r.has(n)||("string"==typeof t||t instanceof Uint8Array)&&e(n,t)}0!==t.length&&(this.tagsElement={id:Ie.Tags,data:[{id:Ie.Tag,data:[{id:Ie.Targets,data:[{id:Ie.TargetTypeValue,data:50},{id:Ie.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.$t,e=[],i=new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+(kt(n.mimeType)??""));;){t=0n;for(let e=0;e<8;e++)t<<=8n,t|=BigInt(Math.floor(256*Math.random()));if(0n!==t&&!i.has(t))break}i.add(t),e.push({id:Ie.AttachedFile,data:[void 0!==n.description?{id:Ie.FileDescription,data:new Xe(n.description)}:null,{id:Ie.FileName,data:new Xe(r)},{id:Ie.FileMediaType,data:n.mimeType},{id:Ie.FileData,data:n.data},{id:Ie.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof Rt&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&&_t(t.data,o.data))||e.push({id:Ie.AttachedFile,data:[void 0!==o.description?{id:Ie.FileDescription,data:new Xe(o.description)}:null,{id:Ie.FileName,data:new Xe(o.name??"")},{id:Ie.FileMediaType,data:o.mimeType??""},{id:Ie.FileData,data:o.data},{id:Ie.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:Ie.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:Ie.Segment,size:this.format.Rt.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=t,this.format.Rt.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format.Rt.onSegmentHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.Rt.onSegmentHeader(t,e)}}createCues(){this.cues={id:Ie.Cues,data:[]}}get segmentDataOffset(){return z(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.gt&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.Ot]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings.filter(Boolean))].join(", ")}"`),e})({isWebM:this.format instanceof ho,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;he(i,t.source.Ot),z(i),z(i.decoderConfig),z(void 0!==i.decoderConfig.codedWidth),z(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:Mt({num:n,den:o}),a={track:t,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:i.decoderConfig,alphaMode:e?!!e.sideData.alpha:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return"vp9"===t.source.Ot?a.codecPrivate=new Uint8Array((t=>{const e=t.split(".");return[1,1,Number(e[1]),2,1,Number(e[2]),3,1,Number(e[3]),4,1,e[4]?Number(e[4]):1]})(a.info.decoderConfig.codec)):"av1"===t.source.Ot?a.codecPrivate=new Uint8Array(Kt(a.info.decoderConfig.codec)):"prores"===t.source.Ot&&(a.codecPrivate=Q.encode(i.decoderConfig.codec)),this.trackDatas.push(a),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;le(i,t.source.Ot),z(i),z(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ot&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=ti(Di.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Dt[t.samplingFrequencyIndex],r=Nt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Vt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}const s={track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.description??null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;de(e),z(e),z(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Q.encode(e.config.description),closed:!1};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);r.info.alphaMode??=!!e.sideData.alpha;let n=e.data;if("prores"===t.source.Ot){if(n.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");n=n.subarray(8)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);let s=e.timestamp,a=e.duration;void 0!==t.metadata.frameRate&&(s=ct(s,t.metadata.frameRate),a=ct(a,t.metadata.frameRate));const h=r.info.alphaMode?e.sideData.alpha??null:null,c=this.createInternalChunk(n,s,a,e.type,h);"vp9"===t.source.Ot&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=ti(Di.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);const s=this.createInternalChunk(n,e.timestamp,e.duration,e.type);r.chunkQueue.push(s),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0);let n=e.text;const o=Math.round(1e3*e.timestamp);Ui.lastIndex=0,n=n.replace(Ui,t=>`<${ji((t=>{const e=zi.exec(t);if(!e)throw new Error("Expected match.");return 36e5*Number(e[1]||"0")+6e4*Number(e[2])+1e3*Number(e[3])+Number(e[4])})(t.slice(1,-1))-o)}>`);const s=Q.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?Q.encode(a):null);r.chunkQueue.push(h),await this.interleaveChunks()}finally{r()}}async interleaveChunks(t=!1){if(t||this.allTracksAreKnown()){t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.chunkQueue.length&&!n.closed)break t;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(e=n,i=n.chunkQueue[0].timestamp)}if(!e)break;const r=e.chunkQueue.shift();this.writeBlock(e,r)}t||await this.writer.flush()}}fixVP9ColorSpace(t,e){if("key"!==e.type)return;if(!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;const i=new $t(e.data);i.skipBits(2);const r=i.readBits(1),n=(i.readBits(1)<<1)+r;if(3===n&&i.skipBits(1),i.readBits(1))return;if(0!==i.readBits(1))return;if(i.skipBits(2),4817730!==i.readBits(24))return;n>=2&&i.skipBits(1);const o={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];((t,e,i,r)=>{for(let n=e;n<i;n++){const e=Math.floor(n/8);let o=t[e];const s=7-(7&n);o&=~(1<<s),o|=(r&1<<i-n-1)>>i-n-1<<s,t[e]=o}})(e.data,i.pos,i.pos+3,o)}createInternalChunk(t,e,i,r,n=null){return{data:t,type:r,timestamp:e,duration:i,additions:n}}writeBlock(t,e){this.segment||this.createSegment();const i=Math.round(1e3*e.timestamp),r=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.chunkQueue[0];return r?"key"===r.type:i.closed});let n=!1;if(this.currentCluster){z(null!==this.currentClusterStartMsTimestamp),z(null!==this.currentClusterMaxMsTimestamp);const t=i-this.currentClusterStartMsTimestamp;n=r&&i>this.currentClusterMaxMsTimestamp&&t>=1e3*(this.format.Rt.minimumClusterDuration??1)||t>32767}else n=!0;n&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768)return;const s=new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:Ie.BlockGroup,data:[{id:Ie.Block,data:[s,e.data]},"delta"===e.type?{id:Ie.ReferenceBlock,data:new We(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:Ie.BlockAdditions,data:[{id:Ie.BlockMore,data:[{id:Ie.BlockAddID,data:1},{id:Ie.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:Ie.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:Ie.SimpleBlock,data:[s,e.data]};this.ebmlWriter.writeEBML(t)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+h),t.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(t){this.currentCluster&&this.finalizeCurrentCluster(),this.format.Rt.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:Ie.Cluster,size:this.format.Rt.appendOnly?-1:5,data:[{id:Ie.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(z(this.currentCluster),!this.format.Rt.appendOnly){const t=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),e=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(t,5),this.writer.seek(e)}if(this.format.Rt.onCluster){z(null!==this.currentClusterStartMsTimestamp);const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.Rt.onCluster(t,e,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)z(this.cues),this.cues.data.push({id:Ie.CuePoint,data:[{id:Ie.CueTime,data:r},...n.map(e=>({id:Ie.CueTrackPositions,data:[{id:Ie.CueTrack,data:e.track.id},{id:Ie.CueClusterPosition,data:t}]}))]})}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),z(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format.Rt.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6);const e=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new He(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),z(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},qn=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e},Gn=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r}),Hn=class{constructor(){this.we=null,this.ve=null,this.gt=!1}be(){if(!this.we)throw new Error("Source is not connected to an output track.");if("canceled"===this.we.output.state)throw new Error("Output has been canceled.");if("finalizing"===this.we.output.state||"finalized"===this.we.output.state)throw new Error("Output has been finalized.");if("pending"===this.we.output.state)throw new Error("Output has not started.");if(this.gt)throw new Error("Source is closed.")}async Vt(){}async ye(t){}close(){if(this.ve)return;const t=this.we;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===t.output.state)throw new Error("Cannot call close before output has been started.");this.ve=(async()=>{await this.ye(!1),this.gt=!0,"finalizing"!==t.output.state&&"finalized"!==t.output.state&&t.output.ge.onTrackClose(t)})()}async xe(t){return this.ve??=(async()=>{await this.ye(t),this.gt=!0})()}},Wn=class extends Hn{constructor(t){if(super(),this.we=null,!Ut.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${Ut.join(", ")}.`);this.Ot=t}},Xn=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Zn=class{setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}constructor(t,e){this.source=t,this.encodingConfig=e,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new pt,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(t,e,i){const r=t;try{this.checkForEncoderError(),this.source.be();const n=this.encodingConfig,o=n.sizeChangeBehavior??"deny";let s=!1;if(null!==this.codedWidth&&null!==this.codedHeight){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(s=!0,"deny"===o))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(void 0!==n.transform?.width||void 0!==n.transform?.height||void 0!==n.transform?.rotate||void 0!==n.transform?.crop||!0===n.transform?.force||s&&"passThrough"!==o){let i=n.transform?.width,r=n.transform?.height,a=n.transform?.fit??"fill";s&&"passThrough"!==o&&(z(this.outputWidth),z(this.outputHeight),z("deny"!==o),i=this.outputWidth,r=this.outputHeight,a=o);const h=await t.transform({width:i,height:r,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,fit:a,alpha:n.alpha});null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=h.displayWidth,this.outputHeight=h.displayHeight),e&&t.close(),t=h,e=!0}else null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);const a=n.transform?.frameRate;if(void 0!==a){const n=t.timestamp+t.duration,o=lt(t.timestamp,a);if(null!==this.frameRateLastSample){if(o<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=n);await this.padFrameRate(o,i)}t===r&&(t=t.clone(),e=!0),t.setTimestamp(o),t.setDuration(1/a),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=o,this.frameRateLastEndTimestamp=n}await this.processAndEncode(t,i)}finally{e&&t.close()}}async processAndEncode(t,e){const i=this.encodingConfig;let r;if(i.transform?.process){let e=i.transform.process(t);if(e instanceof Promise&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof ci?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new ci(i)):o.push(new ci(i,{timestamp:t.timestamp,duration:t.duration}))}catch(n){for(const e of o)e!==t&&e.close();for(const i of e)(i instanceof ci&&i!==t||"undefined"!=typeof VideoFrame&&i instanceof VideoFrame)&&i.close();throw n}r=o}else r=[t];try{for(const t of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),z(this.encoderInitialized),this.closed)break;const i=this.encodingConfig.keyFrameInterval??2,r=Math.floor(t.timestamp/i),n={...this.defaultEncodeOptions,...t.encodeOptions,...e},o={...n,keyFrame:void 0!==n.keyFrame?n.keyFrame:0===i||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;const e=t.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,o)).catch(t=>this.setError(t)).finally(()=>{this.customEncoderQueueSize--,e.close()});this.customEncoderQueueSize>=4&&await i}else{z(this.encoder);const e=t.toVideoFrame(),i=rt(this.preciseTimings,e.timestamp,t=>t.microsecondTimestamp),r=-1!==i?this.preciseTimings[i]:null;if(r&&r.microsecondTimestamp===e.timestamp?(r.timestamp!==t.timestamp&&(r.timestampIsValid=!1),r.duration!==t.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(i+1,0,{microsecondTimestamp:e.timestamp,timestamp:t.timestamp,duration:t.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(e.format&&!e.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(e,o)}finally{e.close()}}else{this.splitter||(this.splitter=new Yn);const{colorFrame:t,alphaFrame:i}=await this.splitter.split(e);this.alphaFrameQueue.push(i);try{this.encoder.encode(t,o)}finally{t.close()}}else try{this.encoder.encode(e,o)}finally{e.close()}this.encoder.encodeQueueSize>=4&&await new Promise(t=>this.encoder.addEventListener("dequeue",t,{once:!0}))}await this.lastMuxerPromise}}finally{for(const e of r)e!==t&&e.close()}}async padFrameRate(t,e){const i=this.encodingConfig.transform.frameRate;z(this.frameRateLastSample);const r=Math.round((t-this.frameRateLastTimestamp)*i);for(let o=1;o<r;o++){const t={stack:[],error:void 0,hasError:!1};try{const r=qn(t,this.frameRateLastSample.clone(),!1);r.setTimestamp(this.frameRateLastTimestamp+o/i),r.setDuration(1/i),await this.processAndEncode(r,e)}catch(n){t.error=n,t.hasError=!0}finally{Gn(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=Ri(this.encodingConfig.quality,this.encodingConfig.bitrate);z(void 0!==e);const i=Ai({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source.we?.metadata.frameRate});let r,n=null;for(const t of i){const e=t.config;if(this.encodingConfig.onEncoderConfig?.(e),r=$i.find(t=>t.supports(this.encodingConfig.codec,e)),r){n=t;break}if("undefined"!=typeof VideoEncoder){if(e.alpha="discard","keep"===this.encodingConfig.alpha&&(e.latencyMode="quality"),!(e.width%2!=1&&e.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw new Error(`The dimensions ${e.width}x${e.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(e)).supported){n=t;break}}catch{}}}if(!n){if("undefined"==typeof VideoEncoder)throw new Error((o="VideoEncoder",void 0===globalThis.isSecureContext||globalThis.isSecureContext?`${o} is not available in this environment.`:`${o} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`));const t=i[0].config,e=i.map(({config:t,quantizer:e})=>null!==e?`quantizer ${e}`:`${t.bitrate} bps`);throw new Error(`This specific encoder configuration (${t.codec}, ${e.join(" / ")}, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}var o;const s=n.config;if(null!==n.quantizer&&(this.defaultEncodeOptions=Fi(this.encodingConfig.codec,n.quantizer)),r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(t,e)=>{if(!(t instanceof qe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Xn(this.source.we,t),this.encodingConfig.onEncodedPacket?.(t,e),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.we,t,e).catch(t=>{this.setError(t)})},this.customEncoder.onError=t=>{this.setError(t)},await this.customEncoder.init();else{const t=[],e=[];let i=0,r=0;const n=(t,e,i)=>{const r={};if(e){const t=new Uint8Array(e.byteLength);e.copyTo(t),r.alpha=t}let n=qe.fromEncodedChunk(t,r);const o=rt(this.preciseTimings,t.timestamp,t=>t.microsecondTimestamp),s=-1!==o?this.preciseTimings[o]:null;let a=null;0===this.emittedEncoderPackets&&"delta"===n.type&&i?.decoderConfig&&(a=((t,e,i)=>{switch(t){case"avc":for(const t of((t,e)=>{if(e.description){const i=1+(3&X(e.description)[4]);return we(t,i)}return me(t)})(i,e)){const e=i[t.offset],r=ve(e);if(r>=Bt.NON_IDR_SLICE&&r<=Bt.SLICE_DPC)return"delta";if(r===Bt.IDR)return"key";if(r===Bt.SEI&&(!gt()||Et()>=144)){const e=i.subarray(t.offset,t.offset+t.length),r=be(e);let n=1;do{let t=0;for(;;){const e=r[n++];if(void 0===e)break;if(t+=e,e<255)break}let e=0;for(;;){const t=r[n++];if(void 0===t)break;if(e+=t,t<255)break}if(6===t){const t=new $t(r);t.pos=8*n;const e=H(t),i=t.readBits(1);if(0===e&&1===i)return"key"}n+=e}while(n<r.length-1)}}return"delta";case"hevc":for(const t of((t,e)=>{if(e.description){const i=1+(3&X(e.description)[21]);return we(t,i)}return me(t)})(i,e)){const e=xe(i[t.offset]);if(e<Ft.BLA_W_LP)return"delta";if(e<=Ft.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new $t(i);if(2!==t.readBits(2))return null;const e=t.readBits(1);return(t.readBits(1)<<1)+e===3&&t.skipBits(1),t.readBits(1)?null:0===t.readBits(1)?"key":"delta"}case"av1":{let t=!1;for(const{type:e,data:r}of function*(t){const e=new $t(t),i=()=>{let t=0;for(let i=0;i<8;i++){const r=e.readAlignedByte();if(t|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return t>=2**32-1?null:t};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),n=e.readBits(1),o=e.readBits(1);let s;if(e.skipBits(1),n&&e.skipBits(8),o){const t=i();if(null===t)return;s=t}else s=Math.floor(e.getBitsLeft()/8);z(e.pos%8==0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+s)},e.skipBits(8*s)}}(i))if(1===e){const e=new $t(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new $t(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:ot(t),z(!1)}})(this.encodingConfig.codec,i.decoderConfig,n.data)),(s&&s.microsecondTimestamp===t.timestamp||null!==a)&&(n=n.clone({timestamp:s?.timestampIsValid?s.timestamp:void 0,duration:s?.durationIsValid?s.duration:void 0,type:a??void 0})),Xn(this.source.we,n),this.encodingConfig.onEncodedPacket?.(n,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.we,n,i).catch(t=>{this.setError(t)}),this.emittedEncoderPackets++},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(o,s)=>{if(!this.alphaEncoder)return void n(o,null,s);const a=this.alphaFrameQueue.shift();z(void 0!==a),a?(this.alphaEncoder.encode(a,{...this.defaultEncodeOptions,keyFrame:"key"===o.type}),r++,a.close(),t.push({chunk:o,meta:s})):0===r?n(o,null,s):(e.push(i+r),t.push({chunk:o,meta:s}))},error:t=>{t.stack=o,this.setError(t)}}),this.encoder.configure(s),"keep"===this.encodingConfig.alpha){const o=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(o,s)=>{r--;const a=t.shift();for(z(void 0!==a),n(a.chunk,o,a.meta),i++;e.length>0&&e[0]===i;){e.shift();const i=t.shift();z(void 0!==i),n(i.chunk,null,i.meta)}},error:t=>{t.stack=o,this.setError(t)}}),this.alphaEncoder.configure(s)}}z(this.source.we),this.muxer=this.source.we.output.ge,this.encoderInitialized=!0})()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,e=lt(this.frameRateLastEndTimestamp,t);await this.padFrameRate(e)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await(this.alphaEncoder?.flush()),await new Promise(t=>setTimeout(t,25))))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&("closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Qn=null,Yn=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!Qn){const t=new Blob([`(${Jn.toString()})()`],{type:"application/javascript"});Qn=URL.createObjectURL(t)}this.worker=new Worker(Qn),this.worker.addEventListener("message",t=>{const e=t.data,i=this.pendingRequests.get(e.id);i&&(this.pendingRequests.delete(e.id),"error"in e?i.reject(new Error(e.error)):i.resolve({colorFrame:e.colorFrame,alphaFrame:e.alphaFrame}))}),this.worker.addEventListener("error",t=>{const e=new Error(t.message||"Color/alpha splitter worker error.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()})}const e=this.nextRequestId++,i=nt();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Jn=()=>{let t=null,e=Promise.resolve();self.addEventListener("message",t=>{const{id:r,sourceFrame:n}=t.data;e=e.then(async()=>{try{const{colorFrame:t,alphaFrame:e}=await i(n);self.postMessage({id:r,colorFrame:t,alphaFrame:e},{transfer:[t,e]})}catch(t){self.postMessage({id:r,error:t.message})}finally{n.close()}})});const i=async e=>{const i=e.format;if(!i)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=e.allocationSize();if(t&&t.byteLength===o||(t=new Uint8Array(o)),await e.copyTo(t),"RGBA"===i||"BGRA"===i)return r(t,i,e);if("I420A"===i||"I420AP10"===i||"I420AP12"===i||"I422A"===i||"I422AP10"===i||"I422AP12"===i||"I444A"===i||"I444AP10"===i||"I444AP12"===i)return n(t,i,e);throw new Error(`CPU color/alpha splitting does not support format '${i}'.`)},r=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=r*n,s=o+Math.ceil(r/2)*Math.ceil(n/2)*2,a=new Uint8Array(s);for(let l=0,d=3;l<o;l++,d+=4)a[l]=t[d];a.fill(128,o);const h=new VideoFrame(t,{format:"RGBA"===e?"RGBX":"BGRX",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),c={format:"I420",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[a.buffer]};return{colorFrame:h,alphaFrame:new VideoFrame(a,c)}},n=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=e.includes("P10"),s=e.includes("P12"),a=o||s?2:1;let h,c;e.startsWith("I420")?(h=Math.ceil(r/2),c=Math.ceil(n/2)):e.startsWith("I422")?(h=Math.ceil(r/2),c=n):(h=r,c=n);const l=r*n,d=l*a,u=l*a+h*c*a*2,f=e.replace("A",""),p=Math.ceil(r/2)*Math.ceil(n/2),m=new Uint8Array(d+p*a*2),w=u;m.set(t.subarray(w,w+d),0);const v=d,b=o?512:s?2048:128;1===a?m.fill(b,v):new Uint16Array(m.buffer,v,2*p).fill(b);const y=o?"I420P10":s?"I420P12":"I420",g=new VideoFrame(t.subarray(0,u),{format:f,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),x={format:y,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[m.buffer]};return{colorFrame:g,alphaFrame:new VideoFrame(m,x)}}},Kn=class extends Wn{constructor(t,e){if(!("undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");(t=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding config must be an object.");if(!Ut.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Ut.join(", ")}.`);const e=t.bitrate;if(void 0===t.quality&&void 0===e)throw new TypeError("config.quality must be provided.");if(void 0!==t.quality&&void 0!==e)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(void 0!==t.quality&&!(t.quality instanceof Si))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof Si)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==t.keyFrameInterval&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==t.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==t.transform){if("object"!=typeof t.transform||!t.transform)throw new TypeError("config.transform, when provided, must be an object.");if(void 0!==t.transform.width&&(!Number.isInteger(t.transform.width)||t.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(void 0!==t.transform.height&&(!Number.isInteger(t.transform.height)||t.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(void 0!==t.transform.fit&&!["fill","contain","cover"].includes(t.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.transform.width&&void 0!==t.transform.height&&void 0===t.transform.fit&&!["fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(void 0!==t.transform.fit&&["fill","contain","cover"].includes(t.sizeChangeBehavior)&&t.transform.fit!==t.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(void 0!==t.transform.rotate&&![0,90,180,270].includes(t.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.transform.crop&&vi(t.transform.crop,"config.transform."),void 0!==t.transform.process&&"function"!=typeof t.transform.process)throw new TypeError("config.transform.process, when provided, must be a function.");if(void 0!==t.transform.frameRate&&(!Number.isFinite(t.transform.frameRate)||t.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(void 0!==t.transform.force&&"boolean"!=typeof t.transform.force)throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(void 0!==t.onEncodedPacket&&"function"!=typeof t.onEncodedPacket)throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(void 0!==t.onEncoderConfig&&"function"!=typeof t.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(void 0!==t.onEncodedSample&&"function"!=typeof t.onEncodedSample)throw new TypeError("config.onEncodedSample, when provided, must be a function.");Mi(t.codec,t)})(e),super(e.codec),this.Ee=new Zn(this,e),this.Te=t}add(t,e=0,i){if(!Number.isFinite(t)||t<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");const r=new ci(this.Te,{timestamp:t,duration:e});return this.Ee.add(r,!0,i)}ye(t){return this.Ee.flushAndClose(t)}},to=class extends Hn{constructor(t){if(super(),this.we=null,!Lt.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${Lt.join(", ")}.`);this.Ot=t}},eo=class extends Hn{constructor(t){if(super(),this.we=null,!qt.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${qt.join(", ")}.`);this.Ot=t}},io=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>Ut.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>Lt.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>qt.includes(t))}ke(t){return""}_e(){return!1}},ro=class extends io{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==t.minimumFragmentDuration&&(!Number.isFinite(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==t.onFtyp&&"function"!=typeof t.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==t.onMoov&&"function"!=typeof t.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==t.onMdat&&"function"!=typeof t.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==t.onMoof&&"function"!=typeof t.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==t.metadataFormat&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this.Rt=t}getSupportedTrackCounts(){const t=2**32-1;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:0,max:t}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}Me(t){return new Un(t,this)}_e(){return"fragmented"===this.Rt.fastStart}},no=class extends ro{constructor(t){super(t)}get Ae(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ut,...jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qt]}ke(t){return(new so).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},oo=class extends ro{constructor(t){super(t)}get Ae(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ut,...jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qt]}},so=class extends ro{constructor(t){super(t)}get Ae(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Ut,...Lt]}ke(t){return(new no).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},ao=class extends io{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.appendOnly&&"boolean"!=typeof t.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==t.minimumClusterDuration&&(!Number.isFinite(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==t.onEbmlHeader&&"function"!=typeof t.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==t.onSegmentHeader&&"function"!=typeof t.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==t.onCluster&&"function"!=typeof t.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this.Rt=t}Me(t){return new Ln(t,this)}get Ae(){return"Matroska"}getSupportedTrackCounts(){const t=127;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:0,max:t}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Ut,...jt,...zt.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...qt]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},ho=class extends ao{constructor(t){super(t)}getSupportedCodecs(){return[...Ut.filter(t=>["vp8","vp9","av1"].includes(t)),...Lt.filter(t=>["opus","vorbis"].includes(t)),...qt]}get Ae(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}ke(t){return(new ao).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},co=["video","audio","subtitle"],lo=class t{constructor(t,e,i,r,n){this.id=t,this.output=e,this.type=i,this.source=r,this.metadata=n}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const i=St(this.metadata.group),r=St(e.metadata.group);for(const t of i){if(this.type!==e.type&&r.some(e=>t===e))return!0;if(r.some(e=>t.Se.has(e)))return!0}return!1}},uo=class extends lo{constructor(t,e,i,r){super(t,e,"video",i,r)}},fo=class extends lo{constructor(t,e,i,r){super(t,e,"audio",i,r)}},po=class extends lo{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},mo=class t{constructor(){this.Se=new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this.Se.add(e),e.Se.add(this)}},wo=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&!(t=>ut.test(t))(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==t.name&&"string"!=typeof t.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==t.disposition&&(t=>{if(!t||"object"!=typeof t)throw new TypeError("disposition must be an object.");if(void 0!==t.default&&"boolean"!=typeof t.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==t.primary&&"boolean"!=typeof t.primary)throw new TypeError("disposition.primary must be a boolean.");if(void 0!==t.forced&&"boolean"!=typeof t.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==t.original&&"boolean"!=typeof t.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==t.commentary&&"boolean"!=typeof t.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==t.hearingImpaired&&"boolean"!=typeof t.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==t.visuallyImpaired&&"boolean"!=typeof t.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(t.disposition),void 0!==t.maximumPacketCount&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==t.group&&!(t.group instanceof mo)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof mo))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},vo=class extends Ct{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this.Ce)throw new TypeError(t);const e=this.Pe();if(e instanceof Promise)throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new mo,this.tracks=[],this.Ie=null,this.Be=new Set,this.Fe=null,this.Oe=null,this.Re=null,this.$e=null,this.De=new it,this.$t={},this.Ne=null,this.Ce=null,this.Ve=null,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!(t.format instanceof io))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof Pn||t.target instanceof $n))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof Pn&&this.Ue(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof Pn)&&"function"!=typeof t.initTarget)throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this.ze=t.target,this.Ie=t.onFinalize??null,this.je=t.initTarget??null,this.je instanceof Pn&&this.Ue(this.je),this.ge=t.format.Me(this)}Le(t){z(this.ze instanceof $n);const e=this.ze.getTarget(t),i=t=>{if(!(t instanceof Pn))throw new TypeError("getTarget must return a Target.");return t};return e instanceof Promise?e.then(i):i(e)}async qe(t){z(this.ze instanceof $n);const e=await this.Le(t);return this.ct("target",{target:e,request:t,isRoot:t.isRoot}),"canceled"===this.state?await e.Qt():this.Ue(e),e}Ue(t){this.Be.add(t),t.on("finalized",()=>this.Be.delete(t),{once:!0})}async me(){if(z(null!==this.je),this.je instanceof Pn)return this.je;const t=await this.je();return"canceled"===this.state?await t.Qt():this.Ue(t),t}pe(){return null!==this.je}Pe(){if(this.Ne)return this.Ne;if(this.Ce)return this.Ce;if(this.ze instanceof Pn)return this.ct("target",{target:this.ze,request:null,isRoot:!0}),this.Ne=this.ze,this.ze;const t={path:this.ze.rootPath,isRoot:!0,mimeType:this.format.mimeType},e=this.Le(t),i=e=>("canceled"===this.state?e.Qt():this.Ue(e),this.ct("target",{target:e,request:t,isRoot:!0}),this.Ne=e,e);return e instanceof Promise?this.Ce=e.then(i):i(e)}fe(t){return this.Fe??=(async()=>{const e=await this.Pe(),i=new Cn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof Wn))throw new TypeError("source must be a VideoSource.");if(wo(e),void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError(`Invalid video rotation: ${e.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&e.rotation)throw new Error(`${this.format.Ae} does not support video rotation metadata.`);if(void 0!==e.frameRate&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.frameRate}. Must be a positive number.`);if(void 0!==e.decoderConfig&&he({decoderConfig:e.decoderConfig},t.Ot),void 0!==e.primingPacket){if(!(e.primingPacket instanceof qe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(void 0===e.decoderConfig)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new uo(this.tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof to))throw new TypeError("source must be an AudioSource.");if(wo(e),void 0!==e.decoderConfig&&le({decoderConfig:e.decoderConfig},t.Ot),void 0!==e.primingPacket){if(!(e.primingPacket instanceof qe))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(void 0===e.decoderConfig)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new fo(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof eo))throw new TypeError("source must be a SubtitleSource.");wo(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new po(this.tracks.length+1,this,t,i))}setMetadataTags(t){if((t=>{if(!t||"object"!=typeof t)throw new TypeError("tags must be an object.");if(void 0!==t.title&&"string"!=typeof t.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==t.description&&"string"!=typeof t.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==t.artist&&"string"!=typeof t.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==t.album&&"string"!=typeof t.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==t.albumArtist&&"string"!=typeof t.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==t.trackNumber&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==t.tracksTotal&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==t.discNumber&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==t.discsTotal&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==t.genre&&"string"!=typeof t.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==t.date&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==t.lyrics&&"string"!=typeof t.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==t.images){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of t.images){if(!e||"object"!=typeof e)throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof e.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==t.comment&&"string"!=typeof t.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==t.raw){if(!t.raw||"object"!=typeof t.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(t.raw))if(!(null===e||"string"==typeof e||e instanceof Uint8Array||e instanceof Ot||e instanceof Rt||Pt(e)))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}})(t),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this.$t=t}Ge(t){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t.source.we)throw new Error("Source is already used for a track.");const e=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((e,i)=>e+(i.type===t.type?1:0),0),r=e[t.type].max;if(i===r)throw new Error(0===r?`${this.format.Ae} does not support ${t.type} tracks.`:`${this.format.Ae} does not support more than ${r} ${t.type} track${1===r?"":"s"}.`);const n=e.total.max;if(this.tracks.length===n)throw new Error(`${this.format.Ae} does not support more than ${n} tracks${1===n?"":"s"} in total.`);if(t.isVideoTrack()){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format.Ae} does not support video tracks.`+this.format.ke(t.source.Ot));if(!e.includes(t.source.Ot))throw new Error(`Codec '${t.source.Ot}' cannot be contained within ${this.format.Ae}. Supported video codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.ke(t.source.Ot))}else if(t.isAudioTrack()){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format.Ae} does not support audio tracks.`+this.format.ke(t.source.Ot));if(!e.includes(t.source.Ot))throw new Error(`Codec '${t.source.Ot}' cannot be contained within ${this.format.Ae}. Supported audio codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.ke(t.source.Ot))}else if(t.isSubtitleTrack()){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format.Ae} does not support subtitle tracks.`+this.format.ke(t.source.Ot));if(!e.includes(t.source.Ot))throw new Error(`Codec '${t.source.Ot}' cannot be contained within ${this.format.Ae}. Supported subtitle codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.ke(t.source.Ot))}return this.tracks.push(t),t.source.we=t,t}hasEnoughTracks(){const t=this.format.getSupportedTrackCounts();for(const i of co)if(this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0)<t[i].min)return!1;const e=t.total.min;return!(this.tracks.length<e)}async start(){const t=this.format.getSupportedTrackCounts();for(const i of co){const e=this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0),r=t[i].min;if(e<r)throw new Error(r===t[i].max?`${this.format.Ae} requires exactly ${r} ${i} track${1===r?"":"s"}.`:`${this.format.Ae} requires at least ${r} ${i} track${1===r?"":"s"}.`)}const e=t.total.min;if(this.tracks.length<e)throw new Error(e===t.total.max?`${this.format.Ae} requires exactly ${e} track${1===e?"":"s"}.`:`${this.format.Ae} requires at least ${e} track${1===e?"":"s"}.`);if("canceled"===this.state)throw new Error("Output has been canceled.");return this.Oe?(It.wt("Output has already been started."),this.Oe):this.Oe=(async()=>{this.state="started";const t=this.De.acquire();try{await this.ge.start();const t=this.tracks.map(t=>t.source.Vt());await Promise.all(t)}finally{(await t)()}})()}getMimeType(){return this.ge.getMimeType()}async cancel(){return this.Re?(It.wt("Output has already been canceled."),this.Re):"finalizing"!==this.state&&"finalized"!==this.state?this.Re=(async()=>{this.state="canceled";const t=await this.De.acquire();try{const t=this.tracks.map(t=>t.source.xe(!0));await Promise.all(t),await Promise.all([...this.Be].map(t=>t.Qt())),this.Be.clear()}finally{t()}})():void("finalized"===this.state&&It.wt("Output has already been finalized."))}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this.$e?(It.wt("Output has already been finalized."),this.$e):this.$e=(async()=>{this.state="finalizing";const t=await this.De.acquire();try{const t=this.tracks.map(t=>t.source.xe(!1));if(await Promise.all(t),await this.ge.finalize(),this.Fe){const t=await this.Fe;t.finalized||(await t.flush(),await t.finalize())}this.Ie&&await this.Ie(),this.state="finalized"}finally{await Promise.all([...this.Be].map(t=>t.Qt().catch(()=>{}))),this.Be.clear(),t()}})()}};function bo(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(D());let s=!1;const a=setTimeout(()=>h(()=>o(N(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(D()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var yo=["vp9","vp8"],go=["avc"],xo=class{async $record(t,e,i,r={kind:"blob"}){this.I(t.signal),this.He();const n=await this.We(t);this.Xe(t,"video export plan",n),this.Ze(i,"recording","probing",0,n.frameCount,n);const o="mp4"===n.format?new no:new ho,s="stream"===r.kind?new On(r.writable,{chunked:!0}):new Fn,a=new vo({format:o,target:s}),h=new Kn(e.canvas,{codec:n.codec,quality:this.Qe(n),alpha:n.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:n.hardwareAcceleration,keyFrameInterval:n.keyFrameInterval,sizeChangeBehavior:"deny",contentHint:"text",onEncoderConfig:e=>this.Xe(t,"video encoder config",e)});a.addVideoTrack(h,{frameRate:n.frameRate});let c=!1,l=!1;const d=()=>{c||(c=!0,h.close())};try{if(await bo(a.start(),"Video output did not start within 30000ms.",t.signal,3e4),await e.$render({frameCount:n.frameCount,frameRate:n.frameRate,signal:t.signal,prepareFrame:t.prepareFrame,onFrame:async({frameIndex:e})=>{this.I(t.signal);const r=y(e,n.frameRate);await this.Ye(h.add(r.startSeconds,r.durationSeconds),t.signal),this.Ze(i,"recording","capturing",e+1,n.frameCount,n)}}),this.I(t.signal),d(),this.Ze(i,"encoding","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),await bo(a.finalize(),"Video output did not finalize within 30000ms.",t.signal,3e4),this.Ze(i,"completed","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),"stream"===r.kind)return;const o=s;if(!o.buffer)throw new $("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:n.mimeType})}catch(u){d(),await(async()=>{if(!l){l=!0;try{await a.cancel()}catch{}}})();const t=this.Je(u);throw i?.({state:"error",message:t.message}),t}}async We(t){const e=U(t),i="mp4"===t.format?new no:new ho,r="mp4"===t.format?go:yo,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t));for(const o of n)if(await Oi(o,{width:e.width,height:e.height,quality:this.Qe(e),alpha:e.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:e.hardwareAcceleration,contentHint:"text"}))return U(t,o);throw new $("VIDEO_CODEC_UNSUPPORTED",`This browser cannot encode ${r.join(" or ")} video at ${e.width}x${e.height}. Try another format, lower the export dimensions, or change the encoder preference.`)}Qe(t){return new Si(t.quality)}He(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new $("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}Ye(t,e){return e?new Promise((i,r)=>{if(e.aborted)return void r(D());const n=()=>r(D());e.addEventListener("abort",n,{once:!0}),t.then(t=>{e.removeEventListener("abort",n),i(t)},t=>{e.removeEventListener("abort",n),r(t)})}):t}I(t){if(t?.aborted)throw D()}Ze(t,e,i,r,n,o){t?.({state:e,phase:i,frameIndex:r,frame:r,totalFrames:n,progress:n>0?r/n:0,codec:o.codec,codedWidth:o.width,codedHeight:o.height,frameRate:o.frameRate})}Je(t){return V(t)}Xe(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},Eo=class{Ke;T;k;constructor(t,e){this.Ke=new xo,this.T=t,this.k=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.Z(e,t),r=U(i);if("file-system"===t.destination){const n=await this.ti((new s).$resolve(t.filename,`.${e}`),r.mimeType);try{await this.ei(i,n,t.onProgress)}catch(o){try{await(n.abort?.(o))}catch{}throw o}return}const n=await this.ei(i,{kind:"blob"},t.onProgress);if(!n)throw new $("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new a).$downloadFile(n,t.filename,`.${e}`)}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.Z(e,t);U(i);const r=await this.ei(i,{kind:"blob"},t.onProgress);if(!r)throw new $("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async ei(t,e,i){const r=new g(this.T,this.k,{width:t.width,height:t.height});try{return await this.Ke.$record(t,r,i,e)}catch(n){if(i?.({state:"error",message:n instanceof Error?n.message:`${t.format.toUpperCase()} export failed`}),n instanceof p||w(n))throw V(n);throw n}}Z(t,e){const i=this.ii(e.frameRate,60),r=this.ri(e.frameCount,300),n=this.ii(e.pixelDensity,1),o=this.ni(),s=Math.max(1,Math.round(this.T.canvas.width/o*n)),a=Math.max(1,Math.round(this.T.canvas.height/o*n));return{filename:e.filename,format:t,frameRate:i,frameCount:r,quality:this.At(e.quality),hardwareAcceleration:this.oi(e.hardwareAcceleration),keyFrameInterval:this.si(e.keyFrameInterval),pixelDensity:n,width:s,height:a,transparent:Boolean(e.transparent),debugLogging:Boolean(e.debugLogging),signal:e.signal,prepareFrame:e.prepareFrame}}ri(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}ii(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}At(t){if(void 0===t)return"medium";if("very-low"===t||"low"===t||"medium"===t||"high"===t||"very-high"===t)return t;if("object"!=typeof t||null===t||!Number.isFinite(t.bitrate)||t.bitrate<=0)throw new TypeError("Video quality must be a Mediabunny quality level or a positive bitrate.");if(void 0!==t.bitrateMode&&!this.ai(t.bitrateMode))throw new TypeError("Video quality bitrateMode must be 'variable' or 'constant'.");return t.bitrateMode?{bitrate:t.bitrate,bitrateMode:t.bitrateMode}:{bitrate:t.bitrate}}ai(t){return"constant"===t||"variable"===t}oi(t){return"prefer-hardware"===t||"prefer-software"===t||"no-preference"===t?t:"no-preference"}si(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}ni(){const t=this.T.pixelDensity?.();return"number"==typeof t&&Number.isFinite(t)&&t>0?t:1}async ti(t,e){const i=globalThis;if(!i.showSaveFilePicker)throw new $("VIDEO_EXPORT_UNSUPPORTED","This browser cannot stream video exports to disk because the File System Access API is unavailable.");const r=await(await i.showSaveFilePicker({suggestedName:t,types:[{description:"Video file",accept:{[e]:[t.slice(t.lastIndexOf("."))]}}]})).createWritable();let n=!1;return{kind:"stream",writable:new WritableStream({write:t=>r.write(t),async close(){n=!0,await r.close()},async abort(t){n=!0,await r.abort(t)}}),async abort(t){n||(n=!0,await r.abort(t))}}}},To=class extends r{$extractCellData(t){const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],r=t.grid,n=t.font;let o=0;for(let s=0;s<r.rows;s++)for(let t=0;t<r.cols;t++){const r=4*o,a=this.$getEncodedCharacterValue(e.characterPixels,r),h=this.$extractCellTransform(e.characterPixels,r),c=l(n,a)?.character??" ";i.push({x:t,y:s,character:c,foreground:x(e.primaryColorPixels,r),background:x(e.secondaryColorPixels,r),transform:{invert:h.isInverted,flipX:h.flipHorizontal,flipY:h.flipVertical,rotation:h.rotation}}),o++}return i}},ko="1.9.0-beta.1",_o="textmode.document",Mo="2.0.0",Ao={[e.LayerBlendMode.NORMAL]:"normal",[e.LayerBlendMode.ADDITIVE]:"additive",[e.LayerBlendMode.MULTIPLY]:"multiply",[e.LayerBlendMode.SCREEN]:"screen",[e.LayerBlendMode.SUBTRACT]:"subtract",[e.LayerBlendMode.DARKEN]:"darken",[e.LayerBlendMode.LIGHTEN]:"lighten",[e.LayerBlendMode.OVERLAY]:"overlay",[e.LayerBlendMode.SOFT_LIGHT]:"softLight",[e.LayerBlendMode.HARD_LIGHT]:"hardLight",[e.LayerBlendMode.COLOR_DODGE]:"colorDodge",[e.LayerBlendMode.COLOR_BURN]:"colorBurn",[e.LayerBlendMode.DIFFERENCE]:"difference",[e.LayerBlendMode.EXCLUSION]:"exclusion"},So=class{Z(t){return{target:t.target??"selected",pretty:t.pretty??!0,colorMode:t.colorMode??"hex",includeMetadata:t.includeMetadata??!0,filename:t.filename,layer:t.layer}}hi(t,e){return t.includeMetadata?{createdAt:e.toISOString(),generator:{name:"textmode.export.js",version:ko}}:void 0}ci(t,e){return"rgba"===e?{...t}:`#${[t.r,t.g,t.b,t.a].map(t=>t.toString(16).padStart(2,"0")).join("")}`}li(t,e,i,r){const n=[];for(let o=0;o<i;o++){const i=o*e,s=t.slice(i,i+e).map(t=>({x:t.x,y:t.y,character:t.character,foreground:this.ci(t.foreground,r),background:this.ci(t.background,r),transform:{...t.transform}}));n.push(s)}return{encoding:"object-rows-v1",rows:n}}di(t){return{cols:t.grid.cols,rows:t.grid.rows,cellWidth:t.grid.cellWidth,cellHeight:t.grid.cellHeight}}ui(t,e){const i=(new To).$extractCellData(t);return this.li(i,t.grid.cols,t.grid.rows,e.colorMode)}fi(t,e){return{id:t.id,visible:t.visible,opacity:t.opacity,blendMode:Ao[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.di(t),cells:this.ui(t,e)}}$generateJSONData(t,i={},r=new Date){const n=this.Z(i),o=this.hi(n,r);if("all"===n.target){const i=function(t){return[t.layers.base,...t.layers.all].map(i=>{const r=f(t,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??e.LayerBlendMode.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(t),r=i[0].grid;return{format:_o,formatVersion:Mo,target:"all",...o?{metadata:o}:{},canvas:{width:r.width,height:r.height},layers:i.map(t=>this.fi(t,n))}}const s=f(t,n.layer);return{format:_o,formatVersion:Mo,target:"selected",...o?{metadata:o}:{},canvas:{width:s.grid.width,height:s.grid.height},grid:this.di(s),layer:{id:s.id,cells:this.ui(s,n)}}}$generateJSONString(t,e={},i=new Date){const r=this.Z(e),n=this.$generateJSONData(t,r,i),o="number"==typeof r.pretty?r.pretty:r.pretty?2:0;return JSON.stringify(n,null,o)}$saveJSON(t,e={}){const i=this.Z(e);(new a).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename,".json")}},Co=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="ZIP_EXPORT_ABORTED"===t?"AbortError":"ZIPExportError",this.code=t,this.cause=i}};function Po(t){return new Co("ZIP_EXPORT_ABORTED","ZIP frame-sequence export was cancelled.",t)}function Io(t){if(t instanceof Co)return t;if(w(t))return Po(t);if(t instanceof p){if("FRAME_SEQUENCE_TIMEOUT"===t.code)return new Co("ZIP_EXPORT_TIMEOUT",t.message,t);if("FRAME_SEQUENCE_BUSY"===t.code)return new Co("ZIP_EXPORT_BUSY",t.message,t);if("FRAME_SEQUENCE_DISPOSED"===t.code)return new Co("ZIP_EXPORT_DISPOSED",t.message,t)}return new Co("ZIP_EXPORT_FAILED",t instanceof Error?t.message:"ZIP frame-sequence export failed.",t)}var Bo=new TextEncoder;function Fo(t){if(!t||"object"!=typeof t||Array.isArray(t))return{};const e={...t};return delete e.filename,delete e.format,e}function Oo(t){const e=new A;return{extension:`.${t}`,compression:"store",getDimensions({canvas:t,frameOptions:e}){const i=Fo(e),r=Math.abs(i.scale??1);return{width:Math.round(t.width*r),height:Math.round(t.height*r)}},async serialize({canvas:i,frameOptions:r}){const n=await e.$toImageBlob(i,{...Fo(r),format:t}),o=M[t];if(n.type.toLowerCase()!==o)throw new Co("ZIP_EXPORT_ENCODING_UNSUPPORTED",`The browser returned '${n.type||"an unknown format"}' instead of '${o}'.`);return new Uint8Array(await n.arrayBuffer())}}}function Ro(t,e){return{extension:`.${t}`,compression:"deflate",getDimensions({frameOptions:i}){const r=Fo(i),n="json"===t&&"all"===r.target?f(e):f(e,r.layer);return{width:n.grid.width,height:n.grid.height}},async serialize({frameOptions:i,createdAt:r}){const n=Fo(i);let o;return o="svg"===t?(new _).$generateSVG(e,n):"json"===t?(new So).$generateJSONString(e,n,r):(new S).$generateTXT(e,n),Bo.encode(o)}}}var $o=Uint8Array,Do=Uint16Array,No=Int32Array,Vo=new $o([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Uo=new $o([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),zo=new $o([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),jo=function(t,e){for(var i=new Do(31),r=0;r<31;++r)i[r]=e+=1<<t[r-1];var n=new No(i[30]);for(r=1;r<30;++r)for(var o=i[r];o<i[r+1];++o)n[o]=o-i[r]<<5|r;return{b:i,r:n}},Lo=jo(Vo,2),qo=Lo.b,Go=Lo.r;qo[28]=258,Go[258]=28;for(var Ho=jo(Uo,0),Wo=(Ho.b,Ho.r),Xo=new Do(32768),Zo=0;Zo<32768;++Zo){var Qo=(43690&Zo)>>1|(21845&Zo)<<1;Qo=(61680&(Qo=(52428&Qo)>>2|(13107&Qo)<<2))>>4|(3855&Qo)<<4,Xo[Zo]=((65280&Qo)>>8|(255&Qo)<<8)>>1}var Yo=function(t,e,i){for(var r=t.length,n=0,o=new Do(e);n<r;++n)t[n]&&++o[t[n]-1];var s,a=new Do(e);for(n=1;n<e;++n)a[n]=a[n-1]+o[n-1]<<1;if(i){s=new Do(1<<e);var h=15-e;for(n=0;n<r;++n)if(t[n])for(var c=n<<4|t[n],l=e-t[n],d=a[t[n]-1]++<<l,u=d|(1<<l)-1;d<=u;++d)s[Xo[d]>>h]=c}else for(s=new Do(r),n=0;n<r;++n)t[n]&&(s[n]=Xo[a[t[n]-1]++]>>15-t[n]);return s},Jo=new $o(288);for(Zo=0;Zo<144;++Zo)Jo[Zo]=8;for(Zo=144;Zo<256;++Zo)Jo[Zo]=9;for(Zo=256;Zo<280;++Zo)Jo[Zo]=7;for(Zo=280;Zo<288;++Zo)Jo[Zo]=8;var Ko=new $o(32);for(Zo=0;Zo<32;++Zo)Ko[Zo]=5;var ts=Yo(Jo,9,0),es=Yo(Ko,5,0),is=function(t){return(t+7)/8|0},rs=function(t,e,i){return(null==e||e<0)&&(e=0),(null==i||i>t.length)&&(i=t.length),new $o(t.subarray(e,i))},ns=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],os=function(t,e,i){var r=new Error(e||ns[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,os),!i)throw r;return r},ss=function(t,e,i){i<<=7&e;var r=e/8|0;t[r]|=i,t[r+1]|=i>>8},as=function(t,e,i){i<<=7&e;var r=e/8|0;t[r]|=i,t[r+1]|=i>>8,t[r+2]|=i>>16},hs=function(t,e){for(var i=[],r=0;r<t.length;++r)t[r]&&i.push({s:r,f:t[r]});var n=i.length,o=i.slice();if(!n)return{t:ms,l:0};if(1==n){var s=new $o(i[0].s+1);return s[i[0].s]=1,{t:s,l:1}}i.sort(function(t,e){return t.f-e.f}),i.push({s:-1,f:25001});var a=i[0],h=i[1],c=0,l=1,d=2;for(i[0]={s:-1,f:a.f+h.f,l:a,r:h};l!=n-1;)a=i[i[c].f<i[d].f?c++:d++],h=i[c!=l&&i[c].f<i[d].f?c++:d++],i[l++]={s:-1,f:a.f+h.f,l:a,r:h};var u=o[0].s;for(r=1;r<n;++r)o[r].s>u&&(u=o[r].s);var f=new Do(u+1),p=cs(i[l-1],f,0);if(p>e){r=0;var m=0,w=p-e,v=1<<w;for(o.sort(function(t,e){return f[e.s]-f[t.s]||t.f-e.f});r<n;++r){var b=o[r].s;if(!(f[b]>e))break;m+=v-(1<<p-f[b]),f[b]=e}for(m>>=w;m>0;){var y=o[r].s;f[y]<e?m-=1<<e-f[y]++-1:++r}for(;r>=0&&m;--r){var g=o[r].s;f[g]==e&&(--f[g],++m)}p=e}return{t:new $o(f),l:p}},cs=function(t,e,i){return-1==t.s?Math.max(cs(t.l,e,i+1),cs(t.r,e,i+1)):e[t.s]=i},ls=function(t){for(var e=t.length;e&&!t[--e];);for(var i=new Do(++e),r=0,n=t[0],o=1,s=function(t){i[r++]=t},a=1;a<=e;++a)if(t[a]==n&&a!=e)++o;else{if(!n&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(s(n),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0)}for(;o--;)s(n);o=1,n=t[a]}return{c:i.subarray(0,r),n:e}},ds=function(t,e){for(var i=0,r=0;r<e.length;++r)i+=t[r]*e[r];return i},us=function(t,e,i){var r=i.length,n=is(e+2);t[n]=255&r,t[n+1]=r>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var o=0;o<r;++o)t[n+o+4]=i[o];return 8*(n+4+r)},fs=function(t,e,i,r,n,o,s,a,h,c,l){ss(e,l++,i),++n[256];for(var d=hs(n,15),u=d.t,f=d.l,p=hs(o,15),m=p.t,w=p.l,v=ls(u),b=v.c,y=v.n,g=ls(m),x=g.c,E=g.n,T=new Do(19),k=0;k<b.length;++k)++T[31&b[k]];for(k=0;k<x.length;++k)++T[31&x[k]];for(var _=hs(T,7),M=_.t,A=_.l,S=19;S>4&&!M[zo[S-1]];--S);var C,P,I,B,F=c+5<<3,O=ds(n,Jo)+ds(o,Ko)+s,R=ds(n,u)+ds(o,m)+s+14+3*S+ds(T,M)+2*T[16]+3*T[17]+7*T[18];if(h>=0&&F<=O&&F<=R)return us(e,l,t.subarray(h,h+c));if(ss(e,l,1+(R<O)),l+=2,R<O){C=Yo(u,f,0),P=u,I=Yo(m,w,0),B=m;var $=Yo(M,A,0);for(ss(e,l,y-257),ss(e,l+5,E-1),ss(e,l+10,S-4),l+=14,k=0;k<S;++k)ss(e,l+3*k,M[zo[k]]);l+=3*S;for(var D=[b,x],N=0;N<2;++N){var V=D[N];for(k=0;k<V.length;++k){var U=31&V[k];ss(e,l,$[U]),l+=M[U],U>15&&(ss(e,l,V[k]>>5&127),l+=V[k]>>12)}}}else C=ts,P=Jo,I=es,B=Ko;for(k=0;k<a;++k){var z=r[k];if(z>255){as(e,l,C[257+(U=z>>18&31)]),l+=P[U+257],U>7&&(ss(e,l,z>>23&31),l+=Vo[U]);var j=31&z;as(e,l,I[j]),l+=B[j],j>3&&(as(e,l,z>>5&8191),l+=Uo[j])}else as(e,l,C[z]),l+=P[z]}return as(e,l,C[256]),l+P[256]},ps=new No([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ms=new $o(0),ws=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var i=e,r=9;--r;)i=(1&i&&-306674912)^i>>>1;t[e]=i}return t}(),vs=function(t,e,i){for(;i;++e)t[e]=i,i>>>=8},bs=function(){function t(t,e){if("function"==typeof t&&(e=t,t={}),this.ondata=e,this.o=t||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new $o(98304),this.o.dictionary){var i=this.o.dictionary.subarray(-32768);this.b.set(i,32768-i.length),this.s.i=32768-i.length}}return t.prototype.p=function(t,e){this.ondata(function(t,e,i,r,n){if(!n&&(n={l:1},e.dictionary)){var o=e.dictionary.subarray(-32768),s=new $o(o.length+t.length);s.set(o),s.set(t,o.length),t=s,n.w=o.length}return function(t,e,i,r,n,o){var s=o.z||t.length,a=new $o(r+s+5*(1+Math.ceil(s/7e3))+n),h=a.subarray(r,a.length-n),c=o.l,l=7&(o.r||0);if(e){l&&(h[0]=o.r>>3);for(var d=ps[e-1],u=d>>13,f=8191&d,p=(1<<i)-1,m=o.p||new Do(32768),w=o.h||new Do(p+1),v=Math.ceil(i/3),b=2*v,y=function(e){return(t[e]^t[e+1]<<v^t[e+2]<<b)&p},g=new No(25e3),x=new Do(288),E=new Do(32),T=0,k=0,_=o.i||0,M=0,A=o.w||0,S=0;_+2<s;++_){var C=y(_),P=32767&_,I=w[C];if(m[P]=I,w[C]=P,A<=_){var B=s-_;if((T>7e3||M>24576)&&(B>423||!c)){l=fs(t,h,0,g,x,E,k,M,S,_-S,l),M=T=k=0,S=_;for(var F=0;F<286;++F)x[F]=0;for(F=0;F<30;++F)E[F]=0}var O=2,R=0,$=f,D=P-I&32767;if(B>2&&C==y(_-D))for(var N=Math.min(u,B)-1,V=Math.min(32767,_),U=Math.min(258,B);D<=V&&--$&&P!=I;){if(t[_+O]==t[_+O-D]){for(var z=0;z<U&&t[_+z]==t[_+z-D];++z);if(z>O){if(O=z,R=D,z>N)break;var j=Math.min(D,z-2),L=0;for(F=0;F<j;++F){var q=_-D+F&32767,G=q-m[q]&32767;G>L&&(L=G,I=q)}}}D+=(P=I)-(I=m[P])&32767}if(R){g[M++]=268435456|Go[O]<<18|Wo[R];var H=31&Go[O],W=31&Wo[R];k+=Vo[H]+Uo[W],++x[257+H],++E[W],A=_+O,++T}else g[M++]=t[_],++x[t[_]]}}for(_=Math.max(_,A);_<s;++_)g[M++]=t[_],++x[t[_]];l=fs(t,h,c,g,x,E,k,M,S,_-S,l),c||(o.r=7&l|h[l/8|0]<<3,l-=7,o.h=w,o.p=m,o.i=_,o.w=A)}else{for(_=o.w||0;_<s+c;_+=65535){var X=_+65535;X>=s&&(h[l/8|0]=c,X=s),l=us(h,l+1,t.subarray(_,X))}o.i=s}return rs(a,0,r+is(l)+n)}(t,null==e.level?6:e.level,null==e.mem?n.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):20:12+e.mem,i,r,n)}(t,this.o,0,0,this.s),e)},t.prototype.push=function(t,e){this.ondata||os(5),this.s.l&&os(4);var i=t.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var r=new $o(-32768&i);r.set(this.b.subarray(0,this.s.z)),this.b=r}var n=this.b.length-this.s.z;this.b.set(t.subarray(0,n),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(t.subarray(n),32768),this.s.z=t.length-n+32768,this.s.i=32766,this.s.w=32768}else this.b.set(t,this.s.z),this.s.z+=t.length;this.s.l=1&e,(this.s.z>this.s.w+8191||e)&&(this.p(this.b,e||!1),this.s.w=this.s.i,this.s.i-=2),e&&(this.s=this.o={},this.b=ms)},t.prototype.flush=function(t){if(this.ondata||os(5),this.s.l&&os(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,t){var e=new $o(6);e[0]=this.s.r>>3;var i=us(e,this.s.r,ms);this.s.r=0,this.ondata(e.subarray(0,i>>3),!1)}},t}(),ys="undefined"!=typeof TextEncoder&&new TextEncoder,gs="undefined"!=typeof TextDecoder&&new TextDecoder;try{gs.decode(ms,{stream:!0})}catch(Da){}function xs(t,e){if(e){for(var i=new $o(t.length),r=0;r<t.length;++r)i[r]=t.charCodeAt(r);return i}if(ys)return ys.encode(t);var n=t.length,o=new $o(t.length+(t.length>>1)),s=0,a=function(t){o[s++]=t};for(r=0;r<n;++r){if(s+5>o.length){var h=new $o(s+8+(n-r<<1));h.set(o),o=h}var c=t.charCodeAt(r);c<128||e?a(c):c<2048?(a(192|c>>6),a(128|63&c)):c>55295&&c<57344?(a(240|(c=65536+(1047552&c)|1023&t.charCodeAt(++r))>>18),a(128|c>>12&63),a(128|c>>6&63),a(128|63&c)):(a(224|c>>12),a(128|c>>6&63),a(128|63&c))}return rs(o,0,s)}var Es=function(t){var e=0;if(t)for(var i in t){var r=t[i].length;r>65535&&os(9),e+=r+4}return e},Ts=function(t,e,i,r,n,o,s,a){var h=r.length,c=i.extra,l=a&&a.length,d=Es(c);vs(t,e,null!=s?33639248:67324752),e+=4,null!=s&&(t[e++]=20,t[e++]=i.os),t[e]=20,e+=2,t[e++]=i.flag<<1|(o<0&&8),t[e++]=n&&8,t[e++]=255&i.compression,t[e++]=i.compression>>8;var u=new Date(null==i.mtime?Date.now():i.mtime),f=u.getFullYear()-1980;if((f<0||f>119)&&os(10),vs(t,e,f<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,-1!=o&&(vs(t,e,i.crc),vs(t,e+4,o<0?-o-2:o),vs(t,e+8,i.size)),vs(t,e+12,h),vs(t,e+14,d),e+=16,null!=s&&(vs(t,e,l),vs(t,e+6,i.attrs),vs(t,e+10,s),e+=14),t.set(r,e),e+=h,d)for(var p in c){var m=c[p],w=m.length;vs(t,e,+p),vs(t,e+2,w),t.set(m,e+4),e+=4+w}return l&&(t.set(a,e),e+=l),e},ks=function(){function t(t){var e;this.filename=t,this.c=(e=-1,{p:function(t){for(var i=e,r=0;r<t.length;++r)i=ws[255&i^t[r]]^i>>>8;e=i},d:function(){return~e}}),this.size=0,this.compression=0}return t.prototype.process=function(t,e){this.ondata(null,t,e)},t.prototype.push=function(t,e){this.ondata||os(5),this.c.p(t),this.size+=t.length,e&&(this.crc=this.c.d()),this.process(t,e||!1)},t}(),_s=function(){function t(t,e){var i,r=this;e||(e={}),ks.call(this,t),this.d=new bs(e,function(t,e){r.ondata(null,t,e)}),this.compression=8,this.flag=1==(i=e.level)?3:i<6?2:9==i?1:0}return t.prototype.process=function(t,e){try{this.d.push(t,e)}catch(Da){this.ondata(Da,null,e)}},t.prototype.push=function(t,e){ks.prototype.push.call(this,t,e)},t}(),Ms=function(){function t(t){this.ondata=t,this.u=[],this.d=1}return t.prototype.add=function(t){var e=this;if(this.ondata||os(5),2&this.d)this.ondata(os(4+8*(1&this.d),0,1),null,!1);else{var i=xs(t.filename),r=i.length,n=t.comment,o=n&&xs(n),s=r!=t.filename.length||o&&n.length!=o.length,a=r+Es(t.extra)+30;r>65535&&this.ondata(os(11,0,1),null,!1);var h=new $o(a);Ts(h,0,t,i,s,-1);var c=[h],l=function(){for(var t=0,i=c;t<i.length;t++){var r=i[t];e.ondata(null,r,!1)}c=[]},d=this.d;this.d=0;var u=this.u.length,f=function(t,e){var i={};for(var r in t)i[r]=t[r];for(var r in e)i[r]=e[r];return i}(t,{f:i,u:s,o,t:function(){t.terminate&&t.terminate()},r:function(){if(l(),d){var t=e.u[u+1];t?t.r():e.d=1}d=1}}),p=0;t.ondata=function(i,r,n){if(i)e.ondata(i,r,n),e.terminate();else if(p+=r.length,c.push(r),n){var o=new $o(16);vs(o,0,134695760),vs(o,4,t.crc),vs(o,8,p),vs(o,12,t.size),c.push(o),f.c=p,f.b=a+p+16,f.crc=t.crc,f.size=t.size,d&&f.r(),d=1}else d&&l()},this.u.push(f)}},t.prototype.end=function(){var t=this;2&this.d?this.ondata(os(4+8*(1&this.d),0,1),null,!0):(this.d?this.e():this.u.push({r:function(){1&t.d&&(t.u.splice(-1,1),t.e())},t:function(){}}),this.d=3)},t.prototype.e=function(){for(var t=0,e=0,i=0,r=0,n=this.u;r<n.length;r++)i+=46+(f=n[r]).f.length+Es(f.extra)+(f.o?f.o.length:0);for(var o,s,a,h,c,l=new $o(i+22),d=0,u=this.u;d<u.length;d++){var f=u[d];Ts(l,t,f,f.f,f.u,-f.c-2,e,f.o),t+=46+f.f.length+Es(f.extra)+(f.o?f.o.length:0),e+=f.b}o=l,s=t,a=this.u.length,h=i,c=e,vs(o,s,101010256),vs(o,s+8,a),vs(o,s+10,a),vs(o,s+12,h),vs(o,s+16,c),this.ondata(null,l,!0),this.d=2},t.prototype.terminate=function(){for(var t=0,e=this.u;t<e.length;t++)e[t].t();this.d=2},t}(),As=class{pi;re=[];mi=new Set;wi;bi;yi="open";gi=0;xi;Ei;Ti;constructor(t,e=4294967295){this.wi=t,this.bi=e,this.pi=new Ms((t,e,i)=>{if("failed"!==this.yi)if(t)this.ki(t);else{if(e.byteLength>0){if(this.gi+e.byteLength>this.bi)return void this.ki(new Co("ZIP_EXPORT_TOO_LARGE",`Classic ZIP archives cannot exceed ${this.bi.toLocaleString("en-US")} bytes.`));const t=new Uint8Array(e.byteLength);t.set(e),this.re.push(t.buffer),this.gi+=e.byteLength}if(i&&"finalizing"===this.yi){this.yi="closed";const t=new Blob(this.re,{type:"application/zip"});this.re.length=0,this.Ei?.(t),this.Ei=void 0,this.Ti=void 0}}})}async $addEntry(t,e,i){if(this._i(),this.Mi(t),this.mi.has(t))throw new Co("ZIP_EXPORT_FAILED",`Duplicate ZIP entry: ${t}`);if(this.mi.size>=65535)throw new Co("ZIP_EXPORT_TOO_LARGE","Classic ZIP archives cannot contain more than 65,535 entries.");if(e.byteLength>this.bi)throw new Co("ZIP_EXPORT_TOO_LARGE",`A classic ZIP entry cannot exceed ${this.bi.toLocaleString("en-US")} bytes.`);const r="store"===i?new ks(t):new _s(t,{level:6});if(r.mtime=this.wi,this.mi.add(t),this.pi.add(r),(r instanceof ks||r instanceof _s)&&r.push(e,!0),this.xi)throw this.xi;await Promise.resolve()}$finalize(){return this._i(),this.yi="finalizing",new Promise((t,e)=>{this.Ei=t,this.Ti=e;try{this.pi.end()}catch(i){this.ki(i)}})}$abort(t=Po()){"closed"!==this.yi&&"failed"!==this.yi&&(this.yi="failed",this.xi=t,this.pi.terminate(),this.re.length=0,this.Ti?.(t),this.Ei=void 0,this.Ti=void 0)}_i(){if("open"!==this.yi)throw new Co("ZIP_EXPORT_FAILED",`ZIP archive writer is ${this.yi}.`,this.xi)}Mi(t){const e=t.split("/");if(!t||t.startsWith("/")||/^[A-Za-z]:/.test(t)||t.includes("\\")||t.includes("\0")||e.some(t=>!t||"."===t||".."===t))throw new Co("ZIP_EXPORT_FAILED",`Unsafe ZIP entry path: ${t}`)}ki(t){"failed"!==this.yi&&(this.yi="failed",this.xi=t,this.re.length=0,this.pi.terminate(),this.Ti?.(t),this.Ei=void 0,this.Ti=void 0)}},Ss=new Set(["png","jpg","webp","svg","json","txt"]),Cs=class{T;k;Ai;constructor(t,e,i={}){this.T=t,this.k=e,this.Ai=i}async $saveZIP(t){await this.Si(t,({blob:t,filename:e})=>{(new a).$downloadFile(t,e,".zip")})}async $generateZIPBlob(t){return(await this.Si(t)).blob}async Si(t,e){try{return await this.Ci(t,e)}catch(i){const e=Io(i);if("ZIP_EXPORT_INVALID_OPTIONS"===e.code)try{t?.onProgress?.({state:"error",frameIndex:0,totalFrames:this.Pi(t?.frameCount),progress:0,message:e.message})}catch(r){throw Io(r)}throw e}}async Ci(t,e){const i=this.Ii(t),r=this.Ai.now?.()??new Date,n=(new s).$resolve(i.filename,".zip",r),o=n.slice(0,-4);let a,h=!1,c=0;try{this.I(i.signal);const t=(l=this.T,{png:Oo("png"),jpg:Oo("jpg"),webp:Oo("webp"),svg:Ro("svg",l),json:Ro("json",l),txt:Ro("txt",l)}),s=this.Ai.resolveSerializer?.(i.format)??t[i.format];a=this.Ai.createWriter?.(r)??new As(r);const d=a,u=this.Ai.createDriver?.()??new g(this.T,this.k),f=s.getDimensions({canvas:u.canvas,frameOptions:i.frameOptions});this.Ze(i,{state:"capturing",frameIndex:0,totalFrames:i.frameCount,progress:0}),this.I(i.signal);const p=function(t){return{schema:"textmode.frame-sequence",schemaVersion:"1.0.0",generator:{name:"textmode.export.js",version:ko},createdAt:t.createdAt.toISOString(),format:t.format,frameCount:t.frameCount,frameRate:t.frameRate,width:t.width,height:t.height,indexBase:1,filePattern:`frames/frame-%06d${t.extension}`}}({createdAt:r,format:i.format,frameCount:i.frameCount,frameRate:i.frameRate,width:f.width,height:f.height,extension:s.extension});await d.$addEntry(`${o}/manifest.json`,function(t){return(new TextEncoder).encode(`${JSON.stringify(t,null,2)}\n`)}(p),"deflate"),this.I(i.signal),await u.$render({frameCount:i.frameCount,frameRate:i.frameRate,prepareFrame:i.prepareFrame,signal:i.signal,onFrame:async({frameIndex:t,canvas:e})=>{this.I(i.signal);const n=await s.serialize({canvas:e,frameOptions:i.frameOptions,createdAt:r});this.I(i.signal),await d.$addEntry(function(t,e,i){return`${t}/frames/frame-${String(e+1).padStart(6,"0")}${i}`}(o,t,s.extension),n,s.compression),this.I(i.signal);const a=t+1;c=a,this.Ze(i,{state:"capturing",frameIndex:a,totalFrames:i.frameCount,progress:a/i.frameCount}),await this.st(i.signal)}}),this.I(i.signal),this.Ze(i,{state:"finalizing",frameIndex:i.frameCount,totalFrames:i.frameCount,progress:1}),this.I(i.signal);const m=await d.$finalize();return this.I(i.signal),await(e?.({blob:m,filename:n})),this.I(i.signal),this.Ze(i,{state:"completed",frameIndex:i.frameCount,totalFrames:i.frameCount,progress:1}),h=!0,{blob:m,filename:n}}catch(d){const t=Io(d);try{this.Ze(i,{state:"error",frameIndex:c,totalFrames:i.frameCount,progress:c/i.frameCount,message:t.message})}catch{}throw t}finally{h||a?.$abort()}var l}Ii(t){if(!t||"object"!=typeof t)throw new Co("ZIP_EXPORT_INVALID_OPTIONS","ZIP export options are required.");const e=t.format;if("string"!=typeof e||!Ss.has(e))throw new Co("ZIP_EXPORT_INVALID_OPTIONS","ZIP frame format must be one of 'png', 'jpg', 'webp', 'svg', 'json', or 'txt'.");const i=t.frameCount??300;if(!Number.isFinite(i)||!Number.isInteger(i)||i<1||i>65534)throw new Co("ZIP_EXPORT_INVALID_OPTIONS","ZIP frameCount must be an integer from 1 through 65534.");const r=t.frameRate??60;if(!Number.isFinite(r)||r<=0)throw new Co("ZIP_EXPORT_INVALID_OPTIONS","ZIP frameRate must be finite and greater than zero.");return{format:e,filename:t.filename,frameCount:i,frameRate:r,frameOptions:t.frameOptions,prepareFrame:t.prepareFrame,signal:t.signal,onProgress:t.onProgress}}Ze(t,e){t.onProgress?.(e)}Pi(t){return Number.isInteger(t)&&t>=1&&t<=65534?t:300}I(t){if(t?.aborted)throw Po()}st(t){return new Promise((e,i)=>{if(t?.aborted)return void i(Po());let r=!1;const n=()=>{r||(r=!0,i(Po()))};t?.addEventListener("abort",n,{once:!0}),setTimeout(()=>{r||(r=!0,t?.removeEventListener("abort",n),e())},0)})}},Ps="textmode-export-overlay__stack",Is="textmode-export-overlay__stack--dense",Bs="textmode-export-overlay__stack--compact",Fs="textmode-export-overlay__section",Os="textmode-export-overlay--dragging",Rs="textmode-export-overlay__label",$s="textmode-export-overlay__field",Ds="textmode-export-overlay__field--compact",Ns="textmode-export-overlay__field--dense",Vs="textmode-export-overlay__field--full",Us="textmode-export-overlay__field--channel",zs="textmode-export-overlay__input",js="textmode-export-overlay__muted",Ls="textmode-export-overlay__button--primary",qs="textmode-export-overlay__button--secondary",Gs="textmode-export-overlay__button--full",Hs="textmode-export-overlay__link-icon",Ws=class{element;mounted=!1;destroyed=!1;mount(t){if(this.destroyed)throw new Error("Cannot mount a destroyed component");if(this.mounted)return;const e=this.render();t.appendChild(e),this.element=e,this.onMount(),this.mounted=!0}unmount(){this.mounted&&this.element&&(this.Bi(),this.element.remove(),this.element=void 0,this.mounted=!1)}destroy(){this.destroyed||(this.unmount(),this.Fi(),this.destroyed=!0)}update(t){this.mounted&&this.onUpdate(t)}onMount(){}Bi(){}Fi(){}onUpdate(t){}get root(){if(!this.element)throw new Error("Component is not mounted yet");return this.element}isMounted(){return this.mounted}},Xs=class t extends Ws{static Oi="http://www.w3.org/2000/svg";Ri;get dragHandleElement(){if(!this.Ri)throw new Error("Header drag handle is not mounted yet");return this.Ri}render(){this.Ri=void 0;const t=document.createElement("div");t.classList.add(Ps,Is,"textmode-export-overlay__header");const e=document.createElement("div");e.classList.add("textmode-export-overlay__header-title-row");const i=document.createElement("div");i.classList.add("textmode-export-overlay__header-identity");const r=this.$i("Move export overlay","textmode-export-overlay__grab-handle",[{d:"M9 5h.01"},{d:"M15 5h.01"},{d:"M9 12h.01"},{d:"M15 12h.01"},{d:"M9 19h.01"},{d:"M15 19h.01"}]);this.Ri=r;const n=document.createElement("strong");n.textContent="textmode.export.js",n.classList.add("textmode-export-overlay__title");const o=document.createElement("div");o.classList.add("textmode-export-overlay__header-links");const s=this.Di("https://github.com/humanbydefinition/textmode.export.js","View repository on GitHub",Hs,[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5"}]),a=this.Di("https://code.textmode.art/docs/support","Support textmode.export.js","textmode-export-overlay__support-icon",[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1"},{d:"M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z"},{d:"M16.746 16.726a3 3 0 1 0 .252 -5.555"}]);o.appendChild(s),o.appendChild(a),i.appendChild(r),i.appendChild(n),e.appendChild(i),e.appendChild(o);const h=document.createElement("div");return h.classList.add("textmode-export-overlay__divider"),t.appendChild(e),t.appendChild(h),t}$i(t,e,i){const r=document.createElement("button");return r.type="button",r.classList.add(e),r.setAttribute("aria-label",t),r.title=t,r.appendChild(this.Ni(Hs,i)),r}Di(t,e,i,r){const n=document.createElement("a");return n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("textmode-export-overlay__support-link"),n.setAttribute("aria-label",e),n.appendChild(this.Ni(i,r)),n}Ni(e,i){const r=document.createElementNS(t.Oi,"svg");r.setAttribute("xmlns",t.Oi),r.setAttribute("width","18"),r.setAttribute("height","18"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","2"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.classList.add(e);for(const n of i){const e=document.createElementNS(t.Oi,"path");for(const[t,i]of Object.entries(n))e.setAttribute(t,i);r.appendChild(e)}return r}},Zs=class extends Ws{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add($s),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(Rs),e.textContent=this.props.label,this.props.labelFor&&(e.htmlFor=this.props.labelFor),t.appendChild(e),this.props.description){const e=document.createElement("span");e.classList.add(js),e.textContent=this.props.description,t.appendChild(e)}return t}attachControl(t){this.root.appendChild(t)}update(t){this.props=t,super.update(t)}onUpdate(t){const e=this.root;for(;e.firstChild;)e.removeChild(e.firstChild);this.props=t,e.classList.add($s),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(Rs),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(js),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(Ds,Ns,Vs,Us),e){case"compact":t.classList.add(Ds);break;case"dense":t.classList.add(Ns);break;case"full":t.classList.add(Vs);break;case"channel":t.classList.add(Us)}}},Qs=class extends Ws{props;select;handleChange=()=>{this.props.defaultValue=this.select.value};constructor(t){super(),this.props=t}render(){return this.select=document.createElement("select"),this.select.classList.add(zs),this.props.id&&(this.select.id=this.props.id),this.populateOptions(),this.select.addEventListener("change",this.handleChange),this.select}get selectElement(){return this.select}get value(){return this.select.value}set value(t){this.select&&(this.select.value=t),this.props.defaultValue=t}Bi(){this.select.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,this.populateOptions(),t.defaultValue&&(this.select.value=t.defaultValue)}update(t){this.props={...this.props,...t},this.select&&(t.id&&(this.select.id=t.id),t.options&&this.populateOptions(),void 0!==t.defaultValue&&(this.select.value=t.defaultValue))}populateOptions(){if(this.select){this.select.innerHTML="";for(const t of this.props.options){const e=document.createElement("option");e.value=t.value,e.textContent=t.label,this.select.appendChild(e)}this.props.defaultValue&&(this.select.value=this.props.defaultValue)}}},Ys=class extends Ws{props;button;constructor(t){super(),this.props=t}render(){return this.button=document.createElement("button"),this.button.type="button",this.button.textContent=this.props.label,this.button.classList.add("textmode-export-overlay__button"),"secondary"===this.props.variant?this.button.classList.add(qs):this.button.classList.add(Ls),this.props.fullWidth&&this.button.classList.add(Gs),this.button.disabled=Boolean(this.props.disabled),this.button}get buttonElement(){return this.button}setLabel(t){this.props.label=t,this.button.textContent=t}setDisabled(t){this.props.disabled=t,this.button.disabled=t}onUpdate(t){this.props=t,this.button.textContent=t.label,this.button.disabled=Boolean(t.disabled),"secondary"===t.variant?(this.button.classList.add(qs),this.button.classList.remove(Ls)):(this.button.classList.add(Ls),this.button.classList.remove(qs)),this.button.classList.toggle(Gs,Boolean(t.fullWidth))}},Js=class{ht={};Vi(t){const e=this.ht[t];if(e)return e;const i=new Set;return this.ht[t]=i,i}$on(t,e){const i=this.Vi(t);return i.add(e),()=>{i.delete(e),0===i.size&&delete this.ht[t]}}$emit(t,e){const i=this.ht[t];if(i)for(const n of[...i])try{n(e)}catch(r){console.error("[textmode-export] Event handler failed",r)}}$clear(){for(const t of Object.keys(this.ht))delete this.ht[t]}},Ks=class{yi;ht=new Set;constructor(t){this.yi=t}get snapshot(){return Object.freeze({...this.yi})}$set(t){const e=Object.keys(t);if(0===e.length)return;let i=!1;for(const o of e)if(this.yi[o]!==t[o]){i=!0;break}if(!i)return;this.yi=Object.assign({},this.yi,t);const r=this.snapshot;for(const o of[...this.ht])try{o(r)}catch(n){console.error("[textmode-export] State listener failed",n)}}$subscribe(t){return this.ht.add(t),t(this.snapshot),()=>{this.ht.delete(t)}}$reset(t){this.yi=t;const e=this.snapshot;for(const i of[...this.ht])i(e)}},ta=new Set(["txt","json","svg","image"]),ea=class{api;constructor(t){this.api=t}async $copy(t,e){switch(t){case"txt":{const t=this.api.toString(e);await navigator.clipboard.writeText(t);break}case"json":{const t=this.api.toJSONString(e);await navigator.clipboard.writeText(t);break}case"svg":{const t=this.api.toSVG(e);await navigator.clipboard.writeText(t);break}case"image":await this.api.copyCanvas(e);break;default:throw new Error(`Clipboard not supported for ${t}`)}}static isClipboardFormat(t){return ta.has(t)}},ia={txt:(t,e)=>Promise.resolve(t.saveStrings(e)),json:(t,e)=>Promise.resolve(t.saveJSON(e)),image:(t,e)=>t.saveCanvas(e),svg:(t,e)=>Promise.resolve(t.saveSVG(e)),gif:(t,e,i)=>{const r={...e,onProgress:i.onGIFProgress};return t.saveGIF(r)},video:(t,e,i)=>{const r={...e,onProgress:i.onVideoProgress};return t.saveVideo(r)}},ra=class{api;events;constructor(t,e){this.api=t,this.events=e}async $requestExport(t,e,i={}){this.events.$emit("export:request",{format:t});try{const r={onGIFProgress:i.onGIFProgress?e=>{i.onGIFProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"gif"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0,onVideoProgress:i.onVideoProgress?e=>{i.onVideoProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"video"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0};await ia[t](this.api,e,r),this.events.$emit("export:success",{format:t})}catch(r){throw this.events.$emit("export:error",{format:t,error:r}),r}}},na=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,oa=class{key;constructor(t="textmode.export.overlay.position.v1"){this.key=t}load(){try{const t=window.localStorage.getItem(this.key);if(!t)return;const e=JSON.parse(t);if(1!==e.version||!na(e.offsetX)||!na(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(na(t)&&na(e))try{const i={version:1,offsetX:t,offsetY:e};window.localStorage.setItem(this.key,JSON.stringify(i))}catch{}}clear(){try{window.localStorage.removeItem(this.key)}catch{}}},sa=class{modifier;host;surface;storage;animationFrameId=null;handleUpdate;bound=!1;dragHandle;dragState;position;renderedOffset;handlePointerDown=t=>this.onPointerDown(t);handlePointerMove=t=>this.onPointerMove(t);handlePointerUp=t=>this.onPointerUp(t);handleKeyDown=t=>this.onKeyDown(t);constructor(t,e,i=e,r=new oa){this.modifier=t,this.host=e,this.surface=i,this.storage=r,this.handleUpdate=()=>this.scheduleUpdate();const n=this.storage.load();this.position=n?{mode:"custom",offsetX:n.offsetX,offsetY:n.offsetY}:{mode:"auto",offsetX:8,offsetY:8},this.renderedOffset={offsetX:this.position.offsetX,offsetY:this.position.offsetY}}getPosition(){return Object.freeze({...this.position})}setPosition(t,e={}){Number.isFinite(t.offsetX)&&Number.isFinite(t.offsetY)&&(this.position={mode:"custom",offsetX:t.offsetX,offsetY:t.offsetY},this.scheduleUpdate(),(e.persist??1)&&this.storage.save(this.position.offsetX,this.position.offsetY))}resetPosition(){this.position={mode:"auto",offsetX:8,offsetY:8},this.storage.clear(),this.scheduleUpdate()}scheduleUpdate(){null!==this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=requestAnimationFrame(()=>this.update())}bind(){this.bound||(window.addEventListener("resize",this.handleUpdate),window.addEventListener("scroll",this.handleUpdate,!0),this.bound=!0,this.handleUpdate())}attachDragHandle(t){this.dragHandle!==t&&(this.detachDragHandle(),this.dragHandle=t,t.addEventListener("pointerdown",this.handlePointerDown),t.addEventListener("keydown",this.handleKeyDown))}detachDragHandle(){this.dragHandle&&(this.dragHandle.removeEventListener("pointerdown",this.handlePointerDown),this.dragHandle.removeEventListener("keydown",this.handleKeyDown),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp),this.dragHandle=void 0,this.dragState=void 0,this.surface.classList.remove(Os))}onPointerDown(t){if(0===t.button&&this.dragHandle){t.preventDefault(),this.dragState={pointerId:t.pointerId,startClientX:t.clientX,startClientY:t.clientY,startOffsetX:this.renderedOffset.offsetX,startOffsetY:this.renderedOffset.offsetY},this.surface.classList.add(Os),this.dragHandle.addEventListener("pointermove",this.handlePointerMove),this.dragHandle.addEventListener("pointerup",this.handlePointerUp),this.dragHandle.addEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.setPointerCapture?.(t.pointerId)}catch{}}}onPointerMove(t){this.dragState&&t.pointerId===this.dragState.pointerId&&(t.preventDefault(),this.setPosition({offsetX:this.dragState.startOffsetX+t.clientX-this.dragState.startClientX,offsetY:this.dragState.startOffsetY+t.clientY-this.dragState.startClientY},{persist:!1}))}onPointerUp(t){if(this.dragState&&t.pointerId===this.dragState.pointerId&&this.dragHandle){t.preventDefault(),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.hasPointerCapture?.(t.pointerId)&&this.dragHandle.releasePointerCapture?.(t.pointerId)}catch{}this.surface.classList.remove(Os),this.dragState=void 0,"custom"===this.position.mode&&this.storage.save(this.position.offsetX,this.position.offsetY)}}onKeyDown(t){const e=t.shiftKey?32:8,i=this.renderedOffset;switch(t.key){case"ArrowUp":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY-e});break;case"ArrowDown":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY+e});break;case"ArrowLeft":t.preventDefault(),this.setPosition({offsetX:i.offsetX-e,offsetY:i.offsetY});break;case"ArrowRight":t.preventDefault(),this.setPosition({offsetX:i.offsetX+e,offsetY:i.offsetY});break;case"Home":t.preventDefault(),this.resetPosition()}}update(){if(this.animationFrameId=null,"none"===this.host.style.display)return;const t=this.modifier.canvas.getBoundingClientRect(),e=this.clampToViewport(t,this.position.offsetX,this.position.offsetY);this.host.style.top=`${t.top+window.scrollY+e.offsetY}px`,this.host.style.left=`${t.left+window.scrollX+e.offsetX}px`,this.renderedOffset=e}clampToViewport(t,e,i){const r=this.surface.getBoundingClientRect(),n=r.width||this.host.getBoundingClientRect().width||0,o=r.height||this.host.getBoundingClientRect().height||0,s=Math.max(8,window.innerWidth-n-8),a=Math.max(8,window.innerHeight-o-8),h=this.clamp(t.left+e,8,s),c=this.clamp(t.top+i,8,a);return{offsetX:h-t.left,offsetY:c-t.top}}clamp(t,e,i){return Math.min(Math.max(t,e),i)}dispose(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.bound&&(window.removeEventListener("resize",this.handleUpdate),window.removeEventListener("scroll",this.handleUpdate,!0),this.bound=!1),this.detachDragHandle()}},aa=class extends Ws{capabilities;Ui;zi=new Set;constructor(t,e){super(),this.Ui=t,this.capabilities={clipboard:t.supportsClipboard,layerTarget:!!t.layerTargetProvider,recording:!1,...e}}ji(t){return this.zi.add(t),t}Bi(){for(const t of this.zi)t.unmount()}Fi(){for(const t of this.zi)t.destroy();this.zi.clear()}},ha=class extends Ws{props;checkbox;labelElement;handleChange=()=>{this.props.defaultChecked=this.checkbox.checked};constructor(t){super(),this.props=t}render(){this.labelElement=document.createElement("label"),this.labelElement.classList.add("textmode-export-overlay__checkbox"),this.checkbox=document.createElement("input"),this.checkbox.type="checkbox",this.props.id&&(this.checkbox.id=this.props.id),this.checkbox.checked=Boolean(this.props.defaultChecked),this.checkbox.addEventListener("change",this.handleChange);const t=document.createElement("span");return t.textContent=this.props.label,this.labelElement.htmlFor=this.props.id??"",this.labelElement.appendChild(this.checkbox),this.labelElement.appendChild(t),this.labelElement}get inputElement(){return this.checkbox}get checked(){return this.checkbox.checked}set checked(t){this.checkbox.checked=t}Bi(){this.checkbox.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,t.id&&(this.checkbox.id=t.id,this.labelElement.htmlFor=t.id),this.checkbox.checked=Boolean(t.defaultChecked),this.labelElement.lastElementChild&&(this.labelElement.lastElementChild.textContent=t.label)}},ca=class extends Ws{props;input;handleInput=()=>{this.props.defaultValue=this.input.value};constructor(t){super(),this.props=t}render(){return this.input=document.createElement("input"),this.input.type="text",this.input.classList.add(zs),this.props.id&&(this.input.id=this.props.id),void 0!==this.props.maxLength&&(this.input.maxLength=this.props.maxLength),void 0!==this.props.defaultValue&&(this.input.value=this.props.defaultValue),this.input.addEventListener("input",this.handleInput),this.input}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t}Bi(){this.input.removeEventListener("input",this.handleInput)}onUpdate(t){this.props=t,t.id&&(this.input.id=t.id),void 0!==t.maxLength&&(this.input.maxLength=t.maxLength),void 0!==t.defaultValue&&(this.input.value=t.defaultValue)}},la=class extends Ws{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new Zs({label:"layer",labelFor:t.id,variant:"full"}),this.select=new Qs({id:t.id,options:[],defaultValue:t.provider.getDefaultId()})}render(){const t=document.createElement("div");return this.field.mount(t),this.refresh(),this.select.mount(this.field.root),t}get layer(){const t=this.provider.getLayerById(this.select.value);if(t)return t;const e=this.provider.getDefaultId();return this.select.value=e,this.provider.getLayerById(e)}setDisabled(t){this.select.selectElement.disabled=t}refresh(){const t=this.provider.getOptions(),e=this.select.isMounted()?this.select.value:this.provider.getDefaultId(),i=t.some(t=>t.id===e)?e:this.provider.getDefaultId();this.select.update({options:t.map(t=>({value:t.id,label:t.label})),defaultValue:i}),this.select.value=i}Bi(){this.select.unmount(),this.field.unmount()}Fi(){this.select.destroy(),this.field.destroy()}},da=class extends aa{layerTarget;trailingSpaces=this.ji(new ha({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.ji(new ca({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.ji(new la({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Ps),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new Zs({label:"empty character",labelFor:"textmode-export-empty-character",variant:"full"});return e.mount(t),this.emptyCharacter.mount(e.root),t}getOptions(){const t=this.Ui.defaultOptions,e=this.emptyCharacter.value||t.emptyCharacter;return{layer:this.layerTarget?.layer,preserveTrailingSpaces:this.trailingSpaces.checked,emptyCharacter:e}}setDefaults(t){Object.assign(this.Ui.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return this.emptyCharacter.value.length<=1}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.Ui.defaultOptions;this.trailingSpaces.checked=t.preserveTrailingSpaces??!1,this.emptyCharacter.value=t.emptyCharacter??" "}},ua=class extends aa{layerTarget;layerTargetContainer;target=this.ji(new Qs({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.ji(new ha({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.ji(new ha({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.ji(new Qs({id:"textmode-export-json-color-mode",options:[{value:"hex",label:"hex"},{value:"rgba",label:"rgba"}],defaultValue:"hex"}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.ji(new la({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Ps);const e=new Zs({label:"target",labelFor:"textmode-export-json-target",variant:"full"});e.mount(t),this.target.mount(e.root),this.target.selectElement.addEventListener("change",()=>this.updateLayerTargetVisibility()),this.layerTarget&&(this.layerTargetContainer=document.createElement("div"),this.layerTarget.mount(this.layerTargetContainer),t.appendChild(this.layerTargetContainer)),this.prettyPrint.mount(t),this.includeMetadata.mount(t);const i=new Zs({label:"color mode",labelFor:"textmode-export-json-color-mode",variant:"full"});return i.mount(t),this.colorMode.mount(i.root),this.updateLayerTargetVisibility(),t}getOptions(){const t=this.target.value;return{target:t,layer:"selected"===t?this.layerTarget?.layer:void 0,pretty:this.prettyPrint.checked,includeMetadata:this.includeMetadata.checked,colorMode:this.colorMode.value}}setDefaults(t){Object.assign(this.Ui.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return!0}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.Ui.defaultOptions;this.target.value=t.target??"selected",this.prettyPrint.checked="number"==typeof t.pretty?t.pretty>0:t.pretty??!0,this.includeMetadata.checked=t.includeMetadata??!0,this.colorMode.value=t.colorMode??"hex",this.updateLayerTargetVisibility()}updateLayerTargetVisibility(){const t="selected"===this.target.value;this.layerTargetContainer&&(this.layerTargetContainer.style.display=t?"":"none"),this.layerTarget?.setDisabled(!t)}},fa="textmode-export-number-input",pa=`${fa}__field`,ma=`${fa}__controls`,wa=`${fa}__control`,va=`${fa}__display`,ba=`${va}--visible`,ya=t=>{const e=document.createElement("button");return e.type="button",e.className=wa,e.textContent=t>0?"▲":"▼",e},ga=class extends Ws{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=fa,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=pa,this.display=document.createElement("div"),this.display.className=va;const e=document.createElement("div");return e.className=ma,this.incrementButton=ya(1),this.decrementButton=ya(-1),e.appendChild(this.incrementButton),e.appendChild(this.decrementButton),t.appendChild(this.input),t.appendChild(this.display),t.appendChild(e),this.bindStepControls(),this.bindHoldBehavior(),this.bindInputListeners(),this.observeDisabledState(t),this.updateDisplay(),t}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t,this.updateDisplay()}refresh(){this.updateDisplay()}Fi(){this.clearHoldTimers(),this.disabledObserver?.disconnect()}bindStepControls(){const t=t=>()=>{if(this.input.disabled)return;const e=this.input.value,i=this.input.getAttribute("step");if(i&&"any"!==i)t>0?this.input.stepUp():this.input.stepDown();else{const e=t>0?1:-1,i=Number.parseFloat(this.input.value||"0"),r=Number.isFinite(i)?i+e:e;this.input.value=String(r)}var r;this.input.value!==e&&((r=this.input).dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0}))),this.updateDisplay(),this.input.focus({preventScroll:!0})},e=t(1),i=t(-1),r=(t,e)=>i=>{if(this.suppressClickAfterPointer.get(t))return this.suppressClickAfterPointer.set(t,!1),void i.preventDefault();e()};this.incrementButton.addEventListener("click",r(this.incrementButton,e)),this.decrementButton.addEventListener("click",r(this.decrementButton,i))}bindHoldBehavior(){const t=(t,e)=>{const i=e>0?()=>this.incrementButton.click():()=>this.decrementButton.click();t.addEventListener("pointerdown",e=>{if(0===e.button){e.preventDefault(),this.suppressClickAfterPointer.set(t,!0),this.activePointerId=e.pointerId;try{t.setPointerCapture(e.pointerId)}catch{}i(),this.holdTimeoutId=window.setTimeout(()=>{this.holdIntervalId=window.setInterval(i,80)},380)}});const r=()=>{if(void 0!==this.activePointerId){try{t.releasePointerCapture(this.activePointerId)}catch{}this.activePointerId=void 0}},n=()=>{this.clearHoldTimers(),r()};t.addEventListener("pointerup",n),t.addEventListener("pointerleave",n),t.addEventListener("pointercancel",n)};t(this.incrementButton,1),t(this.decrementButton,-1)}bindInputListeners(){const t=()=>{this.props.defaultValue=this.input.value,this.updateDisplay()};this.input.addEventListener("input",t),this.input.addEventListener("change",t)}observeDisabledState(t){const e=()=>{const e=this.input.disabled;this.incrementButton.disabled=e,this.decrementButton.disabled=e,t.classList.toggle("is-disabled",e),e?(this.display.classList.remove(ba),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor")):this.updateDisplay()};"undefined"!=typeof MutationObserver&&(this.disabledObserver=new MutationObserver(e),this.disabledObserver.observe(this.input,{attributes:!0,attributeFilter:["disabled"]})),e()}updateDisplay(){const t=this.props.formatDisplay;if(!t)return this.display.textContent="",this.display.classList.remove(ba),this.input.style.removeProperty("color"),void this.input.style.removeProperty("caretColor");const e=this.input.value,i=Number.parseFloat(e),r=t(Number.isFinite(i)?i:NaN,e,this.input);r?(this.display.textContent=r,this.display.classList.add(ba),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(ba),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor"))}clearHoldTimers(){void 0!==this.holdTimeoutId&&(window.clearTimeout(this.holdTimeoutId),this.holdTimeoutId=void 0),void 0!==this.holdIntervalId&&(window.clearInterval(this.holdIntervalId),this.holdIntervalId=void 0)}},xa=class extends Ws{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?Ps:void 0,"stackDense"===this.variant?Is:void 0,"stackCompact"===this.variant?Bs:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?Fs:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},Ea=class extends aa{formatSelect=this.ji(new Qs({id:"textmode-export-image-format",options:[{value:"png",label:"PNG (.png)"},{value:"jpg",label:"JPG (.jpg)"},{value:"webp",label:"WEBP (.webp)"}],defaultValue:"png"}));scaleInput=this.ji(new ga({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(Ps);const e=new xa("row");e.mount(t);const i=new Zs({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Zs({label:"scale",labelFor:"textmode-export-image-scale",variant:"dense"});return r.mount(e.root),this.scaleInput.mount(r.root),this.scaleInput.inputElement.id="textmode-export-image-scale",t}getOptions(){const t=Number.parseFloat(this.scaleInput.value);return{format:this.formatSelect.value,scale:Number.isFinite(t)?t:this.Ui.defaultOptions?.scale??1}}setDefaults(t){Object.assign(this.Ui.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.scaleInput.refresh()}validate(){const t=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0}applyDefaults(){const t=this.Ui.defaultOptions;this.formatSelect.value=t.format??"png",this.scaleInput.value=String(t.scale??1)}},Ta=class extends aa{layerTarget;includeBackground=this.ji(new ha({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.ji(new Qs({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.ji(new ga({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.ji(new la({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Ps),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new xa("row");e.mount(t);const i=new Zs({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new Zs({label:"stroke width",labelFor:"textmode-export-svg-stroke-width",variant:"compact"});return r.mount(e.root),this.strokeWidth.mount(r.root),this.strokeWidth.inputElement.id="textmode-export-svg-stroke-width",this.drawMode.selectElement.addEventListener("change",()=>this.updateStrokeControls()),this.updateStrokeControls(),t}getOptions(){return{layer:this.layerTarget?.layer,includeBackgroundRectangles:this.includeBackground.checked,drawMode:this.drawMode.value,strokeWidth:Number.parseFloat(this.strokeWidth.value)}}setDefaults(t){Object.assign(this.Ui.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.updateStrokeControls()}validate(){const t=Number.parseFloat(this.strokeWidth.value);return"stroke"!==this.drawMode.value||Number.isFinite(t)&&t>=0}refreshLayerTargets(){this.layerTarget?.refresh()}updateStrokeControls(){const t="stroke"===this.drawMode.value;this.strokeWidth.inputElement.disabled=!t,this.strokeWidth.refresh()}applyDefaults(){const t=this.Ui.defaultOptions;this.includeBackground.checked=t.includeBackgroundRectangles??!0,this.drawMode.value=t.drawMode??"fill",this.strokeWidth.value=String(t.strokeWidth??1),this.strokeWidth.refresh()}},ka={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},_a=class extends Ws{props;container;messageElement;constructor(t){super(),this.props=t}render(){this.container=document.createElement("div"),this.container.classList.add("textmode-export-overlay__status"),"gif"===this.props.context?this.container.classList.add("textmode-export-overlay__status--gif"):"video"===this.props.context&&this.container.classList.add("textmode-export-overlay__status--video");const t=document.createElement("span");return t.classList.add("textmode-export-overlay__status-title"),t.textContent=this.props.title,this.messageElement=document.createElement("span"),this.messageElement.classList.add("textmode-export-overlay__status-value"),this.messageElement.textContent=this.props.message,this.applyVariant(this.props.variant??"neutral"),this.container.appendChild(t),this.container.appendChild(this.messageElement),this.container}setMessage(t,e="neutral"){this.messageElement.textContent=t,this.applyVariant(e)}onUpdate(t){this.props=t,this.setMessage(t.message,t.variant??"neutral")}applyVariant(t){this.messageElement.classList.remove(...Object.values(ka)),this.messageElement.classList.add(ka[t])}},Ma=class extends aa{frameCountInput=this.ji(new ga({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.ji(new ga({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.ji(new ga({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.ji(new ga({defaultValue:"0",attributes:{min:"0",max:"50",step:"1"},formatDisplay:(t,e)=>Number.isFinite(t)?0===t?"∞":null:""===e.trim()?null:e}));status=this.ji(new _a({title:"status",message:"ready to record",variant:"neutral",context:"gif"}));recordingState="idle";constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(Ps);const e=new xa("row");e.mount(t);const i=new Zs({label:"number of frames",labelFor:"textmode-export-gif-frame-count",variant:"dense"});i.mount(e.root),this.frameCountInput.mount(i.root),this.frameCountInput.inputElement.id="textmode-export-gif-frame-count";const r=new Zs({label:"frame rate (fps)",labelFor:"textmode-export-gif-frame-rate",variant:"dense"});r.mount(e.root),this.frameRateInput.mount(r.root),this.frameRateInput.inputElement.id="textmode-export-gif-frame-rate";const n=new xa("row");n.mount(t);const o=new Zs({label:"scale",labelFor:"textmode-export-gif-scale",variant:"dense"});o.mount(n.root),this.scaleInput.mount(o.root),this.scaleInput.inputElement.id="textmode-export-gif-scale";const s=new Zs({label:"loop count",labelFor:"textmode-export-gif-repeat",variant:"dense"});return s.mount(n.root),this.repeatInput.mount(s.root),this.repeatInput.inputElement.id="textmode-export-gif-repeat",this.status.mount(t),t}getOptions(){const t=this.Ui.defaultOptions;return{frameCount:this.safeParseInt(this.frameCountInput.value,t.frameCount??300),frameRate:this.safeParseInt(this.frameRateInput.value,t.frameRate??60),scale:this.safeParseFloat(this.scaleInput.value,t.scale??1),repeat:this.safeParseInt(this.repeatInput.value,t.repeat??0)}}setDefaults(t){Object.assign(this.Ui.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.setRecordingState("idle")}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseInt(this.frameRateInput.value,10),i=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;switch(this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.scaleInput.inputElement.disabled=i,this.repeatInput.inputElement.disabled=i,t){case"recording":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`recording ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("recording…","active");break;case"encoding":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`encoding ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("encoding…","active");break;case"completed":this.status.setMessage("GIF saved successfully","active");break;case"error":this.status.setMessage(e?.message??"failed to export GIF","alert");break;default:this.status.setMessage("ready to record","neutral")}}handleProgress(t){if("recording"!==t.state&&"encoding"!==t.state||!t.totalFrames)"completed"===t.state?this.status.setMessage("GIF saved successfully","active"):"error"===t.state&&this.status.setMessage(t.message??"failed to export GIF","alert");else{const e="recording"===t.state?"recording":"encoding";this.status.setMessage(`${e} ${t.frameIndex??0}/${t.totalFrames}`,"active")}}applyDefaults(){const t=this.Ui.defaultOptions;this.frameCountInput.value=String(t.frameCount??300),this.frameRateInput.value=String(t.frameRate??60),this.scaleInput.value=String(t.scale??1),this.repeatInput.value=String(t.repeat??0),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.scaleInput.refresh(),this.repeatInput.refresh()}safeParseInt(t,e){const i=Number.parseInt(t,10);return Number.isFinite(i)?i:e}safeParseFloat(t,e){const i=Number.parseFloat(t);return Number.isFinite(i)?i:e}},Aa=class extends aa{formatSelect=this.ji(new Qs({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));qualitySelect=this.ji(new Qs({id:"textmode-export-video-quality",options:[{value:"very-low",label:"very low"},{value:"low",label:"low"},{value:"medium",label:"medium"},{value:"high",label:"high"},{value:"very-high",label:"very high"}],defaultValue:"medium"}));frameRateInput=this.ji(new ga({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.ji(new ga({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));hardwareAccelerationSelect=this.ji(new Qs({id:"textmode-export-video-hardware-acceleration",options:[{value:"no-preference",label:"no preference"},{value:"prefer-hardware",label:"prefer hardware"},{value:"prefer-software",label:"prefer software"}],defaultValue:"no-preference"}));keyFrameIntervalInput=this.ji(new ga({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.ji(new ha({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.ji(new _a({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.ji(new _a({title:"estimate",message:"logical dimensions · duration · size",variant:"neutral",context:"video"}));recordingState="idle";resizeObserver;constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(Ps);const e=new xa("row");e.mount(t);const i=new Zs({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Zs({label:"quality",labelFor:"textmode-export-video-quality",variant:"compact"});r.mount(e.root),this.qualitySelect.mount(r.root);const n=new xa("row");n.mount(t);const o=new Zs({label:"number of frames",labelFor:"textmode-export-video-frame-count",variant:"compact"});o.mount(n.root),this.frameCountInput.mount(o.root),this.frameCountInput.inputElement.id="textmode-export-video-frame-count";const s=new Zs({label:"frame rate (fps)",labelFor:"textmode-export-video-frame-rate",variant:"compact"});s.mount(n.root),this.frameRateInput.mount(s.root),this.frameRateInput.inputElement.id="textmode-export-video-frame-rate";const a=new xa("row");a.mount(t);const h=new Zs({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(a.root),this.hardwareAccelerationSelect.mount(h.root);const c=new Zs({label:"keyframe interval",labelFor:"textmode-export-video-keyframe-interval",variant:"compact"});return c.mount(a.root),this.keyFrameIntervalInput.mount(c.root),this.keyFrameIntervalInput.inputElement.id="textmode-export-video-keyframe-interval",this.transparencyInput.mount(t),this.formatSelect.selectElement.addEventListener("change",this.handleFormatChange),this.syncTransparencyAvailability(),this.qualitySelect.selectElement.addEventListener("change",this.handleQualityChange),this.frameCountInput.inputElement.addEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.addEventListener("input",this.handleEstimateChange),this.formatSelect.selectElement.addEventListener("change",this.handleEstimateChange),this.estimate.mount(t),this.status.mount(t),this.syncOutputEstimate(),this.Ui.videoDimensionsTarget&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.syncOutputEstimate()),this.resizeObserver.observe(this.Ui.videoDimensionsTarget)),t}getOptions(){const t=this.Ui.defaultOptions,e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value),r=Number.parseFloat(this.keyFrameIntervalInput.value),n=this.formatSelect.value,o={format:n,quality:this.qualitySelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.isFinite(r)?r:t.keyFrameInterval??2,frameCount:Number.isFinite(e)?e:t.frameCount??480,frameRate:Number.isFinite(i)?i:t.frameRate??60};return"webm"===n&&(o.transparent=this.transparencyInput.checked),o}setDefaults(t){Object.assign(this.Ui.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.syncReadyStatus()}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseFloat(this.frameRateInput.value),i=Number.parseFloat(this.keyFrameIntervalInput.value);return Number.isFinite(t)&&t>=1&&Number.isFinite(e)&&e>=1&&Number.isFinite(i)&&i>=0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;this.formatSelect.selectElement.disabled=i,this.qualitySelect.selectElement.disabled=i,this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.hardwareAccelerationSelect.selectElement.disabled=i,this.keyFrameIntervalInput.inputElement.disabled=i,this.transparencyInput.inputElement.disabled=i||"webm"!==this.formatSelect.value,this.syncStatus(t,e)}handleProgress(t){this.syncStatus(t.state,t)}syncStatus(t,e){switch(t){case"recording":{const t=e?.frameIndex??0,i=e?.totalFrames??this.resolvePlannedFrameCount();if(i){const e=Math.min(Math.max(0,Math.round(t)),i);this.status.setMessage(`recording ${e}/${i} frames`,"active")}else this.status.setMessage(`recording ${Math.max(0,Math.round(t))} frames`,"active");break}case"encoding":this.status.setMessage("writing"===e?.phase?"writing video to disk":"finalizing video","active");break;case"completed":this.status.setMessage("saved to disk","active");break;case"error":this.status.setMessage(e?.message?`error: ${e.message}`:"recording failed","alert");break;default:this.syncReadyStatus()}}resolvePlannedFrameCount(){const t=Number.parseInt(this.frameCountInput.value,10);return Number.isFinite(t)&&t>0?Math.round(t):void 0}applyDefaults(){const t=this.Ui.defaultOptions;this.formatSelect.value=t.format??"mp4",this.qualitySelect.value=this.resolveQuality(t.quality),this.frameCountInput.value=String(t.frameCount??480),this.frameRateInput.value=String(t.frameRate??60),this.hardwareAccelerationSelect.value=t.hardwareAcceleration??"no-preference",this.keyFrameIntervalInput.value=String(t.keyFrameInterval??2),this.transparencyInput.checked=Boolean(t.transparent),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.keyFrameIntervalInput.refresh(),this.syncTransparencyAvailability()}resolveQuality(t){return"very-low"===t||"low"===t||"medium"===t||"high"===t||"very-high"===t?t:"medium"}handleQualityChange=()=>{this.isRecording()||this.syncReadyStatus(),this.syncOutputEstimate()};handleEstimateChange=()=>this.syncOutputEstimate();syncReadyStatus(){this.status.setMessage("constant quality; file size depends on content","neutral")}handleFormatChange=()=>{this.syncTransparencyAvailability(),this.syncOutputEstimate()};syncOutputEstimate(){if(!this.estimate.isMounted())return;const t=this.Ui.videoDimensionsProvider?.(),e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value);if(!t||!Number.isFinite(e)||!Number.isFinite(i)||i<=0)return void this.estimate.setMessage("logical dimensions · duration · size","neutral");const r={format:this.formatSelect.value,frameCount:Math.max(1,Math.round(e)),frameRate:i,quality:this.qualitySelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.parseFloat(this.keyFrameIntervalInput.value)||2,pixelDensity:1,width:t.width,height:t.height,transparent:"webm"===this.formatSelect.value&&this.transparencyInput.checked,debugLogging:!1};try{const t=U(r);this.estimate.setMessage(`${t.width}×${t.height} · ${(t.frameCount/t.frameRate).toFixed(1)}s · content-dependent size`,"neutral")}catch{this.estimate.setMessage(`${t.width}×${t.height} · MP4 requires even dimensions`,"alert")}}Bi(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.qualitySelect.selectElement.removeEventListener("change",this.handleQualityChange),this.formatSelect.selectElement.removeEventListener("change",this.handleFormatChange),this.formatSelect.selectElement.removeEventListener("change",this.handleEstimateChange),this.frameCountInput.inputElement.removeEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.removeEventListener("input",this.handleEstimateChange),super.Bi()}syncTransparencyAvailability(){if(!this.transparencyInput.isMounted())return;const t="webm"===this.formatSelect.value;this.transparencyInput.root.style.display=t?"":"none",this.transparencyInput.inputElement.disabled=!t||this.isRecording(),t||(this.transparencyInput.checked=!1)}};function Sa(t){return t.capabilities.recording}var Ca=Object.freeze({format:"txt",txt:Object.freeze({preserveTrailingSpaces:!1,emptyCharacter:" "}),json:Object.freeze({target:"selected",pretty:!0,includeMetadata:!0,colorMode:"hex"}),image:Object.freeze({format:"png",scale:1}),svg:Object.freeze({includeBackgroundRectangles:!0,drawMode:"fill",strokeWidth:1}),gif:Object.freeze({frameCount:300,frameRate:60,scale:1,repeat:0}),video:Object.freeze({format:"mp4",frameCount:480,frameRate:60,quality:"medium",hardwareAcceleration:"no-preference",keyFrameInterval:2,transparent:!1})});function Pa(){return{format:Ca.format,txt:{...Ca.txt},json:{...Ca.json},image:{...Ca.image},svg:{...Ca.svg},gif:{...Ca.gif},video:{...Ca.video}}}function Ia(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var Ba=class{Li;constructor(){this.Li=Pa()}get current(){return this.snapshot()}snapshot(){return{format:(t=this.Li).format,txt:{...t.txt},json:{...t.json},image:{...t.image},svg:{...t.svg},gif:{...t.gif},video:{...t.video}};var t}get(t){return this.Li[t]}merge(t){t.format&&(this.Li.format=t.format),t.txt&&Object.assign(this.Li.txt,t.txt),t.json&&Object.assign(this.Li.json,t.json),t.image&&Object.assign(this.Li.image,t.image),t.svg&&Object.assign(this.Li.svg,t.svg),t.gif&&Object.assign(this.Li.gif,t.gif),t.video&&Object.assign(this.Li.video,t.video)}reset(t){const e=Pa();if(!t)return this.Li.format=e.format,Ia(this.Li.txt,e.txt),Ia(this.Li.json,e.json),Ia(this.Li.image,e.image),Ia(this.Li.svg,e.svg),Ia(this.Li.gif,e.gif),void Ia(this.Li.video,e.video);switch(t){case"format":this.Li.format=e.format;break;case"txt":Ia(this.Li.txt,e.txt);break;case"json":Ia(this.Li.json,e.json);break;case"image":Ia(this.Li.image,e.image);break;case"svg":Ia(this.Li.svg,e.svg);break;case"gif":Ia(this.Li.gif,e.gif);break;case"video":Ia(this.Li.video,e.video)}}},Fa=class{T;qi;yi;Gi;Hi;Wi;Xi;Zi=new Map;Qi=[];Yi;Ji;Ki;tr;er;ir;rr=new Xs;nr=new Zs({label:"export format",labelFor:"textmode-export-format",variant:"full"});sr=new Qs({id:"textmode-export-format",options:[]});ar=new Ys({label:"download file",fullWidth:!0,variant:"primary"});hr=new Ys({label:"copy to clipboard",fullWidth:!0,variant:"primary"});cr;lr;dr=()=>{this.ur(this.sr.value)};pr=()=>{this.mr().catch(t=>{console.error("[textmode-export] Export failed",t)})};wr=()=>{this.vr().catch(t=>{console.error("[textmode-export] Copy failed",t)})};constructor(t,e,i,r){this.T=t,this.qi=i;const n=this.br(i.current.format,r);this.yi=new Ks((t=>({format:t,isBusy:!1}))(n)),this.Gi=new Js,this.Hi=new ra(e,this.Gi),this.Wi=new ea(e),this.Xi=r,this.cr=n,this.yr(),this.gr()}$mount(){this.Er(),this.Tr(),this.ir=new sa(this.T,this.Yi,this.Ki),this.ir.attachDragHandle(this.rr.dragHandleElement),this.ir.bind(),this.kr(this.cr)}show(){this.Yi&&(this.refreshLayerTargets(),this.Yi.style.display="",this.ir?.scheduleUpdate())}hide(){this.Yi&&(this.Yi.style.display="none")}toggle(){this.isVisible()?this.hide():this.show()}isVisible(){return!!this.Yi&&"none"!==this.Yi.style.display}refreshLayerTargets(){this.lr&&this.lr.blade.capabilities.layerTarget&&this.lr.blade.refreshLayerTargets()}resetPosition(){this.ir.resetPosition()}getPosition(){return this.ir.getPosition()}setPosition(t){this.ir.setPosition(t)}setDefaults(t){t.format&&this._r(t.format),this.qi.merge(t),this.Mr(this.Ar(t)),t.format&&this.ur(t.format)}getDefaults(){return this.qi.current}resetDefaults(t){this.qi.reset(t),"format"!==t?(this.Mr(t?[t]:void 0),t||this.ur(this.qi.current.format)):this.ur(this.qi.current.format)}$dispose(){this.sr.isMounted()&&this.sr.selectElement.removeEventListener("change",this.dr),this.ar.isMounted()&&this.ar.buttonElement.removeEventListener("click",this.pr),this.hr.isMounted()&&this.hr.buttonElement.removeEventListener("click",this.wr);for(const t of this.Qi)t();this.Qi.length=0,this.Gi.$clear();for(const t of this.Zi.values())t.blade.destroy();this.Zi.clear(),this.lr=void 0,this.Yi?.isConnected&&this.Yi.remove(),this.ir?.dispose()}Mr(t){const e=new Set(t??this.Zi.keys());for(const[i,r]of this.Zi)e.has(i)&&(r.blade.isMounted()?(r.blade.reset(),r.needsReset=!1):r.needsReset=!0)}yr(){for(const t of this.Xi){const e=t.createBlade();this.Zi.set(t.format,{definition:t,blade:e,initialized:!1,needsReset:!1})}}br(t,e){return e.some(e=>e.format===t)?t:e[0]?.format??t}Ar(t){return this.Xi.map(t=>t.format).filter(e=>void 0!==t[e])}_r(t){if(!this.Zi.has(t))throw new Error(`Unknown export format: ${t}`)}Er(){this.Yi=document.createElement("div"),this.Yi.dataset.plugin="textmode-export-overlay-host",this.Yi.style.cssText="position: absolute; top: 0; left: 0; pointer-events: none; z-index: 2147483647;",this.Ji=this.Yi.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent="@layer textmode-export-overlay{.textmode-export-overlay{--overlay-bg:#141414cc;--overlay-surface:#282828e6;--overlay-border:#ffffff24;--overlay-border-strong:#fff3;--overlay-border-focus:#a0a0a099;--overlay-focus-shadow:0 0 0 1px #8c8c8c47;--overlay-text:#fff;--overlay-muted:#c8c8c8bd;--overlay-radius:.75rem;--overlay-stack-gap:.55rem;gap:var(--overlay-stack-gap);background:var(--overlay-bg);min-width:236px;max-width:236px;color:var(--overlay-text);border-radius:var(--overlay-radius);border:1px solid var(--overlay-border);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);pointer-events:auto;z-index:2147483647;flex-direction:column;padding:.65rem .8rem;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:.82rem;line-height:1.35;display:flex;position:absolute;top:0;left:0;box-shadow:0 12px 28px #0000004d}.textmode-export-overlay *{box-sizing:border-box}.textmode-export-overlay__header{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__header-title-row{justify-content:space-between;align-items:center;gap:.4rem;display:flex}.textmode-export-overlay__header-identity{align-items:center;gap:.35rem;min-width:0;display:inline-flex}.textmode-export-overlay__header-links{flex:none;align-items:center;gap:.3rem;display:inline-flex}.textmode-export-overlay__grab-handle{color:#d7d7d7b8;cursor:grab;touch-action:none;background:0 0;border:1px solid #0000;border-radius:.45rem;flex:none;justify-content:center;align-items:center;width:1.45rem;height:1.45rem;padding:0;line-height:0;transition:background .18s,color .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__grab-handle:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__grab-handle:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay--dragging,.textmode-export-overlay--dragging .textmode-export-overlay__grab-handle{cursor:grabbing}.textmode-export-overlay__support-link{color:#d7d7d7d1;background:0 0;border:1px solid #0000;border-radius:.45rem;justify-content:center;align-items:center;padding:.2rem;line-height:0;text-decoration:none;transition:background .18s,color .18s,transform .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__support-link:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__support-link:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay__support-icon,.textmode-export-overlay__link-icon{width:1rem;height:1rem;display:block}.textmode-export-overlay__stack{gap:var(--overlay-stack-gap);flex-direction:column;display:flex}.textmode-export-overlay__stack--dense{gap:.3rem}.textmode-export-overlay__stack--compact{gap:.45rem}.textmode-export-overlay__section{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__title{white-space:nowrap;font-size:.92rem;font-weight:600}.textmode-export-overlay__divider{background:#ffffff29;width:100%;height:1px;margin-top:.25rem}.textmode-export-overlay__label{opacity:.9;font-weight:500}.textmode-export-overlay__checkbox{align-items:center;gap:.5rem;display:flex}.textmode-export-overlay__checkbox input[type=checkbox]{accent-color:#646464e6;width:1rem;height:1rem}.textmode-export-overlay__row{flex-wrap:wrap;align-items:flex-start;gap:.6rem;width:100%;display:flex}.textmode-export-overlay__field{flex-direction:column;flex:120px;gap:.3rem;min-width:120px;display:flex}.textmode-export-overlay__field--compact{flex:100px;min-width:100px}.textmode-export-overlay__field--dense{flex:90px;min-width:90px}.textmode-export-overlay__field--channel{flex:1 1 0;min-width:0}.textmode-export-overlay__field--full{flex:100%;width:100%}.textmode-export-overlay__input,.textmode-export-overlay select.textmode-export-overlay__input,.textmode-export-overlay input.textmode-export-overlay__input{border:1px solid var(--overlay-border-strong);background:var(--overlay-surface);width:100%;color:var(--overlay-text);font:inherit;border-radius:.4rem;padding:.35rem .5rem;line-height:1.35;transition:border-color .18s,box-shadow .18s,background .18s}.textmode-export-overlay select.textmode-export-overlay__input{appearance:none;background-image:url(\"data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='rgba(200, 200, 200, 0.74)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e\");background-position:right .5rem center;background-repeat:no-repeat;background-size:1rem;padding-right:2rem}.textmode-export-overlay__input:focus{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);background:#2d2f42eb;outline:none}.textmode-export-overlay__input::placeholder{color:var(--overlay-muted);opacity:.7}.textmode-export-overlay__muted{opacity:.7;font-size:.75rem;display:block}.textmode-export-overlay__button{cursor:pointer;border:none;border-radius:.45rem;justify-content:center;align-items:center;gap:.35rem;padding:.45rem .7rem;font-weight:600;transition:background .2s,transform .2s,box-shadow .2s;display:inline-flex}.textmode-export-overlay__button--primary{color:#fff;background:#505050}.textmode-export-overlay__button--secondary{color:#fff;background:#606060}.textmode-export-overlay__button--full{width:100%}.textmode-export-overlay__button:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 7px 18px #00000073}.textmode-export-overlay__button--primary:hover:not(:disabled){background:#404040}.textmode-export-overlay__button--secondary:hover:not(:disabled){background:#4a4a4a}.textmode-export-overlay__button:disabled{cursor:default;opacity:.55;box-shadow:none;transform:none}.textmode-export-overlay__status{background:#4646462e;border:1px solid #6e6e6e38;border-radius:.45rem;flex-direction:column;gap:.25rem;padding:.45rem .55rem;display:flex}.textmode-export-overlay__status--gif{background:#5050501f;border-color:#78787840}.textmode-export-overlay__status--video{background:#4646461f;border-color:#6e6e6e40}.textmode-export-overlay__status-title{opacity:.85;text-transform:uppercase;letter-spacing:.04em;font-size:.75rem;font-weight:600}.textmode-export-overlay__status-value{color:#dedede;font-size:.82rem;transition:color .18s}.textmode-export-overlay__status-value--neutral{color:#cfcfcf}.textmode-export-overlay__status-value--active{color:#f5f5f5}.textmode-export-overlay__status-value--alert{color:#b8b8b8}.textmode-export-number-input,.textmode-export-overlay .textmode-export-number-input{background:var(--overlay-surface);border:1px solid var(--overlay-border-strong);border-radius:.4rem;align-items:stretch;width:100%;transition:border-color .18s,box-shadow .18s,background .18s;display:flex;position:relative;overflow:hidden}.textmode-export-number-input:focus-within{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow)}.textmode-export-number-input.is-disabled{opacity:.55}.textmode-export-number-input__field{min-width:0;color:var(--overlay-text);font:inherit;appearance:textfield;background:0 0;border:none;flex:auto;padding:.35rem .5rem}.textmode-export-number-input__field::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field:focus{outline:none}.textmode-export-number-input__controls{border-left:1px solid #ffffff1f;flex-direction:column;min-width:1.6rem;display:flex}.textmode-export-number-input__control{color:#d0d0d0;cursor:pointer;background:#32323299;border:none;flex:1;justify-content:center;align-items:center;width:100%;padding:0;font-size:.68rem;line-height:1;transition:background .15s,color .15s;display:flex}.textmode-export-number-input__control:hover:not(:disabled){color:#fff;background:#5a5a5ad9}.textmode-export-number-input__control:disabled{cursor:default;opacity:.4;color:#c8c8c866;background:#28282880}.textmode-export-number-input:focus-within .textmode-export-number-input__control{color:#e8e8e8;background:#3c3c3cbf}.textmode-export-number-input__display{pointer-events:none;color:#f8fafc;opacity:0;align-items:center;padding:.4rem .55rem;transition:opacity .14s;display:flex;position:absolute;inset:0}.textmode-export-number-input__display--visible{opacity:1}}",this.Ji.appendChild(t),this.Ki=document.createElement("div"),this.Ki.dataset.plugin="textmode-export-overlay",this.Ki.classList.add("textmode-export-overlay",Ps),this.Ji.appendChild(this.Ki),document.body.appendChild(this.Yi)}Tr(){this.rr.mount(this.Ki);const t=document.createElement("div");t.classList.add(Fs),this.Ki.appendChild(t),this.nr.mount(t),this.Sr(),this.sr.mount(this.nr.root),this.sr.selectElement.addEventListener("change",this.dr),this.tr=document.createElement("div"),this.tr.classList.add(Ps,Bs),this.Ki.appendChild(this.tr),this.ar.mount(this.Ki),this.ar.buttonElement.addEventListener("click",this.pr),this.er=document.createElement("div"),this.er.classList.add(Ps,Is),this.Ki.appendChild(this.er),this.hr.mount(this.er),this.hr.buttonElement.dataset.defaultLabel="copy to clipboard",this.hr.buttonElement.addEventListener("click",this.wr)}Sr(){const t=this.Xi.map(t=>({value:t.format,label:t.label}));this.sr.update({options:t,defaultValue:this.cr})}gr(){this.Qi.push(this.Gi.$on("export:request",({format:t})=>{t===this.cr&&(this.yi.$set({isBusy:!0,error:void 0}),this.Cr())}),this.Gi.$on("export:success",({format:t})=>{if(t===this.cr){const e={isBusy:!1};"gif"===t&&(e.gifProgress=void 0),"video"===t&&(e.videoProgress=void 0),this.yi.$set(e),this.Cr()}}),this.Gi.$on("export:error",({format:t,error:e})=>{t===this.cr&&(this.yi.$set({isBusy:!1,error:e}),this.Cr())}),this.Gi.$on("export:progress",({format:t,progress:e})=>{if(e){if("gif"===t){const t=e;this.yi.$set({gifProgress:t}),"gif"===this.lr?.definition.format&&Sa(this.lr.blade)&&this.lr.blade.handleProgress(t)}else if("video"===t){const t=e;this.yi.$set({videoProgress:t}),"video"===this.lr?.definition.format&&Sa(this.lr.blade)&&this.lr.blade.handleProgress(t)}this.Cr()}}))}ur(t){this.cr=t,this.yi.$set({format:t}),this.kr(t),this.Gi.$emit("format:change",{format:t})}kr(t){const e=this.Zi.get(t);if(!e)throw new Error(`Unknown export format: ${t}`);this.lr&&this.lr.blade.unmount(),this.tr.innerHTML="",e.blade.mount(this.tr),e.initialized&&!e.needsReset||(e.blade.reset(),e.initialized=!0,e.needsReset=!1),this.lr=e,this.sr.value=t,this.refreshLayerTargets(),this.Pr(),this.Cr(),this.ir?.scheduleUpdate()}Pr(){const t=this.lr?.definition.supportsClipboard??!1;this.er.style.display=t?"flex":"none",this.hr.setDisabled(!t)}async mr(){if(!this.lr)return;const t=this.lr.definition.format,e=this.lr.blade.getOptions();if(this.lr.blade.validate()){if(Sa(this.lr.blade)){const r=this.lr.blade;if(r.isRecording())return;r.setRecordingState("recording");try{await this.Hi.$requestExport(t,e,{onGIFProgress:t=>{r.setRecordingState(t.state,t)},onVideoProgress:t=>{r.setRecordingState(t.state,t)}})}catch(i){throw r.setRecordingState("error"),i}return void window.setTimeout(()=>{r.setRecordingState("idle"),this.Cr()},1600)}this.ar.setDisabled(!0),this.ar.setLabel("exporting…");try{await this.Hi.$requestExport(t,e)}finally{this.ar.setDisabled(!1),this.ar.setLabel("download file")}}else console.warn("[textmode-export] Export options failed validation")}async vr(){if(!this.lr||!this.lr.definition.supportsClipboard)return;const t=this.lr.definition.format,e=this.lr.blade.getOptions(),i=this.hr.buttonElement.dataset.defaultLabel??"copy to clipboard";this.hr.setDisabled(!0),this.hr.setLabel("copying…");try{switch(t){case"txt":await this.Wi.$copy("txt",e);break;case"json":await this.Wi.$copy("json",e);break;case"svg":await this.Wi.$copy("svg",e);break;case"image":await this.Wi.$copy("image",e);break;default:return}this.hr.setLabel("copied!")}catch(r){console.error("[textmode-export] Failed to copy to clipboard",r),this.hr.setLabel("copy failed!")}finally{window.setTimeout(()=>{this.hr.setLabel(i),this.hr.setDisabled(!1)},1200)}}Cr(){if(!this.lr)return;const t=this.lr.definition.format;if(Sa(this.lr.blade)){const e=this.lr.blade,i="gif"===t?this.yi.snapshot.gifProgress:this.yi.snapshot.videoProgress;if(e.isRecording())if(this.ar.setDisabled(!0),i?.totalFrames){const e=i.frameIndex??0,r="encoding"===i.state?"encoding":"recording";this.ar.setLabel("gif"===t?`${r} ${e}/${i.totalFrames}`:`recording ${e}/${i.totalFrames} frames`)}else this.ar.setLabel("encoding"===i?.state?"encoding…":"recording…");else this.ar.setDisabled(!1),this.ar.setLabel("start recording");return}const e=this.yi.snapshot.isBusy;this.ar.setDisabled(e),this.ar.setLabel(e?"exporting…":"download file")}};var Oa=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob","saveZip","toZipBlob"],Ra=class{api;k;Ir=new Set;Br=new v;Fr;Or;v=!1;constructor(t,e){this.k=e;const i={saveCanvas:async(e={})=>(this.Rr(),(new A).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.Rr(),(new A).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.Rr(),(new A).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.Rr(),(new _).$saveSVG(t,e)},saveStrings:(e={})=>{this.Rr(),(new S).$saveTXT(t,e)},toSVG:(e={})=>(this.Rr(),(new _).$generateSVG(t,e)),toString:(e={})=>(this.Rr(),(new S).$generateTXT(t,e)),toJSON:(e={})=>(this.Rr(),(new So).$generateJSONData(t,e)),toJSONString:(e={})=>(this.Rr(),(new So).$generateJSONString(t,e)),saveJSON:(e={})=>{this.Rr(),(new So).$saveJSON(t,e)},saveGIF:(e={})=>this.$r("gif",e.signal,i=>new R(t,t=>this.k(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.$r("gif",e.signal,i=>new R(t,t=>this.k(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.$r("video",e.signal,i=>new Eo(t,t=>this.k(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.$r("video",e.signal,i=>new Eo(t,t=>this.k(t)).$generateVideoBlob({...e,signal:i})),saveZip:async e=>this.$r("zip",e?.signal,i=>new Cs(t,t=>this.k(t)).$saveZIP({...e,signal:i}),t=>this.Dr(e,t)),toZipBlob:async e=>this.$r("zip",e?.signal,i=>new Cs(t,t=>this.k(t)).$generateZIPBlob({...e,signal:i}),t=>this.Dr(e,t)),exportOverlay:void 0};this.api=i;const r=function(t,e,i){const r=new Ba,n=new Fa(t,e,r,function(t,e=(()=>{const t=Pa();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new da({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new ua({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new Ea({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Ta({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new Ma({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new Aa({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:e("video"),videoDimensionsProvider:i,videoDimensionsTarget:r})}]}(i,t=>r.get(t),()=>{const e=t.pixelDensity?.()??1;return{width:Math.max(1,Math.round(t.canvas.width/e)),height:Math.max(1,Math.round(t.canvas.height/e))}},t.canvas));try{n.$mount()}catch(o){throw n.$dispose(),o}return n}(t,i,function(t){return{getOptions:()=>u(t),getLayerById:e=>u(t).find(t=>t.id===e)?.layer,getDefaultId:()=>"base"}}(t));let n;try{n=this.k(()=>{!this.v&&r.isVisible()&&r.refreshLayerTargets()})}catch(o){throw r.$dispose(),o}this.Fr=r,this.Or=n,i.exportOverlay=this.Nr()}dispose(){if(!this.v){this.v=!0;for(const t of this.Ir)t.abort();this.Ir.clear(),this.Br.dispose(),this.Or(),this.Fr.$dispose()}}Nr(){return{show:()=>{this.Rr(),this.Fr.show()},hide:()=>{this.Rr(),this.Fr.hide()},toggle:()=>{this.Rr(),this.Fr.toggle()},isVisible:()=>(this.Rr(),this.Fr.isVisible()),resetPosition:()=>{this.Rr(),this.Fr.resetPosition()},getPosition:()=>(this.Rr(),this.Fr.getPosition()),setPosition:t=>{this.Rr(),this.Fr.setPosition(t)},setDefaults:t=>{this.Rr(),this.Fr.setDefaults(t)},getDefaults:()=>(this.Rr(),this.Fr.getDefaults()),resetDefaults:t=>{this.Rr(),this.Fr.resetDefaults(t)}}}Vr(t,e){this.Rr();const i=new AbortController,r=new AbortController,n=()=>r.abort(),o=()=>r.abort();return t?.addEventListener("abort",n,{once:!0}),i.signal.addEventListener("abort",o,{once:!0}),t?.aborted&&r.abort(),this.Ir.add(i),Promise.resolve().then(()=>e(r.signal)).finally(()=>{t?.removeEventListener("abort",n),i.signal.removeEventListener("abort",o),this.Ir.delete(i)})}$r(t,e,i,r){return this.Vr(e,async e=>{let n;try{n=this.Br.acquire()}catch(o){if("video"===t)throw V(o);if("zip"===t){const t=Io(o);throw r?.(t),t}throw o}try{return await i(e)}finally{n()}})}Dr(t,e){const i=t?.frameCount,r=Number.isInteger(i)&&i>=1&&i<=65534?i:300;t?.onProgress?.({state:"error",frameIndex:0,totalFrames:r,progress:0,message:e.message})}Rr(){if(this.v)throw new Error("Textmode export plugin has been disposed.")}},$a={name:"textmode.export.js",install(t,e){const i=new Ra(t,t=>e.on("postDraw",t));try{for(const t of Oa)e.defineExtension("textmodifier",t,{value:i.api[t]});e.defineExtension("textmodifier","exportOverlay",{get:()=>i.api.exportOverlay})}catch(r){throw i.dispose(),r}return()=>i.dispose()}};"undefined"!=typeof window&&(window.ExportPlugin=$a),t.ExportPlugin=$a,t.ZIPExportError=Co});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("textmode.js")):"function"==typeof define&&define.amd?define(["exports","textmode.js"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TextmodeExport={},t.textmode)}(this,function(t,e){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var i=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),r=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},n=new TextEncoder;function o(t,e){let i="",r=0;for(const o of t){const t=n.encode(o).byteLength;if(r+t>e)break;i+=o,r+=t}return i}var s=class{$resolve(t,e,i=new Date){const r=e.toLowerCase(),o=t?.trim(),s=o?.toLowerCase().endsWith(r)?o.slice(0,-r.length):o;return`${this.$sanitizeStem(s,i,255-n.encode(e).length)}${r}`}$sanitizeStem(t,e=new Date,i=255){const r=this.$defaultStem(e);return t?.trim()&&o(Array.from(t.normalize("NFC"),t=>{const e=t.codePointAt(0)??0;return e<32||127===e?"_":t}).join("").trim().replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/\.{2,}/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,""),i).replace(/[._]+$/g,"")||o(r,i)}$defaultStem(t=new Date){return`textmode-export-${t.toISOString().slice(0,19).replace(/:/g,"-")}`}},a=class{$downloadFile(t,e,i){const r=i?(new s).$resolve(e,i):(new s).$sanitizeStem(e),n=URL.createObjectURL(t),o=document.createElement("a");try{o.href=n,o.download=r,o.style.display="none",o.rel="noopener",document.body.appendChild(o),o.click()}finally{o.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}}},h=new WeakMap;function c(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function l(t,e){let i=h.get(t);if(!i){i=new Map;for(const e of t.characters)i.set(c(e.color),e);h.set(t,i)}return i.get(e)}function d(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function u(t){return[{id:"base",layer:t.layers.base},...t.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:d(t,e),layer:e}))}function f(t,e){const i=e??t.layers.base,r=function(t,e){if(e===t.layers.base)return"base";const i=t.layers.all.indexOf(e);if(i>=0)return`layer-${i+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")}(t,i),n=i.grid,o=i.font,s=i.drawFramebuffer;if(!n||!s)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:r,label:d(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}var p=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="FRAME_SEQUENCE_ABORTED"===t?"AbortError":"FrameSequenceError",this.code=t,this.cause=i}};function m(){return new p("FRAME_SEQUENCE_ABORTED","Frame-sequence capture was cancelled.")}function w(t){return t instanceof p&&"FRAME_SEQUENCE_ABORTED"===t.code||t instanceof DOMException&&"AbortError"===t.name}var v=class{m=!1;v=!1;acquire(){if(this.v)throw new p("FRAME_SEQUENCE_DISPOSED","The textmode export plugin has been disposed.");if(this.m)throw new p("FRAME_SEQUENCE_BUSY","Another deterministic frame capture is already active for this textmode instance.");this.m=!0;let t=!1;return()=>{t||(t=!0,this.m=!1)}}dispose(){this.v=!0}},b=1e6;function y(t,e){const i=Math.round(t*b/e),r=Math.max(i+1,Math.round((t+1)*b/e));return{startSeconds:i/b,centerSeconds:(i+Math.floor((r-i)/2))/b,endSeconds:r/b,durationSeconds:(r-i)/b}}var g=class{canvas;T;k;_;M;C=null;A=0;S=0;constructor(t,e,i){if(this.T=t,this.k=e,this.M=t.canvas,this.canvas=i?this.P(i):this.M,i){const t=this.canvas.getContext("2d");if(!t)throw new Error("Frame-sequence export requires a 2D canvas context for staging frames.");t.imageSmoothingEnabled=!1,this._=t}else this._=null}async $render(t){this.I(t.signal);const e=this.T,i=e.isLooping(),r=e.frameCount,n=e.millis,o="secs"in e,s=e.frameRate(),a=this.B(),h=this.F(),c=this.k(()=>this.$());try{e.noLoop(),this.A=r,this.S=n,this.O(o),this.R(t.frameRate,1e3/t.frameRate),this.D();for(let e=0;e<t.frameCount;e++){this.I(t.signal);const i=y(e,t.frameRate);this.A=r+e+1,this.S=1e3*i.startSeconds,await(t.prepareFrame?.({frameIndex:e,frameCount:t.frameCount,startSeconds:i.startSeconds,centerSeconds:i.centerSeconds,endSeconds:i.endSeconds,timeSeconds:i.startSeconds,frameRate:t.frameRate,signal:t.signal})),this.I(t.signal),await this.N(e,t.signal),this.I(t.signal),await t.onFrame({frameIndex:e,canvas:this.canvas}),this.I(t.signal)}}finally{try{c()}catch{}this.C?.reject(new Error("Frame-sequence rendering was interrupted.")),this.C=null,this.V(h),this.U(a),"number"==typeof s&&e.frameRate(s),i?e.loop():e.noLoop()}}N(t,e){if(this.C)throw new Error("A frame-sequence render is already pending.");return function(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(m());let s=!1;const a=t=>{s||(s=!0,clearTimeout(c),i?.removeEventListener("abort",h),t())},h=()=>a(()=>o(m())),c=setTimeout(()=>a(()=>o(function(t){return new p("FRAME_SEQUENCE_TIMEOUT",t,void 0)}(e))),r);i?.addEventListener("abort",h,{once:!0}),t.then(t=>a(()=>n(t)),t=>a(()=>o(t)))})}(new Promise((e,i)=>{this.C={frameIndex:t,resolve:e,reject:i};try{this.T.redraw(1)}catch(r){this.C=null,i(r)}}),`Frame ${t+1} did not render within 30000ms.`,e,3e4).catch(e=>{throw this.C?.frameIndex===t&&(this.C=null),e})}$(){const t=this.C;if(t)try{this._&&(this._.clearRect(0,0,this.canvas.width,this.canvas.height),this._.drawImage(this.M,0,0,this.M.width,this.M.height,0,0,this.canvas.width,this.canvas.height)),this.C=null,t.resolve()}catch(e){this.C=null,t.reject(e)}}P(t){const e=document.createElement("canvas");return e.width=Math.max(1,Math.round(t.width)),e.height=Math.max(1,Math.round(t.height)),e}B(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this.T,t),value:this.T[t]}))}F(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this.T,t),descriptor:Object.getOwnPropertyDescriptor(this.T,t)}))}O(t){Object.defineProperty(this.T,"frameCount",{configurable:!0,enumerable:!0,get:()=>this.A,set:t=>{this.A=t}}),Object.defineProperty(this.T,"millis",{configurable:!0,enumerable:!0,get:()=>this.S,set:t=>{this.S=t}}),t&&Object.defineProperty(this.T,"secs",{configurable:!0,enumerable:!0,get:()=>this.S/1e3,set:t=>{this.S=1e3*t}})}R(t,e){const i=this.T.frameRate;this.T.deltaTime=()=>e,this.T.frameRate=function(e){return void 0===e?t:i.call(this,e)}}D(){this.T.resizeCanvas=()=>{}}U(t){const e=this.T;for(const i of t)i.hadOwnProperty?e[i.key]=i.value:delete e[i.key]}V(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this.T,e.key,e.descriptor):delete this.T[e.key]}I(t){if(t?.aborted)throw m()}};function x(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var E=class extends r{j(t,e,i){return{x:t,y:e,cellX:t*i.cellWidth,cellY:e*i.cellHeight}}$extractSVGCellData(t,e){const i=[];let r=0;for(let n=0;n<e.rows;n++)for(let o=0;o<e.cols;o++){const s=4*r,a=this.$getEncodedCharacterValue(t.characterPixels,s);let h=x(t.primaryColorPixels,s),c=x(t.secondaryColorPixels,s);const l=this.$extractCellTransform(t.characterPixels,s);if(l.isInverted){const t=h;h=c,c=t}const d=this.j(o,n,e);i.push({encodedGlyphSlot:a,primaryColor:h,secondaryColor:c,transform:l,position:d}),r++}return i}},T=class{L(t,e,i,r,n){const o=n/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:i+e.xMin*o,y1:r+-e.yMax*o,x2:i+e.xMax*o,y2:r+-e.yMin*o}),toSVG:()=>this.q(e,i,r,o)}}q(t,e,i,r){if(!t||!t.xs)return"";const{xs:n,ys:o,endPts:s,flags:a}=t;if(!(n&&o&&s&&a))return"";let h="",c=0;for(let l=0;l<s.length;l++){const t=s[l];if(!(t<c)){if(t>=c){const s=e+n[c]*r,l=i-o[c]*r;h+=`M${s.toFixed(2)},${l.toFixed(2)}`;let d=c+1;for(;d<=t;)if(1&a[d]){const t=e+n[d]*r,s=i-o[d]*r;h+=`L${t.toFixed(2)},${s.toFixed(2)}`,d++}else{const s=e+n[d]*r,l=i-o[d]*r,u=d+1>t?c:d+1;if(1&a[u]){const t=e+n[u]*r,a=i-o[u]*r;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u+1}else{const t=(s+(e+n[u]*r))/2,a=(l+(i-o[u]*r))/2;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u}}h+="Z"}c=t+1}}return h}$generatePositionedCharacterPath(t,e,i,r,n,o,s,a){if(!a)return null;const h=e.font,c=s/h.head.unitsPerEm,l=i+(n-a.advanceWidth*c)/2,d=r+h.hhea.ascender*c;return this.L(h,a,l,d,s).toSVG()||null}},k=class{H;constructor(){this.H=new T}$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>"}G(t,e){const{transform:i,position:r}=t;if(!i.flipHorizontal&&!i.flipVertical&&!i.rotation)return"";const n=r.cellX+e.cellWidth/2,o=r.cellY+e.cellHeight/2,s=[];if(i.flipHorizontal||i.flipVertical){const t=i.flipHorizontal?-1:1,e=i.flipVertical?-1:1;s.push(`translate(${n} ${o})scale(${t} ${e})translate(${-n} ${-o})`)}return i.rotation&&s.push(`rotate(${i.rotation} ${n} ${o})`),` transform="${s.join(" ")}"`}W(t,e,i){if(!i.includeBackgroundRectangles||0===t.secondaryColor.a)return"";const{position:r}=t,{r:n,g:o,b:s,a}=t.secondaryColor,h=`rgba(${n},${o},${s},${a/255})`;return"stroke"===i.drawMode?`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${h}" fill="none" stroke-width="${i.strokeWidth}"/>`:`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${h}"/>`}X(t,e,i,r){const n=l(i,t.encodedGlyphSlot);if(!n)return"";const o=this.H.$generatePositionedCharacterPath(n.character,i,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,i.fontSize,n.glyphData);if(!o)return"";const{r:s,g:a,b:h,a:c}=t.primaryColor,d=`rgba(${s},${a},${h},${c/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.W(t,e,r);o&&n.push(o);const s=this.X(t,e,i,r);if(s){const i=this.G(t,e);n.push(i?`<g${i}>${s}</g>`:s)}return n.join("")}$generateSVGContent(t,e,i,r){const n=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)n.push(this.$generateCellContent(o,e,i,r));return n.push(this.$generateSVGFooter()),n.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}},_=class{Z(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 E,r=new k,n=this.Z(e),o=f(t,n.layer),s=i.$extractSVGCellData(i.$extractFramebufferData(o.drawFramebuffer),o.grid),a=r.$generateSVGContent(s,o.grid,o.font,n);return r.$optimizeSVGContent(a)}$saveSVG(t,e={}){(new a).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename,".svg")}},M={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},C=class{Z(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}Y(t){if(!(t.format in M))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},M[e.format])})}async $saveImage(t,e={}){const i=this.Z(e);this.Y(i);const r=await this.$toImageBlob(t,e);(new a).$downloadFile(r,i.filename,`.${i.format}`)}async $toImageBlob(t,e={}){const i=this.Z(e);return this.Y(i),this.$generateImageBlob(t,i)}async $copyImageToClipboard(t,e={}){if("undefined"==typeof navigator||!navigator.clipboard||"function"!=typeof navigator.clipboard.write)throw new Error("Clipboard API is not available in this environment");const i=this.Z(e);this.Y(i);const r=await this.$generateImageBlob(t,i),n=new ClipboardItem({[M[i.format]]:r});await navigator.clipboard.write([n])}},A=class{Z(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}J(t,e){const i=new r,n=f(t,e.layer),o=i.$extractFramebufferData(n.drawFramebuffer),s=[];let a=0;for(let r=0;r<n.grid.rows;r++){let t="";for(let r=0;r<n.grid.cols;r++){const r=4*a,s=i.$getEncodedCharacterValue(o.characterPixels,r);t+=l(n.font,s)?.character||e.emptyCharacter,a++}e.preserveTrailingSpaces||(t=t.trimEnd()),s.push(t)}return s.join("\n")}$generateTXT(t,e={}){return this.J(t,this.Z(e))}$saveTXT(t,e={}){const i=this.Z(e),r=this.J(t,i),n=new Blob([r],{type:"text/plain;charset=utf-8"});(new a).$downloadFile(n,i.filename,".txt")}},S=i(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>M,applyPalette:()=>b,default:()=>I,nearestColor:()=>_,nearestColorIndex:()=>T,nearestColorIndexWithDistance:()=>k,prequantize:()=>v,quantize:()=>f,snapColorsToPalette:()=>x});var i={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function r(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView:()=>i.subarray(0,e),bytes:()=>i.slice(0,e),writeByte(t){r(e+1),i[e]=t,e++},writeBytes(t,n=0,o=t.length){r(e+o);for(let r=0;r<o;r++)i[e++]=t[r+n]},writeBytesView(t,n=0,o=t.byteLength){r(e+o),i.set(t.subarray(n,n+o),e),e+=o}};function r(t){var r=i.length;if(r>=t)return;t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));const n=i;i=new Uint8Array(t),e>0&&i.set(n.subarray(0,e),0)}}var n=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],o=function(t,e,i,o,s=r(512),a=new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,v=m,b=(1<<v)-1;const y=1<<p-1,g=y+1;let x=y+2,E=0,T=i[0],k=0;for(let r=l;r<65536;r*=2)++k;k=8-k,s.writeByte(d),M(y);const _=i.length;for(let r=1;r<_;r++)t:{const t=i[r],e=(t<<12)+T;let n=t<<k^T;if(h[n]===e){T=c[n];break t}const o=0===n?1:l-n;for(;h[n]>=0;)if(n-=o,n<0&&(n+=l),h[n]===e){T=c[n];break t}M(T),T=t,x<4096?(c[n]=x++,h[n]=e):(h.fill(-1),x=y+2,w=!0,M(y))}return M(T),M(g),s.writeByte(0),s.bytesView();function M(t){for(u&=n[f],f>0?u|=t<<f:u=t,f+=v;f>=8;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;if((x>b||w)&&(w?(v=m,b=(1<<v)-1,w=!1):(++v,b=12===v?1<<v:(1<<v)-1)),t==g){for(;f>0;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;E>0&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0)}}};function s(t,e,i){return t<<8&63488|e<<2&992|i>>3}function a(t,e,i,r){return t>>4|240&e|(240&i)<<4|(240&r)<<8}function h(t,e,i){return t>>4<<8|240&e|i>>4}function c(t,e,i){return t<e?e:t>i?i:t}function l(t){return t*t}function d(t,e,i){var r=0,n=1e100;const o=t[e],s=o.cnt,a=o.ac,h=o.rc,c=o.gc,d=o.bc;for(var u=o.fw;0!=u;u=t[u].fw){const e=t[u],o=e.cnt,p=s*o/(s+o);if(!(p>=n)){var f=0;i&&(f+=p*l(e.ac-a))>=n||(f+=p*l(e.rc-h))>=n||(f+=p*l(e.gc-c))>=n||(f+=p*l(e.bc-d))>=n||(n=f,r=u)}}o.err=n,o.nn=r}function u(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function f(t,e,i={}){const{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:o=0,clearAlphaThreshold:f=0,oneBitAlpha:m=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");const w=new Uint32Array(t.buffer);let v=!1!==i.useSqrt;const b="rgba4444"===r,y=function(t,e){const i=new Array("rgb444"===e?4096:65536),r=t.length;if("rgba4444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>24&255,o=e>>16&255,s=e>>8&255,h=255&e,c=a(h,s,o,r);let l=c in i?i[c]:i[c]=u();l.rc+=h,l.gc+=s,l.bc+=o,l.ac+=r,l.cnt++}else if("rgb444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,s=255&e,a=h(s,o,r);let c=a in i?i[a]:i[a]=u();c.rc+=s,c.gc+=o,c.bc+=r,c.cnt++}else for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,a=255&e,h=s(a,o,r);let c=h in i?i[h]:i[h]=u();c.rc+=a,c.gc+=o,c.bc+=r,c.cnt++}return i}(w,r),g=y.length,x=g-1,E=new Uint32Array(g+1);for(var T=0,k=0;k<g;++k){const t=y[k];if(null!=t){var _=1/t.cnt;b&&(t.ac*=_),t.rc*=_,t.gc*=_,t.bc*=_,y[T++]=t}}var M,C,A;for(l(e)/T<.022&&(v=!1),k=0;k<T-1;++k)y[k].fw=k+1,y[k+1].bk=k,v&&(y[k].cnt=Math.sqrt(y[k].cnt));for(v&&(y[k].cnt=Math.sqrt(y[k].cnt)),k=0;k<T;++k){d(y,k,!1);var S=y[k].err;for(C=++E[0];C>1&&!(y[M=E[A=C>>1]].err<=S);C=A)E[C]=M;E[C]=k}var P=T-e;for(k=0;k<P;){for(var I;;){var B=E[1];if((I=y[B]).tm>=I.mtm&&y[I.nn].mtm<=I.tm)break;for(I.mtm==x?B=E[1]=E[E[0]--]:(d(y,B,!1),I.tm=k),S=y[B].err,C=1;(A=C+C)<=E[0]&&(A<E[0]&&y[E[A]].err>y[E[A+1]].err&&A++,!(S<=y[M=E[A]].err));C=A)E[C]=M;E[C]=B}var F=y[I.nn],$=I.cnt,O=F.cnt;_=1/($+O),b&&(I.ac=_*($*I.ac+O*F.ac)),I.rc=_*($*I.rc+O*F.rc),I.gc=_*($*I.gc+O*F.gc),I.bc=_*($*I.bc+O*F.bc),I.cnt+=F.cnt,I.mtm=++k,y[F.bk].fw=F.fw,y[F.fw].bk=F.bk,F.mtm=x}let R=[];var D=0;for(k=0;;++D){let t=c(Math.round(y[k].rc),0,255),e=c(Math.round(y[k].gc),0,255),i=c(Math.round(y[k].bc),0,255),r=255;b&&(r=c(Math.round(y[k].ac),0,255),m&&(r=r<=("number"==typeof m?m:127)?0:255),n&&r<=f&&(t=e=i=o,r=0));const s=b?[t,e,i,r]:[t,e,i];if(p(R,s)||R.push(s),0==(k=y[k].fw))break}return R}function p(t,e){for(let i=0;i<t.length;i++){const r=t[i];let n=r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2],o=!(r.length>=4&&e.length>=4)||r[3]===e[3];if(n&&o)return!0}return!1}function m(t,e){var i,r=0;for(i=0;i<t.length;i++){const n=t[i]-e[i];r+=n*n}return r}function w(t,e){return e>1?Math.round(t/e)*e:t}function v(t,{roundRGB:e=5,roundAlpha:i=10,oneBitAlpha:r=null}={}){const n=new Uint32Array(t.buffer);for(let o=0;o<n.length;o++){const t=n[o];let s=t>>24&255,a=t>>16&255,h=t>>8&255,c=255&t;s=w(s,i),r&&(s=s<=("number"==typeof r?r:127)?0:255),c=w(c,e),h=w(h,e),a=w(a,e),n[o]=s<<24|a<<16|h<<8|c}}function b(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");const r=new Uint32Array(t.buffer),n=r.length,o="rgb444"===i?4096:65536,c=new Uint8Array(n),l=new Array(o);if("rgba4444"===i)for(let s=0;s<n;s++){const t=r[s],i=t>>24&255,n=t>>16&255,o=t>>8&255,h=255&t,d=a(h,o,n,i);c[s]=d in l?l[d]:l[d]=y(h,o,n,i,e)}else{const t="rgb444"===i?h:s;for(let i=0;i<n;i++){const n=r[i],o=n>>16&255,s=n>>8&255,a=255&n,h=t(a,s,o);c[i]=h in l?l[h]:l[h]=g(a,s,o,e)}}return c}function y(t,e,i,r,n){let o=0,s=1e100;for(let a=0;a<n.length;a++){const h=n[a];let c=E(h[3]-r);c>s||(c+=E(h[0]-t),c>s||(c+=E(h[1]-e),c>s||(c+=E(h[2]-i),c>s||(s=c,o=a))))}return o}function g(t,e,i,r){let n=0,o=1e100;for(let s=0;s<r.length;s++){const a=r[s];let h=E(a[0]-t);h>o||(h+=E(a[1]-e),h>o||(h+=E(a[2]-i),h>o||(o=h,n=s)))}return n}function x(t,e,i=5){if(!t.length||!e.length)return;const r=t.map(t=>t.slice(0,3)),n=i*i,o=t[0].length;for(let s=0;s<e.length;s++){let i=e[s];i=i.length<o?[i[0],i[1],i[2],255]:i.length>o?i.slice(0,3):i.slice();const a=k(r,i.slice(0,3),m),h=a[0],c=a[1];c>0&&c<=n&&(t[h]=i)}}function E(t){return t*t}function T(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return n}function k(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return[n,r]}function _(t,e,i=m){return t[T(t,e,i)]}function M(t={}){const{initialCapacity:e=4096,auto:n=!0}=t,s=r(e),a=new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth:v=8,dispose:b=-1}=r;let y=!1;if(n?l||(y=!0,d(),l=!0):y=Boolean(r.first),e=Math.max(0,Math.floor(e)),i=Math.max(0,Math.floor(i)),y){if(!m)throw new Error("First frame must include a { palette } option");!function(t,e,i,r,n=8){const o=n-1<<4|128|P(r.length)-1;A(t,e),A(t,i),t.writeBytes([o,0,0])}(s,e,i,m,v),C(s,m),w>=0&&function(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),S(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),A(t,e),t.writeByte(0)}(s,w)}const g=Math.round(p/10);!function(t,e,i,r,n){var o,s;t.writeByte(33),t.writeByte(249),t.writeByte(4),n<0&&(n=0,r=!1),r?(o=1,s=2):(o=0,s=0),e>=0&&(s=7&e),s<<=2,t.writeByte(0|s|o),A(t,i),t.writeByte(n||0),t.writeByte(0)}(s,b,g,u,f);const x=Boolean(m)&&!y;!function(t,e,i,r){if(t.writeByte(44),A(t,0),A(t,0),A(t,e),A(t,i),r){const e=P(r.length)-1;t.writeByte(128|e)}else t.writeByte(0)}(s,e,i,x?m:null),x&&C(s,m),function(t,e,i,r,n=8,s,a,h){o(i,r,e,n,t,s,a,h)}(s,t,e,i,v,a,h,c)}};function d(){S(s,"GIF89a")}}function C(t,e){const i=1<<P(e.length);for(let r=0;r<i;r++){let i=[0,0,0];r<e.length&&(i=e[r]),t.writeByte(i[0]),t.writeByte(i[1]),t.writeByte(i[2])}}function A(t,e){t.writeByte(255&e),t.writeByte(e>>8&255)}function S(t,e){for(var i=0;i<e.length;i++)t.writeByte(e.charCodeAt(i))}function P(t){return Math.max(Math.ceil(Math.log2(t)),1)}var I=M}),P='(function() {\n\tvar r = ((t, r) => () => (r || (t((r = { exports: {} }).exports, r), t = null), r.exports))((t) => {\n\t\tvar r = Object.defineProperty;\n\t\tr(t, "__esModule", { value: !0 }), ((t, e) => {\n\t\t\tfor (var n in e) r(t, n, {\n\t\t\t\tget: e[n],\n\t\t\t\tenumerable: !0\n\t\t\t});\n\t\t})(t, {\n\t\t\tGIFEncoder: () => I,\n\t\t\tapplyPalette: () => b,\n\t\t\tdefault: () => x,\n\t\t\tnearestColor: () => C,\n\t\t\tnearestColorIndex: () => k,\n\t\t\tnearestColorIndexWithDistance: () => U,\n\t\t\tprequantize: () => A,\n\t\t\tquantize: () => y,\n\t\t\tsnapColorsToPalette: () => v\n\t\t});\n\t\tvar e = {\n\t\t\tsignature: "GIF",\n\t\t\tversion: "89a",\n\t\t\ttrailer: 59,\n\t\t\textensionIntroducer: 33,\n\t\t\tapplicationExtensionLabel: 255,\n\t\t\tgraphicControlExtensionLabel: 249,\n\t\t\timageSeparator: 44,\n\t\t\tsignatureSize: 3,\n\t\t\tversionSize: 3,\n\t\t\tglobalColorTableFlagMask: 128,\n\t\t\tcolorResolutionMask: 112,\n\t\t\tsortFlagMask: 8,\n\t\t\tglobalColorTableSizeMask: 7,\n\t\t\tapplicationIdentifierSize: 8,\n\t\t\tapplicationAuthCodeSize: 3,\n\t\t\tdisposalMethodMask: 28,\n\t\t\tuserInputFlagMask: 2,\n\t\t\ttransparentColorFlagMask: 1,\n\t\t\tlocalColorTableFlagMask: 128,\n\t\t\tinterlaceFlagMask: 64,\n\t\t\tidSortFlagMask: 32,\n\t\t\tlocalColorTableSizeMask: 7\n\t\t};\n\t\tfunction n(t = 256) {\n\t\t\tlet r = 0, e = new Uint8Array(t);\n\t\t\treturn {\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn e.buffer;\n\t\t\t\t},\n\t\t\t\treset() {\n\t\t\t\t\tr = 0;\n\t\t\t\t},\n\t\t\t\tbytesView: () => e.subarray(0, r),\n\t\t\t\tbytes: () => e.slice(0, r),\n\t\t\t\twriteByte(t) {\n\t\t\t\t\tn(r + 1), e[r] = t, r++;\n\t\t\t\t},\n\t\t\t\twriteBytes(t, o = 0, a = t.length) {\n\t\t\t\t\tn(r + a);\n\t\t\t\t\tfor (let n = 0; n < a; n++) e[r++] = t[n + o];\n\t\t\t\t},\n\t\t\t\twriteBytesView(t, o = 0, a = t.byteLength) {\n\t\t\t\t\tn(r + a), e.set(t.subarray(o, o + a), r), r += a;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction n(t) {\n\t\t\t\tvar n = e.length;\n\t\t\t\tif (n >= t) return;\n\t\t\t\tt = Math.max(t, n * (n < 1048576 ? 2 : 1.125) >>> 0), 0 != n && (t = Math.max(t, 256));\n\t\t\t\tconst o = e;\n\t\t\t\te = new Uint8Array(t), r > 0 && e.set(o.subarray(0, r), 0);\n\t\t\t}\n\t\t}\n\t\tvar o = [\n\t\t\t0,\n\t\t\t1,\n\t\t\t3,\n\t\t\t7,\n\t\t\t15,\n\t\t\t31,\n\t\t\t63,\n\t\t\t127,\n\t\t\t255,\n\t\t\t511,\n\t\t\t1023,\n\t\t\t2047,\n\t\t\t4095,\n\t\t\t8191,\n\t\t\t16383,\n\t\t\t32767,\n\t\t\t65535\n\t\t], a = function(t, r, e, a, i = n(512), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003)) {\n\t\t\tconst s = c.length, u = Math.max(2, a);\n\t\t\tl.fill(0), f.fill(0), c.fill(-1);\n\t\t\tlet p = 0, y = 0;\n\t\t\tconst h = u + 1, w = h;\n\t\t\tlet d = !1, A = w, b = (1 << A) - 1;\n\t\t\tconst M = 1 << h - 1, g = M + 1;\n\t\t\tlet v = M + 2, m = 0, k = e[0], U = 0;\n\t\t\tfor (let n = s; n < 65536; n *= 2) ++U;\n\t\t\tU = 8 - U, i.writeByte(u), I(M);\n\t\t\tconst C = e.length;\n\t\t\tfor (let n = 1; n < C; n++) t: {\n\t\t\t\tconst t = e[n], r = (t << 12) + k;\n\t\t\t\tlet o = t << U ^ k;\n\t\t\t\tif (c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tconst a = 0 === o ? 1 : s - o;\n\t\t\t\tfor (; c[o] >= 0;) if (o -= a, o < 0 && (o += s), c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tI(k), k = t, v < 4096 ? (f[o] = v++, c[o] = r) : (c.fill(-1), v = M + 2, d = !0, I(M));\n\t\t\t}\n\t\t\treturn I(k), I(g), i.writeByte(0), i.bytesView();\n\t\t\tfunction I(t) {\n\t\t\t\tfor (p &= o[y], y > 0 ? p |= t << y : p = t, y += A; y >= 8;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\tif ((v > b || d) && (d ? (A = w, b = (1 << A) - 1, d = !1) : (++A, b = 12 === A ? 1 << A : (1 << A) - 1)), t == g) {\n\t\t\t\t\tfor (; y > 0;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\t\tm > 0 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tfunction i(t, r, e) {\n\t\t\treturn t << 8 & 63488 | r << 2 & 992 | e >> 3;\n\t\t}\n\t\tfunction l(t, r, e, n) {\n\t\t\treturn t >> 4 | 240 & r | (240 & e) << 4 | (240 & n) << 8;\n\t\t}\n\t\tfunction c(t, r, e) {\n\t\t\treturn t >> 4 << 8 | 240 & r | e >> 4;\n\t\t}\n\t\tfunction f(t, r, e) {\n\t\t\treturn t < r ? r : t > e ? e : t;\n\t\t}\n\t\tfunction s(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction u(t, r, e) {\n\t\t\tvar n = 0, o = 1e100;\n\t\t\tconst a = t[r], i = a.cnt, l = a.ac, c = a.rc, f = a.gc, u = a.bc;\n\t\t\tfor (var p = a.fw; 0 != p; p = t[p].fw) {\n\t\t\t\tconst r = t[p], a = r.cnt, h = i * a / (i + a);\n\t\t\t\tif (!(h >= o)) {\n\t\t\t\t\tvar y = 0;\n\t\t\t\t\te && (y += h * s(r.ac - l)) >= o || (y += h * s(r.rc - c)) >= o || (y += h * s(r.gc - f)) >= o || (y += h * s(r.bc - u)) >= o || (o = y, n = p);\n\t\t\t\t}\n\t\t\t}\n\t\t\ta.err = o, a.nn = n;\n\t\t}\n\t\tfunction p() {\n\t\t\treturn {\n\t\t\t\tac: 0,\n\t\t\t\trc: 0,\n\t\t\t\tgc: 0,\n\t\t\t\tbc: 0,\n\t\t\t\tcnt: 0,\n\t\t\t\tnn: 0,\n\t\t\t\tfw: 0,\n\t\t\t\tbk: 0,\n\t\t\t\ttm: 0,\n\t\t\t\tmtm: 0,\n\t\t\t\terr: 0\n\t\t\t};\n\t\t}\n\t\tfunction y(t, r, e = {}) {\n\t\t\tconst { format: n = "rgb565", clearAlpha: o = !0, clearAlphaColor: a = 0, clearAlphaThreshold: y = 0, oneBitAlpha: w = !1 } = e;\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tconst d = new Uint32Array(t.buffer);\n\t\t\tlet A = !1 !== e.useSqrt;\n\t\t\tconst b = "rgba4444" === n, M = function(t, r) {\n\t\t\t\tconst e = new Array("rgb444" === r ? 4096 : 65536), n = t.length;\n\t\t\t\tif ("rgba4444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 24 & 255, a = r >> 16 & 255, i = r >> 8 & 255, c = 255 & r, f = l(c, i, a, n);\n\t\t\t\t\tlet s = f in e ? e[f] : e[f] = p();\n\t\t\t\t\ts.rc += c, s.gc += i, s.bc += a, s.ac += n, s.cnt++;\n\t\t\t\t}\n\t\t\t\telse if ("rgb444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, i = 255 & r, l = c(i, a, n);\n\t\t\t\t\tlet f = l in e ? e[l] : e[l] = p();\n\t\t\t\t\tf.rc += i, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\telse for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, l = 255 & r, c = i(l, a, n);\n\t\t\t\t\tlet f = c in e ? e[c] : e[c] = p();\n\t\t\t\t\tf.rc += l, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\treturn e;\n\t\t\t}(d, n), g = M.length, v = g - 1, m = new Uint32Array(g + 1);\n\t\t\tfor (var k = 0, U = 0; U < g; ++U) {\n\t\t\t\tconst t = M[U];\n\t\t\t\tif (null != t) {\n\t\t\t\t\tvar C = 1 / t.cnt;\n\t\t\t\t\tb && (t.ac *= C), t.rc *= C, t.gc *= C, t.bc *= C, M[k++] = t;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar I, F, z;\n\t\t\tfor (s(r) / k < .022 && (A = !1), U = 0; U < k - 1; ++U) M[U].fw = U + 1, M[U + 1].bk = U, A && (M[U].cnt = Math.sqrt(M[U].cnt));\n\t\t\tfor (A && (M[U].cnt = Math.sqrt(M[U].cnt)), U = 0; U < k; ++U) {\n\t\t\t\tu(M, U, !1);\n\t\t\t\tvar B = M[U].err;\n\t\t\t\tfor (F = ++m[0]; F > 1 && !(M[I = m[z = F >> 1]].err <= B); F = z) m[F] = I;\n\t\t\t\tm[F] = U;\n\t\t\t}\n\t\t\tvar E = k - r;\n\t\t\tfor (U = 0; U < E;) {\n\t\t\t\tfor (var x;;) {\n\t\t\t\t\tvar G = m[1];\n\t\t\t\t\tif ((x = M[G]).tm >= x.mtm && M[x.nn].mtm <= x.tm) break;\n\t\t\t\t\tfor (x.mtm == v ? G = m[1] = m[m[0]--] : (u(M, G, !1), x.tm = U), B = M[G].err, F = 1; (z = F + F) <= m[0] && (z < m[0] && M[m[z]].err > M[m[z + 1]].err && z++, !(B <= M[I = m[z]].err)); F = z) m[F] = I;\n\t\t\t\t\tm[F] = G;\n\t\t\t\t}\n\t\t\t\tvar S = M[x.nn], T = x.cnt, q = S.cnt;\n\t\t\t\tC = 1 / (T + q), b && (x.ac = C * (T * x.ac + q * S.ac)), x.rc = C * (T * x.rc + q * S.rc), x.gc = C * (T * x.gc + q * S.gc), x.bc = C * (T * x.bc + q * S.bc), x.cnt += S.cnt, x.mtm = ++U, M[S.bk].fw = S.fw, M[S.fw].bk = S.bk, S.mtm = v;\n\t\t\t}\n\t\t\tlet R = [];\n\t\t\tvar P = 0;\n\t\t\tfor (U = 0;; ++P) {\n\t\t\t\tlet t = f(Math.round(M[U].rc), 0, 255), r = f(Math.round(M[U].gc), 0, 255), e = f(Math.round(M[U].bc), 0, 255), n = 255;\n\t\t\t\tb && (n = f(Math.round(M[U].ac), 0, 255), w && (n = n <= ("number" == typeof w ? w : 127) ? 0 : 255), o && n <= y && (t = r = e = a, n = 0));\n\t\t\t\tconst i = b ? [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te,\n\t\t\t\t\tn\n\t\t\t\t] : [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te\n\t\t\t\t];\n\t\t\t\tif (h(R, i) || R.push(i), 0 == (U = M[U].fw)) break;\n\t\t\t}\n\t\t\treturn R;\n\t\t}\n\t\tfunction h(t, r) {\n\t\t\tfor (let e = 0; e < t.length; e++) {\n\t\t\t\tconst n = t[e];\n\t\t\t\tlet o = n[0] === r[0] && n[1] === r[1] && n[2] === r[2], a = !(n.length >= 4 && r.length >= 4) || n[3] === r[3];\n\t\t\t\tif (o && a) return !0;\n\t\t\t}\n\t\t\treturn !1;\n\t\t}\n\t\tfunction w(t, r) {\n\t\t\tvar e, n = 0;\n\t\t\tfor (e = 0; e < t.length; e++) {\n\t\t\t\tconst o = t[e] - r[e];\n\t\t\t\tn += o * o;\n\t\t\t}\n\t\t\treturn n;\n\t\t}\n\t\tfunction d(t, r) {\n\t\t\treturn r > 1 ? Math.round(t / r) * r : t;\n\t\t}\n\t\tfunction A(t, { roundRGB: r = 5, roundAlpha: e = 10, oneBitAlpha: n = null } = {}) {\n\t\t\tconst o = new Uint32Array(t.buffer);\n\t\t\tfor (let a = 0; a < o.length; a++) {\n\t\t\t\tconst t = o[a];\n\t\t\t\tlet i = t >> 24 & 255, l = t >> 16 & 255, c = t >> 8 & 255, f = 255 & t;\n\t\t\t\ti = d(i, e), n && (i = i <= ("number" == typeof n ? n : 127) ? 0 : 255), f = d(f, r), c = d(c, r), l = d(l, r), o[a] = i << 24 | l << 16 | c << 8 | f;\n\t\t\t}\n\t\t}\n\t\tfunction b(t, r, e = "rgb565") {\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (r.length > 256) throw new Error("applyPalette() only works with 256 colors or less");\n\t\t\tconst n = new Uint32Array(t.buffer), o = n.length, a = "rgb444" === e ? 4096 : 65536, f = new Uint8Array(o), s = new Array(a);\n\t\t\tif ("rgba4444" === e) for (let i = 0; i < o; i++) {\n\t\t\t\tconst t = n[i], e = t >> 24 & 255, o = t >> 16 & 255, a = t >> 8 & 255, c = 255 & t, u = l(c, a, o, e);\n\t\t\t\tf[i] = u in s ? s[u] : s[u] = M(c, a, o, e, r);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst t = "rgb444" === e ? c : i;\n\t\t\t\tfor (let e = 0; e < o; e++) {\n\t\t\t\t\tconst o = n[e], a = o >> 16 & 255, i = o >> 8 & 255, l = 255 & o, c = t(l, i, a);\n\t\t\t\t\tf[e] = c in s ? s[c] : s[c] = g(l, i, a, r);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn f;\n\t\t}\n\t\tfunction M(t, r, e, n, o) {\n\t\t\tlet a = 0, i = 1e100;\n\t\t\tfor (let l = 0; l < o.length; l++) {\n\t\t\t\tconst c = o[l];\n\t\t\t\tlet f = m(c[3] - n);\n\t\t\t\tf > i || (f += m(c[0] - t), f > i || (f += m(c[1] - r), f > i || (f += m(c[2] - e), f > i || (i = f, a = l))));\n\t\t\t}\n\t\t\treturn a;\n\t\t}\n\t\tfunction g(t, r, e, n) {\n\t\t\tlet o = 0, a = 1e100;\n\t\t\tfor (let i = 0; i < n.length; i++) {\n\t\t\t\tconst l = n[i];\n\t\t\t\tlet c = m(l[0] - t);\n\t\t\t\tc > a || (c += m(l[1] - r), c > a || (c += m(l[2] - e), c > a || (a = c, o = i)));\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction v(t, r, e = 5) {\n\t\t\tif (!t.length || !r.length) return;\n\t\t\tconst n = t.map((t) => t.slice(0, 3)), o = e * e, a = t[0].length;\n\t\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\t\tlet e = r[i];\n\t\t\t\te = e.length < a ? [\n\t\t\t\t\te[0],\n\t\t\t\t\te[1],\n\t\t\t\t\te[2],\n\t\t\t\t\t255\n\t\t\t\t] : e.length > a ? e.slice(0, 3) : e.slice();\n\t\t\t\tconst l = U(n, e.slice(0, 3), w), c = l[0], f = l[1];\n\t\t\t\tf > 0 && f <= o && (t[c] = e);\n\t\t\t}\n\t\t}\n\t\tfunction m(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction k(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction U(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn [o, n];\n\t\t}\n\t\tfunction C(t, r, e = w) {\n\t\t\treturn t[k(t, r, e)];\n\t\t}\n\t\tfunction I(t = {}) {\n\t\t\tconst { initialCapacity: r = 4096, auto: o = !0 } = t, i = n(r), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003);\n\t\t\tlet s = !1;\n\t\t\treturn {\n\t\t\t\treset() {\n\t\t\t\t\ti.reset(), s = !1;\n\t\t\t\t},\n\t\t\t\tfinish() {\n\t\t\t\t\ti.writeByte(e.trailer);\n\t\t\t\t},\n\t\t\t\tbytes: () => i.bytes(),\n\t\t\t\tbytesView: () => i.bytesView(),\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn i.buffer;\n\t\t\t\t},\n\t\t\t\tget stream() {\n\t\t\t\t\treturn i;\n\t\t\t\t},\n\t\t\t\twriteHeader: u,\n\t\t\t\twriteFrame(t, r, e, n = {}) {\n\t\t\t\t\tconst { transparent: p = !1, transparentIndex: y = 0, delay: h = 0, palette: w = null, repeat: d = 0, colorDepth: A = 8, dispose: b = -1 } = n;\n\t\t\t\t\tlet M = !1;\n\t\t\t\t\tif (o ? s || (M = !0, u(), s = !0) : M = Boolean(n.first), r = Math.max(0, Math.floor(r)), e = Math.max(0, Math.floor(e)), M) {\n\t\t\t\t\t\tif (!w) throw new Error("First frame must include a { palette } option");\n\t\t\t\t\t\t(function(t, r, e, n, o = 8) {\n\t\t\t\t\t\t\tconst a = o - 1 << 4 | 128 | E(n.length) - 1;\n\t\t\t\t\t\t\tz(t, r), z(t, e), t.writeBytes([\n\t\t\t\t\t\t\t\ta,\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t0\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t})(i, r, e, w, A), F(i, w), d >= 0 && function(t, r) {\n\t\t\t\t\t\t\tt.writeByte(33), t.writeByte(255), t.writeByte(11), B(t, "NETSCAPE2.0"), t.writeByte(3), t.writeByte(1), z(t, r), t.writeByte(0);\n\t\t\t\t\t\t}(i, d);\n\t\t\t\t\t}\n\t\t\t\t\tconst g = Math.round(h / 10);\n\t\t\t\t\t(function(t, r, e, n, o) {\n\t\t\t\t\t\tvar a, i;\n\t\t\t\t\t\tt.writeByte(33), t.writeByte(249), t.writeByte(4), o < 0 && (o = 0, n = !1), n ? (a = 1, i = 2) : (a = 0, i = 0), r >= 0 && (i = 7 & r), i <<= 2, t.writeByte(0 | i | a), z(t, e), t.writeByte(o || 0), t.writeByte(0);\n\t\t\t\t\t})(i, b, g, p, y);\n\t\t\t\t\tconst v = Boolean(w) && !M;\n\t\t\t\t\t(function(t, r, e, n) {\n\t\t\t\t\t\tif (t.writeByte(44), z(t, 0), z(t, 0), z(t, r), z(t, e), n) {\n\t\t\t\t\t\t\tconst r = E(n.length) - 1;\n\t\t\t\t\t\t\tt.writeByte(128 | r);\n\t\t\t\t\t\t} else t.writeByte(0);\n\t\t\t\t\t})(i, r, e, v ? w : null), v && F(i, w), function(t, r, e, n, o = 8, i, l, c) {\n\t\t\t\t\t\ta(e, n, r, o, t, i, l, c);\n\t\t\t\t\t}(i, t, r, e, A, l, c, f);\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction u() {\n\t\t\t\tB(i, "GIF89a");\n\t\t\t}\n\t\t}\n\t\tfunction F(t, r) {\n\t\t\tconst e = 1 << E(r.length);\n\t\t\tfor (let n = 0; n < e; n++) {\n\t\t\t\tlet e = [\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\t0\n\t\t\t\t];\n\t\t\t\tn < r.length && (e = r[n]), t.writeByte(e[0]), t.writeByte(e[1]), t.writeByte(e[2]);\n\t\t\t}\n\t\t}\n\t\tfunction z(t, r) {\n\t\t\tt.writeByte(255 & r), t.writeByte(r >> 8 & 255);\n\t\t}\n\t\tfunction B(t, r) {\n\t\t\tfor (var e = 0; e < r.length; e++) t.writeByte(r.charCodeAt(e));\n\t\t}\n\t\tfunction E(t) {\n\t\t\treturn Math.max(Math.ceil(Math.log2(t)), 1);\n\t\t}\n\t\tvar x = I;\n\t})();\n\tconst e = (0, r.GIFEncoder)();\n\tlet n = 1, o = 1, a = 16, i = 0;\n\tconst l = self;\n\tl.addEventListener("message", (t) => {\n\t\tconst c = t.data;\n\t\ttry {\n\t\t\tif ("init" === c.type) return n = c.width ?? n, o = c.height ?? o, a = c.delay ?? a, i = c.repeat ?? i, void l.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "ready"\n\t\t\t});\n\t\t\tif ("frame" === c.type && c.buffer) {\n\t\t\t\tconst t = new Uint8ClampedArray(c.buffer), f = (0, r.quantize)(t, 256, {}), s = (0, r.applyPalette)(t, f);\n\t\t\t\te.writeFrame(s, n, o, {\n\t\t\t\t\tpalette: f,\n\t\t\t\t\tdelay: a,\n\t\t\t\t\trepeat: 0 === c.frameIndex ? i : -1\n\t\t\t\t}), l.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "frame-complete"\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ("finish" === c.type) {\n\t\t\t\te.finish();\n\t\t\t\tconst t = e.bytes(), r = t.buffer.slice(t.byteOffset, t.byteOffset + t.byteLength);\n\t\t\t\tl.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "complete",\n\t\t\t\t\tbuffer: r\n\t\t\t\t}, [r]);\n\t\t\t}\n\t\t} catch (f) {\n\t\t\tl.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "error",\n\t\t\t\tmessage: f instanceof Error ? f.message : "GIF worker failed"\n\t\t\t});\n\t\t}\n\t});\n})();\n',I="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",P],{type:"text/javascript;charset=utf-8"});function B(t){let e;try{if(e=I&&(self.URL||self.webkitURL).createObjectURL(I),!e)throw"";const i=new Worker(e,{name:t?.name});return i.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),i}catch(i){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(P),{name:t?.name})}}var F=class{K;tt=new Map;et;it=0;v=!1;constructor(t,e,i,r,n){this.K=new B,this.K.addEventListener("message",this.rt),this.K.addEventListener("error",this.nt),n?.addEventListener("abort",this.dispose,{once:!0}),this.et=this.ot({type:"init",width:t,height:e,delay:Math.round(1e3/i),repeat:r})}async encodeFrame(t,e){await this.et,await this.ot({type:"frame",buffer:t,frameIndex:e},[t])}async finish(){await this.et;const t=await this.ot({type:"finish"});if(!t.buffer)throw new Error("GIF worker returned no encoded output.");return t.buffer}dispose=()=>{if(!this.v){this.v=!0,this.K.terminate();for(const t of this.tt.values())t.reject(new DOMException("GIF export was cancelled.","AbortError"));this.tt.clear()}};ot(t,e=[]){if(this.v)return Promise.reject(new DOMException("GIF export was cancelled.","AbortError"));const i=++this.it;return new Promise((r,n)=>{this.tt.set(i,{resolve:r,reject:n}),this.K.postMessage({...t,id:i},e)})}rt=t=>{const e=t.data,i=this.tt.get(e.id);i&&(this.tt.delete(e.id),"error"!==e.type?i.resolve(e):i.reject(new Error(e.message??"GIF worker failed")))};nt=t=>{const e=new Error(t.message||"GIF worker failed");for(const i of this.tt.values())i.reject(e);this.tt.clear()}},$=S(),O=class{T;k;constructor(t,e){this.T=t,this.k=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new a).$downloadFile(e,t.filename,".gif")}async $generateGIFBlob(t={}){const e=this.Z(t),i=this.T.canvas,r=Math.max(1,Math.round(i.width*e.scale)),n=Math.max(1,Math.round(i.height*e.scale)),o=new g(this.T,this.k,{width:r,height:n}),s=o.canvas.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("GIF export requires a 2D canvas context.");const a="undefined"==typeof Worker?(0,$.GIFEncoder)():null,h="undefined"==typeof Worker?null:new F(r,n,e.frameRate,e.repeat,e.signal);try{let i;if(this.I(e.signal),await o.$render({frameCount:e.frameCount,frameRate:e.frameRate,signal:e.signal,prepareFrame:e.prepareFrame,onFrame:async({frameIndex:i,canvas:r})=>{this.I(e.signal);const n=s.getImageData(0,0,r.width,r.height);if(h)await h.encodeFrame(n.data.buffer,i);else if(a){const t=n.data,o=(0,$.quantize)(t,256,{}),s=(0,$.applyPalette)(t,o);a.writeFrame(s,r.width,r.height,{palette:o,delay:Math.round(1e3/e.frameRate),repeat:0===i?e.repeat:-1})}t.onProgress?.({state:"encoding",frameIndex:i+1,totalFrames:e.frameCount}),(i+1)%2==0&&await this.st(e.signal)}}),this.I(e.signal),h)i=await h.finish();else{if(!a)throw new Error("No GIF encoder is available.");{a.finish();const t=a.bytes();i=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}return t.onProgress?.({state:"completed",totalFrames:e.frameCount}),new Blob([i],{type:"image/gif"})}catch(c){throw t.onProgress?.({state:"error",message:c instanceof Error?c.message:"GIF export failed"}),c}finally{h?.dispose()}}Z(t){return{filename:t.filename,frameCount:Math.max(1,Math.abs(Math.round(t.frameCount??300))),frameRate:Math.max(1,Math.abs(t.frameRate??60)),scale:Math.max(Number.EPSILON,Math.abs(t.scale??1)),repeat:Math.max(-1,Math.round(t.repeat??0)),signal:t.signal,prepareFrame:t.prepareFrame}}I(t){if(t?.aborted)throw new DOMException("GIF export was cancelled.","AbortError")}st(t){return new Promise((e,i)=>{t?.aborted?i(new DOMException("GIF export was cancelled.","AbortError")):setTimeout(e,0)})}},R=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function D(){return new R("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function N(t,e){return new R("VIDEO_EXPORT_TIMEOUT",t,e)}function V(t){return t instanceof R?t:w(t)?D():t instanceof p&&"FRAME_SEQUENCE_TIMEOUT"===t.code?N(t.message,t):new R("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}function U(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new R("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const i=Math.max(1,Math.round(t.width)),r=Math.max(1,Math.round(t.height));if("mp4"===t.format&&(i%2!=0||r%2!=0))throw new R("VIDEO_DIMENSIONS_UNSUPPORTED",`MP4/H.264 requires even dimensions; received ${i}x${r}. Increase pixel density or choose WebM.`);return{format:t.format,extension:"mp4"===t.format?".mp4":".webm",mimeType:"mp4"===t.format?"video/mp4":"video/webm",codec:e,quality:t.quality,hardwareAcceleration:t.hardwareAcceleration,keyFrameInterval:t.keyFrameInterval,frameRate:t.frameRate,frameCount:t.frameCount,width:i,height:r,transparent:t.transparent}}function z(t){if(!t)throw new Error("Assertion failed.")}var j,L=Math.PI/180,q=180/Math.PI,H=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},G=[1,0,0,0,1,0,0,0,1],W=t=>{const e=t*L,i=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[i,r,0,-r,i,0,0,0,1]},X=(t,e)=>[1,0,0,0,1,0,t,e,1],Z=(t,e)=>{const i=new Array(9);for(let r=0;r<3;r++)for(let n=0;n<3;n++)i[3*r+n]=t[3*r]*e[n]+t[3*r+1]*e[3+n]+t[3*r+2]*e[6+n];return i},Q=t=>t&&t[t.length-1],Y=t=>t>=0&&t<2**32,J=t=>{let e=0;for(;0===t.readBits(1)&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return 2**e-1+t.readBits(e)},K=t=>{const e=J(t);return e%2==0?-e/2:(e+1)/2},tt=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),et=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),it=void 0!==globalThis.TextEncoder?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(t=""){const e=new Uint8Array(3*t.length);let i=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);if(n<128)e[i++]=n;else if(n<2048)e[i++]=192|n>>6,e[i++]=128|63&n;else if(n<55296||n>57343)e[i++]=224|n>>12,e[i++]=128|n>>6&63,e[i++]=128|63&n;else{const o=r+1<t.length?t.charCodeAt(r+1):0;n<56320&&o>=56320&&o<=57343?(n=65536+(n-55296<<10)+(o-56320),r++,e[i++]=240|n>>18,e[i++]=128|n>>12&63,e[i++]=128|n>>6&63,e[i++]=128|63&n):(e[i++]=239,e[i++]=191,e[i++]=189)}}return e.slice(0,i)}},rt=(void 0!==globalThis.TextDecoder&&globalThis.TextDecoder,new it),nt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ot={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},st={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},at=t=>!t||null==t.primaries&&null==t.transfer&&null==t.matrix&&null==t.fullRange,ht=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),ct=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(e=>{let i=!1;t=()=>{i||(e(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=e,this.pending++,await i,t}},lt=t=>[...t].map(t=>t.toString(16).padStart(2,"0")).join(""),dt=t=>(t=(t=(t=(t=(t=t>>1&1431655765|(1431655765&t)<<1)>>2&858993459|(858993459&t)<<2)>>4&252645135|(252645135&t)<<4)>>8&16711935|(16711935&t)<<8)>>16&65535|(65535&t)<<16)>>>0,ut=(t,e,i)=>{let r=0,n=t.length-1,o=-1;for(;r<=n;){const s=r+(n-r+1)/2|0;i(t[s])<=e?(o=s,r=s+1):n=s-1}return o},ft=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},pt=t=>{throw new Error(`Unexpected value: ${t}`)},mt=(t,e,i)=>{const r=t.getUint8(e),n=t.getUint8(e+1),o=t.getUint8(e+2);return i?r|n<<8|o<<16:r<<16|n<<8|o},wt=(t,e,i)=>Math.max(e,Math.min(i,t)),vt=(t,e)=>Math.round(t/e)*e,bt=(t,e)=>Math.round(t*e)/e,yt=(t,e)=>Math.floor(t*e)/e,gt=t=>{let e=0;for(;0!==t;)t&=t-1,e++;return e},xt=/^[a-z]{3}$/,Et=1e6*(1+Number.EPSILON),Tt=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},kt=null,_t=()=>null!==kt?kt:kt=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Mt=null,Ct=()=>null!==Mt?Mt:Mt="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),At=null,St=()=>null!==At?At:At=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),Pt=null,It=(async()=>{})().constructor,Bt=t=>t instanceof It||t instanceof Promise||"function"==typeof t?.then,Ft=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},$t=t=>{switch(t.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},Ot=(t,e)=>{if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0},Rt=t=>"number"==typeof t&&!Number.isNaN(t),Dt=t=>{z(Number.isInteger(t.num)),z(Number.isInteger(t.den)),z(0!==t.den);let e=Math.abs(t.num),i=Math.abs(t.den);for(;0!==i;){const t=e%i;e=i,i=t}const r=e||1;return{num:t.num/r,den:t.den/r}},Nt=(t,e)=>{if("object"!=typeof t||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},Vt=t=>Array.isArray(t)?t:[t],Ut=class{constructor(){this.ht=new Map}on(t,e,i){this.ht.has(t)||this.ht.set(t,new Set);const r={fn:e,once:i?.once??!1};return this.ht.get(t).add(r),()=>{this.ht.get(t)?.delete(r)}}ct(...t){const[e,i]=t,r=this.ht.get(e);if(r)for(const o of r){try{o.fn(i)}catch(n){console.error(n)}o.once&&r.delete(o)}}},zt=t=>null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(t=>"string"==typeof t);!function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"}(j||(j={}));var jt=class t{constructor(){}static get level(){return t.lt}static set level(e){if(e!==j.Silent&&e!==j.Errors&&e!==j.Warnings&&e!==j.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");t.lt=e}static get dt(){return t.ut??=new Ut}static on(e,i,r){return t.dt.on(e,i,r)}static ft(...e){t.dt.ct("error",e),t.lt>=j.Errors&&console.error(...e)}static wt(...e){t.dt.ct("warn",e),t.lt>=j.Warnings&&console.warn(...e)}static vt(...e){t.dt.ct("info",e),t.lt>=j.Info&&console.info(...e)}};jt.lt=j.Info,jt.ut=null;var Lt,qt,Ht=class{constructor(t,e){if(this.data=t,this.mimeType=e,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof e)throw new TypeError("mimeType must be a string.")}},Gt=class{constructor(t,e,i,r){if(this.data=t,this.mimeType=e,this.name=i,this.description=r,!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==e&&"string"!=typeof e)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}},Wt=class t{constructor(t){this.bytes=t,this.pos=0}seekToByte(t){this.pos=8*t}readBit(){const t=Math.floor(this.pos/8),e=this.bytes[t]??0,i=7-(7&this.pos),r=(e&1<<i)>>i;return this.pos++,r}readBits(t){if(1===t)return this.readBit();let e=0;for(let i=0;i<t;i++)e<<=1,e|=this.readBit();return e}writeBits(t,e){const i=this.pos+t;for(let r=this.pos;r<i;r++){const t=Math.floor(r/8);let n=this.bytes[t];const o=7-(7&r);n&=~(1<<o),n|=(e&1<<i-r-1)>>i-r-1<<o,this.bytes[t]=n}this.pos=i}copyBits(t,e){let i=0;for(;i<t-7;i+=8)this.writeBits(8,e.readBits(8));const r=t-i;r>0&&this.writeBits(r,e.readBits(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 e=new t(this.bytes);return e.pos=this.pos,e}},Xt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Zt=[-1,1,2,3,4,5,6,8],Qt=t=>{const e=5===t.objectType||29===t.objectType,i=29===t.objectType,r=e?t.outputSampleRate/2:t.outputSampleRate,n=i?1:t.outputNumberOfChannels,o=Zt.indexOf(n);if(-1===o)throw new TypeError(`Unsupported number of channels: ${t.outputNumberOfChannels}`);let s=16;t.objectType>=32&&(s+=6),15===Kt(r)&&(s+=24),e&&(s+=9,15===Kt(t.outputSampleRate)&&(s+=24));const a=Math.ceil(s/8),h=new Uint8Array(a),c=new Wt(h);return Yt(c,t.objectType),Jt(c,r),c.writeBits(4,o),e&&(Jt(c,t.outputSampleRate),Yt(c,2)),c.writeBits(3,0),h},Yt=(t,e)=>{e<32?t.writeBits(5,e):(t.writeBits(5,31),t.writeBits(6,e-32))},Jt=(t,e)=>{const i=Kt(e);t.writeBits(4,i),15===i&&t.writeBits(24,e)},Kt=t=>{const e=Xt.indexOf(t);return-1===e?15:e},te=[48e3,44100,32e3],ee=[24e3,22050,16e3],ie="Mediabunny v1.62.1";!function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"}(Lt||(Lt={})),function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(qt||(qt={}));var re,ne=function*(t){let e=0,i=-1;for(;e<t.length-2;){const r=t.indexOf(0,e);if(-1===r||r>=t.length-2)break;e=r;let n=0;e+3<t.length&&0===t[e+1]&&0===t[e+2]&&1===t[e+3]?n=4:0===t[e+1]&&1===t[e+2]&&(n=3),0!==n?(-1!==i&&e>i&&(yield{offset:i,length:e-i}),i=e+n,e=i):e++}-1!==i&&i<t.length&&(yield{offset:i,length:t.length-i})},oe=function*(t,e){let i=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let t;1===e?t=r.getUint8(i):2===e?t=r.getUint16(i,!1):3===e?t=mt(r,i,!1):(z(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},se=t=>31&t,ae=t=>{const e=new Uint8Array(t.length),i=t.length;let r=0;for(let n=0;n<i;n++)n+2<i&&0===t[n]&&0===t[n+1]&&3===t[n+2]?(e[r++]=0,e[r++]=0,n+=2):e[r++]=t[n];return e.subarray(0,r)},he=(new Uint8Array([0,0,0,1]),t=>{try{const e=[],i=[],r=[];for(const a of ne(t)){const n=t.subarray(a.offset,a.offset+a.length),o=se(n[0]);o===Lt.SPS&&e.length<31?e.push(n):o===Lt.PPS&&i.length<255?i.push(n):o===Lt.SPS_EXT&&r.length<255&&r.push(n)}if(0===e.length)return null;if(0===i.length)return null;const n=e[0],o=de(n);if(!o)return null;const s=100===o.profileIdc||110===o.profileIdc||122===o.profileIdc||144===o.profileIdc;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:i,chromaFormat:s?o.chromaFormatIdc:null,bitDepthLumaMinus8:s?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:s?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:s?r:null}}catch(e){return jt.ft("Error building AVC Decoder Configuration Record:",e),null}}),ce=t=>{const e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|3&t.lengthSizeMinusOne),e.push(224|31&t.sequenceParameterSets.length);for(const i of t.sequenceParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}e.push(t.pictureParameterSets.length);for(const i of t.pictureParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}if((100===t.avcProfileIndication||110===t.avcProfileIndication||122===t.avcProfileIndication||144===t.avcProfileIndication)&&null!==t.chromaFormat){z(null!==t.bitDepthLumaMinus8),z(null!==t.bitDepthChromaMinus8),z(null!==t.sequenceParameterSetExt),e.push(252|3&t.chromaFormat),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.sequenceParameterSetExt.length);for(const i of t.sequenceParameterSetExt){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}}return new Uint8Array(e)},le={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}},de=t=>{try{const e=ae(t),i=new Wt(e);if(i.skipBits(1),i.skipBits(2),7!==i.readBits(5))return null;const r=i.readAlignedByte(),n=i.readAlignedByte(),o=i.readAlignedByte();J(i);let s=1,a=0,h=0,c=0;if((100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r)&&(s=J(i),3===s&&(c=i.readBits(1)),a=J(i),h=J(i),i.skipBits(1),i.readBits(1)))for(let t=0;t<(3!==s?8:12);t++)if(i.readBits(1)){const e=t<6?16:64;let r=8,n=8;for(let t=0;t<e;t++)0!==n&&(n=(r+K(i)+256)%256),r=0===n?r:n}J(i);const l=J(i);if(0===l)J(i);else if(1===l){i.skipBits(1),K(i),K(i);const t=J(i);for(let e=0;e<t;e++)K(i)}J(i),i.skipBits(1);const d=J(i),u=J(i),f=16*(d+1),p=16*(u+1);let m=f,w=p;const v=i.readBits(1);if(v||i.skipBits(1),i.skipBits(1),i.readBits(1)){const t=J(i),e=J(i),r=J(i),n=J(i);let o,a;0===(0===c?s:0)?(o=1,a=2-v):(o=3===s?1:2,a=(1===s?2:1)*(2-v)),m-=o*(t+e),w-=a*(r+n)}if(m<=0||w<=0)return null;let b=2,y=2,g=2,x=0,E={num:1,den:1},T=null,k=null,_=null,M=null;const C=i.pos;if(i.readBits(1)){if(i.readBits(1)){const t=i.readBits(8);if(255===t)E={num:i.readBits(16),den:i.readBits(16)};else{const e=le[t];e&&(E=e)}}i.readBits(1)&&i.skipBits(1),i.readBits(1)&&(i.skipBits(3),x=i.readBits(1),i.readBits(1)&&(b=i.readBits(8),y=i.readBits(8),g=i.readBits(8))),i.readBits(1)&&(J(i),J(i)),i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.skipBits(1));const t=i.readBits(1);t&&ue(i);const e=i.readBits(1);e&&ue(i),(t||e)&&i.skipBits(1),i.skipBits(1),_=i.pos,M=i.readBits(1),M&&(i.skipBits(1),J(i),J(i),J(i),J(i),T=Math.min(J(i),16),k=Math.min(J(i),16))}if(null===T)if(z(null===k),(44===r||86===r||100===r||110===r||122===r||244===r)&&16&n)T=0,k=0;else{const t=d+1,e=(2-v)*(u+1),i=He.find(t=>t.level>=o)??Q(He),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);T=r,k=r}return z(null!==k),{emulationUnpreventedBytes:e,profileIdc:r,constraintFlags:n,levelIdc:o,frameMbsOnlyFlag:v,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:h,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:w,pixelAspectRatio:E,colourPrimaries:b,matrixCoefficients:g,transferCharacteristics:y,fullRangeFlag:x,numReorderFrames:T,maxDecFrameBuffering:k,vuiParametersFlagBitOffset:C,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:M}}catch(e){return jt.ft("Error parsing AVC SPS:",e),null}},ue=t=>{const e=J(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)J(t),J(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},fe=t=>t>>1&63,pe=t=>{try{const e=[],i=[],r=[],n=[],o=65535;for(const c of ne(t)){const s=t.subarray(c.offset,c.offset+c.length),a=fe(s[0]);a===qt.VPS_NUT&&e.length<o?e.push(s):a===qt.SPS_NUT&&i.length<o?i.push(s):a===qt.PPS_NUT&&r.length<o?r.push(s):(a===qt.PREFIX_SEI_NUT||a===qt.SUFFIX_SEI_NUT)&&n.length<o&&n.push(s)}if(0===i.length||0===r.length)return null;const s=(t=>{try{const e=new Wt(ae(t));e.skipBits(16),e.readBits(4);const i=e.readBits(3),r=e.readBits(1),{general_profile_space:n,general_tier_flag:o,general_profile_idc:s,general_profile_compatibility_flags:a,general_constraint_indicator_flags:h,general_level_idc:c}=me(e,i);J(e);const l=J(e);let d=0;3===l&&(d=e.readBits(1));const u=J(e),f=J(e);let p=u,m=f;if(e.readBits(1)){const t=J(e),i=J(e),r=J(e),n=J(e);let o=1,s=1;const a=0===d?l:0;1===a?(o=2,s=2):2===a&&(o=2,s=1),p-=(t+i)*o,m-=(r+n)*s}if(p<=0||m<=0)return null;const w=J(e),v=J(e);J(e);const b=e.readBits(1)?0:i;let y=0;for(let t=b;t<=i;t++)J(e),y=J(e),J(e);J(e),J(e),J(e),J(e),J(e),J(e),e.readBits(1)&&e.readBits(1)&&we(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),J(e),J(e),e.skipBits(1));const g=J(e);if(ve(e,g),e.readBits(1)){const t=J(e);for(let i=0;i<t;i++)J(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,E=2,T=2,k=0,_=0,M={num:1,den:1};if(e.readBits(1)){const t=ye(e,i);M=t.pixelAspectRatio,x=t.colourPrimaries,E=t.transferCharacteristics,T=t.matrixCoefficients,k=t.fullRangeFlag,_=t.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:M,colourPrimaries:x,transferCharacteristics:E,matrixCoefficients:T,fullRangeFlag:k,maxDecFrameBuffering:Math.min(y+1,16),spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:h,generalLevelIdc:c,chromaFormatIdc:l,bitDepthLumaMinus8:w,bitDepthChromaMinus8:v,minSpatialSegmentationIdc:_}}catch(e){return jt.ft("Error parsing HEVC SPS:",e),null}})(i[0]);if(!s)return null;let a=0;if(r.length>0){const t=r[0],e=new Wt(ae(t));e.skipBits(16),J(e),J(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),J(e),J(e),K(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&J(e),K(e),K(e),e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const i=e.readBits(1),n=e.readBits(1);a=i||n?i&&!n?2:!i&&n?3:0:0}const h=[...e.length?[{arrayCompleteness:1,nalUnitType:qt.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:qt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:qt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:fe(n[0][0]),nalUnits:n}]:[]];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:a,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:h}}catch(e){return jt.ft("Error building HEVC Decoder Configuration Record:",e),null}},me=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},we=t=>{for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBits(1)){const i=Math.min(64,1<<4+(e<<1));e>1&&K(t);for(let e=0;e<i;e++)K(t)}else J(t)},ve=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=be(t,r,e,i)},be=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(J(t)+1):e-1,t.readBits(1),J(t);const o=r[s]??0;for(let e=0;e<=o;e++)t.readBits(1)||t.readBits(1);n=r[s]}else{const e=J(t),i=J(t);for(let r=0;r<e;r++)J(t),t.readBits(1);for(let r=0;r<i;r++)J(t),t.readBits(1);n=e+i}return n},ye=(t,e)=>{let i=2,r=2,n=2,o=0,s=0,a={num:1,den:1};if(t.readBits(1)){const e=t.readBits(8);if(255===e)a={num:t.readBits(16),den:t.readBits(16)};else{const t=le[e];t&&(a=t)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),o=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(J(t),J(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(J(t),J(t),J(t),J(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&J(t),t.readBits(1)&&ge(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=J(t),J(t),J(t),J(t),J(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},ge=(t,e,i)=>{let r=!1,n=!1,o=!1;e&&(r=1===t.readBits(1),n=1===t.readBits(1),(r||n)&&(o=1===t.readBits(1),o&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),o&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let s=0;s<=i;s++){let e=!0;1===t.readBits(1)||(e=1===t.readBits(1));let i=!1;e?J(t):i=1===t.readBits(1);let s=1;i||(s=J(t)+1),r&&xe(t,s,o),n&&xe(t,s,o)}},xe=(t,e,i)=>{for(let r=0;r<e;r++)J(t),J(t),i&&(J(t),J(t)),t.readBits(1)};!function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"}(re||(re={}));var Ee,Te={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},ke=t=>{const e=new Wt(t);if(2!==e.readBits(2))return null;const i=e.readBits(1),r=(e.readBits(1)<<1)+i;if(3===r&&e.skipBits(1),1===e.readBits(1))return null;if(0!==e.readBits(1))return null;if(e.skipBits(2),4817730!==e.readBits(24))return null;let n=8;r>=2&&(n=e.readBits(1)?12:10);const o=e.readBits(3);let s=0,a=0;if(7!==o)if(a=e.readBits(1),1===r||3===r){const t=e.readBits(1),i=e.readBits(1);s=t||i?t&&!i?2:1:3,e.skipBits(1)}else s=1;else s=3,a=1;const h=(e.readBits(16)+1)*(e.readBits(16)+1);let c=Q(We).level;for(const d of We)if(h<=d.maxPictureSize){c=d.level;break}const l=Te[o];return{profile:r,level:c,bitDepth:n,chromaSubsampling:s,videoFullRangeFlag:a,colourPrimaries:l?.colourPrimaries??2,transferCharacteristics:l?.transferCharacteristics??2,matrixCoefficients:l?.matrixCoefficients??2}},_e=function*(t){const e=new Wt(t),i=()=>{let t=0;for(let i=0;i<8;i++){const r=e.readAlignedByte();if(t+=(127&r)*2**(7*i),!(128&r))break;if(7===i&&128&r)return null}return t>2**32-1?null:t};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),n=e.readBits(1),o=e.readBits(1);let s;if(e.skipBits(1),n&&e.skipBits(8),o){const t=i();if(null===t)return;s=t}else s=Math.floor(e.getBitsLeft()/8);z(e.pos%8==0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+s)},e.skipBits(8*s)}},Me=t=>{for(const{type:e,data:i}of _e(t)){if(1!==e)continue;const t=new Wt(i),r=t.readBits(3);t.readBits(1);const n=t.readBits(1);let o=0,s=0,a=0;if(n)o=t.readBits(5);else{let e=0;if(t.readBits(1)){if(t.skipBits(32),t.skipBits(32),t.readBits(1)){let e=0;for(;e<32&&!t.readBits(1);)e++;e<32&&t.skipBits(e)}e=t.readBits(1),e&&(a=t.readBits(5),t.skipBits(32),t.skipBits(5),t.skipBits(5))}const i=t.readBits(1),r=t.readBits(5);for(let n=0;n<=r;n++){t.skipBits(12);const r=t.readBits(5);if(0===n&&(o=r),r>7){const e=t.readBits(1);0===n&&(s=e)}if(e&&t.readBits(1)){const e=a+1;t.skipBits(e),t.skipBits(e),t.skipBits(1)}i&&t.readBits(1)&&t.skipBits(4)}}const h=t.readBits(4),c=t.readBits(4),l=h+1;t.skipBits(l);const d=c+1;t.skipBits(d);let u=0;if(u=n?0:t.readBits(1),u&&(t.skipBits(4),t.skipBits(3)),t.skipBits(1),t.skipBits(1),t.skipBits(1),!n){t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const e=t.readBits(1);e&&(t.skipBits(1),t.skipBits(1));let i=0;i=t.readBits(1)?2:t.readBits(1),i>0&&(t.readBits(1)||t.skipBits(1)),e&&t.skipBits(3)}t.skipBits(1),t.skipBits(1),t.skipBits(1);const f=t.readBits(1);let p=8;2===r&&f?p=t.readBits(1)?12:10:r<=2&&(p=f?10:8);let m=0;1!==r&&(m=t.readBits(1));let w=2,v=2,b=2;t.readBits(1)&&(w=t.readBits(8),v=t.readBits(8),b=t.readBits(8));let y=0,g=1,x=1,E=0;return m?y=t.readBits(1):1===w&&13===v&&0===b?(y=1,g=0,x=0):(y=t.readBits(1),0===r?(g=1,x=1):1===r?(g=0,x=0):12===p?(g=t.readBits(1),x=g?t.readBits(1):0):(g=1,x=0),g&&x&&(E=t.readBits(2))),{profile:r,level:o,tier:s,bitDepth:p,monochrome:m,chromaSubsamplingX:g,chromaSubsamplingY:x,chromaSamplePosition:E,videoFullRangeFlag:y,colourPrimaries:w,transferCharacteristics:v,matrixCoefficients:b}}return null},Ce=t=>{if(t.byteLength<19)throw new Error("Invalid Opus identification header: too short.");const e=et(t),i=e.getUint8(9),r=e.getUint16(10,!0),n=e.getUint32(12,!0),o=e.getInt16(16,!0),s=e.getUint8(18);let a=null;return s&&(a=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:o,channelMappingFamily:s,channelMappingTable:a}};!function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"}(Ee||(Ee={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var Ae,Se=[1,2,3,6],Pe=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Ie=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Be=[16,16,20,20,0,24,24,0],Fe=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],$e=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Oe=[32e3,44100,48e3,0],Re=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],De=[512,1024,2048,4096],Ne=t=>{if(t.length<10)return null;if(100!==t[0]||88!==t[1]||32!==t[2]||37!==t[3])return null;const e=new Wt(t);e.skipBits(32),e.skipBits(8);const i=e.readBits(2),r=e.readBits(1),n=8+4*r,o=16+4*r;e.skipBits(n);const s=e.readBits(o)+1,a={frameSize:s,asset:null};if(!e.readBits(1))return a;const h=Oe[e.readBits(2)],c=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const l=e.readBits(3)+1,d=e.readBits(3)+1,u=[];for(let v=0;v<l;v++)u.push(e.readBits(i+1));for(const v of u)e.skipBits(8*gt(v));if(e.readBits(1)){e.skipBits(2);const t=e.readBits(2)+1<<2,i=e.readBits(2)+1;e.skipBits(i*t)}for(let v=0;v<d;v++)e.skipBits(o);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const f=e.readBits(5)+1,p=Re[e.readBits(4)],m=e.readBits(8)+1;let w=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const t=e.readBits(2)+1<<2;w=e.readBits(t)}return 0===h||e.getBitsLeft()<0?a:{frameSize:s,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(c*p/h),channelLayout:w,pcmResolution:f}}},Ve=t=>{const e=new Uint8Array(20),i=et(e);i.setUint32(0,t.sampleRate),i.setUint32(4,t.bitRate),i.setUint32(8,t.bitRate),e[12]=t.pcmResolution;const r=t.core&&!t.hasExtensions?1:0,n=new Wt(e);return n.seekToByte(13),n.writeBits(2,Math.max(De.indexOf(t.sampleCount),0)),n.writeBits(5,r),n.writeBits(1,t.core?.lfePresent?1:0),n.writeBits(6,t.core?.amode??0),n.writeBits(14,t.core?t.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,t.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e},Ue=["avc","hevc","vp9","av1","vp8","prores"],ze=["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"],je=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Le=[...je,...ze],qe=["webvtt"],He=[{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}],Ge=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],We=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Xe=[{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}],Ze=["ap4x","ap4h","apch","apcn","apcs","apco"],Qe=["dtsc","dtsh","dtsl","dtse"],Ye=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],Je=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=He.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??Q(He),s=o?o.level:0;return`avc1.${t.toString(16).padStart(2,"0")}00${s.toString(16).padStart(2,"0")}`}if("hevc"===t){const t="",n=1,o="6",s=e*i,a=Ge.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??Q(Ge);return`hev1.${t}${n}.${o}.${a.tier}${a.level}.B0`}if("vp8"===t)return"vp8";if("vp9"===t){const t=e*i;return`vp09.00.${(We.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??Q(We)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=Xe.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??Q(Xe);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Ye.filter(t=>t.alpha===n);let s=o[0].fourCc,a=1/0;for(const{fourCc:e,bitrate:i}of o){const n=Math.abs(i*t-r);n<a&&(a=n,s=e)}return s}throw pt(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Ke=t=>{const e=t.split("."),i=Number(e[1]),r=e[2],n=(i<<5)+Number(r.slice(0,-1)),o="H"===r.slice(-1)?1:0,s=Number(e[3]);return[129,n,(o<<7)+((8===s?0:1)<<6)+((12===s?1:0)<<5)+((e[4]?Number(e[4]):0)<<4)+((e[5]?Number(e[5][0]):1)<<3)+((e[5]?Number(e[5][1]):1)<<2)+(e[5]?Number(e[5][2]):0),0]},ti=/^pcm-([usf])(\d+)(be)?$/,ei=t=>{if(z(ze.includes(t)),"ulaw"===t)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===t)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=ti.exec(t);let i;return z(e),i="u"===e[1]?"unsigned":"s"===e[1]?"signed":"float",{dataType:i,sampleSize:Number(e[2])/8,littleEndian:"be"!==e[3],silentValue:"pcm-u8"===t?128:0}},ii=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":"vp8"===t?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":Ze.includes(t)?"prores":"mp3"===t||"mp4a.69"===t||"mp4a.6B"===t||"mp4a.6b"===t||"mp4a.40.34"===t?"mp3":t.startsWith("mp4a.40.")||"mp4a.67"===t?"aac":"opus"===t||"Opus"===t?"opus":"vorbis"===t?"vorbis":"flac"===t?"flac":"ac-3"===t||"ac3"===t?"ac3":"ec-3"===t||"eac3"===t?"eac3":Qe.includes(t)?"dts":"ulaw"===t?"ulaw":"alaw"===t?"alaw":ti.test(t)?t:"webvtt"===t?"webvtt":null,ri=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Ze],ni=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,oi=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,si=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ai=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,hi=(t,e)=>{if(!t)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Video chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!ri.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==t.decoderConfig.displayAspectWidth&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectHeight&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectWidth!=(void 0!==t.decoderConfig.displayAspectHeight))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(void 0!==t.decoderConfig.description&&!ht(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==t.decoderConfig.colorSpace){const{colorSpace:e}=t.decoderConfig;if("object"!=typeof e)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(nt);if(null!=e.primaries&&!i.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(ot);if(null!=e.transfer&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const n=Object.keys(st);if(null!=e.matrix&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!ni.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!oi.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if("vp8"!==t.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!si.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(t.decoderConfig.codec.startsWith("av01")){if(!ai.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(Ze.some(e=>t.decoderConfig.codec.startsWith(e))&&!Ze.some(e=>t.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Ze.join(", ")}.`);if(null!==e&&ii(t.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},ci=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],li=(t,e)=>{if(!t)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof t)throw new TypeError("Audio chunk metadata must be an object.");if(!t.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof t.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof t.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!ci.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==t.decoderConfig.description&&!ht(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==t.decoderConfig.codec&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if("opus"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if("flac"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if("ac-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if("ec-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(t.decoderConfig.codec.startsWith("dts")){if(!Qe.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Qe.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!ze.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ze.join(", ")}).`);if(null!==e&&ii(t.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${t.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},di=t=>{if(!t)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof t)throw new TypeError("Subtitle metadata must be an object.");if(!t.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof t.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof t.config.description)throw new TypeError("Subtitle metadata config description must be a string.")},ui=new Uint8Array(0),fi=class t{constructor(t,e,i,r,n=-1,o,s){if(this.data=t,this.type=e,this.timestamp=i,this.duration=r,this.sequenceNumber=n,t===ui&&void 0===o)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===o&&(o=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==e&&"delta"!==e)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==s&&("object"!=typeof s||!s))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==s?.alpha&&!(s.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==s?.alphaByteLength&&(!Number.isInteger(s.alphaByteLength)||s.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=s??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===ui}get microsecondTimestamp(){return Math.trunc(Et*this.timestamp)}get microsecondDuration(){return Math.trunc(Et*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,i){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new t(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,i)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!=typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}},pi=class{constructor(t){this.value=t}},mi=class{constructor(t){this.value=t}},wi=class{constructor(t){this.value=t}},vi=class{constructor(t){this.value=t}};!function(t){t[t.EBML=440786851]="EBML",t[t.EBMLVersion=17030]="EBMLVersion",t[t.EBMLReadVersion=17143]="EBMLReadVersion",t[t.EBMLMaxIDLength=17138]="EBMLMaxIDLength",t[t.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",t[t.DocType=17026]="DocType",t[t.DocTypeVersion=17031]="DocTypeVersion",t[t.DocTypeReadVersion=17029]="DocTypeReadVersion",t[t.Void=236]="Void",t[t.Segment=408125543]="Segment",t[t.SeekHead=290298740]="SeekHead",t[t.Seek=19899]="Seek",t[t.SeekID=21419]="SeekID",t[t.SeekPosition=21420]="SeekPosition",t[t.Duration=17545]="Duration",t[t.Info=357149030]="Info",t[t.TimestampScale=2807729]="TimestampScale",t[t.MuxingApp=19840]="MuxingApp",t[t.WritingApp=22337]="WritingApp",t[t.Tracks=374648427]="Tracks",t[t.TrackEntry=174]="TrackEntry",t[t.TrackNumber=215]="TrackNumber",t[t.TrackUID=29637]="TrackUID",t[t.TrackType=131]="TrackType",t[t.FlagEnabled=185]="FlagEnabled",t[t.FlagDefault=136]="FlagDefault",t[t.FlagForced=21930]="FlagForced",t[t.FlagOriginal=21934]="FlagOriginal",t[t.FlagHearingImpaired=21931]="FlagHearingImpaired",t[t.FlagVisualImpaired=21932]="FlagVisualImpaired",t[t.FlagCommentary=21935]="FlagCommentary",t[t.FlagLacing=156]="FlagLacing",t[t.Name=21358]="Name",t[t.Language=2274716]="Language",t[t.LanguageBCP47=2274717]="LanguageBCP47",t[t.CodecID=134]="CodecID",t[t.CodecPrivate=25506]="CodecPrivate",t[t.CodecDelay=22186]="CodecDelay",t[t.SeekPreRoll=22203]="SeekPreRoll",t[t.DefaultDuration=2352003]="DefaultDuration",t[t.Video=224]="Video",t[t.PixelWidth=176]="PixelWidth",t[t.PixelHeight=186]="PixelHeight",t[t.DisplayWidth=21680]="DisplayWidth",t[t.DisplayHeight=21690]="DisplayHeight",t[t.DisplayUnit=21682]="DisplayUnit",t[t.AlphaMode=21440]="AlphaMode",t[t.Audio=225]="Audio",t[t.SamplingFrequency=181]="SamplingFrequency",t[t.Channels=159]="Channels",t[t.BitDepth=25188]="BitDepth",t[t.SimpleBlock=163]="SimpleBlock",t[t.BlockGroup=160]="BlockGroup",t[t.Block=161]="Block",t[t.BlockAdditions=30113]="BlockAdditions",t[t.BlockMore=166]="BlockMore",t[t.BlockAdditional=165]="BlockAdditional",t[t.BlockAddID=238]="BlockAddID",t[t.BlockDuration=155]="BlockDuration",t[t.ReferenceBlock=251]="ReferenceBlock",t[t.Cluster=524531317]="Cluster",t[t.Timestamp=231]="Timestamp",t[t.Cues=475249515]="Cues",t[t.CuePoint=187]="CuePoint",t[t.CueTime=179]="CueTime",t[t.CueTrackPositions=183]="CueTrackPositions",t[t.CueTrack=247]="CueTrack",t[t.CueClusterPosition=241]="CueClusterPosition",t[t.Colour=21936]="Colour",t[t.MatrixCoefficients=21937]="MatrixCoefficients",t[t.TransferCharacteristics=21946]="TransferCharacteristics",t[t.Primaries=21947]="Primaries",t[t.Range=21945]="Range",t[t.Projection=30320]="Projection",t[t.ProjectionType=30321]="ProjectionType",t[t.ProjectionPoseYaw=30323]="ProjectionPoseYaw",t[t.ProjectionPosePitch=30324]="ProjectionPosePitch",t[t.ProjectionPoseRoll=30325]="ProjectionPoseRoll",t[t.Attachments=423732329]="Attachments",t[t.AttachedFile=24999]="AttachedFile",t[t.FileDescription=18046]="FileDescription",t[t.FileName=18030]="FileName",t[t.FileMediaType=18016]="FileMediaType",t[t.FileData=18012]="FileData",t[t.FileUID=18094]="FileUID",t[t.Chapters=272869232]="Chapters",t[t.Tags=307544935]="Tags",t[t.Tag=29555]="Tag",t[t.Targets=25536]="Targets",t[t.TargetTypeValue=26826]="TargetTypeValue",t[t.TargetType=25546]="TargetType",t[t.TagTrackUID=25541]="TagTrackUID",t[t.TagEditionUID=25545]="TagEditionUID",t[t.TagChapterUID=25540]="TagChapterUID",t[t.TagAttachmentUID=25542]="TagAttachmentUID",t[t.SimpleTag=26568]="SimpleTag",t[t.TagName=17827]="TagName",t[t.TagLanguage=17530]="TagLanguage",t[t.TagString=17543]="TagString",t[t.TagBinary=17541]="TagBinary",t[t.ContentEncodings=28032]="ContentEncodings",t[t.ContentEncoding=25152]="ContentEncoding",t[t.ContentEncodingOrder=20529]="ContentEncodingOrder",t[t.ContentEncodingScope=20530]="ContentEncodingScope",t[t.ContentCompression=20532]="ContentCompression",t[t.ContentCompAlgo=16980]="ContentCompAlgo",t[t.ContentCompSettings=16981]="ContentCompSettings",t[t.ContentEncryption=20533]="ContentEncryption"}(Ae||(Ae={})),Ae.EBML,Ae.Segment,Ae.SeekHead,Ae.Info,Ae.Cluster,Ae.Tracks,Ae.Cues,Ae.Attachments,Ae.Chapters,Ae.Tags;var bi=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,yi=t=>t<256n?1:t<65536n?2:t<1n<<24n?3:t<1n<<32n?4:t<1n<<40n?5:t<1n<<48n?6:t<1n<<56n?7:8,gi=t=>t>=-64&&t<64?1:t>=-8192&&t<8192?2:t>=-1048576&&t<1<<20?3:t>=-134217728&&t<1<<27?4:t>=-(2**34)&&t<2**34?5:6,xi=class{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=bi(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=yi(t)){let i=0;for(let r=e-1;r>=0;r--)this.helperView.setUint8(i++,Number(t>>BigInt(8*r)&255n));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(t,e=gi(t)){t<0&&(t+=2**(8*e)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=(t=>{if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML varint size not supported "+t)})(t)){let i=0;switch(e){case 1:this.helperView.setUint8(i++,128|t);break;case 2:this.helperView.setUint8(i++,64|t>>8),this.helperView.setUint8(i++,t);break;case 3:this.helperView.setUint8(i++,32|t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 4:this.helperView.setUint8(i++,16|t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 5:this.helperView.setUint8(i++,8|t/2**32&7),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 6:this.helperView.setUint8(i++,4|t/2**40&3),this.helperView.setUint8(i++,t/2**32|0),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(t=>t.charCodeAt(0))))}writeEBML(t){if(null!==t)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(const e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data)){const e=this.writer.getPos(),i=-1===t.size?1:t.size??4;-1===t.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const r=this.writer.getPos();if(this.dataOffsets.set(t,r),this.writeEBML(t.data),-1!==t.size){const t=this.writer.getPos()-r,n=this.writer.getPos();this.writer.seek(e),this.writeVarInt(t,i),this.writer.seek(n)}}else if("number"==typeof t.data){const e=t.size??bi(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??yi(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if("string"==typeof t.data)this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof pi)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof mi)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof wi){const e=t.size??gi(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof vi){const e=rt.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else pt(t.data)}},Ei={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS","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"},Ti=t=>{const e=t.filePos;if(t.remainingLength<7)return null;const i=new Wt(hr(t,7));if(4095!==i.readBits(12))return null;if(i.skipBits(1),0!==i.readBits(2))return null;const r=i.readBits(1),n=i.readBits(2)+1,o=i.readBits(4);if(o>=Xt.length)return null;i.skipBits(1);const s=i.readBits(3);if(0===s)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const a=i.readBits(13);i.skipBits(11);const h=i.readBits(2)+1;if(1!==h)throw new Error("ADTS frames with more than one AAC frame are not supported.");let c=null;if(0===r){if(t.remainingLength<2)return null;c=cr(t)}return a<t.filePos-e?null:{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s,frameLength:a,numberOfAacFrames:h,crcCheck:c,startPos:e}},ki=i((t,e)=>{e.exports={}}),_i=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r});Symbol.dispose??=Symbol("Symbol.dispose");var Mi=-1/0,Ci=-1/0,Ai=null;"undefined"!=typeof FinalizationRegistry&&(Ai=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-Mi>=1e3&&(jt.ft("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."),Mi=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-Ci>=1e3&&(jt.ft("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."),Ci=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var Si=class{constructor(){this.bt=0,this.yt=null}},Pi=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Ii=new Set(Pi),Bi=class t{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Et*this.timestamp)}get microsecondDuration(){return Math.trunc(Et*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,i){if(this.gt=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0===i.format||!Ii.has(i.format))throw new TypeError("init.format must be one of: "+Pi.join(", "));if(!Number.isInteger(i.codedWidth)||i.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(i.codedHeight)||i.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==i.flip&&"boolean"!=typeof i.flip)throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==i.layout){if(!Array.isArray(i.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const t of i.layout){if(!t||"object"!=typeof t||Array.isArray(t))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==i.visibleRect&&Nt(i.visibleRect,"init.visibleRect"),void 0!==i.displayWidth&&(!Number.isInteger(i.displayWidth)||i.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==i.displayHeight&&(!Number.isInteger(i.displayHeight)||i.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==i.displayWidth!=(void 0!==i.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=i.format,this.rotation=i.rotation??0,this.flip=i.flip??!1,this.timestamp=i.timestamp,this.duration=i.duration??0;const t=i.layout??ji(i.format,i.codedWidth,i.codedHeight);let r=i.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},void 0!==i.displayWidth?(this.squarePixelWidth=this.rotation%180==0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180==0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this.xt=i.Et?tt(e):tt(e).slice(),this.Tt=t,this.colorSpace=new Di(r)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==i?.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==i?.flip&&"boolean"!=typeof i.flip)throw new TypeError("init.flip, when provided, must be a boolean.");if(void 0!==i?.timestamp&&!Number.isFinite(i?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==i?.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==i?.visibleRect&&Nt(i.visibleRect,"init.visibleRect"),this.xt=e,this.Tt=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=i?.rotation??0,this.flip=i?.flip??!1,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=i?.timestamp??e.timestamp/1e6,this.duration=i?.duration??(e.duration??0)/1e6;const{primaries:t,transfer:r,matrix:n,fullRange:o}=e.colorSpace;this.colorSpace=new Di({primaries:null!==t&&t in nt?t:null,transfer:null!==r&&r in ot?r:null,matrix:null!==n&&n in st?n:null,fullRange:o})}else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==i.flip&&"boolean"!=typeof i.flip)throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==i.visibleRect&&Nt(i.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*Et),duration:Math.trunc((i.duration??0)*Et)||void 0,visibleRect:i.visibleRect&&{x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height}}),i);let r=0,n=0;if("naturalWidth"in e?(r=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,n=e.videoHeight):"width"in e&&(r=Number(e.width),n=Number(e.height)),!r||!n)throw new TypeError("Could not determine dimensions.");const o=i.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(o.width,o.height),a=s.getContext("2d",{alpha:Ct(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-o.left,-o.top),this.xt=s,this.Tt=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:o.width,height:o.height},this.squarePixelWidth=o.width,this.squarePixelHeight=o.height,this.rotation=i.rotation??0,this.flip=i.flip??!1,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=new Di({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Si))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==i.flip&&"boolean"!=typeof i.flip)throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this.xt=e,e.bt++,this.format=e.getFormat(),null!==this.format&&!Pi.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=i.rotation??0,this.flip=i.flip??!1,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=i?.encodeOptions??{},this.pixelAspectRatio=Dt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ai?.register(this,{type:"video",data:this.xt},this)}clone(){if(this.gt)throw new Error("VideoSample is closed.");return z(null!==this.xt),this.xt instanceof Si?new t(this.xt,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Ni(this.xt)?new t(this.xt.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this.xt instanceof Uint8Array?(z(this.Tt),new t(this.xt,{format:this.format,layout:this.Tt,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,Et:!0})):new t(this.xt,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this.gt||(Ai?.unregister(this),this.xt instanceof Si?(this.xt.bt--,0===this.xt.bt&&this.xt.close()):Ni(this.xt)?this.xt.close():this.xt=null,this.gt=!0)}allocationSize(t={}){if(zi(t),this.gt)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot get allocation size when format is null.");return Ni(this.xt)?this.xt.allocationSize(t):qi(this,t).allocationSize}async copyTo(e,i={}){if(!ht(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(zi(i),this.gt)throw new Error("VideoSample is closed.");if(null==(i.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(z(null!==this.xt),Ni(this.xt))return this.xt.copyTo(e,i);if(i.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(i.format)){if(!(this.xt instanceof Si)){if("undefined"==typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const t=this.toVideoFrame(),r=await t.copyTo(e,i);return t.close(),r}{const r={stack:[],error:void 0,hasError:!1};try{const n=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e}(r,await this.xt.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},i.colorSpace??"srgb"),!1);if(!(n instanceof t))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return await n.copyTo(e,i)}catch(c){r.error=c,r.hasError=!0}finally{_i(r)}}}const r=qi(this,i);z(this.format);const n=tt(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=Li(this.format);let s;if(this.xt instanceof Si){let t=this.xt.getDataPlanes();if(Bt(t)&&(t=await t),!Array.isArray(t)||t.some(t=>!(t.data instanceof Uint8Array)||!Number.isInteger(t.stride)||t.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=t}else if(this.xt instanceof Uint8Array)z(this.Tt),z(this.Tt.length===o.length),s=this.Tt.map((t,e)=>{const i=Math.ceil(this.codedHeight/o[e].heightDivisor);return{data:this.xt.subarray(t.offset,t.offset+t.stride*i),stride:t.stride}});else{const t=this.xt.getContext("2d");z(t),s=[{data:tt(t.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const a=[],h=o.length;for(let t=0;t<h;t++){const e=r.computedLayouts[t],i=s[t].stride,o=s[t].data;let h=e.sourceTop*i;h+=e.sourceLeftBytes;let c=e.destinationOffset;const l=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let t=0;t<e.sourceHeight;t++){if(h+l>o.byteLength)throw new Error("Source buffer OOB read.");if(c+l>n.byteLength)throw new Error("Destination buffer OOB write.");const t=o.subarray(h,h+l);n.set(t,c),h+=i,c+=e.destinationStride}a.push(d)}if(void 0!==i.format){const t=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),e=this.format.includes("X")&&i.format.includes("A");if(t||e)for(let i=0;i<r.allocationSize;i+=4){if(t){const t=n[i];n[i]=n[i+2],n[i+2]=t}e&&(n[i+3]=255)}}return a}toVideoFrame(){if(this.gt)throw new Error("VideoSample is closed.");if(z(null!==this.xt),this.xt instanceof Si){if(null===this.format)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const t=this.xt.getDataPlanes();if(Bt(t))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const e=t.reduce((t,e)=>t+e.data.byteLength,0),i=new Uint8Array(e);let r=0;const n=[];for(const o of t)i.set(o.data,r),n.push(r),r+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:t.map((t,e)=>({offset:n[e],stride:t.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Ni(this.xt)?new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.xt instanceof Uint8Array?(z(this.Tt),new VideoFrame(this.xt,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this.Tt,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,r,n,o,s,a,h){let c=0,l=0,d=this.displayWidth,u=this.displayHeight,f=0,p=0,m=this.displayWidth,w=this.displayHeight;if(void 0!==o?(c=e,l=i,d=r,u=n,f=o,p=s,void 0!==a?(m=a,w=h):(m=d,w=u)):(f=e,p=i,void 0!==r&&(m=r,w=n)),!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this.gt)throw new Error("VideoSample is closed.");({sx:c,sy:l,sWidth:d,sHeight:u}=this.kt(c,l,d,u,this.rotation,this.flip));const v=this.toCanvasImageSource();t.save();const b=f+m/2,y=p+w/2;t.translate(b,y),this.flip&&t.scale(-1,1),t.rotate(this.rotation*Math.PI/180);const g=this.rotation%180==0?1:m/w;t.scale(1/g,g),t.drawImage(v,c,l,d,u,-m/2,-w/2,m,w),t.restore()}drawWithFit(t,e){if(!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==e.flip&&"boolean"!=typeof e.flip)throw new TypeError("options.flip, when provided, must be a boolean.");void 0!==e.crop&&Ui(e.crop,"options.");const i=t.canvas.width,r=t.canvas.height,n=e.rotation??this.rotation,o=e.flip??this.flip,[s,a]=n%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let h,c,l,d,u=e.crop;u&&(u=Vi(u,s,a));const{sx:f,sy:p,sWidth:m,sHeight:w}=this.kt(e.crop?.left??0,e.crop?.top??0,e.crop?.width??s,e.crop?.height??a,n,o);if("fill"===e.fit)h=0,c=0,l=i,d=r;else{const[t,n]=e.crop?[e.crop.width,e.crop.height]:[s,a],o="contain"===e.fit?Math.min(i/t,r/n):Math.max(i/t,r/n);l=t*o,d=n*o,h=(i-l)/2,c=(r-d)/2}t.save();const v=n%180==0?1:l/d;t.translate(i/2,r/2),o&&t.scale(-1,1),t.rotate(n*Math.PI/180),t.scale(1/v,v),t.translate(-i/2,-r/2),t.drawImage(this.toCanvasImageSource(),f,p,m,w,h,c,l,d),t.restore()}kt(t,e,i,r,n,o){return o&&(t=(n%180==0?this.squarePixelWidth:this.squarePixelHeight)-t-i),90===n?[t,e,i,r]=[e,this.squarePixelHeight-t-i,r,i]:180===n?[t,e]=[this.squarePixelWidth-t-i,this.squarePixelHeight-e-r]:270===n&&([t,e,i,r]=[this.squarePixelWidth-e-r,t,r,i]),{sx:t,sy:e,sWidth:i,sHeight:r}}_t(t,e,i){const r=t.width,n=t.height,[o,s]=i.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],a=i.crop?i.crop.width:o,h=i.crop?i.crop.height:s;let c=0;2*r<a&&2*n<h&&(c=Math.floor(Math.log2(Math.min(a/r,h/n))));const l=r*2**c,d=n*2**c,{canvas:u,context:f,isNew:p}=c>0?Ri(l,d):{canvas:t,context:e,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,l,d)):p||f.clearRect(0,0,l,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,flip:i.flip,crop:i.crop}),f.globalCompositeOperation="copy";for(let m=c;m>1;m--){const t=r*2**m,e=n*2**m;f.drawImage(u,0,0,t,e,0,0,t/2,e/2)}f.globalCompositeOperation="source-over",c>0&&(e.imageSmoothingQuality="high",e.globalCompositeOperation="copy",e.drawImage(u,0,0,2*r,2*n,0,0,r,n),e.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this.gt)throw new Error("VideoSample is closed.");if(z(null!==this.xt),this.xt instanceof Si||this.xt instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this.xt}async transform(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.flip&&"boolean"!=typeof e.flip)throw new TypeError("options.flip, when provided, must be a boolean.");if(void 0!==e.crop&&Ui(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const{rotation:i,flip:r}=(n=this.rotation,o=this.flip,s=e.rotate??0,a=e.flip??!1,{rotation:H(n+(o?-s:s)),flip:o!==a});var n,o,s,a;const[h,c]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let l=e.crop;l&&(l=Vi(l,h,c));const d=l?l.width:h,u=l?l.height:c,f=d/u;let p,m;void 0!==e.width&&void 0===e.height?(p=e.width,m=p/f):void 0===e.width&&void 0!==e.height?(m=e.height,p=m*f):void 0!==e.width&&void 0!==e.height?(p=e.width,m=e.height):(p=d,m=u),p=vt(p,e.roundDimensionsTo??1),m=vt(m,e.roundDimensionsTo??1);const w={width:p,height:m,fit:e.fit??"fill",rotation:i,flip:r,crop:l??{left:0,top:0,width:h,height:c},alpha:e.alpha??"keep"};for(const t of Fi){let e=t(this,w);if(Bt(e)&&(e=await e),null!==e)return e}const{canvas:v,context:b,isNew:y}=Ri(w.width,w.height);return this._t(v,b,{fit:w.fit,rotation:w.rotation,flip:w.flip,crop:w.crop,targetIsFresh:y,fillBlack:"discard"===w.alpha}),new t(v,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setFlip(t){if("boolean"!=typeof t)throw new TypeError("newFlip must be a boolean.");this.flip=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||"object"!=typeof t)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},Fi=[],$i=[],Oi=0,Ri=(t,e)=>{for(const n of $i)if(n.canvas.width===t&&n.canvas.height===e)return n.age=Oi++,{canvas:n.canvas,context:n.context,isNew:!1};let i;if("undefined"!=typeof OffscreenCanvas)i=new OffscreenCanvas(t,e);else{if("undefined"==typeof window||"undefined"==typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=t,i.height=e}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return $i.length>=3&&$i.splice(((t,e)=>{let i=-1,r=1/0;for(let n=0;n<t.length;n++){const o=e(t[n]);o<r&&(r=o,i=n)}return i})($i,t=>t.age),1),$i.push({canvas:i,context:r,age:Oi++}),{canvas:i,context:r,isNew:!0}},Di=class{constructor(t){if(void 0!==t){if(!t||"object"!=typeof t)throw new TypeError("init.colorSpace, when provided, must be an object.");const e=Object.keys(nt);if(null!=t.primaries&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);const i=Object.keys(ot);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(st);if(null!=t.matrix&&!r.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Ni=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,Vi=(t,e,i)=>{const r=Math.min(t.left,e),n=Math.min(t.top,i),o=Math.min(t.width,e-r),s=Math.min(t.height,i-n);return z(o>=0),z(s>=0),{left:r,top:n,width:o,height:s}},Ui=(t,e)=>{if(!t||"object"!=typeof t)throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},zi=t=>{if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.colorSpace&&!["display-p3","srgb"].includes(t.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==t.format&&"string"!=typeof t.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!=typeof e)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.rect){if(!t.rect||"object"!=typeof t.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==t.rect.x&&(!Number.isInteger(t.rect.x)||t.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==t.rect.y&&(!Number.isInteger(t.rect.y)||t.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==t.rect.width&&(!Number.isInteger(t.rect.width)||t.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==t.rect.height&&(!Number.isInteger(t.rect.height)||t.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},ji=(t,e,i)=>{const r=Li(t),n=[];let o=0;for(const s of r){const t=Math.ceil(e/s.widthDivisor),r=Math.ceil(i/s.heightDivisor),a=t*s.sampleBytes,h=a*r;n.push({offset:o,stride:a}),o+=h}return n},Li=t=>{const e=(t,e,i,r,n)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:e,widthDivisor:i,heightDivisor:r},{sampleBytes:e,widthDivisor:i,heightDivisor:r}];return n&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:pt(t),z(!1)}},qi=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=Hi(i,r,t.codedWidth,t.codedHeight,t.format),o=e.layout;let s;if(e.format&&e.format!==t.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(e.format))throw new Error("NotSupportedError: Invalid destination format.");s=e.format}else s=t.format;return Wi(n,s,o)},Hi=(t,e,i,r,n)=>{const o={...t};if(void 0!==e){if(0===e.width||0===e.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");o.x=e.x||0,o.y=e.y||0,o.width=e.width||0,o.height=e.height||0}if(!Gi(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},Gi=(t,e)=>{if(null===t)return!0;const i=Li(t);for(let r=0;r<i.length;r++){const t=i[r],n=t.widthDivisor,o=t.heightDivisor;if((e.x||0)%n!==0)return!1;if((e.y||0)%o!==0)return!1}return!0},Wi=(t,e,i)=>{const r=Li(e),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let o=0;const s=[],a=[];for(let h=0;h<n;h++){const e=r[h],n=e.sampleBytes,c=e.widthDivisor,l=e.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(t.y||0)/l),d.sourceHeight=Math.ceil(Math.trunc(t.height||0)/l),d.sourceLeftBytes=Math.floor(Math.trunc(t.x||0)/c)*n,d.sourceWidthBytes=Math.floor(Math.trunc(t.width||0)/c)*n,void 0!==i){const t=i[h];if(t.stride<d.sourceWidthBytes)throw new TypeError(`Stride for plane ${h} is too small.`);d.destinationOffset=t.offset,d.destinationStride=t.stride}else d.destinationOffset=o,d.destinationStride=d.sourceWidthBytes;const u=d.destinationStride*d.sourceHeight+d.destinationOffset;if(u>4294967295)throw new TypeError("Allocation size exceeds limit.");a.push(u),o=Math.max(o,u);for(let t=0;t<h;t++){const e=s[t];if(!(a[h]<=e.destinationOffset||a[t]<=d.destinationOffset))throw new TypeError("Planes overlap.")}s.push(d)}return{allocationSize:o,computedLayouts:s}},Xi=new Map,Zi=(t,e)=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding options must be an object.");if(void 0!==e.alpha&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const i=e.bitrateMode;if(void 0!==i&&!["constant","variable"].includes(i))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==e.latencyMode&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==e.fullCodecString&&"string"!=typeof e.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==e.fullCodecString&&ii(e.fullCodecString)!==t)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${t}).`);if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.scalabilityMode&&"string"!=typeof e.scalabilityMode)throw new TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==e.contentHint&&"string"!=typeof e.contentHint)throw new TypeError("contentHint, when provided, must be a string.")},Qi=t=>{const e=t.bitrateMode,i=t.quality.Mt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Je(t.codec,t.width,t.height,r,"keep"===t.alpha),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:e,bitrateMode:i,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...(n=t.codec,"avc"===n?{avc:{format:"avc"}}:"hevc"===n?{hevc:{format:"hevc"}}:{})};var n},n=[];return null!==i.quantizer&&n.push({config:r(void 0,"quantizer",i.bitrate),quantizer:i.quantizer}),"quantizer"!==i.bitrateMode&&n.push({config:r(i.bitrate,i.bitrateMode,i.bitrate),quantizer:null}),z(n.length>0),n},Yi=class{constructor(t){if("number"!=typeof t&&"string"!=typeof t||(t={quality:t}),!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if("string"==typeof t.quality?!(t.quality in Ji):"number"!=typeof t.quality||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(void 0!==t.preferBitrate&&"boolean"!=typeof t.preferBitrate)throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this.Ct="string"==typeof t.quality?Ji[t.quality]:t.quality,this.At=t.preferBitrate??!1,this.St=void 0,this.Pt=void 0}else{if(void 0!==t.bitrate&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(void 0!==t.quantizer&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(void 0===t.bitrate&&void 0===t.quantizer)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this.Ct=void 0,this.At=!1,this.St=t.bitrate,this.Pt=t.quantizer}this.It=t.bitrateMode}Mt(t,e,i,r){const n=Ki[t];let o=null,s=this.It??r??"variable";if(void 0!==this.Pt){if(n)if(this.Pt<n.min||this.Pt>n.max){if(void 0===this.St)throw new Error(`Quantizer ${this.Pt} is out of range for codec '${t}'; must be between ${n.min} and ${n.max}.`)}else o=this.Pt,void 0===this.St&&(s="quantizer");else if(void 0===this.St)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else void 0===this.St&&n&&!this.At&&(z(void 0!==this.Ct),o=wt(Math.round((a=n.worst)+(n.best-a)*this.Ct),n.min,n.max));var a;let h;if(void 0!==this.St)h=this.St;else{let r=this.Ct;void 0===r&&(z(null!==o&&n),r=wt((o-n.worst)/(n.best-n.worst),0,1)),h=er(t,e,i,tr(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}Bt(t,e,i){return void 0!==this.St?this.St:(z(void 0!==this.Ct),er(t,e,i,tr(this.Ct)))}Ft(t){if(ze.includes(t)||"flac"===t)return;if(void 0!==this.St)return this.St;if(void 0===this.Ct)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const e=tr(this.Ct),i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!i)throw new Error(`Unhandled codec: ${t}`);let r=i*e;return"aac"===t?r=[96e3,128e3,16e4,192e3].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t):"opus"===t||"vorbis"===t?r=Math.max(6e3,r):"mp3"===t&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((t,e)=>Math.abs(e-r)<Math.abs(t-r)?e:t)),1e3*Math.round(r/1e3)}},Ji={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Ki={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:((()=>{if(null!==Pt)return Pt;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?Pt=Number(t[1]):null})()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},tr=t=>.3*Math.exp(2.5538*t),er=(t,e,i,r)=>{const n=e*i,o=3e6*Math.pow(n/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:73.33333333333333}[t]*r;return 1e3*Math.ceil(o/1e3)},ir=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void z(!1),rr=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,frameRate:s,...a}=e;if(!Ue.includes(t))return!1;if(!Number.isInteger(i)||i<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(void 0!==n&&!(n instanceof Yi))throw new TypeError("quality, when provided, must be a Quality.");if(void 0!==n&&void 0!==o)throw new TypeError("quality and bitrate cannot both be provided.");if(void 0!==o&&!(o instanceof Yi)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(void 0!==s&&(!Number.isFinite(s)||s<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");Zi(t,a);const h=nr(n,o)??new Yi("medium");let c;try{c=Qi({codec:t,width:i,height:r,quality:h,framerate:s,...a,alpha:"discard"})}catch{return!1}const l=JSON.stringify(c),d=Xi.get(l);if(d)return d;const u=(async()=>{for(const{config:e}of c)if(or.some(i=>i.supports(t,e)))return!0;if("undefined"==typeof VideoEncoder)return!1;if(!(i%2!=1&&r%2!=1||"avc"!==t&&"hevc"!==t))return!1;for(const{config:e,quantizer:n}of c){try{if(!(await VideoEncoder.isConfigSupported(e)).supported)continue}catch{continue}if(!Ct())return!0;if(await new Promise(async o=>{try{const s=new VideoEncoder({output:()=>{},error:()=>o(!1)});s.configure(e);const a=new Uint8Array(i*r*4),h=new VideoFrame(a,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});s.encode(h,null!==n?ir(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return Xi.set(l,u),u},nr=(t,e)=>void 0!==t?t:void 0!==e?e instanceof Yi?e:new Yi({bitrate:e}):void 0,or=[],sr=class t{constructor(t,e,i,r,n){this.bytes=t,this.view=e,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new t(e,et(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(e,i=this.end-e){if(e<this.start||e+i>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+i)}},ar=(t,e)=>{if(e<0||t.filePos<t.start||t.filePos+e>t.end)throw new RangeError(`Tried reading [${t.filePos}, ${t.filePos+e}), but slice is [${t.start}, ${t.end}). This is likely an internal error, please report it alongside the file that caused it.`)},hr=(t,e)=>{ar(t,e);const i=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,i},cr=t=>{ar(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},lr=class{constructor(t){this.mutex=new ct,this.trackTimestampInfo=new WeakMap,this.output=t}onTrackClose(t){}validateTimestamp(t,e,i){let r=this.trackTimestampInfo.get(t);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,r)}}},dr=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ur=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,fr=t=>{const e=Math.floor(t/36e5),i=Math.floor(t%36e5/6e4),r=Math.floor(t%6e4/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")},pr=class{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 n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);z(void 0!==e);const i=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(i)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(const i of t.children)i&&(e+=this.measureBox(i));return e}}},mr=new Uint8Array(8),wr=new DataView(mr.buffer),vr=t=>[(t%256+256)%256],br=t=>(wr.setUint16(0,t,!1),[mr[0],mr[1]]),yr=t=>(wr.setInt16(0,t,!1),[mr[0],mr[1]]),gr=t=>(wr.setUint32(0,t,!1),[mr[1],mr[2],mr[3]]),xr=t=>(wr.setUint32(0,t,!1),[mr[0],mr[1],mr[2],mr[3]]),Er=t=>(wr.setInt32(0,t,!1),[mr[0],mr[1],mr[2],mr[3]]),Tr=t=>(wr.setUint32(0,Math.floor(t/2**32),!1),wr.setUint32(4,t,!1),[mr[0],mr[1],mr[2],mr[3],mr[4],mr[5],mr[6],mr[7]]),kr=t=>(wr.setInt32(0,Math.floor(t/2**32),!1),wr.setUint32(4,t,!1),[mr[0],mr[1],mr[2],mr[3],mr[4],mr[5],mr[6],mr[7]]),_r=t=>(wr.setInt16(0,256*t,!1),[mr[0],mr[1]]),Mr=t=>(wr.setInt32(0,65536*t,!1),[mr[0],mr[1],mr[2],mr[3]]),Cr=t=>(wr.setInt32(0,2**30*t,!1),[mr[0],mr[1],mr[2],mr[3]]),Ar=(t,e)=>{const i=[];let r=t;do{let t=127&r;r>>=7,i.length>0&&(t|=128),i.push(t),void 0!==e&&e--}while(r>0||e);return i.reverse()},Sr=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},Pr=t=>[Mr(t[0]),Mr(t[1]),Cr(t[2]),Mr(t[3]),Mr(t[4]),Cr(t[5]),Mr(t[6]),Mr(t[7]),Cr(t[8])],Ir=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),Br=(t,e,i,r,n)=>Ir(t,[vr(e),gr(i),r??[]],n),Fr=()=>Ir("styp",[Sr("iso5"),xr(0),Sr("iso5"),Sr("iso6"),Sr("mp41"),Sr("cmfc"),Sr("dash")]),$r=(t,e)=>{const i=Math.max(0,t.minWrittenTimestamp);let r=Math.max(0,t.maxWrittenEndTimestamp-i);return Number.isFinite(r)||(r=0),Br("sidx",1,0,[xr(1),xr(so),Tr(ho(i,so)),Tr(0),br(0),br(1),xr(2147483647&e),xr(ho(r,so)),xr(0)])},Or=t=>({type:"mdat",largeSize:t}),Rr=t=>Ir("moov",void 0,[Dr(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Nr(e,t.creationTime)),t.isFragmented?kn(t.trackDatas):null,Dn(t)]),Dr=(t,e)=>{const i=Math.max(0,...e.map(t=>Math.max(0,ho(co(t),so)+ho(t.startTimestampOffset??0,so)))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!Y(t)||!Y(i),o=n?Tr:xr;return Br("mvhd",+n,0,[o(t),o(t),xr(so),o(i),Mr(1),_r(1),Array(10).fill(0),Pr(G),Array(24).fill(0),xr(r)])},Nr=(t,e)=>{const i=ao(t),r=null!==t.startTimestampOffset&&0!==t.startTimestampOffset;return Ir("trak",void 0,[Vr(t,e),r?Ur(t):null,zr(t,e),void 0!==i.name?Ir("udta",void 0,[Ir("name",[...rt.encode(i.name)])]):null])},Vr=(t,e)=>{const i=Math.max(0,ho(co(t),so)+ho(t.startTimestampOffset??0,so)),r=!Y(e)||!Y(i),n=r?Tr:xr;let o;if("video"===t.type&&t.track.metadata.transformationMatrix)o=t.track.metadata.transformationMatrix;else if("video"===t.type){const{rotation:e,flip:i}=t.track.metadata;o=((t,e,i)=>{const[r,n,,o,s]=t,a=Math.abs(r)*e+Math.abs(o)*i,h=Math.abs(n)*e+Math.abs(s)*i;return Z(Z(X(-e/2,-i/2),t),X(a/2,h/2))})(Z(W(e??0),(t=>[t,0,0,0,1,0,0,0,1])(i?-1:1)),t.info.width,t.info.height)}else o=G;let s=2;!1!==t.track.metadata.disposition?.default&&(s|=1);const a="video"===t.type?0:"audio"===t.type?1:"subtitle"===t.type?2:pt(t);return Br("tkhd",+r,s,[n(e),n(e),xr(t.track.id),xr(0),n(i),Array(8).fill(0),br(0),br(a),_r("audio"===t.type?1:0),br(0),Pr(o),Mr("video"===t.type?t.info.width:0),Mr("video"===t.type?t.info.height:0)])},Ur=t=>{const e=t.startTimestampOffset;if(z(null!==e),e>0){const i=ho(e,so),r=ho(co(t),so),n=!Y(i)||!Y(r),o=n?Tr:xr,s=n?kr:Er;return Ir("edts",void 0,[Br("elst",n?1:0,0,[xr(2),o(i),s(-1),Mr(1),o(r),s(0),Mr(1)])])}{const r=ho(-e,t.timescale),n=Math.max(0,ho(co(t),so)+ho(e,so)),o=!((i=r)>=-(2**31)&&i<2**31&&Y(n)),s=o?Tr:xr,a=o?kr:Er;return Ir("edts",void 0,[Br("elst",o?1:0,0,[xr(1),s(n),a(r),Mr(1)])])}var i},zr=(t,e)=>Ir("mdia",void 0,[jr(t,e),Hr(!0,Lr[t.type],qr[t.type]),Gr(t)]),jr=(t,e)=>{const i=ho(co(t),t.timescale),r=!Y(e)||!Y(i),n=r?Tr:xr;return Br("mdhd",+r,0,[n(e),n(e),xr(t.timescale),n(i),br(Yn(t.track.metadata.languageCode??"und")),br(0)])},Lr={video:"vide",audio:"soun",subtitle:"text"},qr={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Hr=(t,e,i,r="\0\0\0\0")=>Br("hdlr",0,0,[t?Sr("mhlr"):xr(0),Sr(e),Sr(r),xr(0),xr(0),Sr(i,!0)]),Gr=t=>Ir("minf",void 0,[Wr[t.type](),Xr(),Yr(t)]),Wr={video:()=>Br("vmhd",0,1,[br(0),br(0),br(0),br(0)]),audio:()=>Br("smhd",0,0,[br(0),br(0)]),subtitle:()=>Br("nmhd",0,0)},Xr=()=>Ir("dinf",void 0,[Zr()]),Zr=()=>Br("dref",0,0,[xr(1)],[Qr()]),Qr=()=>Br("url ",0,1),Yr=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return Ir("stbl",void 0,[Jr(t),vn(t),e?En(t):null,e?Tn(t):null,yn(t),gn(t),xn(t),bn(t)])},Jr=t=>{let e;if("video"===t.type)e=Kr(Hn(t.track.source.$t,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=Wn(t.track.source.$t,t.info.decoderConfig.codec,t.muxer.isQuickTime);z(i),e=on(i,t)}else"subtitle"===t.type&&(e=wn(Zn[t.track.source.$t],t));return z(e),Br("stsd",0,0,[xr(1)],[e])},Kr=(t,e)=>Ir(t,[Array(6).fill(0),br(1),br(0),br(0),Array(12).fill(0),br(e.info.width),br(e.info.height),xr(4718592),xr(4718592),xr(0),br(1),vr(18),Sr(ie),Array(13).fill(0),br(e.info.hasAlphaChannel?32:24),yr(65535)],[Gn[e.track.source.$t]?.(e)??null,en(e),at(e.info.decoderConfig.colorSpace)?null:rn(e),tn(e)]),tn=t=>0===t.avgBitrate&&0===t.maxBitrate?null:Ir("btrt",[xr(0),xr(t.maxBitrate),xr(t.avgBitrate)]),en=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:Ir("pasp",[xr(t.info.pixelAspectRatio.num),xr(t.info.pixelAspectRatio.den)]),rn=t=>{const e=t.info.decoderConfig.colorSpace;return Ir("colr",[Sr(t.muxer.isQuickTime?"nclc":"nclx"),br(null!=e?.primaries?nt[e.primaries]:2),br(null!=e?.transfer?ot[e.transfer]:2),br(null!=e?.matrix?st[e.matrix]:2),t.muxer.isQuickTime?[]:vr((e?.fullRange?1:0)<<7)])},nn=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,i=e.codec.split("."),r=Number(i[1]),n=Number(i[2]),o=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(e.colorSpace?.fullRange??0)),s=i[5]?Number(i[5]):e.colorSpace?.primaries?nt[e.colorSpace.primaries]:1,a=i[6]?Number(i[6]):e.colorSpace?.transfer?ot[e.colorSpace.transfer]:1,h=i[7]?Number(i[7]):e.colorSpace?.matrix?st[e.colorSpace.matrix]:1;return Br("vpcC",1,0,[vr(r),vr(n),vr(o),vr(s),vr(a),vr(h),br(0)])},on=(t,e)=>{let i,r=0,n=16;const o=ze.includes(e.track.source.$t);if(o){const t=e.track.source.$t,{sampleSize:i}=ei(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),br(1),br(r),br(0),xr(0),br(e.info.numberOfChannels),br(n),br(0),br(0),br(e.info.sampleRate<65536?e.info.sampleRate:0),br(0)];else{const t=o?0:-2;i=[Array(6).fill(0),br(1),br(r),br(0),xr(0),br(e.info.numberOfChannels),br(Math.min(n,16)),yr(t),br(0),br(e.info.sampleRate<65536?e.info.sampleRate:0),br(0),o?[xr(1),xr(n/8),xr(e.info.numberOfChannels*n/8)]:[xr(0),xr(0),xr(0)],xr(2)]}return Ir(t,i,[Xn(e.track.source.$t,e.muxer.isQuickTime)?.(e)??null,tn(e)])},sn=t=>{let e;switch(t.track.source.$t){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${t.track.source.$t}`)}let i=[...vr(e),...vr(21),...gr(0),...xr(t.maxBitrate),...xr(t.avgBitrate)];if(t.info.decoderConfig.description){const e=tt(t.info.decoderConfig.description);i=[...i,...vr(5),...Ar(e.byteLength),...e]}return i=[...br(1),...vr(0),...vr(4),...Ar(i.length),...i,...vr(6),...vr(1),...vr(2)],i=[...vr(3),...Ar(i.length),...i],Br("esds",0,0,i)},an=t=>Ir("wave",void 0,[hn(t),cn(t),Ir("\0\0\0\0")]),hn=t=>Ir("frma",[Sr(Wn(t.track.source.$t,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),cn=t=>{const{littleEndian:e}=ei(t.track.source.$t);return Ir("enda",[br(+e)])},ln=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){z(a.byteLength>=18);const t=Ce(tt(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return Ir("dOps",[vr(0),vr(e),br(i),xr(r),yr(n),vr(o),...s])},dn=t=>{const e=t.info.decoderConfig?.description;z(e);const i=tt(e);return Br("dfLa",0,0,[...i.subarray(4)])},un=t=>{const{littleEndian:e,sampleSize:i}=ei(t.track.source.$t);return Br("pcmC",0,0,[vr(+e),vr(8*i)])},fn=t=>{z(t.info.primingPacket);const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new Wt(t);e.skipBits(16),e.skipBits(16);const i=e.readBits(2);if(3===i)return null;const r=e.readBits(6),n=e.readBits(5);if(n>8)return null;const o=e.readBits(3),s=e.readBits(3);return 1&s&&1!==s&&e.skipBits(2),4&s&&e.skipBits(2),2===s&&e.skipBits(2),{fscod:i,bsid:n,bsmod:o,acmod:s,lfeon:e.readBits(1),bitRateCode:Math.floor(r/2)}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const i=new Uint8Array(3),r=new Wt(i);return r.writeBits(2,e.fscod),r.writeBits(5,e.bsid),r.writeBits(3,e.bsmod),r.writeBits(3,e.acmod),r.writeBits(1,e.lfeon),r.writeBits(5,e.bitRateCode),r.writeBits(5,0),Ir("dac3",[...i])},pn=t=>{z(t.info.primingPacket);const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new Wt(t);e.skipBits(16);const i=e.readBits(2);if(e.skipBits(3),0!==i&&2!==i)return null;const r=e.readBits(11),n=e.readBits(2);let o,s=0;3===n?(s=e.readBits(2),o=3):o=e.readBits(2);const a=e.readBits(3),h=e.readBits(1),c=e.readBits(5);if(c<11||c>16)return null;const l=Se[o];let d;return d=n<3?te[n]/1e3:ee[s]/1e3,{dataRate:Math.round((r+1)*d/(16*l)),substreams:[{fscod:n,fscod2:s,bsid:c,bsmod:0,acmod:a,lfeon:h,numDepSub:0,chanLoc:0}]}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let i=16;for(const s of e.substreams)i+=23,s.numDepSub>0?i+=9:i+=1;const r=Math.ceil(i/8),n=new Uint8Array(r),o=new Wt(n);o.writeBits(13,e.dataRate),o.writeBits(3,e.substreams.length-1);for(const s of e.substreams)o.writeBits(2,s.fscod),o.writeBits(5,s.bsid),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(3,s.bsmod),o.writeBits(3,s.acmod),o.writeBits(1,s.lfeon),o.writeBits(3,0),o.writeBits(4,s.numDepSub),s.numDepSub>0?o.writeBits(9,s.chanLoc):o.writeBits(1,0);return Ir("dec3",[...n])},mn=t=>{z(t.info.primingPacket);const e=(t=>{const e=(t=>{if(t.length<18)return null;if(127!==t[0]||254!==t[1]||128!==t[2]||1!==t[3])return null;const e=new Wt(t);if(e.skipBits(32),e.skipBits(1),31!==e.readBits(5))return null;const i=e.readBits(1),r=e.readBits(7)+1;if(r%8!=0)return null;const n=e.readBits(14)+1;if(n<96)return null;const o=e.readBits(6);if(o>=Fe.length)return null;const s=Pe[e.readBits(4)];if(0===s)return null;const a=Ie[e.readBits(5)];if(0!==e.readBits(1))return null;e.skipBits(4),e.skipBits(5);const h=e.readBits(2);if(3===h)return null;e.skipBits(1),i&&e.skipBits(16),e.skipBits(7);const c=Be[e.readBits(3)];if(0===c)return null;const l=0!==h;return{frameSize:n,sampleRate:s,numberOfChannels:Fe[o]+(l?1:0),sampleCount:32*r,channelLayout:$e[o]|(l?8:0),amode:o,lfePresent:l,bitRate:a,pcmResolution:c}})(t),i=et(t);let r=e?4*Math.ceil(e.frameSize/4):0,n=null;for(;r+4<=t.length&&1683496997===i.getUint32(r);){const e=Ne(t.subarray(r));if(!e)break;n??=e,r+=e.frameSize}if(e)return{frameSize:n?r:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:null!==n};if(!n?.asset)return null;const{asset:o}=n;return{frameSize:r,sampleRate:o.sampleRate,numberOfChannels:o.numberOfChannels,sampleCount:o.sampleCount,channelLayout:o.channelLayout,pcmResolution:o.pcmResolution,bitRate:0,core:null,hasExtensions:!0}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return Ir("ddts",[...Ve(e)])},wn=(t,e)=>Ir(t,[Array(6).fill(0),br(1)],[Qn[e.track.source.$t](e),tn(e)]),vn=t=>Br("stts",0,0,[xr(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[xr(t.sampleCount),xr(t.sampleDelta)])]),bn=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return Br("stss",0,0,[xr(e.length),e.map(([t])=>xr(t+1))])},yn=t=>Br("stsc",0,0,[xr(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[xr(t.firstChunk),xr(t.samplesPerChunk),xr(1)])]),gn=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=ei(t.track.source.$t);return Br("stsz",0,0,[xr(e*t.info.numberOfChannels),xr(t.samples.reduce((e,i)=>e+ho(i.duration,t.timescale),0))])}return Br("stsz",0,0,[xr(0),xr(t.samples.length),t.samples.map(t=>xr(t.size))])},xn=t=>t.finalizedChunks.length>0&&Q(t.finalizedChunks).offset>=2**32?Br("co64",0,0,[xr(t.finalizedChunks.length),t.finalizedChunks.map(t=>Tr(t.offset))]):Br("stco",0,0,[xr(t.finalizedChunks.length),t.finalizedChunks.map(t=>xr(t.offset))]),En=t=>Br("ctts",1,0,[xr(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[xr(t.sampleCount),Er(t.sampleCompositionTimeOffset)])]),Tn=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;z(t.compositionTimeOffsetTable.length>0),z(t.samples.length>0);for(let s=0;s<t.compositionTimeOffsetTable.length;s++){const r=t.compositionTimeOffsetTable[s];e=Math.min(e,r.sampleCompositionTimeOffset),i=Math.max(i,r.sampleCompositionTimeOffset)}for(let s=0;s<t.samples.length;s++){const e=t.samples[s];r=Math.min(r,ho(e.timestamp,t.timescale)),n=Math.max(n,ho(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:Br("cslg",0,0,[Er(o),Er(e),Er(i),Er(r),Er(n)])},kn=t=>Ir("mvex",void 0,t.map(_n)),_n=t=>Br("trex",0,0,[xr(t.track.id),xr(1),xr(0),xr(0),xr(0)]),Mn=(t,e)=>Ir("moof",void 0,[Cn(t),...e.map(Sn)]),Cn=t=>Br("mfhd",0,0,[xr(t)]),An=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},Sn=t=>Ir("traf",void 0,[Pn(t),In(t),Bn(t)]),Pn=t=>{z(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:An(i)};return Br("tfhd",0,131128,[xr(t.track.id),xr(r.duration),xr(r.size),xr(r.flags)])},In=t=>(z(t.currentChunk),Br("tfdt",1,0,[Tr(ho(t.currentChunk.startTimestamp,t.timescale))])),Bn=t=>{z(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(An),n=t.currentChunk.samples.map(e=>ho(e.timestamp-e.decodeTimestamp,t.timescale)),o=new Set(e),s=new Set(i),a=new Set(r),h=new Set(n),c=2===a.size&&r[0]!==r[1],l=o.size>1,d=s.size>1,u=!c&&a.size>1,f=h.size>1||[...h].some(t=>0!==t);let p=0;return p|=1,p|=4*+c,p|=256*+l,p|=512*+d,p|=1024*+u,p|=2048*+f,Br("trun",1,p,[xr(t.currentChunk.samples.length),xr(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?xr(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?xr(e[o]):[],d?xr(i[o]):[],u?xr(r[o]):[],f?Er(n[o]):[]])])},Fn=t=>{const e=[];for(const i of t.finalizedChunks){const r=i.samples.findIndex(t=>"key"===t.type);if(-1===r)continue;const n=i.samples[r];e.push([Tr(ho(n.timestamp,t.timescale)),Tr(i.moofOffset),xr(i.trafIndex+1),xr(1),xr(r+1)])}return Br("tfra",1,0,[xr(t.track.id),xr(63),xr(e.length),e])},$n=()=>Ir("vtte"),On=(t,e,i,r,n)=>Ir("vttc",void 0,[null!==n?Ir("vsid",[Er(n)]):null,null!==i?Ir("iden",[...rt.encode(i)]):null,null!==e?Ir("ctim",[...rt.encode(fr(e))]):null,null!==r?Ir("sttg",[...rt.encode(r)]):null,Ir("payl",[...rt.encode(t)])]),Rn=t=>Ir("vtta",[...rt.encode(t)]),Dn=t=>{const e=[],i=t.format.Ot.metadataFormat??"auto",r=t.output.Rt;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=jn(r);t&&e.push(t)}else if("mdta"===i){const t=Ln(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&Nn(e,t.output.Rt);return 0===e.length?null:Ir("udta",void 0,e)},Nn=(t,e)=>{for(const{key:i,value:r}of Ft(e))switch(i){case"title":t.push(Vn("©nam",r));break;case"description":t.push(Vn("©des",r));break;case"artist":t.push(Vn("©ART",r));break;case"album":t.push(Vn("©alb",r));break;case"albumArtist":t.push(Vn("albr",r));break;case"genre":t.push(Vn("©gen",r));break;case"date":t.push(Vn("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(Vn("©cmt",r));break;case"lyrics":t.push(Vn("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:pt(i)}if(e.raw)for(const i in e.raw){const r=e.raw[i];null==r||4!==i.length||t.some(t=>t.type===i)||("string"==typeof r?t.push(Vn(i,r)):r instanceof Uint8Array&&t.push(Ir(i,Array.from(r))))}},Vn=(t,e)=>{const i=rt.encode(e);return Ir(t,[br(i.length),br(Yn("und")),Array.from(i)])},Un={"image/jpeg":13,"image/png":14,"image/bmp":27},zn=(t,e)=>{const i=[];for(const{key:r,value:n}of Ft(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:qn(n)});break;case"description":i.push({key:e?"description":"©des",value:qn(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:qn(n)});break;case"album":i.push({key:e?"album":"©alb",value:qn(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:qn(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:qn(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:qn(n)});break;case"beatsPerMinute":e||i.push({key:"tmpo",value:Ir("data",[xr(21),xr(0),br(n)])});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:qn(n)});break;case"date":i.push({key:e?"date":"©day",value:qn(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:Ir("data",[xr(Un[t.mimeType]??0),xr(0),Array.from(t.data)])});break;case"trackNumber":if(e){const e=void 0!==t.tracksTotal?`${n}/${t.tracksTotal}`:n.toString();i.push({key:"track",value:qn(e)})}else i.push({key:"trkn",value:Ir("data",[xr(0),xr(0),br(0),br(n),br(t.tracksTotal??0),br(0)])});break;case"discNumber":e||i.push({key:"disc",value:Ir("data",[xr(0),xr(0),br(0),br(n),br(t.discsTotal??0),br(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:pt(r)}if(t.raw)for(const r in t.raw){const n=t.raw[r];null==n||!e&&4!==r.length||i.some(t=>t.key===r)||("string"==typeof n?i.push({key:r,value:qn(n)}):n instanceof Uint8Array?i.push({key:r,value:Ir("data",[xr(0),xr(0),Array.from(n)])}):n instanceof Ht&&i.push({key:r,value:Ir("data",[xr(Un[n.mimeType]??0),xr(0),Array.from(n.data)])}))}return i},jn=t=>{const e=zn(t,!1);return 0===e.length?null:Br("meta",0,0,void 0,[Hr(!1,"mdir","","appl"),Ir("ilst",void 0,e.map(t=>Ir(t.key,void 0,[t.value])))])},Ln=t=>{const e=zn(t,!0);return 0===e.length?null:Ir("meta",void 0,[Hr(!1,"mdta",""),Br("keys",0,0,[xr(e.length)],e.map(t=>Ir("mdta",[...rt.encode(t.key)]))),Ir("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...xr(e+1));return Ir(i,void 0,[t.value])}))])},qn=t=>Ir("data",[xr(1),xr(0),...rt.encode(t)]),Hn=(t,e)=>{switch(t){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return e}},Gn={avc:t=>t.info.decoderConfig&&Ir("avcC",[...tt(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&Ir("hvcC",[...tt(t.info.decoderConfig.description)]),vp8:nn,vp9:nn,av1:t=>Ir("av1C",Ke(t.info.decoderConfig.codec)),prores:null},Wn=(t,e,i)=>{switch(t){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e}if(i)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},Xn=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return sn;case"opus":return ln;case"flac":return dn;case"ac3":return fn;case"eac3":return pn;case"dts":return mn}if(e)switch(t){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return an}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return un}return null},Zn={webvtt:"wvtt"},Qn={webvtt:t=>Ir("vttC",[...rt.encode(t.info.config.description)])},Yn=t=>{z(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},Jn=class{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t.Dt)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t.Nt(e),t.Dt=!0}start(){z(!this.started),this.target.Vt(),this.started=!0}write(t){z(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target.Ut(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return z(this.started&&!this.finalized),this.target.zt()}async finalize(){z(this.started&&!this.finalized),await this.target.jt(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=0}const i=e+t.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const t=new Uint8Array(r);t.set(this.trackedWrites,0),this.trackedWrites=t}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},Kn=(ki(),class extends Ut{constructor(){super(...arguments),this.Dt=!1,this.Lt=null,this.onwrite=null}Nt(t){!1!==this.Lt&&(this.Lt=t)}qt(t,e){this.onwrite?.(t,e),this.ct("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 no(this,t)}}),to=65536,eo=2**32,io=class extends Kn{constructor(t={}){if(super(),this.buffer=null,this.Ht=0,!t||"object"!=typeof t)throw new TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");if(this.Ot=t,this.Gt="resize"in new ArrayBuffer(0),this.Gt)try{this.Wt=new ArrayBuffer(to,{maxByteLength:eo})}catch{this.Wt=new ArrayBuffer(to),this.Gt=!1}else this.Wt=new ArrayBuffer(to);this.Xt=new Uint8Array(this.Wt)}Zt(t){let e=this.Wt.byteLength;for(;e<t;)e*=2;if(e!==this.Wt.byteLength){if(e>eo)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.Gt)this.Wt.resize(e);else{const t=new ArrayBuffer(e),i=new Uint8Array(t);i.set(this.Xt,0),this.Wt=t,this.Xt=i}}}Vt(){}Ut(t,e){this.Zt(e+t.byteLength),this.Xt.set(t,e),this.Ht=Math.max(this.Ht,e+t.byteLength),this.qt(e,e+t.byteLength)}async zt(){}async jt(){this.buffer=this.Wt.slice(0,this.Ht),this.Ot.onFinalize&&await this.Ot.onFinalize(this.buffer),this.ct("finalized")}async Qt(){}Yt(t,e){return this.Xt.slice(t,e)}},ro=class extends Kn{constructor(t,e={}){if(super(),this.Jt=[],this.Kt=0,this.te=0,this.ee=null,this.ie=null,this.re=[],!(t instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=e&&"object"!=typeof e)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==e.chunked&&"boolean"!=typeof e.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==e.chunkSize&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this.ne=t,this.Ot=e,this.oe=e.chunked??!1,this.se=e.chunkSize??16777216}Vt(){this.ee=this.ne.getWriter()}Ut(t,e){if(e>this.Kt){const t=e-this.Kt;this.Ut(new Uint8Array(t),this.Kt)}this.Jt.push({data:t.slice(),start:e}),this.Kt=Math.max(this.Kt,e+t.byteLength),this.qt(e,e+t.byteLength)}async zt(){if(null!==this.ie)throw this.ie;if(z(this.ee),0===this.Jt.length)return;const t=[],e=[...this.Jt].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){const r=t[t.length-1],n=e[i];n.start<=r.start+r.size?r.size=Math.max(r.size,n.start+n.data.byteLength-r.start):t.push({start:n.start,size:n.data.byteLength})}for(const i of t){i.data=new Uint8Array(i.size);for(const t of this.Jt)i.start<=t.start&&t.start<i.start+i.size&&i.data.set(t.data,t.start-i.start);if(null!==this.ee.desiredSize&&this.ee.desiredSize<=0&&await this.ee.ready,this.oe)this.ae(i.data,i.start),this.he();else{if(!0===this.Lt&&i.start!==this.te)throw new Error("Internal error: Monotonicity violation.");this.ee.write({type:"write",data:i.data,position:i.start}).catch(t=>{this.ie??=t}),this.te=i.start+i.data.byteLength}}this.Jt.length=0}ae(t,e){let i=this.re.findIndex(t=>t.start<=e&&e<t.start+this.se);-1===i&&(i=this.ce(e));const r=this.re[i],n=e-r.start,o=t.subarray(0,Math.min(this.se-n,t.byteLength));r.data.set(o,n);const s={start:n,end:n+o.byteLength};if(this.le(r,s),0===r.written[0].start&&r.written[0].end===this.se&&(r.shouldFlush=!0),this.re.length>2){for(let t=0;t<this.re.length-1;t++)this.re[t].shouldFlush=!0;this.he()}o.byteLength<t.byteLength&&this.ae(t.subarray(o.byteLength),e+o.byteLength)}le(t,e){let i=0,r=t.written.length-1,n=-1;for(;i<=r;){const o=Math.floor(i+(r-i+1)/2);t.written[o].start<=e.start?(i=o+1,n=o):r=o-1}for(t.written.splice(n+1,0,e),(-1===n||t.written[n].end<e.start)&&n++;n<t.written.length-1&&t.written[n].end>=t.written[n+1].start;)t.written[n].end=Math.max(t.written[n].end,t.written[n+1].end),t.written.splice(n+1,1)}ce(t){const e={start:Math.floor(t/this.se)*this.se,data:new Uint8Array(this.se),written:[],shouldFlush:!1};return this.re.push(e),this.re.sort((t,e)=>t.start-e.start),this.re.indexOf(e)}he(t=!1){z(this.ee);for(let e=0;e<this.re.length;e++){const i=this.re[e];if(i.shouldFlush||t){for(const t of i.written){const e=i.start+t.start;if(!0===this.Lt&&e!==this.te)throw new Error("Internal error: Monotonicity violation.");let r;r=0===t.start&&t.end===i.data.byteLength||!_t()?i.data.subarray(t.start,t.end):i.data.slice(t.start,t.end),this.ee.write({type:"write",data:r,position:e}).catch(t=>{this.ie??=t}),this.te=i.start+t.end}this.re.splice(e--,1)}}}async jt(){if(this.oe&&this.he(!0),null!==this.ie)throw this.ie;z(this.ee),await this.ee.ready,await this.ee.close(),this.ct("finalized")}async Qt(){return this.ee?.close()}},no=class extends Kn{constructor(t,e){super(),this.de=t,this.ue=e}Vt(){}Ut(t,e){this.de.Ut(t,this.ue+e),this.qt(e,e+t.byteLength)}zt(){return this.de.zt()}async jt(){this.ct("finalized")}async Qt(){}Nt(t){super.Nt(t),this.de.Nt(t)}},oo=class{constructor(t,e){if(this.rootPath=t,this.getTarget=e,"string"!=typeof t)throw new TypeError("rootPath must be a string.");if("function"!=typeof e)throw new TypeError("getTarget must be a function.")}},so=57600,ao=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},ho=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},co=t=>{if(0===t.samples.length)return 0;let e=1/0,i=-1/0;for(let r=0;r<t.samples.length;r++){const n=t.samples[r];n.timestamp<e&&(e=n.timestamp),n.timestamp+n.duration>i&&(i=n.timestamp+n.duration)}return e===1/0?0:i-e},lo=class extends lr{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new io,this.auxWriter=new Jn(this.auxTarget,!1),this.auxBoxWriter=new pr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ft(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=e,this.formatOptions={...e.Ot},this.isQuickTime=e instanceof Bo,this.isCmaf=e instanceof Io,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(e instanceof Io?1/0:1),this.auxWriter.start()}async start(){const t=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output.fe(t=>void 0!==this.formatOptions.fastStart?"fragmented"===this.formatOptions.fastStart:t instanceof io),this.boxWriter=new pr(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof io&&"in-memory"),this.isFragmented="fragmented"===this.fastStart),this.isCmaf){if(!this.output.pe())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const t=new Jn(await this.output.me(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new pr(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.$t);{const t=this.initBoxWriter??this.boxWriter;if(z(t),this.formatOptions.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return Ir("ftyp",t.isQuickTime?[Sr("qt "),xr(e),Sr("qt ")]:t.fragmented?t.cmaf?[Sr("iso5"),xr(e),Sr("iso5"),Sr("iso6"),Sr("mp41"),Sr("cmfc"),Sr("dash")]:[Sr("iso5"),xr(e),Sr("iso5"),Sr("iso6"),Sr("mp41")]:[Sr("isom"),xr(e),Sr("isom"),t.holdsAvc?Sr("avc1"):[],Sr("mp41")])})({isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onFtyp(e,i)}this.ftypSize=t.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const i of this.output.tracks)if(void 0===i.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(z(this.writer),z(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Or(!0),this.boxWriter.writeBox(this.mdat));await(this.writer?.flush());for(const i of this.output.tracks)i.isVideoTrack()&&i.metadata.decoderConfig?this.getVideoTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig}):i.isAudioTrack()&&i.metadata.decoderConfig&&this.getAudioTrackData(i,i.metadata.primingPacket??null,{decoderConfig:i.metadata.decoderConfig});t()}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.gt&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.$t]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isQuickTime?"quicktime":"mp4");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings)].join(", ")}"`),e})({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;hi(i,t.source.$t),z(i),z(i.decoderConfig);const n={...i.decoderConfig};z(void 0!==n.codedWidth),z(void 0!==n.codedHeight);let o=!1;if("avc"!==t.source.$t||n.description){if("hevc"===t.source.$t&&!n.description){if(!e)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const t=pe(e.data);if(!t)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push((3&t.generalProfileSpace)<<6|(1&t.generalTierFlag)<<5|31&t.generalProfileIdc),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(255&t.generalProfileCompatibilityFlags),e.push(...t.generalConstraintIndicatorFlags),e.push(255&t.generalLevelIdc),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(255&t.minSpatialSegmentationIdc),e.push(252|3&t.parallelismType),e.push(252|3&t.chromaFormatIdc),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.avgFrameRate>>8&255),e.push(255&t.avgFrameRate),e.push((3&t.constantFrameRate)<<6|(7&t.numTemporalLayers)<<3|(1&t.temporalIdNested)<<2|3&t.lengthSizeMinusOne),e.push(255&t.arrays.length);for(const i of t.arrays){e.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),e.push(i.nalUnits.length>>8&255),e.push(255&i.nalUnits.length);for(const t of i.nalUnits){e.push(t.length>>8&255),e.push(255&t.length);for(let i=0;i<t.length;i++)e.push(t[i])}}return new Uint8Array(e)})(t),o=!0}}else{if(!e)throw new Error("No AVC description provided; you must therefore provide a priming packet.");const t=he(e.data);if(!t)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=ce(t),o=!0}const s=(t=>{const e=t<0?-1:1;let i=0,r=1,n=1,o=0,s=t=Math.abs(t);for(;;){const t=Math.floor(s),a=t*n+i,h=t*o+r;if(h>1e6)return{num:e*n,den:o};if(i=n,r=o,n=a,o=h,s=1/(s-t),!isFinite(s))break}return{num:e*n,den:o}})(1/(t.metadata.frameRate??57600)).den,a=n.displayAspectWidth,h=n.displayAspectHeight,c=void 0===a||void 0===h?{num:1,den:1}:Dt({num:a*n.codedHeight,den:h*n.codedWidth}),l="ap4h"===n.codec||"ap4x"===n.codec,d={muxer:this,track:t,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:c,decoderConfig:n,requiresAnnexBTransformation:o,hasAlphaChannel:l},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:t.source.we??t.metadata.averageBitrate??0,maxBitrate:t.source.we??t.metadata.bitrate??0};return this.trackDatas.push(d),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;li(i,t.source.$t),z(i),z(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.$t&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=Ti(sr.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Xt[t.samplingFrequencyIndex],r=Zt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Qt({objectType:t.objectType,outputSampleRate:i,outputNumberOfChannels:r}),o=!0}if(!e){if("ac3"===t.source.$t||"eac3"===t.source.$t)throw new Error("AC-3/E-AC-3 require a priming packet.");if("dts"===t.source.$t)throw new Error("DTS requires a priming packet.")}const s={muxer:this,track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&ze.includes(t.source.$t),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:e},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:t.source.we??t.metadata.averageBitrate??0,maxBitrate:t.source.we??t.metadata.bitrate??0};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;di(e),z(e),z(e.config);const r={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:t.source.we??t.metadata.averageBitrate??0,maxBitrate:t.source.we??t.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...ne(n)].map(t=>n.subarray(t.offset,t.offset+t.length));if(0===t.length)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");n=(t=>{const e=t.reduce((t,e)=>t+4+e.byteLength,0),i=new Uint8Array(e);let r=0;for(const n of t){const t=new DataView(i.buffer,i.byteOffset,i.byteLength);t.setUint32(r,n.byteLength,!1),r+=4,i.set(n,r),r+=n.byteLength}return i})(t)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);const o=this.createSampleForTrack(r,n,e.timestamp,e.duration,e.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=Ti(sr.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}this.validateTimestamp(r.track,e.timestamp,"key"===e.type);let o=e.timestamp,s=e.duration;if(r.info.requiresPcmTransformation){const t=ei(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(s=n.byteLength/t/r.info.sampleRate,null!==r.info.expectedNextPcmPacketTimestamp){const t=o-r.info.expectedNextPcmPacketTimestamp;if(t<.01)o=r.info.expectedNextPcmPacketTimestamp;else{const e=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,t);o=r.info.expectedNextPcmPacketTimestamp+e}}r.info.expectedNextPcmPacketTimestamp=o+s}const a=this.createSampleForTrack(r,n,o,s,e.type);await this.registerSample(r,a)}finally{r()}}async padWithSilence(t,e,i){const r=ho(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=ei(t.info.decoderConfig.codec),s=r*t.info.numberOfChannels,a=new Uint8Array(n*s).fill(o),h=this.createSampleForTrack(t,new Uint8Array(a.buffer),e,i,"key");await this.registerSample(t,h)}return i}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0),"webvtt"===t.source.$t&&(r.cueQueue.push(e),await this.processWebVTTCues(r,e.timestamp))}finally{r()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){t.lastCueEndTimestamp??=Math.min(0,t.cueQueue[0].timestamp);const i=new Set([]);for(const h of t.cueQueue)z(h.timestamp<=e),z(t.lastCueEndTimestamp<=h.timestamp+h.duration),i.add(Math.max(h.timestamp,t.lastCueEndTimestamp)),i.add(h.timestamp+h.duration);const r=[...i].sort((t,e)=>t-e),n=r[0],o=r[1]??n;if(e<o)break;if(t.lastCueEndTimestamp<n){this.auxWriter.seek(0);const e=$n();this.auxBoxWriter.writeBox(e);const i=this.auxTarget.Yt(0,this.auxWriter.getPos()),r=this.createSampleForTrack(t,i,t.lastCueEndTimestamp,n-t.lastCueEndTimestamp,"key");await this.registerSample(t,r),t.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let e=0;e<t.cueQueue.length;e++){const i=t.cueQueue[e];if(i.timestamp>=o)break;dr.lastIndex=0;const r=dr.test(i.text),s=i.timestamp+i.duration;let a=t.cueToSourceId.get(i);if(void 0===a&&o<s&&(a=t.nextSourceId++,t.cueToSourceId.set(i,a)),i.notes){const t=Rn(i.notes);this.auxBoxWriter.writeBox(t)}const h=On(i.text,r?n:null,i.identifier??null,i.settings??null,a??null);this.auxBoxWriter.writeBox(h),s===o&&t.cueQueue.splice(e--,1)}const s=this.auxTarget.Yt(0,this.auxWriter.getPos()),a=this.createSampleForTrack(t,s,n,o-n,"key");await this.registerSample(t,a),t.lastCueEndTimestamp=o}}createSampleForTrack(t,e,i,r,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:e,size:e.byteLength,type:n,timescaleUnitsToNextSample:ho(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){z(!this.isFragmented),t.startTimestampOffset??=t.timestampProcessingQueue[0].timestamp;let e=0;for(let i=0;i<t.timestampProcessingQueue.length;i++){const r=t.timestampProcessingQueue[i];e+=ho(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):Q(t.timeToSampleTable).sampleCount+=e,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(t=>t.timestamp).sort((t,e)=>t-e);this.isFragmented?t.startTimestampOffset??=Math.min(i[0],0):t.startTimestampOffset??=i[0];for(let r=0;r<t.timestampProcessingQueue.length;r++){const e=t.timestampProcessingQueue[r];e.decodeTimestamp=i[r];const n=ho(e.timestamp-e.decodeTimestamp,t.timescale),o=ho(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){z(t.lastSample);const i=ho(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(z(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=Q(t.timeToSampleTable);if(z(e),1===e.sampleCount){e.sampleDelta=r;const i=t.timeToSampleTable[t.timeToSampleTable.length-2];i&&i.sampleDelta===r&&(i.sampleCount++,t.timeToSampleTable.pop(),e=i)}else e.sampleDelta!==r&&(e.sampleCount--,t.timeToSampleTable.push(e={sampleCount:1,sampleDelta:r}));e.sampleDelta===o?e.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const i=Q(t.compositionTimeOffsetTable);z(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=ho(e.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));t.lastSample=e}if(t.timestampProcessingQueue.length=0,z(t.lastSample),z(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){z("key"===e.type);const i=ho(e.timestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=r}}async registerSample(t,e){"key"===e.type&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),"reserve"===this.fastStart)){const e=t.track.metadata.maximumPacketCount;if(z(void 0!==e),t.samples.length>e)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${e}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(t.currentChunk){t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,e.timestamp);const r=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.closed});r>=this.minimumFragmentDuration&&n&&e.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),z(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(z(!this.isFragmented),z(this.writer),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if("audio"===t.type&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((e,i)=>e+ho(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&Q(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),"in-memory"!==this.fastStart){t.currentChunk.offset=this.writer.getPos();for(const e of t.currentChunk.samples)z(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(z(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.sampleQueue.length&&!n.closed)break t;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(e=n,i=n.sampleQueue[0].timestamp)}if(!e)break;const r=e.sampleQueue.shift();await this.addSampleToTrack(e,r)}}async finalizeFragment(t=!this.isCmaf){if(z(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const t=this.initBoxWriter??this.boxWriter;z(t),this.formatOptions.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=Rr(this);if(t.writeBox(e),this.formatOptions.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onMoov(e,i)}if(this.isCmaf){z(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.fe(!0),this.boxWriter=new pr(this.writer);const t=this.boxWriter.measureBox(Fr()),e=this.boxWriter.measureBox($r(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}z(this.writer),z(this.boxWriter);const e=this.trackDatas.filter(t=>t.currentChunk);if(0===e.length)return void(t&&await this.writer.flush());const i=this.nextFragmentNumber++,r=Mn(i,e),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let s=o+8,a=1/0;for(let u=0;u<e.length;u++){const t=e[u];z(t.currentChunk),z(null!==t.startTimestampOffset),t.currentChunk.offset=s,t.currentChunk.moofOffset=n,t.currentChunk.trafIndex=u,t.currentChunk.startTimestamp-=t.startTimestampOffset;for(const e of t.currentChunk.samples)s+=e.size,e.timestamp-=t.startTimestampOffset,e.decodeTimestamp-=t.startTimestampOffset;a=Math.min(a,t.currentChunk.startTimestamp)}const h=s-o,c=h>=2**32;if(c)for(const u of e)u.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const l=Mn(i,e);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(t,e,a)}z(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const d=Or(c);d.size=h,this.boxWriter.writeBox(d),this.writer.seek(o+(c?16:8));for(const u of e)for(const t of u.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}for(const u of e)u.finalizedChunks.push(u.currentChunk),this.finalizedChunks.push(u.currentChunk),u.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(t,e)):t.sampleQueue.push(e)}async createFastStartReserveMdat(){z(this.writer),z(this.boxWriter),this.ensureOneEnabledTrack();const t=Rr(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;z(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Or(!0),this.boxWriter.writeBox(this.mdat);for(const i of this.trackDatas){for(const t of i.sampleQueue)await this.addSampleToTrack(i,t);i.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){z("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;z(void 0!==i),t+=8*Math.ceil(2/3*i),t+=4*i,t+=8*Math.ceil(2/3*i),t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i}return t}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0,"subtitle"===i.type&&"webvtt"===t.source.$t&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}ensureOneEnabledTrack(){for(const t of["video","audio","subtitle"]){const e=this.trackDatas.filter(e=>e.type===t);if(0!==e.length&&!e.some(t=>!1!==t.track.metadata.disposition?.default)){const t=e[0];t.track.metadata.disposition={...t.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){z(this.isFragmented);const t=await this.mutex.acquire();try{for(const t of this.trackDatas)"subtitle"===t.type&&"webvtt"===t.track.source.$t&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{t()}}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),this.mdat||"reserve"!==this.fastStart||await this.createFastStartReserveMdat();for(const i of this.trackDatas)i.closed=!0,"subtitle"===i.type&&"webvtt"===i.track.source.$t&&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);const t=co(i);if(t>0){let e=0;for(const t of i.samples)e+=t.size;i.avgBitrate=Math.round(8*e/t)}else i.avgBitrate=0;let e=0,r=0,n=0;for(let o=0;o<i.samples.length;o++){const t=i.samples[o];for(r+=t.size;t.decodeTimestamp-i.samples[e].decodeTimestamp>=1;)r-=i.samples[e].size,e++;n=Math.max(n,r)}if(i.maxBitrate=8*n,null!==i.startTimestampOffset)for(let o=0;o<i.samples.length;o++){const t=i.samples[o];t.timestamp-=i.startTimestampOffset,t.decodeTimestamp-=i.startTimestampOffset}}if(z(this.writer),z(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=Or(!1);for(let i=0;i<2;i++){const e=Rr(this),i=this.boxWriter.measureBox(e);t=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+t;for(const n of this.finalizedChunks){n.offset=r;for(const{data:e}of n.samples)z(e),r+=e.byteLength,t+=e.byteLength}if(r<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const e=Rr(this);if(this.boxWriter.writeBox(e),this.formatOptions.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(t,e)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const t of i.samples)z(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}}else if(this.isFragmented)if(this.isCmaf){const t=null!==this.segmentHeaderSize?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(Fr()),this.boxWriter.writeBox($r(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,Ir("mfra",void 0,[...e.map(Fn),Br("mfro",0,0,[xr(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{z(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);z(void 0!==t);const e=this.writer.getPos()-t;if(this.mdat.size=e,this.mdat.largeSize=e>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}const i=Rr(this);if("reserve"===this.fastStart){z(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const t=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:t})}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.formatOptions.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(t,e)}}var e;t()}},uo={video:1,audio:2,subtitle:17},fo=class extends lr{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=ft(),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.warnedAboutTooNegativeTimestamp=!1,this.format=e}async start(){const t=await this.mutex.acquire();this.writer=await this.output.fe(!!this.format.Ot.appendOnly),this.ebmlWriter=new xi(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(const e of this.output.tracks)e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});t()}writeEBMLHeader(){this.format.Ot.onEbmlHeader&&this.writer.startTrackingWrites();const t={id:Ae.EBML,data:[{id:Ae.EBMLVersion,data:1},{id:Ae.EBMLReadVersion,data:1},{id:Ae.EBMLMaxIDLength,data:4},{id:Ae.EBMLMaxSizeLength,data:8},{id:Ae.DocType,data:this.format instanceof $o?"webm":"matroska"},{id:Ae.DocTypeVersion,data:4},{id:Ae.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format.Ot.onEbmlHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.Ot.onEbmlHeader(t,e)}}maybeCreateSeekHead(t){if(this.format.Ot.appendOnly)return;const e=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),s={id:Ae.SeekHead,data:[{id:Ae.Seek,data:[{id:Ae.SeekID,data:i},{id:Ae.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:Ae.Seek,data:[{id:Ae.SeekID,data:r},{id:Ae.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:Ae.Seek,data:[{id:Ae.SeekID,data:n},{id:Ae.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:Ae.Seek,data:[{id:Ae.SeekID,data:o},{id:Ae.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:Ae.Seek,data:[{id:Ae.SeekID,data:e},{id:Ae.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=s}createSegmentInfo(){const t={id:Ae.Duration,data:new mi(0)};this.segmentDuration=t;const e={id:Ae.Info,data:[{id:Ae.TimestampScale,data:1e6},{id:Ae.MuxingApp,data:ie},{id:Ae.WritingApp,data:ie},this.format.Ot.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:Ae.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){let i=Ei[e.track.source.$t];z(i),"audio"===e.type&&"dts"===e.track.source.$t&&("dtse"===e.info.decoderConfig.codec?i="A_DTS/EXPRESS":"dtsl"===e.info.decoderConfig.codec&&(i="A_DTS/LOSSLESS"));let r=0;if("audio"===e.type&&"opus"===e.track.source.$t){r=8e7;const t=e.info.decoderConfig.description;if(t){const e=Ce(tt(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:Ae.TrackEntry,data:[{id:Ae.TrackNumber,data:e.track.id},{id:Ae.TrackUID,data:e.track.id},{id:Ae.TrackType,data:uo[e.type]},!1===e.track.metadata.disposition?.default?{id:Ae.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:Ae.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:Ae.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:Ae.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:Ae.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:Ae.FlagCommentary,data:1}:null,{id:Ae.FlagLacing,data:0},{id:Ae.Language,data:e.track.metadata.languageCode??"und"},{id:Ae.CodecID,data:i},e.codecPrivate?{id:Ae.CodecPrivate,data:tt(e.codecPrivate)}:null,r>0?{id:Ae.SeekPreRoll,data:r}:null,void 0!==e.track.metadata.name?{id:Ae.Name,data:new vi(e.track.metadata.name)}:null,"video"===e.type?this.videoSpecificTrackInfo(e):null,"audio"===e.type?this.audioSpecificTrackInfo(e):null,"subtitle"===e.type?this.subtitleSpecificTrackInfo(e):null]})}}videoSpecificTrackInfo(t){const{frameRate:e,transformationMatrix:i}=t.track.metadata,r=[e?{id:Ae.DefaultDuration,data:1e9/e}:null];let n,o,s;if(i){n=(t=>{const[e,i]=t,r=Math.atan2(i,(t=>{const[e,i,,r,n]=t;return e*n-i*r<0})(t)?-e:e);return H(vt(r*q,90))})(i);const t=Z(W(-n),i);o=Math.sign(t[0]),s=Math.sign(t[4]),-1===s&&(s=1,o=-o,n=H(n+180))}else n=t.track.metadata.rotation??0,o=t.track.metadata.flip?-1:1,s=1;const a=n?H(-1===o?n:-n):0,h=Math.round(Math.acos(o)*q),c=Math.round(Math.acos(s)*q),l=!!t.info.aspectRatio&&t.info.aspectRatio.num*t.info.height!==t.info.aspectRatio.den*t.info.width,d=t.info.decoderConfig.colorSpace,u={id:Ae.Video,data:[{id:Ae.PixelWidth,data:t.info.width},{id:Ae.PixelHeight,data:t.info.height},l?{id:Ae.DisplayWidth,data:t.info.aspectRatio.num}:null,l?{id:Ae.DisplayHeight,data:t.info.aspectRatio.den}:null,l?{id:Ae.DisplayUnit,data:3}:null,t.info.alphaMode?{id:Ae.AlphaMode,data:1}:null,at(d)?null:{id:Ae.Colour,data:[{id:Ae.MatrixCoefficients,data:null!=d?.matrix?st[d.matrix]:2},{id:Ae.TransferCharacteristics,data:null!=d?.transfer?ot[d.transfer]:2},{id:Ae.Primaries,data:null!=d?.primaries?nt[d.primaries]:2},{id:Ae.Range,data:null!=d?.fullRange?d.fullRange?2:1:0}]},a||h||c?{id:Ae.Projection,data:[{id:Ae.ProjectionType,data:0},h?{id:Ae.ProjectionPoseYaw,data:new pi(h)}:null,c?{id:Ae.ProjectionPosePitch,data:new pi(c)}:null,a?{id:Ae.ProjectionPoseRoll,data:new pi((a+180)%360-180)}:null]}:null]};return r.push(u),r}audioSpecificTrackInfo(t){const e=ze.includes(t.track.source.$t)?ei(t.track.source.$t):null;return[{id:Ae.Audio,data:[{id:Ae.SamplingFrequency,data:new pi(t.info.sampleRate)},{id:Ae.Channels,data:t.info.numberOfChannels},e?{id:Ae.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:Ae.SimpleTag,data:[{id:Ae.TagName,data:new vi(e)},"string"==typeof i?{id:Ae.TagString,data:new vi(i)}:{id:Ae.TagBinary,data:i}]})},i=this.output.Rt,r=new Set;for(const{key:n,value:o}of Ft(i))switch(n){case"title":e("TITLE",o),r.add("TITLE");break;case"description":e("DESCRIPTION",o),r.add("DESCRIPTION");break;case"artist":e("ARTIST",o),r.add("ARTIST");break;case"album":e("ALBUM",o),r.add("ALBUM");break;case"albumArtist":e("ALBUM_ARTIST",o),r.add("ALBUM_ARTIST");break;case"genre":e("GENRE",o),r.add("GENRE");break;case"beatsPerMinute":e("BPM",o.toString()),r.add("BPM");break;case"comment":e("COMMENT",o),r.add("COMMENT");break;case"lyrics":e("LYRICS",o),r.add("LYRICS");break;case"date":e("DATE",o.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":e("PART_NUMBER",void 0!==i.tracksTotal?`${o}/${i.tracksTotal}`:o.toString()),r.add("PART_NUMBER");break;case"discNumber":e("DISC",void 0!==i.discsTotal?`${o}/${i.discsTotal}`:o.toString()),r.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:pt(n)}if(i.raw)for(const n in i.raw){const t=i.raw[n];null==t||r.has(n)||("string"==typeof t||t instanceof Uint8Array)&&e(n,t)}0!==t.length&&(this.tagsElement={id:Ae.Tags,data:[{id:Ae.Tag,data:[{id:Ae.Targets,data:[{id:Ae.TargetTypeValue,data:50},{id:Ae.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.Rt,e=[],i=new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+($t(n.mimeType)??""));;){t=0n;for(let e=0;e<8;e++)t<<=8n,t|=BigInt(Math.floor(256*Math.random()));if(0n!==t&&!i.has(t))break}i.add(t),e.push({id:Ae.AttachedFile,data:[void 0!==n.description?{id:Ae.FileDescription,data:new vi(n.description)}:null,{id:Ae.FileName,data:new vi(r)},{id:Ae.FileMediaType,data:n.mimeType},{id:Ae.FileData,data:n.data},{id:Ae.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof Gt&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&&Ot(t.data,o.data))||e.push({id:Ae.AttachedFile,data:[void 0!==o.description?{id:Ae.FileDescription,data:new vi(o.description)}:null,{id:Ae.FileName,data:new vi(o.name??"")},{id:Ae.FileMediaType,data:o.mimeType??""},{id:Ae.FileData,data:o.data},{id:Ae.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:Ae.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:Ae.Segment,size:this.format.Ot.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=t,this.format.Ot.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format.Ot.onSegmentHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.Ot.onSegmentHeader(t,e)}}createCues(){this.cues={id:Ae.Cues,data:[]}}get segmentDataOffset(){return z(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.gt&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.$t]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings.filter(Boolean))].join(", ")}"`),e})({isWebM:this.format instanceof $o,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;hi(i,t.source.$t),z(i),z(i.decoderConfig),z(void 0!==i.decoderConfig.codedWidth),z(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:Dt({num:n,den:o}),a={track:t,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:i.decoderConfig,alphaMode:t.metadata.canBeTransparent||(e?!!e.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return"vp9"===t.source.$t?a.codecPrivate=new Uint8Array((t=>{const e=t.split(".");return[1,1,Number(e[1]),2,1,Number(e[2]),3,1,Number(e[3]),4,1,e[4]?Number(e[4]):1]})(a.info.decoderConfig.codec)):"av1"===t.source.$t?a.codecPrivate=new Uint8Array(Ke(a.info.decoderConfig.codec)):"prores"===t.source.$t&&(a.codecPrivate=rt.encode(i.decoderConfig.codec)),this.trackDatas.push(a),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;li(i,t.source.$t),z(i),z(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.$t&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=Ti(sr.tempFromBytes(e.data));if(!t)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const i=Xt[t.samplingFrequencyIndex],r=Zt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Qt({objectType:t.objectType,outputSampleRate:i,outputNumberOfChannels:r}),o=!0}const s={track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.description??null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;di(e),z(e),z(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:rt.encode(e.config.description),closed:!1};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);r.info.alphaMode??=!!e.sideData.alpha;let n=e.data;if("prores"===t.source.$t){if(n.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");n=n.subarray(8)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);let s=e.timestamp,a=e.duration;void 0!==t.metadata.frameRate&&(s=bt(s,t.metadata.frameRate),a=bt(a,t.metadata.frameRate));const h=r.info.alphaMode?e.sideData.alpha??null:null,c=this.createInternalChunk(n,s,a,e.type,h);"vp9"===t.source.$t&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=Ti(sr.tempFromBytes(n));if(!t)throw new Error("Expected ADTS frame, didn't get one.");const e=null===t.crcCheck?7:9;n=n.subarray(e)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);const s=this.createInternalChunk(n,e.timestamp,e.duration,e.type);r.chunkQueue.push(s),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(t,e,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(t,i);this.validateTimestamp(r.track,e.timestamp,!0);let n=e.text;const o=Math.round(1e3*e.timestamp);dr.lastIndex=0,n=n.replace(dr,t=>`<${fr((t=>{const e=ur.exec(t);if(!e)throw new Error("Expected match.");return 36e5*Number(e[1]||"0")+6e4*Number(e[2])+1e3*Number(e[3])+Number(e[4])})(t.slice(1,-1))-o)}>`);const s=rt.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?rt.encode(a):null);r.chunkQueue.push(h),await this.interleaveChunks()}finally{r()}}async interleaveChunks(t=!1){if(t||this.allTracksAreKnown()){t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.chunkQueue.length&&!n.closed)break t;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(e=n,i=n.chunkQueue[0].timestamp)}if(!e)break;const r=e.chunkQueue.shift();this.writeBlock(e,r)}t||await this.writer.flush()}}fixVP9ColorSpace(t,e){if("key"!==e.type)return;if(!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;const i=new Wt(e.data);i.skipBits(2);const r=i.readBits(1),n=(i.readBits(1)<<1)+r;if(3===n&&i.skipBits(1),i.readBits(1))return;if(0!==i.readBits(1))return;if(i.skipBits(2),4817730!==i.readBits(24))return;n>=2&&i.skipBits(1);const o={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];((t,e,i,r)=>{for(let n=e;n<i;n++){const e=Math.floor(n/8);let o=t[e];const s=7-(7&n);o&=~(1<<s),o|=(r&1<<i-n-1)>>i-n-1<<s,t[e]=o}})(e.data,i.pos,i.pos+3,o)}createInternalChunk(t,e,i,r,n=null){return{data:t,type:r,timestamp:e,duration:i,additions:n}}writeBlock(t,e){this.segment||this.createSegment();const i=Math.round(1e3*e.timestamp),r=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.chunkQueue[0];return r?"key"===r.type:i.closed});let n=!1;if(this.currentCluster){z(null!==this.currentClusterStartMsTimestamp),z(null!==this.currentClusterMaxMsTimestamp);const t=i-this.currentClusterStartMsTimestamp;n=r&&i>this.currentClusterMaxMsTimestamp&&t>=1e3*(this.format.Ot.minimumClusterDuration??1)||t>32767}else n=!0;n&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768){if(!this.warnedAboutTooNegativeTimestamp){const t=this.format instanceof $o?"WebM":"Matroska";jt.wt(`Packets had to be discarded because their timestamp is too negative to represent in ${t}.`),this.warnedAboutTooNegativeTimestamp=!0}return}const s=new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:Ae.BlockGroup,data:[{id:Ae.Block,data:[s,e.data]},"delta"===e.type?{id:Ae.ReferenceBlock,data:new wi(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:Ae.BlockAdditions,data:[{id:Ae.BlockMore,data:[{id:Ae.BlockAddID,data:1},{id:Ae.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:Ae.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:Ae.SimpleBlock,data:[s,e.data]};this.ebmlWriter.writeEBML(t)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+h),t.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(t){t=Math.max(0,t),this.currentCluster&&this.finalizeCurrentCluster(),this.format.Ot.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:Ae.Cluster,size:this.format.Ot.appendOnly?-1:5,data:[{id:Ae.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(z(this.currentCluster),!this.format.Ot.appendOnly){const t=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),e=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(t,5),this.writer.seek(e)}if(this.format.Ot.onCluster){z(null!==this.currentClusterStartMsTimestamp);const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.Ot.onCluster(t,e,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)z(this.cues),this.cues.data.push({id:Ae.CuePoint,data:[{id:Ae.CueTime,data:Math.max(0,r)},...n.map(e=>({id:Ae.CueTrackPositions,data:[{id:Ae.CueTrack,data:e.track.id},{id:Ae.CueClusterPosition,data:t}]}))]})}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),z(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format.Ot.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6);const e=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new mi(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),z(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},po=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e},mo=function(t){return function(e){function i(i){e.error=e.hasError?new t(i,e.error,"An error was suppressed during disposal."):i,e.hasError=!0}var r,n=0;return function t(){for(;r=e.stack.pop();)try{if(!r.async&&1===n)return n=0,e.stack.push(r),Promise.resolve().then(t);if(r.dispose){var o=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(o).then(t,function(e){return i(e),t()})}else n|=1}catch(s){i(s)}if(1===n)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()}}("function"==typeof SuppressedError?SuppressedError:function(t,e,i){var r=new Error(i);return r.name="SuppressedError",r.error=t,r.suppressed=e,r}),wo=class{constructor(){this.ve=null,this.be=null,this.gt=!1,this.we=null}ye(){if(!this.ve)throw new Error("Source is not connected to an output track.");if("canceled"===this.ve.output.state)throw new Error("Output has been canceled.");if("finalizing"===this.ve.output.state||"finalized"===this.ve.output.state)throw new Error("Output has been finalized.");if("pending"===this.ve.output.state)throw new Error("Output has not started.");if(this.gt)throw new Error("Source is closed.")}async Vt(){}async ge(t){}close(){if(this.be)return;const t=this.ve;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if("pending"===t.output.state)throw new Error("Cannot call close before output has been started.");this.be=(async()=>{await this.ge(!1),this.gt=!0,"finalizing"!==t.output.state&&"finalized"!==t.output.state&&t.output.xe.onTrackClose(t)})()}async Ee(t){return this.be??=(async()=>{await this.ge(t),this.gt=!0})()}},vo=class extends wo{constructor(t){if(super(),!Ue.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${Ue.join(", ")}.`);this.$t=t}},bo=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},yo=class{setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}constructor(t,e){this.source=t,this.encodingConfig=e,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.encoderConfig=null,this.encodersReclaimed=!1,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.chunkTimestampsAreShiftedByDuration=!1,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 Tt,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(t,e,i){const r=t;try{this.checkForEncoderError(),this.source.ye();const n=this.encodingConfig,o=n.sizeChangeBehavior??"deny";let s=!1;if(null!==this.codedWidth&&null!==this.codedHeight){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(s=!0,"deny"===o))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(void 0!==n.transform?.width||void 0!==n.transform?.height||void 0!==n.transform?.rotate||void 0!==n.transform?.flip||void 0!==n.transform?.crop||!0===n.transform?.force||s&&"passThrough"!==o){let i=n.transform?.width,r=n.transform?.height,a=n.transform?.fit??"fill";s&&"passThrough"!==o&&(z(this.outputWidth),z(this.outputHeight),z("deny"!==o),i=this.outputWidth,r=this.outputHeight,a=o);const h=await t.transform({width:i,height:r,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,flip:n.transform?.flip,fit:a,alpha:n.alpha});null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=h.displayWidth,this.outputHeight=h.displayHeight),e&&t.close(),t=h,e=!0}else null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);const a=n.transform?.frameRate;if(void 0!==a){const n=t.timestamp+t.duration,o=yt(t.timestamp,a);if(null!==this.frameRateLastSample){if(o<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=n);await this.padFrameRate(o,i)}t===r&&(t=t.clone(),e=!0),t.setTimestamp(o),t.setDuration(1/a),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=o,this.frameRateLastEndTimestamp=n}await this.processAndEncode(t,i)}finally{e&&t.close()}}async processAndEncode(t,e){const i=this.encodingConfig;let r;if(i.transform?.process){let e=i.transform.process(t);if(Bt(e)&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof Bi?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new Bi(i)):o.push(new Bi(i,{timestamp:t.timestamp,duration:t.duration}))}catch(n){for(const e of o)e!==t&&e.close();for(const i of e)(i instanceof Bi&&i!==t||"undefined"!=typeof VideoFrame&&i instanceof VideoFrame)&&i.close();throw n}r=o}else r=[t];try{for(const t of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),z(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();const i=this.encodingConfig.keyFrameInterval??2,r=Math.floor(t.timestamp/i),n={...this.defaultEncodeOptions,...t.encodeOptions,...e},o={...n,keyFrame:void 0!==n.keyFrame?n.keyFrame:0===i||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;const e=t.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,o)).catch(t=>this.setError(t)).finally(()=>{this.customEncoderQueueSize--,e.close()});this.customEncoderQueueSize>=4&&await i}else{z(this.encoder);const e=t.toVideoFrame(),i=ut(this.preciseTimings,e.timestamp,t=>t.microsecondTimestamp),r=-1!==i?this.preciseTimings[i]:null;if(r&&r.microsecondTimestamp===e.timestamp?(r.timestamp!==t.timestamp&&(r.timestampIsValid=!1),r.duration!==t.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(i+1,0,{microsecondTimestamp:e.timestamp,timestamp:t.timestamp,duration:t.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(e.format&&!e.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(e,o)}finally{e.close()}}else{this.splitter||(this.splitter=new To);const{colorFrame:t,alphaFrame:i}=await this.splitter.split(e);this.alphaFrameQueue.push(i);try{this.encoder.encode(t,o)}finally{t.close()}}else try{this.encoder.encode(e,o)}finally{e.close()}this.encoder.encodeQueueSize>=4&&await new Promise(t=>this.encoder.addEventListener("dequeue",t,{once:!0}))}await this.lastMuxerPromise}}finally{for(const e of r)e!==t&&e.close()}}async padFrameRate(t,e){const i=this.encodingConfig.transform.frameRate;z(this.frameRateLastSample);const r=Math.round((t-this.frameRateLastTimestamp)*i);for(let o=1;o<r;o++){const t={stack:[],error:void 0,hasError:!1};try{const r=po(t,this.frameRateLastSample.clone(),!1);r.setTimestamp(this.frameRateLastTimestamp+o/i),r.setDuration(1/i),await this.processAndEncode(r,e)}catch(n){t.error=n,t.hasError=!0}finally{mo(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=nr(this.encodingConfig.quality,this.encodingConfig.bitrate);z(void 0!==e);const i=Qi({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source.ve?.metadata.frameRate});let r,n=null;for(const t of i){const e=t.config;if(this.encodingConfig.onEncoderConfig?.(e),r=or.find(t=>t.supports(this.encodingConfig.codec,e)),r){n=t;break}if("undefined"!=typeof VideoEncoder){if(e.alpha="discard","keep"===this.encodingConfig.alpha&&(e.latencyMode="quality"),!(e.width%2!=1&&e.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw new Error(`The dimensions ${e.width}x${e.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(e)).supported){n=t;break}}catch{}}}if(!n){if("undefined"==typeof VideoEncoder)throw new Error((o="VideoEncoder",void 0===globalThis.isSecureContext||globalThis.isSecureContext?`${o} is not available in this environment.`:`${o} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`));const t=i[0].config,e=i.map(({config:t,quantizer:e})=>null!==e?`quantizer ${e}`:`${t.bitrate} bps`);throw new Error(`This specific encoder configuration (${t.codec}, ${e.join(" / ")}, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}var o;const s=n.config;null!==n.quantizer?this.defaultEncodeOptions=ir(this.encodingConfig.codec,n.quantizer):this.source.we=s.bitrate??null,r?(this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(t,e)=>{if(!(t instanceof fi))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");bo(this.source.ve,t),this.encodingConfig.onEncodedPacket?.(t,e),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.ve,t,e).catch(t=>{this.setError(t)})},this.customEncoder.onError=t=>{this.setError(t)},await this.customEncoder.init()):(this.encoderConfig=s,"avc"===this.encodingConfig.codec&&Ct()&&(this.chunkTimestampsAreShiftedByDuration=await xo()),this.createWebCodecsEncoders()),z(this.source.ve),this.muxer=this.source.ve.output.xe,this.encoderInitialized=!0})()}createWebCodecsEncoders(){const t=this.encoderConfig;z(t);const e=[],i=[];let r=0,n=0;const o=(t,e)=>{(t=>t instanceof DOMException&&"QuotaExceededError"===t.name&&/reclaimed/i.test(t.message))(t)?this.encodersReclaimed=!0:(t.stack=e,this.setError(t))},s=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder)return void this.addPacket(t,null,o);const s=this.alphaFrameQueue.shift();z(void 0!==s),s?(this.alphaEncoder.encode(s,{...this.defaultEncodeOptions,keyFrame:"key"===t.type}),n++,s.close(),e.push({chunk:t,meta:o})):0===n?this.addPacket(t,null,o):(i.push(r+n),e.push({chunk:t,meta:o}))},error:t=>o(t,s)}),this.encoder.configure(t),"keep"===this.encodingConfig.alpha){const s=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{n--;const s=e.shift();for(z(void 0!==s),this.addPacket(s.chunk,t,s.meta),r++;i.length>0&&i[0]===r;){i.shift();const t=e.shift();z(void 0!==t),this.addPacket(t.chunk,null,t.meta)}},error:t=>o(t,s)}),this.alphaEncoder.configure(t)}}addPacket(t,e,i){const r={};if(e){const t=new Uint8Array(e.byteLength);e.copyTo(t),r.alpha=t}let n=fi.fromEncodedChunk(t,r);const o=this.encoderConfig;if(z(o),i?.decoderConfig&&(i.decoderConfig.codec=(t=>{const{codec:e,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:s,av1CodecInfo:a,proresFormat:h}=t;if("avc"===e){if(z(null!==t.avcType),n){const e=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${lt(e)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${t.avcType}.${lt(i.subarray(1,4))}`}if("hevc"===e){let t,e,r,n,s,a;if(o)t=o.generalProfileSpace,e=o.generalProfileIdc,r=dt(o.generalProfileCompatibilityFlags),n=o.generalTierFlag,s=o.generalLevelIdc,a=[...o.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=et(i),h=o.getUint8(1);t=h>>6&3,e=31&h,r=dt(o.getUint32(2)),n=h>>5&1,s=o.getUint8(12),a=[];for(let t=0;t<6;t++)a.push(o.getUint8(6+t))}let h="hev1.";for(h+=["","A","B","C"][t]+e,h+=".",h+=r.toString(16).toUpperCase(),h+=".",h+=0===n?"L":"H",h+=s;a.length>0&&0===a[a.length-1];)a.pop();return a.length>0&&(h+=".",h+=a.map(t=>t.toString(16).toUpperCase()).join(".")),h}if("vp8"===e)return"vp8";if("vp9"===e){if(!s){const e=t.width*t.height;let i=Q(We).level;for(const t of We)if(e<=t.maxPictureSize){i=t.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let e=`vp09.${s.profile.toString().padStart(2,"0")}.${s.level.toString().padStart(2,"0")}.${s.bitDepth.toString().padStart(2,"0")}.${s.chromaSubsampling.toString().padStart(2,"0")}`;return e+=`.${s.colourPrimaries.toString().padStart(2,"0")}.${s.transferCharacteristics.toString().padStart(2,"0")}.${s.matrixCoefficients.toString().padStart(2,"0")}.${s.videoFullRangeFlag.toString().padStart(2,"0")}`,e.endsWith(".01.01.01.01.00")&&(e=e.slice(0,-15)),e}if("av1"===e){if(!a){const e=t.width*t.height;let i=Q(We).level;for(const t of We)if(e<=t.maxPictureSize){i=t.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const e=a.profile,i=a.level.toString().padStart(2,"0"),n=a.tier?"H":"M",o=a.bitDepth.toString().padStart(2,"0"),s=a.monochrome?"1":"0",h=100*a.chromaSubsamplingX+10*a.chromaSubsamplingY+1*(a.chromaSubsamplingX&&a.chromaSubsamplingY?a.chromaSamplePosition:0);let l,d,u,f;2!==(c=a).colourPrimaries||2!==c.transferCharacteristics||2!==c.matrixCoefficients?(l=a.colourPrimaries,d=a.transferCharacteristics,u=a.matrixCoefficients,f=a.videoFullRangeFlag):(l=r?.primaries?nt[r.primaries]:1,d=r?.transfer?ot[r.transfer]:1,u=r?.matrix?st[r.matrix]:1,f=r?.fullRange?1:0);let p=`av01.${e}.${i}${n}.${o}`;return p+=`.${s}.${h.toString().padStart(3,"0")}`,p+=`.${l.toString().padStart(2,"0")}`,p+=`.${d.toString().padStart(2,"0")}`,p+=`.${u.toString().padStart(2,"0")}`,p+=`.${f}`,p.endsWith(".0.110.01.01.01.0")&&(p=p.slice(0,-17)),p}if("prores"===e)return h??"apch";var c;throw null!==e&&pt(e),new TypeError(`Unhandled codec '${e}'.`)})({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:i.decoderConfig.description?tt(i.decoderConfig.description):null,colorSpace:i.decoderConfig.colorSpace??null,avcType:o.codec.includes("avc1.")?1:o.codec.includes("avc3.")?3:null,avcCodecInfo:"avc"!==this.encodingConfig.codec||i.decoderConfig.description?null:he(n.data),hevcCodecInfo:"hevc"!==this.encodingConfig.codec||i.decoderConfig.description?null:pe(n.data),vp9CodecInfo:"vp9"===this.encodingConfig.codec?ke(n.data):null,av1CodecInfo:"av1"===this.encodingConfig.codec?Me(n.data):null,proresFormat:null}),"avc"===this.encodingConfig.codec&&i.decoderConfig.description&&Ct())){const t=(t=>{try{const e=et(t);let i=0;const r=e.getUint8(i++),n=e.getUint8(i++),o=e.getUint8(i++),s=e.getUint8(i++),a=3&e.getUint8(i++),h=31&e.getUint8(i++),c=[];for(let f=0;f<h;f++){const r=e.getUint16(i,!1);i+=2,c.push(t.subarray(i,i+r)),i+=r}const l=e.getUint8(i++),d=[];for(let f=0;f<l;f++){const r=e.getUint16(i,!1);i+=2,d.push(t.subarray(i,i+r)),i+=r}const u={configurationVersion:r,avcProfileIndication:n,profileCompatibility:o,avcLevelIndication:s,lengthSizeMinusOne:a,sequenceParameterSets:c,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===n||110===n||122===n||144===n)&&i+4<=t.length){const r=3&e.getUint8(i++),n=7&e.getUint8(i++),o=7&e.getUint8(i++),s=e.getUint8(i++);u.chromaFormat=r,u.bitDepthLumaMinus8=n,u.bitDepthChromaMinus8=o;const a=[];for(let h=0;h<s;h++){const r=e.getUint16(i,!1);i+=2,a.push(t.subarray(i,i+r)),i+=r}u.sequenceParameterSetExt=a}return u}catch(e){return jt.ft("Error deserializing AVC Decoder Configuration Record:",e),null}})(tt(i.decoderConfig.description));let e=t?.sequenceParameterSets[0];if(e&&e[0]===e[1]){z(t),e=e.subarray(1);let r=t.pictureParameterSets[0];r&&(r=r.subarray(1));const n=ce({...t,sequenceParameterSets:[e],pictureParameterSets:r?[r]:[]});i.decoderConfig.description=n}}let s=t.timestamp;this.chunkTimestampsAreShiftedByDuration&&(s-=t.duration??0,n=n.clone({timestamp:s/1e6}));const a=ut(this.preciseTimings,s,t=>t.microsecondTimestamp),h=-1!==a?this.preciseTimings[a]:null;let c=null;0===this.emittedEncoderPackets&&"delta"===n.type&&i?.decoderConfig&&(c=((t,e,i)=>{switch(t){case"avc":for(const t of((t,e)=>{if(e.description){const i=1+(3&tt(e.description)[4]);return oe(t,i)}return ne(t)})(i,e)){const e=i[t.offset],r=se(e);if(r>=Lt.NON_IDR_SLICE&&r<=Lt.SLICE_DPC)return"delta";if(r===Lt.IDR)return"key";if(r===Lt.SEI&&!St()){const e=i.subarray(t.offset,t.offset+t.length),r=ae(e);let n=1;do{let t=0;for(;;){const e=r[n++];if(void 0===e)break;if(t+=e,e<255)break}let e=0;for(;;){const t=r[n++];if(void 0===t)break;if(e+=t,t<255)break}if(6===t){const t=new Wt(r);t.pos=8*n;let e=-1;try{e=J(t)}catch{}const i=t.readBits(1);if(0===e&&1===i)return"key"}n+=e}while(n<r.length-1)}}return"delta";case"hevc":for(const t of((t,e)=>{if(e.description){const i=1+(3&tt(e.description)[21]);return oe(t,i)}return ne(t)})(i,e)){const e=fe(i[t.offset]);if(e<qt.BLA_W_LP)return"delta";if(e<=qt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new Wt(i);if(2!==t.readBits(2))return null;const e=t.readBits(1);return(t.readBits(1)<<1)+e===3&&t.skipBits(1),t.readBits(1)?null:0===t.readBits(1)?"key":"delta"}case"av1":{let t=!1;for(const{type:e,data:r}of _e(i))if(1===e){const e=new Wt(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new Wt(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:pt(t),z(!1)}})(this.encodingConfig.codec,i.decoderConfig,n.data)),(h&&h.microsecondTimestamp===s||null!==c)&&(n=n.clone({timestamp:h?.timestampIsValid?h.timestamp:void 0,duration:h?.durationIsValid?h.duration:void 0,type:c??void 0})),bo(this.source.ve,n),this.encodingConfig.onEncodedPacket?.(n,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.ve,n,i).catch(t=>{this.setError(t)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){z(this.encoder),"closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=-1,this.createWebCodecsEncoders()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,e=yt(this.frameRateLastEndTimestamp,t);await this.padFrameRate(e)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await(this.alphaEncoder?.flush()),await new Promise(t=>setTimeout(t,25))))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&("closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},go=null,xo=()=>go??=(async()=>{let t=null;const e=new VideoEncoder({output:e=>{t??=e.timestamp},error:()=>{}});try{e.configure({codec:"avc1.64001f",width:1280,height:720});const t=new VideoFrame(new Uint8Array(1382400),{format:"I420",codedWidth:1280,codedHeight:720,timestamp:0,duration:500});e.encode(t,{keyFrame:!0}),t.close(),await e.flush()}catch{return!1}finally{"closed"!==e.state&&e.close()}return 500===t})(),Eo=null,To=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!Eo){const t=new Blob([`(${ko.toString()})()`],{type:"application/javascript"});Eo=URL.createObjectURL(t)}this.worker=new Worker(Eo),this.worker.addEventListener("message",t=>{const e=t.data,i=this.pendingRequests.get(e.id);i&&(this.pendingRequests.delete(e.id),"error"in e?i.reject(new Error(e.error)):i.resolve({colorFrame:e.colorFrame,alphaFrame:e.alphaFrame}))}),this.worker.addEventListener("error",t=>{const e=new Error(t.message||"Color/alpha splitter worker error.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()})}const e=this.nextRequestId++,i=ft();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},ko=()=>{let t=null,e=Promise.resolve();self.addEventListener("message",t=>{const{id:r,sourceFrame:n}=t.data;e=e.then(async()=>{try{const{colorFrame:t,alphaFrame:e}=await i(n);self.postMessage({id:r,colorFrame:t,alphaFrame:e},{transfer:[t,e]})}catch(t){self.postMessage({id:r,error:t.message})}finally{n.close()}})});const i=async e=>{const i=e.format;if(!i)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=e.allocationSize();if(t&&t.byteLength===o||(t=new Uint8Array(o)),await e.copyTo(t),"RGBA"===i||"BGRA"===i)return r(t,i,e);if("I420A"===i||"I420AP10"===i||"I420AP12"===i||"I422A"===i||"I422AP10"===i||"I422AP12"===i||"I444A"===i||"I444AP10"===i||"I444AP12"===i)return n(t,i,e);throw new Error(`CPU color/alpha splitting does not support format '${i}'.`)},r=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=r*n,s=o+Math.ceil(r/2)*Math.ceil(n/2)*2,a=new Uint8Array(s);for(let l=0,d=3;l<o;l++,d+=4)a[l]=t[d];a.fill(128,o);const h=new VideoFrame(t,{format:"RGBA"===e?"RGBX":"BGRX",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),c={format:"I420",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[a.buffer]};return{colorFrame:h,alphaFrame:new VideoFrame(a,c)}},n=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=e.includes("P10"),s=e.includes("P12"),a=o||s?2:1;let h,c;e.startsWith("I420")?(h=Math.ceil(r/2),c=Math.ceil(n/2)):e.startsWith("I422")?(h=Math.ceil(r/2),c=n):(h=r,c=n);const l=r*n,d=l*a,u=l*a+h*c*a*2,f=e.replace("A",""),p=Math.ceil(r/2)*Math.ceil(n/2),m=new Uint8Array(d+p*a*2),w=u;m.set(t.subarray(w,w+d),0);const v=d,b=o?512:s?2048:128;1===a?m.fill(b,v):new Uint16Array(m.buffer,v,2*p).fill(b);const y=o?"I420P10":s?"I420P12":"I420",g=new VideoFrame(t.subarray(0,u),{format:f,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),x={format:y,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[m.buffer]};return{colorFrame:g,alphaFrame:new VideoFrame(m,x)}}},_o=class extends vo{constructor(t,e){if(!("undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");(t=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding config must be an object.");if(!Ue.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Ue.join(", ")}.`);const e=t.bitrate;if(void 0===t.quality&&void 0===e)throw new TypeError("config.quality must be provided.");if(void 0!==t.quality&&void 0!==e)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(void 0!==t.quality&&!(t.quality instanceof Yi))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof Yi)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==t.keyFrameInterval&&(!Number.isFinite(t.keyFrameInterval)||t.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==t.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==t.transform){if("object"!=typeof t.transform||!t.transform)throw new TypeError("config.transform, when provided, must be an object.");if(void 0!==t.transform.width&&(!Number.isInteger(t.transform.width)||t.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(void 0!==t.transform.height&&(!Number.isInteger(t.transform.height)||t.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(void 0!==t.transform.fit&&!["fill","contain","cover"].includes(t.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.transform.width&&void 0!==t.transform.height&&void 0===t.transform.fit&&!["fill","contain","cover"].includes(t.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(void 0!==t.transform.fit&&["fill","contain","cover"].includes(t.sizeChangeBehavior)&&t.transform.fit!==t.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(void 0!==t.transform.rotate&&![0,90,180,270].includes(t.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.transform.flip&&"boolean"!=typeof t.transform.flip)throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(void 0!==t.transform.crop&&Ui(t.transform.crop,"config.transform."),void 0!==t.transform.process&&"function"!=typeof t.transform.process)throw new TypeError("config.transform.process, when provided, must be a function.");if(void 0!==t.transform.frameRate&&(!Number.isFinite(t.transform.frameRate)||t.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(void 0!==t.transform.force&&"boolean"!=typeof t.transform.force)throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(void 0!==t.onEncodedPacket&&"function"!=typeof t.onEncodedPacket)throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(void 0!==t.onEncoderConfig&&"function"!=typeof t.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(void 0!==t.onEncodedSample&&"function"!=typeof t.onEncodedSample)throw new TypeError("config.onEncodedSample, when provided, must be a function.");Zi(t.codec,t)})(e),super(e.codec),this.Te=new yo(this,e),this.ke=t}add(t,e=0,i){if(!Number.isFinite(t))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");const r=new Bi(this.ke,{timestamp:t,duration:e});return this.Te.add(r,!0,i)}ge(t){return this.Te.flushAndClose(t)}},Mo=class extends wo{constructor(t){if(super(),!Le.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${Le.join(", ")}.`);this.$t=t}},Co=class extends wo{constructor(t){if(super(),!qe.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${qe.join(", ")}.`);this.$t=t}},Ao=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>Ue.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>Le.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>qe.includes(t))}_e(t){return""}Me(){return!1}},So=class extends Ao{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==t.minimumFragmentDuration&&(!Rt(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==t.onFtyp&&"function"!=typeof t.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==t.onMoov&&"function"!=typeof t.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==t.onMdat&&"function"!=typeof t.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==t.onMoof&&"function"!=typeof t.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==t.metadataFormat&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this.Ot=t}getSupportedTrackCounts(){const t=2**32-1;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:0,max:t}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}Ce(t){return new lo(t,this)}Me(){return"fragmented"===this.Ot.fastStart}},Po=class extends So{constructor(t){super(t)}get Ae(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ue,...je,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qe]}_e(t){return(new Bo).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},Io=class extends So{constructor(t){super(t)}get Ae(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ue,...je,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qe]}},Bo=class extends So{constructor(t){super(t)}get Ae(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Ue,...Le]}_e(t){return(new Po).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Fo=class extends Ao{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.appendOnly&&"boolean"!=typeof t.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==t.minimumClusterDuration&&(!Rt(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==t.onEbmlHeader&&"function"!=typeof t.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==t.onSegmentHeader&&"function"!=typeof t.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==t.onCluster&&"function"!=typeof t.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this.Ot=t}Ce(t){return new fo(t,this)}get Ae(){return"Matroska"}getSupportedTrackCounts(){const t=127;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:0,max:t}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Ue,...je,...ze.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...qe]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},$o=class extends Fo{constructor(t){super(t)}getSupportedCodecs(){return[...Ue.filter(t=>["vp8","vp9","av1"].includes(t)),...Le.filter(t=>["opus","vorbis"].includes(t)),...qe]}get Ae(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_e(t){return(new Fo).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},Oo=["video","audio","subtitle"],Ro=class t{constructor(t,e,i,r,n){this.id=t,this.output=e,this.type=i,this.source=r,this.metadata=n}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const i=Vt(this.metadata.group),r=Vt(e.metadata.group);for(const t of i){if(this.type!==e.type&&r.some(e=>t===e))return!0;if(r.some(e=>t.Se.has(e)))return!0}return!1}},Do=class extends Ro{constructor(t,e,i,r){super(t,e,"video",i,r)}},No=class extends Ro{constructor(t,e,i,r){super(t,e,"audio",i,r)}},Vo=class extends Ro{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},Uo=class t{constructor(){this.Se=new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this.Se.add(e),e.Se.add(this)}},zo=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&!(t=>xt.test(t))(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==t.name&&"string"!=typeof t.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==t.disposition&&(t=>{if(!t||"object"!=typeof t)throw new TypeError("disposition must be an object.");if(void 0!==t.default&&"boolean"!=typeof t.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==t.primary&&"boolean"!=typeof t.primary)throw new TypeError("disposition.primary must be a boolean.");if(void 0!==t.forced&&"boolean"!=typeof t.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==t.original&&"boolean"!=typeof t.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==t.commentary&&"boolean"!=typeof t.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==t.hearingImpaired&&"boolean"!=typeof t.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==t.visuallyImpaired&&"boolean"!=typeof t.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(t.disposition),void 0!==t.maximumPacketCount&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==t.bitrate&&(!Number.isFinite(t.bitrate)||t.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(void 0!==t.averageBitrate&&(!Number.isFinite(t.averageBitrate)||t.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(void 0!==t.group&&!(t.group instanceof Uo)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof Uo))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},jo=class extends Ut{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this.Pe)throw new TypeError(t);const e=this.Ie();if(Bt(e))throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new Uo,this.tracks=[],this.Be=null,this.Fe=new Set,this.$e=null,this.Oe=null,this.Re=null,this.De=null,this.Ne=new ct,this.Rt={},this.Ve=null,this.Pe=null,this.Ue=null,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!(t.format instanceof Ao))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof Kn||t.target instanceof oo))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof Kn&&this.ze(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof Kn)&&"function"!=typeof t.initTarget)throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this.je=t.target,this.Be=t.onFinalize??null,this.Le=t.initTarget??null,this.Le instanceof Kn&&this.ze(this.Le),this.xe=t.format.Ce(this)}qe(t){z(this.je instanceof oo);const e=this.je.getTarget(t),i=t=>{if(!(t instanceof Kn))throw new TypeError("getTarget must return a Target.");return t};return Bt(e)?e.then(i):i(e)}async He(t){z(this.je instanceof oo);const e=await this.qe(t);return this.ct("target",{target:e,request:t,isRoot:t.isRoot}),"canceled"===this.state?await e.Qt():this.ze(e),e}ze(t){this.Fe.add(t),t.on("finalized",()=>this.Fe.delete(t),{once:!0})}async me(){if(z(null!==this.Le),this.Le instanceof Kn)return this.Le;const t=await this.Le();return"canceled"===this.state?await t.Qt():this.ze(t),t}pe(){return null!==this.Le}Ie(){if(this.Ve)return this.Ve;if(this.Pe)return this.Pe;if(this.je instanceof Kn)return this.ct("target",{target:this.je,request:null,isRoot:!0}),this.Ve=this.je,this.je;const t={path:this.je.rootPath,isRoot:!0,mimeType:this.format.mimeType},e=this.qe(t),i=e=>("canceled"===this.state?e.Qt():this.ze(e),this.ct("target",{target:e,request:t,isRoot:!0}),this.Ve=e,e);return Bt(e)?this.Pe=e.then(i):i(e)}fe(t){return this.$e??=(async()=>{const e=await this.Ie(),i=new Jn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof vo))throw new TypeError("source must be a VideoSource.");if(zo(e),void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError(`Invalid video rotation: ${e.rotation}. Has to be 0, 90, 180 or 270.`);if(void 0!==e.flip&&"boolean"!=typeof e.flip)throw new TypeError("metadata.flip, when provided, must be a boolean.");if(!(void 0===e.transformationMatrix||Array.isArray(e.transformationMatrix)&&9===e.transformationMatrix.length&&e.transformationMatrix.every(t=>Number.isFinite(t))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(void 0!==e.frameRate&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${e.frameRate}. Must be a positive number.`);if(void 0!==e.hasOnlyKeyPackets&&"boolean"!=typeof e.hasOnlyKeyPackets)throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(void 0!==e.canBeTransparent&&"boolean"!=typeof e.canBeTransparent)throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(void 0!==e.decoderConfig&&hi({decoderConfig:e.decoderConfig},t.$t),void 0!==e.primingPacket){if(!(e.primingPacket instanceof fi))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(void 0===e.decoderConfig)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new Do(this.tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof Mo))throw new TypeError("source must be an AudioSource.");if(zo(e),void 0!==e.decoderConfig&&li({decoderConfig:e.decoderConfig},t.$t),void 0!==e.primingPacket){if(!(e.primingPacket instanceof fi))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(void 0===e.decoderConfig)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new No(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof Co))throw new TypeError("source must be a SubtitleSource.");zo(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new Vo(this.tracks.length+1,this,t,i))}setMetadataTags(t){if((t=>{if(!t||"object"!=typeof t)throw new TypeError("tags must be an object.");if(void 0!==t.title&&"string"!=typeof t.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==t.description&&"string"!=typeof t.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==t.artist&&"string"!=typeof t.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==t.album&&"string"!=typeof t.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==t.albumArtist&&"string"!=typeof t.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==t.trackNumber&&(!Number.isInteger(t.trackNumber)||t.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==t.tracksTotal&&(!Number.isInteger(t.tracksTotal)||t.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==t.discNumber&&(!Number.isInteger(t.discNumber)||t.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==t.discsTotal&&(!Number.isInteger(t.discsTotal)||t.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==t.genre&&"string"!=typeof t.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==t.date&&(!(t.date instanceof Date)||Number.isNaN(t.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==t.beatsPerMinute&&(!Number.isInteger(t.beatsPerMinute)||t.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(void 0!==t.lyrics&&"string"!=typeof t.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==t.images){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of t.images){if(!e||"object"!=typeof e)throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof e.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==t.comment&&"string"!=typeof t.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==t.raw){if(!t.raw||"object"!=typeof t.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(t.raw))if(!(null===e||"string"==typeof e||Array.isArray(e)&&e.every(t=>"string"==typeof t)||e instanceof Uint8Array||e instanceof Ht||e instanceof Gt||zt(e)))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}})(t),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this.Rt=t}Ge(t){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t.source.ve)throw new Error("Source is already used for a track.");const e=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((e,i)=>e+(i.type===t.type?1:0),0),r=e[t.type].max;if(i===r)throw new Error(0===r?`${this.format.Ae} does not support ${t.type} tracks.`:`${this.format.Ae} does not support more than ${r} ${t.type} track${1===r?"":"s"}.`);const n=e.total.max;if(this.tracks.length===n)throw new Error(`${this.format.Ae} does not support more than ${n} tracks${1===n?"":"s"} in total.`);if(t.isVideoTrack()){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format.Ae} does not support video tracks.`+this.format._e(t.source.$t));if(!e.includes(t.source.$t))throw new Error(`Codec '${t.source.$t}' cannot be contained within ${this.format.Ae}. Supported video codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format._e(t.source.$t))}else if(t.isAudioTrack()){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format.Ae} does not support audio tracks.`+this.format._e(t.source.$t));if(!e.includes(t.source.$t))throw new Error(`Codec '${t.source.$t}' cannot be contained within ${this.format.Ae}. Supported audio codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format._e(t.source.$t))}else if(t.isSubtitleTrack()){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format.Ae} does not support subtitle tracks.`+this.format._e(t.source.$t));if(!e.includes(t.source.$t))throw new Error(`Codec '${t.source.$t}' cannot be contained within ${this.format.Ae}. Supported subtitle codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format._e(t.source.$t))}return this.tracks.push(t),t.source.ve=t,t}hasEnoughTracks(){const t=this.format.getSupportedTrackCounts();for(const i of Oo)if(this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0)<t[i].min)return!1;const e=t.total.min;return!(this.tracks.length<e)}async start(){const t=this.format.getSupportedTrackCounts();for(const i of Oo){const e=this.tracks.reduce((t,e)=>t+(e.type===i?1:0),0),r=t[i].min;if(e<r)throw new Error(r===t[i].max?`${this.format.Ae} requires exactly ${r} ${i} track${1===r?"":"s"}.`:`${this.format.Ae} requires at least ${r} ${i} track${1===r?"":"s"}.`)}const e=t.total.min;if(this.tracks.length<e)throw new Error(e===t.total.max?`${this.format.Ae} requires exactly ${e} track${1===e?"":"s"}.`:`${this.format.Ae} requires at least ${e} track${1===e?"":"s"}.`);if("canceled"===this.state)throw new Error("Output has been canceled.");return this.Oe?(jt.wt("Output has already been started."),this.Oe):this.Oe=(async()=>{this.state="started";const t=this.Ne.acquire();try{await this.xe.start();const t=this.tracks.map(t=>t.source.Vt());await Promise.all(t)}finally{(await t)()}})()}getMimeType(){return this.xe.getMimeType()}async cancel(){return"canceled"===this.state?this.Re??void 0:"finalizing"!==this.state&&"finalized"!==this.state?this.Re=(async()=>{this.state="canceled";const t=await this.Ne.acquire();try{const t=this.tracks.map(t=>t.source.Ee(!0));await Promise.all(t),await Promise.all([...this.Fe].map(t=>t.Qt())),this.Fe.clear()}finally{t()}})():void("finalized"===this.state&&jt.wt("Output has already been finalized."))}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this.De?(jt.wt("Output has already been finalized."),this.De):this.De=(async()=>{this.state="finalizing";const t=await this.Ne.acquire();try{const t=this.tracks.map(t=>t.source.Ee(!1));if(await Promise.all(t),await this.xe.finalize(),this.$e){const t=await this.$e;t.finalized||(await t.flush(),await t.finalize())}this.Be&&await this.Be(),this.state="finalized"}catch(e){throw this.state="canceled",e}finally{await Promise.all([...this.Fe].map(t=>t.Qt().catch(()=>{}))),this.Fe.clear(),t()}})()}};function Lo(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(D());let s=!1;const a=setTimeout(()=>h(()=>o(N(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(D()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var qo=["vp9","vp8"],Ho=["avc"],Go=class{async $record(t,e,i,r={kind:"blob"}){this.I(t.signal),this.We();const n=await this.Xe(t);this.Ze(t,"video export plan",n),this.Qe(i,"recording","probing",0,n.frameCount,n);const o="mp4"===n.format?new Po:new $o,s="stream"===r.kind?new ro(r.writable,{chunked:!0}):new io,a=new jo({format:o,target:s}),h=new _o(e.canvas,{codec:n.codec,quality:this.Ye(n),alpha:n.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:n.hardwareAcceleration,keyFrameInterval:n.keyFrameInterval,sizeChangeBehavior:"deny",contentHint:"text",onEncoderConfig:e=>this.Ze(t,"video encoder config",e)});a.addVideoTrack(h,{frameRate:n.frameRate});let c=!1,l=!1;const d=()=>{c||(c=!0,h.close())};try{if(await Lo(a.start(),"Video output did not start within 30000ms.",t.signal,3e4),await e.$render({frameCount:n.frameCount,frameRate:n.frameRate,signal:t.signal,prepareFrame:t.prepareFrame,onFrame:async({frameIndex:e})=>{this.I(t.signal);const r=y(e,n.frameRate);await this.Je(h.add(r.startSeconds,r.durationSeconds),t.signal),this.Qe(i,"recording","capturing",e+1,n.frameCount,n)}}),this.I(t.signal),d(),this.Qe(i,"encoding","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),await Lo(a.finalize(),"Video output did not finalize within 30000ms.",t.signal,3e4),this.Qe(i,"completed","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),"stream"===r.kind)return;const o=s;if(!o.buffer)throw new R("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:n.mimeType})}catch(u){d(),await(async()=>{if(!l){l=!0;try{await a.cancel()}catch{}}})();const t=this.Ke(u);throw i?.({state:"error",message:t.message}),t}}async Xe(t){const e=U(t),i="mp4"===t.format?new Po:new $o,r="mp4"===t.format?Ho:qo,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t));for(const o of n)if(await rr(o,{width:e.width,height:e.height,quality:this.Ye(e),alpha:e.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:e.hardwareAcceleration,contentHint:"text"}))return U(t,o);throw new R("VIDEO_CODEC_UNSUPPORTED",`This browser cannot encode ${r.join(" or ")} video at ${e.width}x${e.height}. Try another format, lower the export dimensions, or change the encoder preference.`)}Ye(t){return new Yi(t.quality)}We(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new R("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}Je(t,e){return e?new Promise((i,r)=>{if(e.aborted)return void r(D());const n=()=>r(D());e.addEventListener("abort",n,{once:!0}),t.then(t=>{e.removeEventListener("abort",n),i(t)},t=>{e.removeEventListener("abort",n),r(t)})}):t}I(t){if(t?.aborted)throw D()}Qe(t,e,i,r,n,o){t?.({state:e,phase:i,frameIndex:r,frame:r,totalFrames:n,progress:n>0?r/n:0,codec:o.codec,codedWidth:o.width,codedHeight:o.height,frameRate:o.frameRate})}Ke(t){return V(t)}Ze(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},Wo=class{ti;T;k;constructor(t,e){this.ti=new Go,this.T=t,this.k=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.Z(e,t),r=U(i);if("file-system"===t.destination){const n=await this.ei((new s).$resolve(t.filename,`.${e}`),r.mimeType);try{await this.ii(i,n,t.onProgress)}catch(o){try{await(n.abort?.(o))}catch{}throw o}return}const n=await this.ii(i,{kind:"blob"},t.onProgress);if(!n)throw new R("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new a).$downloadFile(n,t.filename,`.${e}`)}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.Z(e,t);U(i);const r=await this.ii(i,{kind:"blob"},t.onProgress);if(!r)throw new R("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async ii(t,e,i){const r=new g(this.T,this.k,{width:t.width,height:t.height});try{return await this.ti.$record(t,r,i,e)}catch(n){if(i?.({state:"error",message:n instanceof Error?n.message:`${t.format.toUpperCase()} export failed`}),n instanceof p||w(n))throw V(n);throw n}}Z(t,e){const i=this.ri(e.frameRate,60),r=this.ni(e.frameCount,300),n=this.ri(e.pixelDensity,1),o=this.oi(),s=Math.max(1,Math.round(this.T.canvas.width/o*n)),a=Math.max(1,Math.round(this.T.canvas.height/o*n));return{filename:e.filename,format:t,frameRate:i,frameCount:r,quality:this.Ct(e.quality),hardwareAcceleration:this.si(e.hardwareAcceleration),keyFrameInterval:this.ai(e.keyFrameInterval),pixelDensity:n,width:s,height:a,transparent:Boolean(e.transparent),debugLogging:Boolean(e.debugLogging),signal:e.signal,prepareFrame:e.prepareFrame}}ni(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}ri(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}Ct(t){if(void 0===t)return"medium";if("very-low"===t||"low"===t||"medium"===t||"high"===t||"very-high"===t)return t;if("object"!=typeof t||null===t||!Number.isFinite(t.bitrate)||t.bitrate<=0)throw new TypeError("Video quality must be a Mediabunny quality level or a positive bitrate.");if(void 0!==t.bitrateMode&&!this.hi(t.bitrateMode))throw new TypeError("Video quality bitrateMode must be 'variable' or 'constant'.");return t.bitrateMode?{bitrate:t.bitrate,bitrateMode:t.bitrateMode}:{bitrate:t.bitrate}}hi(t){return"constant"===t||"variable"===t}si(t){return"prefer-hardware"===t||"prefer-software"===t||"no-preference"===t?t:"no-preference"}ai(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}oi(){const t=this.T.pixelDensity?.();return"number"==typeof t&&Number.isFinite(t)&&t>0?t:1}async ei(t,e){const i=globalThis;if(!i.showSaveFilePicker)throw new R("VIDEO_EXPORT_UNSUPPORTED","This browser cannot stream video exports to disk because the File System Access API is unavailable.");const r=await(await i.showSaveFilePicker({suggestedName:t,types:[{description:"Video file",accept:{[e]:[t.slice(t.lastIndexOf("."))]}}]})).createWritable();let n=!1;return{kind:"stream",writable:new WritableStream({write:t=>r.write(t),async close(){n=!0,await r.close()},async abort(t){n=!0,await r.abort(t)}}),async abort(t){n||(n=!0,await r.abort(t))}}}},Xo=class extends r{$extractCellData(t){const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],r=t.grid,n=t.font;let o=0;for(let s=0;s<r.rows;s++)for(let t=0;t<r.cols;t++){const r=4*o,a=this.$getEncodedCharacterValue(e.characterPixels,r),h=this.$extractCellTransform(e.characterPixels,r),c=l(n,a)?.character??" ";i.push({x:t,y:s,character:c,foreground:x(e.primaryColorPixels,r),background:x(e.secondaryColorPixels,r),transform:{invert:h.isInverted,flipX:h.flipHorizontal,flipY:h.flipVertical,rotation:h.rotation}}),o++}return i}},Zo="1.9.0",Qo={[e.LayerBlendMode.NORMAL]:"normal",[e.LayerBlendMode.ADDITIVE]:"additive",[e.LayerBlendMode.MULTIPLY]:"multiply",[e.LayerBlendMode.SCREEN]:"screen",[e.LayerBlendMode.SUBTRACT]:"subtract",[e.LayerBlendMode.DARKEN]:"darken",[e.LayerBlendMode.LIGHTEN]:"lighten",[e.LayerBlendMode.OVERLAY]:"overlay",[e.LayerBlendMode.SOFT_LIGHT]:"softLight",[e.LayerBlendMode.HARD_LIGHT]:"hardLight",[e.LayerBlendMode.COLOR_DODGE]:"colorDodge",[e.LayerBlendMode.COLOR_BURN]:"colorBurn",[e.LayerBlendMode.DIFFERENCE]:"difference",[e.LayerBlendMode.EXCLUSION]:"exclusion"},Yo=class{Z(t){return{target:t.target??"selected",pretty:t.pretty??!0,colorMode:t.colorMode??"hex",includeMetadata:t.includeMetadata??!0,filename:t.filename,layer:t.layer}}ci(t,e){return t.includeMetadata?{createdAt:e.toISOString(),generator:{name:"textmode.export.js",version:Zo}}:void 0}li(t,e){return"rgba"===e?{...t}:`#${[t.r,t.g,t.b,t.a].map(t=>t.toString(16).padStart(2,"0")).join("")}`}di(t,e,i,r){const n=[];for(let o=0;o<i;o++){const i=o*e,s=t.slice(i,i+e).map(t=>({x:t.x,y:t.y,character:t.character,foreground:this.li(t.foreground,r),background:this.li(t.background,r),transform:{...t.transform}}));n.push(s)}return{encoding:"object-rows-v1",rows:n}}ui(t){return{cols:t.grid.cols,rows:t.grid.rows,cellWidth:t.grid.cellWidth,cellHeight:t.grid.cellHeight}}fi(t,e){const i=(new Xo).$extractCellData(t);return this.di(i,t.grid.cols,t.grid.rows,e.colorMode)}pi(t,e){return{id:t.id,visible:t.visible,opacity:t.opacity,blendMode:Qo[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.ui(t),cells:this.fi(t,e)}}$generateJSONData(t,i={},r=new Date){const n=this.Z(i),o=this.ci(n,r),s=function(t,i){return(i??[t.layers.base,...t.layers.all]).map(i=>{const r=f(t,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??e.LayerBlendMode.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(t,"selected"===n.target?[n.layer??t.layers.base]:void 0);return{format:"textmode.document",formatVersion:"3.0.0",...o?{metadata:o}:{},layers:s.map(t=>this.pi(t,n))}}$generateJSONString(t,e={},i=new Date){const r=this.Z(e),n=this.$generateJSONData(t,r,i),o="number"==typeof r.pretty?r.pretty:r.pretty?2:0;return JSON.stringify(n,null,o)}$saveJSON(t,e={}){const i=this.Z(e);(new a).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename,".json")}},Jo=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="ZIP_EXPORT_ABORTED"===t?"AbortError":"ZIPExportError",this.code=t,this.cause=i}};function Ko(t){return new Jo("ZIP_EXPORT_ABORTED","ZIP frame-sequence export was cancelled.",t)}function ts(t){if(t instanceof Jo)return t;if(w(t))return Ko(t);if(t instanceof p){if("FRAME_SEQUENCE_TIMEOUT"===t.code)return new Jo("ZIP_EXPORT_TIMEOUT",t.message,t);if("FRAME_SEQUENCE_BUSY"===t.code)return new Jo("ZIP_EXPORT_BUSY",t.message,t);if("FRAME_SEQUENCE_DISPOSED"===t.code)return new Jo("ZIP_EXPORT_DISPOSED",t.message,t)}return new Jo("ZIP_EXPORT_FAILED",t instanceof Error?t.message:"ZIP frame-sequence export failed.",t)}var es=new TextEncoder;function is(t){if(!t||"object"!=typeof t||Array.isArray(t))return{};const e={...t};return delete e.filename,delete e.format,e}function rs(t){const e=new C;return{extension:`.${t}`,compression:"store",getDimensions({canvas:t,frameOptions:e}){const i=is(e),r=Math.abs(i.scale??1);return{width:Math.round(t.width*r),height:Math.round(t.height*r)}},async serialize({canvas:i,frameOptions:r}){const n=await e.$toImageBlob(i,{...is(r),format:t}),o=M[t];if(n.type.toLowerCase()!==o)throw new Jo("ZIP_EXPORT_ENCODING_UNSUPPORTED",`The browser returned '${n.type||"an unknown format"}' instead of '${o}'.`);return new Uint8Array(await n.arrayBuffer())}}}function ns(t,e){return{extension:`.${t}`,compression:"deflate",getDimensions({frameOptions:i}){const r=is(i),n="json"===t&&"all"===r.target?f(e):f(e,r.layer);return{width:n.grid.width,height:n.grid.height}},async serialize({frameOptions:i,createdAt:r}){const n=is(i);let o;return o="svg"===t?(new _).$generateSVG(e,n):"json"===t?(new Yo).$generateJSONString(e,n,r):(new A).$generateTXT(e,n),es.encode(o)}}}var os=Uint8Array,ss=Uint16Array,as=Int32Array,hs=new os([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),cs=new os([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ls=new os([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ds=function(t,e){for(var i=new ss(31),r=0;r<31;++r)i[r]=e+=1<<t[r-1];var n=new as(i[30]);for(r=1;r<30;++r)for(var o=i[r];o<i[r+1];++o)n[o]=o-i[r]<<5|r;return{b:i,r:n}},us=ds(hs,2),fs=us.b,ps=us.r;fs[28]=258,ps[258]=28;for(var ms=ds(cs,0),ws=(ms.b,ms.r),vs=new ss(32768),bs=0;bs<32768;++bs){var ys=(43690&bs)>>1|(21845&bs)<<1;ys=(61680&(ys=(52428&ys)>>2|(13107&ys)<<2))>>4|(3855&ys)<<4,vs[bs]=((65280&ys)>>8|(255&ys)<<8)>>1}var gs=function(t,e,i){for(var r=t.length,n=0,o=new ss(e);n<r;++n)t[n]&&++o[t[n]-1];var s,a=new ss(e);for(n=1;n<e;++n)a[n]=a[n-1]+o[n-1]<<1;if(i){s=new ss(1<<e);var h=15-e;for(n=0;n<r;++n)if(t[n])for(var c=n<<4|t[n],l=e-t[n],d=a[t[n]-1]++<<l,u=d|(1<<l)-1;d<=u;++d)s[vs[d]>>h]=c}else for(s=new ss(r),n=0;n<r;++n)t[n]&&(s[n]=vs[a[t[n]-1]++]>>15-t[n]);return s},xs=new os(288);for(bs=0;bs<144;++bs)xs[bs]=8;for(bs=144;bs<256;++bs)xs[bs]=9;for(bs=256;bs<280;++bs)xs[bs]=7;for(bs=280;bs<288;++bs)xs[bs]=8;var Es=new os(32);for(bs=0;bs<32;++bs)Es[bs]=5;var Ts=gs(xs,9,0),ks=gs(Es,5,0),_s=function(t){return(t+7)/8|0},Ms=function(t,e,i){return(null==e||e<0)&&(e=0),(null==i||i>t.length)&&(i=t.length),new os(t.subarray(e,i))},Cs=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],As=function(t,e,i){var r=new Error(e||Cs[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,As),!i)throw r;return r},Ss=function(t,e,i){i<<=7&e;var r=e/8|0;t[r]|=i,t[r+1]|=i>>8},Ps=function(t,e,i){i<<=7&e;var r=e/8|0;t[r]|=i,t[r+1]|=i>>8,t[r+2]|=i>>16},Is=function(t,e){for(var i=[],r=0;r<t.length;++r)t[r]&&i.push({s:r,f:t[r]});var n=i.length,o=i.slice();if(!n)return{t:Ns,l:0};if(1==n){var s=new os(i[0].s+1);return s[i[0].s]=1,{t:s,l:1}}i.sort(function(t,e){return t.f-e.f}),i.push({s:-1,f:25001});var a=i[0],h=i[1],c=0,l=1,d=2;for(i[0]={s:-1,f:a.f+h.f,l:a,r:h};l!=n-1;)a=i[i[c].f<i[d].f?c++:d++],h=i[c!=l&&i[c].f<i[d].f?c++:d++],i[l++]={s:-1,f:a.f+h.f,l:a,r:h};var u=o[0].s;for(r=1;r<n;++r)o[r].s>u&&(u=o[r].s);var f=new ss(u+1),p=Bs(i[l-1],f,0);if(p>e){r=0;var m=0,w=p-e,v=1<<w;for(o.sort(function(t,e){return f[e.s]-f[t.s]||t.f-e.f});r<n;++r){var b=o[r].s;if(!(f[b]>e))break;m+=v-(1<<p-f[b]),f[b]=e}for(m>>=w;m>0;){var y=o[r].s;f[y]<e?m-=1<<e-f[y]++-1:++r}for(;r>=0&&m;--r){var g=o[r].s;f[g]==e&&(--f[g],++m)}p=e}return{t:new os(f),l:p}},Bs=function(t,e,i){return-1==t.s?Math.max(Bs(t.l,e,i+1),Bs(t.r,e,i+1)):e[t.s]=i},Fs=function(t){for(var e=t.length;e&&!t[--e];);for(var i=new ss(++e),r=0,n=t[0],o=1,s=function(t){i[r++]=t},a=1;a<=e;++a)if(t[a]==n&&a!=e)++o;else{if(!n&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(s(n),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0)}for(;o--;)s(n);o=1,n=t[a]}return{c:i.subarray(0,r),n:e}},$s=function(t,e){for(var i=0,r=0;r<e.length;++r)i+=t[r]*e[r];return i},Os=function(t,e,i){var r=i.length,n=_s(e+2);t[n]=255&r,t[n+1]=r>>8,t[n+2]=255^t[n],t[n+3]=255^t[n+1];for(var o=0;o<r;++o)t[n+o+4]=i[o];return 8*(n+4+r)},Rs=function(t,e,i,r,n,o,s,a,h,c,l){Ss(e,l++,i),++n[256];for(var d=Is(n,15),u=d.t,f=d.l,p=Is(o,15),m=p.t,w=p.l,v=Fs(u),b=v.c,y=v.n,g=Fs(m),x=g.c,E=g.n,T=new ss(19),k=0;k<b.length;++k)++T[31&b[k]];for(k=0;k<x.length;++k)++T[31&x[k]];for(var _=Is(T,7),M=_.t,C=_.l,A=19;A>4&&!M[ls[A-1]];--A);var S,P,I,B,F=c+5<<3,$=$s(n,xs)+$s(o,Es)+s,O=$s(n,u)+$s(o,m)+s+14+3*A+$s(T,M)+2*T[16]+3*T[17]+7*T[18];if(h>=0&&F<=$&&F<=O)return Os(e,l,t.subarray(h,h+c));if(Ss(e,l,1+(O<$)),l+=2,O<$){S=gs(u,f,0),P=u,I=gs(m,w,0),B=m;var R=gs(M,C,0);for(Ss(e,l,y-257),Ss(e,l+5,E-1),Ss(e,l+10,A-4),l+=14,k=0;k<A;++k)Ss(e,l+3*k,M[ls[k]]);l+=3*A;for(var D=[b,x],N=0;N<2;++N){var V=D[N];for(k=0;k<V.length;++k){var U=31&V[k];Ss(e,l,R[U]),l+=M[U],U>15&&(Ss(e,l,V[k]>>5&127),l+=V[k]>>12)}}}else S=Ts,P=xs,I=ks,B=Es;for(k=0;k<a;++k){var z=r[k];if(z>255){Ps(e,l,S[257+(U=z>>18&31)]),l+=P[U+257],U>7&&(Ss(e,l,z>>23&31),l+=hs[U]);var j=31&z;Ps(e,l,I[j]),l+=B[j],j>3&&(Ps(e,l,z>>5&8191),l+=cs[j])}else Ps(e,l,S[z]),l+=P[z]}return Ps(e,l,S[256]),l+P[256]},Ds=new as([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ns=new os(0),Vs=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var i=e,r=9;--r;)i=(1&i&&-306674912)^i>>>1;t[e]=i}return t}(),Us=function(t,e,i){for(;i;++e)t[e]=i,i>>>=8},zs=function(){function t(t,e){if("function"==typeof t&&(e=t,t={}),this.ondata=e,this.o=t||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new os(98304),this.o.dictionary){var i=this.o.dictionary.subarray(-32768);this.b.set(i,32768-i.length),this.s.i=32768-i.length}}return t.prototype.p=function(t,e){this.ondata(function(t,e,i,r,n){if(!n&&(n={l:1},e.dictionary)){var o=e.dictionary.subarray(-32768),s=new os(o.length+t.length);s.set(o),s.set(t,o.length),t=s,n.w=o.length}return function(t,e,i,r,n,o){var s=o.z||t.length,a=new os(r+s+5*(1+Math.ceil(s/7e3))+n),h=a.subarray(r,a.length-n),c=o.l,l=7&(o.r||0);if(e){l&&(h[0]=o.r>>3);for(var d=Ds[e-1],u=d>>13,f=8191&d,p=(1<<i)-1,m=o.p||new ss(32768),w=o.h||new ss(p+1),v=Math.ceil(i/3),b=2*v,y=function(e){return(t[e]^t[e+1]<<v^t[e+2]<<b)&p},g=new as(25e3),x=new ss(288),E=new ss(32),T=0,k=0,_=o.i||0,M=0,C=o.w||0,A=0;_+2<s;++_){var S=y(_),P=32767&_,I=w[S];if(m[P]=I,w[S]=P,C<=_){var B=s-_;if((T>7e3||M>24576)&&(B>423||!c)){l=Rs(t,h,0,g,x,E,k,M,A,_-A,l),M=T=k=0,A=_;for(var F=0;F<286;++F)x[F]=0;for(F=0;F<30;++F)E[F]=0}var $=2,O=0,R=f,D=P-I&32767;if(B>2&&S==y(_-D))for(var N=Math.min(u,B)-1,V=Math.min(32767,_),U=Math.min(258,B);D<=V&&--R&&P!=I;){if(t[_+$]==t[_+$-D]){for(var z=0;z<U&&t[_+z]==t[_+z-D];++z);if(z>$){if($=z,O=D,z>N)break;var j=Math.min(D,z-2),L=0;for(F=0;F<j;++F){var q=_-D+F&32767,H=q-m[q]&32767;H>L&&(L=H,I=q)}}}D+=(P=I)-(I=m[P])&32767}if(O){g[M++]=268435456|ps[$]<<18|ws[O];var G=31&ps[$],W=31&ws[O];k+=hs[G]+cs[W],++x[257+G],++E[W],C=_+$,++T}else g[M++]=t[_],++x[t[_]]}}for(_=Math.max(_,C);_<s;++_)g[M++]=t[_],++x[t[_]];l=Rs(t,h,c,g,x,E,k,M,A,_-A,l),c||(o.r=7&l|h[l/8|0]<<3,l-=7,o.h=w,o.p=m,o.i=_,o.w=C)}else{for(_=o.w||0;_<s+c;_+=65535){var X=_+65535;X>=s&&(h[l/8|0]=c,X=s),l=Os(h,l+1,t.subarray(_,X))}o.i=s}return Ms(a,0,r+_s(l)+n)}(t,null==e.level?6:e.level,null==e.mem?n.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):20:12+e.mem,i,r,n)}(t,this.o,0,0,this.s),e)},t.prototype.push=function(t,e){this.ondata||As(5),this.s.l&&As(4);var i=t.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var r=new os(-32768&i);r.set(this.b.subarray(0,this.s.z)),this.b=r}var n=this.b.length-this.s.z;this.b.set(t.subarray(0,n),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(t.subarray(n),32768),this.s.z=t.length-n+32768,this.s.i=32766,this.s.w=32768}else this.b.set(t,this.s.z),this.s.z+=t.length;this.s.l=1&e,(this.s.z>this.s.w+8191||e)&&(this.p(this.b,e||!1),this.s.w=this.s.i,this.s.i-=2),e&&(this.s=this.o={},this.b=Ns)},t.prototype.flush=function(t){if(this.ondata||As(5),this.s.l&&As(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,t){var e=new os(6);e[0]=this.s.r>>3;var i=Os(e,this.s.r,Ns);this.s.r=0,this.ondata(e.subarray(0,i>>3),!1)}},t}(),js="undefined"!=typeof TextEncoder&&new TextEncoder,Ls="undefined"!=typeof TextDecoder&&new TextDecoder;try{Ls.decode(Ns,{stream:!0})}catch(sh){}function qs(t,e){if(e){for(var i=new os(t.length),r=0;r<t.length;++r)i[r]=t.charCodeAt(r);return i}if(js)return js.encode(t);var n=t.length,o=new os(t.length+(t.length>>1)),s=0,a=function(t){o[s++]=t};for(r=0;r<n;++r){if(s+5>o.length){var h=new os(s+8+(n-r<<1));h.set(o),o=h}var c=t.charCodeAt(r);c<128||e?a(c):c<2048?(a(192|c>>6),a(128|63&c)):c>55295&&c<57344?(a(240|(c=65536+(1047552&c)|1023&t.charCodeAt(++r))>>18),a(128|c>>12&63),a(128|c>>6&63),a(128|63&c)):(a(224|c>>12),a(128|c>>6&63),a(128|63&c))}return Ms(o,0,s)}var Hs=function(t){var e=0;if(t)for(var i in t){var r=t[i].length;r>65535&&As(9),e+=r+4}return e},Gs=function(t,e,i,r,n,o,s,a){var h=r.length,c=i.extra,l=a&&a.length,d=Hs(c);Us(t,e,null!=s?33639248:67324752),e+=4,null!=s&&(t[e++]=20,t[e++]=i.os),t[e]=20,e+=2,t[e++]=i.flag<<1|(o<0&&8),t[e++]=n&&8,t[e++]=255&i.compression,t[e++]=i.compression>>8;var u=new Date(null==i.mtime?Date.now():i.mtime),f=u.getFullYear()-1980;if((f<0||f>119)&&As(10),Us(t,e,f<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,-1!=o&&(Us(t,e,i.crc),Us(t,e+4,o<0?-o-2:o),Us(t,e+8,i.size)),Us(t,e+12,h),Us(t,e+14,d),e+=16,null!=s&&(Us(t,e,l),Us(t,e+6,i.attrs),Us(t,e+10,s),e+=14),t.set(r,e),e+=h,d)for(var p in c){var m=c[p],w=m.length;Us(t,e,+p),Us(t,e+2,w),t.set(m,e+4),e+=4+w}return l&&(t.set(a,e),e+=l),e},Ws=function(){function t(t){var e;this.filename=t,this.c=(e=-1,{p:function(t){for(var i=e,r=0;r<t.length;++r)i=Vs[255&i^t[r]]^i>>>8;e=i},d:function(){return~e}}),this.size=0,this.compression=0}return t.prototype.process=function(t,e){this.ondata(null,t,e)},t.prototype.push=function(t,e){this.ondata||As(5),this.c.p(t),this.size+=t.length,e&&(this.crc=this.c.d()),this.process(t,e||!1)},t}(),Xs=function(){function t(t,e){var i,r=this;e||(e={}),Ws.call(this,t),this.d=new zs(e,function(t,e){r.ondata(null,t,e)}),this.compression=8,this.flag=1==(i=e.level)?3:i<6?2:9==i?1:0}return t.prototype.process=function(t,e){try{this.d.push(t,e)}catch(sh){this.ondata(sh,null,e)}},t.prototype.push=function(t,e){Ws.prototype.push.call(this,t,e)},t}(),Zs=function(){function t(t){this.ondata=t,this.u=[],this.d=1}return t.prototype.add=function(t){var e=this;if(this.ondata||As(5),2&this.d)this.ondata(As(4+8*(1&this.d),0,1),null,!1);else{var i=qs(t.filename),r=i.length,n=t.comment,o=n&&qs(n),s=r!=t.filename.length||o&&n.length!=o.length,a=r+Hs(t.extra)+30;r>65535&&this.ondata(As(11,0,1),null,!1);var h=new os(a);Gs(h,0,t,i,s,-1);var c=[h],l=function(){for(var t=0,i=c;t<i.length;t++){var r=i[t];e.ondata(null,r,!1)}c=[]},d=this.d;this.d=0;var u=this.u.length,f=function(t,e){var i={};for(var r in t)i[r]=t[r];for(var r in e)i[r]=e[r];return i}(t,{f:i,u:s,o,t:function(){t.terminate&&t.terminate()},r:function(){if(l(),d){var t=e.u[u+1];t?t.r():e.d=1}d=1}}),p=0;t.ondata=function(i,r,n){if(i)e.ondata(i,r,n),e.terminate();else if(p+=r.length,c.push(r),n){var o=new os(16);Us(o,0,134695760),Us(o,4,t.crc),Us(o,8,p),Us(o,12,t.size),c.push(o),f.c=p,f.b=a+p+16,f.crc=t.crc,f.size=t.size,d&&f.r(),d=1}else d&&l()},this.u.push(f)}},t.prototype.end=function(){var t=this;2&this.d?this.ondata(As(4+8*(1&this.d),0,1),null,!0):(this.d?this.e():this.u.push({r:function(){1&t.d&&(t.u.splice(-1,1),t.e())},t:function(){}}),this.d=3)},t.prototype.e=function(){for(var t=0,e=0,i=0,r=0,n=this.u;r<n.length;r++)i+=46+(f=n[r]).f.length+Hs(f.extra)+(f.o?f.o.length:0);for(var o,s,a,h,c,l=new os(i+22),d=0,u=this.u;d<u.length;d++){var f=u[d];Gs(l,t,f,f.f,f.u,-f.c-2,e,f.o),t+=46+f.f.length+Hs(f.extra)+(f.o?f.o.length:0),e+=f.b}o=l,s=t,a=this.u.length,h=i,c=e,Us(o,s,101010256),Us(o,s+8,a),Us(o,s+10,a),Us(o,s+12,h),Us(o,s+16,c),this.ondata(null,l,!0),this.d=2},t.prototype.terminate=function(){for(var t=0,e=this.u;t<e.length;t++)e[t].t();this.d=2},t}(),Qs=class{mi;re=[];wi=new Set;bi;yi;gi="open";xi=0;Ei;Ti;ki;constructor(t,e=4294967295){this.bi=t,this.yi=e,this.mi=new Zs((t,e,i)=>{if("failed"!==this.gi)if(t)this._i(t);else{if(e.byteLength>0){if(this.xi+e.byteLength>this.yi)return void this._i(new Jo("ZIP_EXPORT_TOO_LARGE",`Classic ZIP archives cannot exceed ${this.yi.toLocaleString("en-US")} bytes.`));const t=new Uint8Array(e.byteLength);t.set(e),this.re.push(t.buffer),this.xi+=e.byteLength}if(i&&"finalizing"===this.gi){this.gi="closed";const t=new Blob(this.re,{type:"application/zip"});this.re.length=0,this.Ti?.(t),this.Ti=void 0,this.ki=void 0}}})}async $addEntry(t,e,i){if(this.Mi(),this.Ci(t),this.wi.has(t))throw new Jo("ZIP_EXPORT_FAILED",`Duplicate ZIP entry: ${t}`);if(this.wi.size>=65535)throw new Jo("ZIP_EXPORT_TOO_LARGE","Classic ZIP archives cannot contain more than 65,535 entries.");if(e.byteLength>this.yi)throw new Jo("ZIP_EXPORT_TOO_LARGE",`A classic ZIP entry cannot exceed ${this.yi.toLocaleString("en-US")} bytes.`);const r="store"===i?new Ws(t):new Xs(t,{level:6});if(r.mtime=this.bi,this.wi.add(t),this.mi.add(r),(r instanceof Ws||r instanceof Xs)&&r.push(e,!0),this.Ei)throw this.Ei;await Promise.resolve()}$finalize(){return this.Mi(),this.gi="finalizing",new Promise((t,e)=>{this.Ti=t,this.ki=e;try{this.mi.end()}catch(i){this._i(i)}})}$abort(t=Ko()){"closed"!==this.gi&&"failed"!==this.gi&&(this.gi="failed",this.Ei=t,this.mi.terminate(),this.re.length=0,this.ki?.(t),this.Ti=void 0,this.ki=void 0)}Mi(){if("open"!==this.gi)throw new Jo("ZIP_EXPORT_FAILED",`ZIP archive writer is ${this.gi}.`,this.Ei)}Ci(t){const e=t.split("/");if(!t||t.startsWith("/")||/^[A-Za-z]:/.test(t)||t.includes("\\")||t.includes("\0")||e.some(t=>!t||"."===t||".."===t))throw new Jo("ZIP_EXPORT_FAILED",`Unsafe ZIP entry path: ${t}`)}_i(t){"failed"!==this.gi&&(this.gi="failed",this.Ei=t,this.re.length=0,this.mi.terminate(),this.ki?.(t),this.Ti=void 0,this.ki=void 0)}},Ys=new Set(["png","jpg","webp","svg","json","txt"]),Js=class{T;k;Ai;constructor(t,e,i={}){this.T=t,this.k=e,this.Ai=i}async $saveZIP(t){await this.Si(t,({blob:t,filename:e})=>{(new a).$downloadFile(t,e,".zip")})}async $generateZIPBlob(t){return(await this.Si(t)).blob}async Si(t,e){try{return await this.Pi(t,e)}catch(i){const e=ts(i);if("ZIP_EXPORT_INVALID_OPTIONS"===e.code)try{t?.onProgress?.({state:"error",frameIndex:0,totalFrames:this.Ii(t?.frameCount),progress:0,message:e.message})}catch(r){throw ts(r)}throw e}}async Pi(t,e){const i=this.Bi(t),r=this.Ai.now?.()??new Date,n=(new s).$resolve(i.filename,".zip",r),o=n.slice(0,-4);let a,h=!1,c=0;try{this.I(i.signal);const t=(l=this.T,{png:rs("png"),jpg:rs("jpg"),webp:rs("webp"),svg:ns("svg",l),json:ns("json",l),txt:ns("txt",l)}),s=this.Ai.resolveSerializer?.(i.format)??t[i.format];a=this.Ai.createWriter?.(r)??new Qs(r);const d=a,u=this.Ai.createDriver?.()??new g(this.T,this.k),f=s.getDimensions({canvas:u.canvas,frameOptions:i.frameOptions});this.Qe(i,{state:"capturing",frameIndex:0,totalFrames:i.frameCount,progress:0}),this.I(i.signal);const p=function(t){return{schema:"textmode.frame-sequence",schemaVersion:"1.0.0",generator:{name:"textmode.export.js",version:Zo},createdAt:t.createdAt.toISOString(),format:t.format,frameCount:t.frameCount,frameRate:t.frameRate,width:t.width,height:t.height,indexBase:1,filePattern:`frames/frame-%06d${t.extension}`}}({createdAt:r,format:i.format,frameCount:i.frameCount,frameRate:i.frameRate,width:f.width,height:f.height,extension:s.extension});await d.$addEntry(`${o}/manifest.json`,function(t){return(new TextEncoder).encode(`${JSON.stringify(t,null,2)}\n`)}(p),"deflate"),this.I(i.signal),await u.$render({frameCount:i.frameCount,frameRate:i.frameRate,prepareFrame:i.prepareFrame,signal:i.signal,onFrame:async({frameIndex:t,canvas:e})=>{this.I(i.signal);const n=await s.serialize({canvas:e,frameOptions:i.frameOptions,createdAt:r});this.I(i.signal),await d.$addEntry(function(t,e,i){return`${t}/frames/frame-${String(e+1).padStart(6,"0")}${i}`}(o,t,s.extension),n,s.compression),this.I(i.signal);const a=t+1;c=a,this.Qe(i,{state:"capturing",frameIndex:a,totalFrames:i.frameCount,progress:a/i.frameCount}),await this.st(i.signal)}}),this.I(i.signal),this.Qe(i,{state:"finalizing",frameIndex:i.frameCount,totalFrames:i.frameCount,progress:1}),this.I(i.signal);const m=await d.$finalize();return this.I(i.signal),await(e?.({blob:m,filename:n})),this.I(i.signal),this.Qe(i,{state:"completed",frameIndex:i.frameCount,totalFrames:i.frameCount,progress:1}),h=!0,{blob:m,filename:n}}catch(d){const t=ts(d);try{this.Qe(i,{state:"error",frameIndex:c,totalFrames:i.frameCount,progress:c/i.frameCount,message:t.message})}catch{}throw t}finally{h||a?.$abort()}var l}Bi(t){if(!t||"object"!=typeof t)throw new Jo("ZIP_EXPORT_INVALID_OPTIONS","ZIP export options are required.");const e=t.format;if("string"!=typeof e||!Ys.has(e))throw new Jo("ZIP_EXPORT_INVALID_OPTIONS","ZIP frame format must be one of 'png', 'jpg', 'webp', 'svg', 'json', or 'txt'.");const i=t.frameCount??300;if(!Number.isFinite(i)||!Number.isInteger(i)||i<1||i>65534)throw new Jo("ZIP_EXPORT_INVALID_OPTIONS","ZIP frameCount must be an integer from 1 through 65534.");const r=t.frameRate??60;if(!Number.isFinite(r)||r<=0)throw new Jo("ZIP_EXPORT_INVALID_OPTIONS","ZIP frameRate must be finite and greater than zero.");return{format:e,filename:t.filename,frameCount:i,frameRate:r,frameOptions:t.frameOptions,prepareFrame:t.prepareFrame,signal:t.signal,onProgress:t.onProgress}}Qe(t,e){t.onProgress?.(e)}Ii(t){return Number.isInteger(t)&&t>=1&&t<=65534?t:300}I(t){if(t?.aborted)throw Ko()}st(t){return new Promise((e,i)=>{if(t?.aborted)return void i(Ko());let r=!1;const n=()=>{r||(r=!0,i(Ko()))};t?.addEventListener("abort",n,{once:!0}),setTimeout(()=>{r||(r=!0,t?.removeEventListener("abort",n),e())},0)})}},Ks="textmode-export-overlay__stack",ta="textmode-export-overlay__stack--dense",ea="textmode-export-overlay__stack--compact",ia="textmode-export-overlay__section",ra="textmode-export-overlay--dragging",na="textmode-export-overlay__label",oa="textmode-export-overlay__field",sa="textmode-export-overlay__field--compact",aa="textmode-export-overlay__field--dense",ha="textmode-export-overlay__field--full",ca="textmode-export-overlay__field--channel",la="textmode-export-overlay__input",da="textmode-export-overlay__muted",ua="textmode-export-overlay__button--primary",fa="textmode-export-overlay__button--secondary",pa="textmode-export-overlay__button--full",ma="textmode-export-overlay__link-icon",wa=class{element;mounted=!1;destroyed=!1;mount(t){if(this.destroyed)throw new Error("Cannot mount a destroyed component");if(this.mounted)return;const e=this.render();t.appendChild(e),this.element=e,this.onMount(),this.mounted=!0}unmount(){this.mounted&&this.element&&(this.Fi(),this.element.remove(),this.element=void 0,this.mounted=!1)}destroy(){this.destroyed||(this.unmount(),this.$i(),this.destroyed=!0)}update(t){this.mounted&&this.onUpdate(t)}onMount(){}Fi(){}$i(){}onUpdate(t){}get root(){if(!this.element)throw new Error("Component is not mounted yet");return this.element}isMounted(){return this.mounted}},va=class t extends wa{static Oi="http://www.w3.org/2000/svg";Ri;get dragHandleElement(){if(!this.Ri)throw new Error("Header drag handle is not mounted yet");return this.Ri}render(){this.Ri=void 0;const t=document.createElement("div");t.classList.add(Ks,ta,"textmode-export-overlay__header");const e=document.createElement("div");e.classList.add("textmode-export-overlay__header-title-row");const i=document.createElement("div");i.classList.add("textmode-export-overlay__header-identity");const r=this.Di("Move export overlay","textmode-export-overlay__grab-handle",[{d:"M9 5h.01"},{d:"M15 5h.01"},{d:"M9 12h.01"},{d:"M15 12h.01"},{d:"M9 19h.01"},{d:"M15 19h.01"}]);this.Ri=r;const n=document.createElement("strong");n.textContent="textmode.export.js",n.classList.add("textmode-export-overlay__title");const o=document.createElement("div");o.classList.add("textmode-export-overlay__header-links");const s=this.Ni("https://github.com/humanbydefinition/textmode.export.js","View repository on GitHub",ma,[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5"}]),a=this.Ni("https://code.textmode.art/docs/support","Support textmode.export.js","textmode-export-overlay__support-icon",[{d:"M0 0h24v24H0z",fill:"none",stroke:"none"},{d:"M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1"},{d:"M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"},{d:"M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z"},{d:"M16.746 16.726a3 3 0 1 0 .252 -5.555"}]);o.appendChild(s),o.appendChild(a),i.appendChild(r),i.appendChild(n),e.appendChild(i),e.appendChild(o);const h=document.createElement("div");return h.classList.add("textmode-export-overlay__divider"),t.appendChild(e),t.appendChild(h),t}Di(t,e,i){const r=document.createElement("button");return r.type="button",r.classList.add(e),r.setAttribute("aria-label",t),r.title=t,r.appendChild(this.Vi(ma,i)),r}Ni(t,e,i,r){const n=document.createElement("a");return n.href=t,n.target="_blank",n.rel="noopener noreferrer",n.classList.add("textmode-export-overlay__support-link"),n.setAttribute("aria-label",e),n.appendChild(this.Vi(i,r)),n}Vi(e,i){const r=document.createElementNS(t.Oi,"svg");r.setAttribute("xmlns",t.Oi),r.setAttribute("width","18"),r.setAttribute("height","18"),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke","currentColor"),r.setAttribute("stroke-width","2"),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.classList.add(e);for(const n of i){const e=document.createElementNS(t.Oi,"path");for(const[t,i]of Object.entries(n))e.setAttribute(t,i);r.appendChild(e)}return r}},ba=class extends wa{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(oa),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(na),e.textContent=this.props.label,this.props.labelFor&&(e.htmlFor=this.props.labelFor),t.appendChild(e),this.props.description){const e=document.createElement("span");e.classList.add(da),e.textContent=this.props.description,t.appendChild(e)}return t}attachControl(t){this.root.appendChild(t)}update(t){this.props=t,super.update(t)}onUpdate(t){const e=this.root;for(;e.firstChild;)e.removeChild(e.firstChild);this.props=t,e.classList.add(oa),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(na),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(da),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(sa,aa,ha,ca),e){case"compact":t.classList.add(sa);break;case"dense":t.classList.add(aa);break;case"full":t.classList.add(ha);break;case"channel":t.classList.add(ca)}}},ya=class extends wa{props;select;handleChange=()=>{this.props.defaultValue=this.select.value};constructor(t){super(),this.props=t}render(){return this.select=document.createElement("select"),this.select.classList.add(la),this.props.id&&(this.select.id=this.props.id),this.populateOptions(),this.select.addEventListener("change",this.handleChange),this.select}get selectElement(){return this.select}get value(){return this.select.value}set value(t){this.select&&(this.select.value=t),this.props.defaultValue=t}Fi(){this.select.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,this.populateOptions(),t.defaultValue&&(this.select.value=t.defaultValue)}update(t){this.props={...this.props,...t},this.select&&(t.id&&(this.select.id=t.id),t.options&&this.populateOptions(),void 0!==t.defaultValue&&(this.select.value=t.defaultValue))}populateOptions(){if(this.select){this.select.innerHTML="";for(const t of this.props.options){const e=document.createElement("option");e.value=t.value,e.textContent=t.label,this.select.appendChild(e)}this.props.defaultValue&&(this.select.value=this.props.defaultValue)}}},ga=class extends wa{props;button;constructor(t){super(),this.props=t}render(){return this.button=document.createElement("button"),this.button.type="button",this.button.textContent=this.props.label,this.button.classList.add("textmode-export-overlay__button"),"secondary"===this.props.variant?this.button.classList.add(fa):this.button.classList.add(ua),this.props.fullWidth&&this.button.classList.add(pa),this.button.disabled=Boolean(this.props.disabled),this.button}get buttonElement(){return this.button}setLabel(t){this.props.label=t,this.button.textContent=t}setDisabled(t){this.props.disabled=t,this.button.disabled=t}onUpdate(t){this.props=t,this.button.textContent=t.label,this.button.disabled=Boolean(t.disabled),"secondary"===t.variant?(this.button.classList.add(fa),this.button.classList.remove(ua)):(this.button.classList.add(ua),this.button.classList.remove(fa)),this.button.classList.toggle(pa,Boolean(t.fullWidth))}},xa=class{ht={};Ui(t){const e=this.ht[t];if(e)return e;const i=new Set;return this.ht[t]=i,i}$on(t,e){const i=this.Ui(t);return i.add(e),()=>{i.delete(e),0===i.size&&delete this.ht[t]}}$emit(t,e){const i=this.ht[t];if(i)for(const n of[...i])try{n(e)}catch(r){console.error("[textmode-export] Event handler failed",r)}}$clear(){for(const t of Object.keys(this.ht))delete this.ht[t]}},Ea=class{gi;ht=new Set;constructor(t){this.gi=t}get snapshot(){return Object.freeze({...this.gi})}$set(t){const e=Object.keys(t);if(0===e.length)return;let i=!1;for(const o of e)if(this.gi[o]!==t[o]){i=!0;break}if(!i)return;this.gi=Object.assign({},this.gi,t);const r=this.snapshot;for(const o of[...this.ht])try{o(r)}catch(n){console.error("[textmode-export] State listener failed",n)}}$subscribe(t){return this.ht.add(t),t(this.snapshot),()=>{this.ht.delete(t)}}$reset(t){this.gi=t;const e=this.snapshot;for(const i of[...this.ht])i(e)}},Ta=new Set(["txt","json","svg","image"]),ka=class{api;constructor(t){this.api=t}async $copy(t,e){switch(t){case"txt":{const t=this.api.toString(e);await navigator.clipboard.writeText(t);break}case"json":{const t=this.api.toJSONString(e);await navigator.clipboard.writeText(t);break}case"svg":{const t=this.api.toSVG(e);await navigator.clipboard.writeText(t);break}case"image":await this.api.copyCanvas(e);break;default:throw new Error(`Clipboard not supported for ${t}`)}}static isClipboardFormat(t){return Ta.has(t)}},_a={txt:(t,e)=>Promise.resolve(t.saveStrings(e)),json:(t,e)=>Promise.resolve(t.saveJSON(e)),image:(t,e)=>t.saveCanvas(e),svg:(t,e)=>Promise.resolve(t.saveSVG(e)),gif:(t,e,i)=>{const r={...e,onProgress:i.onGIFProgress};return t.saveGIF(r)},video:(t,e,i)=>{const r={...e,onProgress:i.onVideoProgress};return t.saveVideo(r)}},Ma=class{api;events;constructor(t,e){this.api=t,this.events=e}async $requestExport(t,e,i={}){this.events.$emit("export:request",{format:t});try{const r={onGIFProgress:i.onGIFProgress?e=>{i.onGIFProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"gif"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0,onVideoProgress:i.onVideoProgress?e=>{i.onVideoProgress?.(e),this.events.$emit("export:progress",{format:t,progress:e})}:"video"===t?e=>this.events.$emit("export:progress",{format:t,progress:e}):void 0};await _a[t](this.api,e,r),this.events.$emit("export:success",{format:t})}catch(r){throw this.events.$emit("export:error",{format:t,error:r}),r}}},Ca=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,Aa=class{key;constructor(t="textmode.export.overlay.position.v1"){this.key=t}load(){try{const t=window.localStorage.getItem(this.key);if(!t)return;const e=JSON.parse(t);if(1!==e.version||!Ca(e.offsetX)||!Ca(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(Ca(t)&&Ca(e))try{const i={version:1,offsetX:t,offsetY:e};window.localStorage.setItem(this.key,JSON.stringify(i))}catch{}}clear(){try{window.localStorage.removeItem(this.key)}catch{}}},Sa=class{modifier;host;surface;storage;animationFrameId=null;handleUpdate;bound=!1;dragHandle;dragState;position;renderedOffset;handlePointerDown=t=>this.onPointerDown(t);handlePointerMove=t=>this.onPointerMove(t);handlePointerUp=t=>this.onPointerUp(t);handleKeyDown=t=>this.onKeyDown(t);constructor(t,e,i=e,r=new Aa){this.modifier=t,this.host=e,this.surface=i,this.storage=r,this.handleUpdate=()=>this.scheduleUpdate();const n=this.storage.load();this.position=n?{mode:"custom",offsetX:n.offsetX,offsetY:n.offsetY}:{mode:"auto",offsetX:8,offsetY:8},this.renderedOffset={offsetX:this.position.offsetX,offsetY:this.position.offsetY}}getPosition(){return Object.freeze({...this.position})}setPosition(t,e={}){Number.isFinite(t.offsetX)&&Number.isFinite(t.offsetY)&&(this.position={mode:"custom",offsetX:t.offsetX,offsetY:t.offsetY},this.scheduleUpdate(),(e.persist??!0)&&this.storage.save(this.position.offsetX,this.position.offsetY))}resetPosition(){this.position={mode:"auto",offsetX:8,offsetY:8},this.storage.clear(),this.scheduleUpdate()}scheduleUpdate(){null!==this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=requestAnimationFrame(()=>this.update())}bind(){this.bound||(window.addEventListener("resize",this.handleUpdate),window.addEventListener("scroll",this.handleUpdate,!0),this.bound=!0,this.handleUpdate())}attachDragHandle(t){this.dragHandle!==t&&(this.detachDragHandle(),this.dragHandle=t,t.addEventListener("pointerdown",this.handlePointerDown),t.addEventListener("keydown",this.handleKeyDown))}detachDragHandle(){this.dragHandle&&(this.dragHandle.removeEventListener("pointerdown",this.handlePointerDown),this.dragHandle.removeEventListener("keydown",this.handleKeyDown),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp),this.dragHandle=void 0,this.dragState=void 0,this.surface.classList.remove(ra))}onPointerDown(t){if(0===t.button&&this.dragHandle){t.preventDefault(),this.dragState={pointerId:t.pointerId,startClientX:t.clientX,startClientY:t.clientY,startOffsetX:this.renderedOffset.offsetX,startOffsetY:this.renderedOffset.offsetY},this.surface.classList.add(ra),this.dragHandle.addEventListener("pointermove",this.handlePointerMove),this.dragHandle.addEventListener("pointerup",this.handlePointerUp),this.dragHandle.addEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.setPointerCapture?.(t.pointerId)}catch{}}}onPointerMove(t){this.dragState&&t.pointerId===this.dragState.pointerId&&(t.preventDefault(),this.setPosition({offsetX:this.dragState.startOffsetX+t.clientX-this.dragState.startClientX,offsetY:this.dragState.startOffsetY+t.clientY-this.dragState.startClientY},{persist:!1}))}onPointerUp(t){if(this.dragState&&t.pointerId===this.dragState.pointerId&&this.dragHandle){t.preventDefault(),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp);try{this.dragHandle.hasPointerCapture?.(t.pointerId)&&this.dragHandle.releasePointerCapture?.(t.pointerId)}catch{}this.surface.classList.remove(ra),this.dragState=void 0,"custom"===this.position.mode&&this.storage.save(this.position.offsetX,this.position.offsetY)}}onKeyDown(t){const e=t.shiftKey?32:8,i=this.renderedOffset;switch(t.key){case"ArrowUp":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY-e});break;case"ArrowDown":t.preventDefault(),this.setPosition({offsetX:i.offsetX,offsetY:i.offsetY+e});break;case"ArrowLeft":t.preventDefault(),this.setPosition({offsetX:i.offsetX-e,offsetY:i.offsetY});break;case"ArrowRight":t.preventDefault(),this.setPosition({offsetX:i.offsetX+e,offsetY:i.offsetY});break;case"Home":t.preventDefault(),this.resetPosition()}}update(){if(this.animationFrameId=null,"none"===this.host.style.display)return;const t=this.modifier.canvas.getBoundingClientRect(),e=this.clampToViewport(t,this.position.offsetX,this.position.offsetY);this.host.style.top=`${t.top+window.scrollY+e.offsetY}px`,this.host.style.left=`${t.left+window.scrollX+e.offsetX}px`,this.renderedOffset=e}clampToViewport(t,e,i){const r=this.surface.getBoundingClientRect(),n=r.width||this.host.getBoundingClientRect().width||0,o=r.height||this.host.getBoundingClientRect().height||0,s=Math.max(8,window.innerWidth-n-8),a=Math.max(8,window.innerHeight-o-8),h=this.clamp(t.left+e,8,s),c=this.clamp(t.top+i,8,a);return{offsetX:h-t.left,offsetY:c-t.top}}clamp(t,e,i){return Math.min(Math.max(t,e),i)}dispose(){null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.bound&&(window.removeEventListener("resize",this.handleUpdate),window.removeEventListener("scroll",this.handleUpdate,!0),this.bound=!1),this.detachDragHandle()}},Pa=class extends wa{capabilities;zi;ji=new Set;constructor(t,e){super(),this.zi=t,this.capabilities={clipboard:t.supportsClipboard,layerTarget:!!t.layerTargetProvider,recording:!1,...e}}Li(t){return this.ji.add(t),t}Fi(){for(const t of this.ji)t.unmount()}$i(){for(const t of this.ji)t.destroy();this.ji.clear()}},Ia=class extends wa{props;checkbox;labelElement;handleChange=()=>{this.props.defaultChecked=this.checkbox.checked};constructor(t){super(),this.props=t}render(){this.labelElement=document.createElement("label"),this.labelElement.classList.add("textmode-export-overlay__checkbox"),this.checkbox=document.createElement("input"),this.checkbox.type="checkbox",this.props.id&&(this.checkbox.id=this.props.id),this.checkbox.checked=Boolean(this.props.defaultChecked),this.checkbox.addEventListener("change",this.handleChange);const t=document.createElement("span");return t.textContent=this.props.label,this.labelElement.htmlFor=this.props.id??"",this.labelElement.appendChild(this.checkbox),this.labelElement.appendChild(t),this.labelElement}get inputElement(){return this.checkbox}get checked(){return this.checkbox.checked}set checked(t){this.checkbox.checked=t}Fi(){this.checkbox.removeEventListener("change",this.handleChange)}onUpdate(t){this.props=t,t.id&&(this.checkbox.id=t.id,this.labelElement.htmlFor=t.id),this.checkbox.checked=Boolean(t.defaultChecked),this.labelElement.lastElementChild&&(this.labelElement.lastElementChild.textContent=t.label)}},Ba=class extends wa{props;input;handleInput=()=>{this.props.defaultValue=this.input.value};constructor(t){super(),this.props=t}render(){return this.input=document.createElement("input"),this.input.type="text",this.input.classList.add(la),this.props.id&&(this.input.id=this.props.id),void 0!==this.props.maxLength&&(this.input.maxLength=this.props.maxLength),void 0!==this.props.defaultValue&&(this.input.value=this.props.defaultValue),this.input.addEventListener("input",this.handleInput),this.input}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t}Fi(){this.input.removeEventListener("input",this.handleInput)}onUpdate(t){this.props=t,t.id&&(this.input.id=t.id),void 0!==t.maxLength&&(this.input.maxLength=t.maxLength),void 0!==t.defaultValue&&(this.input.value=t.defaultValue)}},Fa=class extends wa{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new ba({label:"layer",labelFor:t.id,variant:"full"}),this.select=new ya({id:t.id,options:[],defaultValue:t.provider.getDefaultId()})}render(){const t=document.createElement("div");return this.field.mount(t),this.refresh(),this.select.mount(this.field.root),t}get layer(){const t=this.provider.getLayerById(this.select.value);if(t)return t;const e=this.provider.getDefaultId();return this.select.value=e,this.provider.getLayerById(e)}setDisabled(t){this.select.selectElement.disabled=t}refresh(){const t=this.provider.getOptions(),e=this.select.isMounted()?this.select.value:this.provider.getDefaultId(),i=t.some(t=>t.id===e)?e:this.provider.getDefaultId();this.select.update({options:t.map(t=>({value:t.id,label:t.label})),defaultValue:i}),this.select.value=i}Fi(){this.select.unmount(),this.field.unmount()}$i(){this.select.destroy(),this.field.destroy()}},$a=class extends Pa{layerTarget;trailingSpaces=this.Li(new Ia({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.Li(new Ba({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.Li(new Fa({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Ks),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new ba({label:"empty character",labelFor:"textmode-export-empty-character",variant:"full"});return e.mount(t),this.emptyCharacter.mount(e.root),t}getOptions(){const t=this.zi.defaultOptions,e=this.emptyCharacter.value||t.emptyCharacter;return{layer:this.layerTarget?.layer,preserveTrailingSpaces:this.trailingSpaces.checked,emptyCharacter:e}}setDefaults(t){Object.assign(this.zi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return this.emptyCharacter.value.length<=1}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.zi.defaultOptions;this.trailingSpaces.checked=t.preserveTrailingSpaces??!1,this.emptyCharacter.value=t.emptyCharacter??" "}},Oa=class extends Pa{layerTarget;layerTargetContainer;target=this.Li(new ya({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.Li(new Ia({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.Li(new Ia({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.Li(new ya({id:"textmode-export-json-color-mode",options:[{value:"hex",label:"hex"},{value:"rgba",label:"rgba"}],defaultValue:"hex"}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.Li(new Fa({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Ks);const e=new ba({label:"layers",labelFor:"textmode-export-json-target",variant:"full"});e.mount(t),this.target.mount(e.root),this.target.selectElement.addEventListener("change",()=>this.updateLayerTargetVisibility()),this.layerTarget&&(this.layerTargetContainer=document.createElement("div"),this.layerTarget.mount(this.layerTargetContainer),t.appendChild(this.layerTargetContainer)),this.prettyPrint.mount(t),this.includeMetadata.mount(t);const i=new ba({label:"color mode",labelFor:"textmode-export-json-color-mode",variant:"full"});return i.mount(t),this.colorMode.mount(i.root),this.updateLayerTargetVisibility(),t}getOptions(){const t=this.target.value;return{target:t,layer:"selected"===t?this.layerTarget?.layer:void 0,pretty:this.prettyPrint.checked,includeMetadata:this.includeMetadata.checked,colorMode:this.colorMode.value}}setDefaults(t){Object.assign(this.zi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return!0}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.zi.defaultOptions;this.target.value=t.target??"selected",this.prettyPrint.checked="number"==typeof t.pretty?t.pretty>0:t.pretty??!0,this.includeMetadata.checked=t.includeMetadata??!0,this.colorMode.value=t.colorMode??"hex",this.updateLayerTargetVisibility()}updateLayerTargetVisibility(){const t="selected"===this.target.value;this.layerTargetContainer&&(this.layerTargetContainer.style.display=t?"":"none"),this.layerTarget?.setDisabled(!t)}},Ra="textmode-export-number-input",Da=`${Ra}__field`,Na=`${Ra}__controls`,Va=`${Ra}__control`,Ua=`${Ra}__display`,za=`${Ua}--visible`,ja=t=>{const e=document.createElement("button");return e.type="button",e.className=Va,e.textContent=t>0?"▲":"▼",e},La=class extends wa{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=Ra,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=Da,this.display=document.createElement("div"),this.display.className=Ua;const e=document.createElement("div");return e.className=Na,this.incrementButton=ja(1),this.decrementButton=ja(-1),e.appendChild(this.incrementButton),e.appendChild(this.decrementButton),t.appendChild(this.input),t.appendChild(this.display),t.appendChild(e),this.bindStepControls(),this.bindHoldBehavior(),this.bindInputListeners(),this.observeDisabledState(t),this.updateDisplay(),t}get inputElement(){return this.input}get value(){return this.input.value}set value(t){this.input.value=t,this.updateDisplay()}refresh(){this.updateDisplay()}$i(){this.clearHoldTimers(),this.disabledObserver?.disconnect()}bindStepControls(){const t=t=>()=>{if(this.input.disabled)return;const e=this.input.value,i=this.input.getAttribute("step");if(i&&"any"!==i)t>0?this.input.stepUp():this.input.stepDown();else{const e=t>0?1:-1,i=Number.parseFloat(this.input.value||"0"),r=Number.isFinite(i)?i+e:e;this.input.value=String(r)}var r;this.input.value!==e&&((r=this.input).dispatchEvent(new Event("input",{bubbles:!0})),r.dispatchEvent(new Event("change",{bubbles:!0}))),this.updateDisplay(),this.input.focus({preventScroll:!0})},e=t(1),i=t(-1),r=(t,e)=>i=>{if(this.suppressClickAfterPointer.get(t))return this.suppressClickAfterPointer.set(t,!1),void i.preventDefault();e()};this.incrementButton.addEventListener("click",r(this.incrementButton,e)),this.decrementButton.addEventListener("click",r(this.decrementButton,i))}bindHoldBehavior(){const t=(t,e)=>{const i=e>0?()=>this.incrementButton.click():()=>this.decrementButton.click();t.addEventListener("pointerdown",e=>{if(0===e.button){e.preventDefault(),this.suppressClickAfterPointer.set(t,!0),this.activePointerId=e.pointerId;try{t.setPointerCapture(e.pointerId)}catch{}i(),this.holdTimeoutId=window.setTimeout(()=>{this.holdIntervalId=window.setInterval(i,80)},380)}});const r=()=>{if(void 0!==this.activePointerId){try{t.releasePointerCapture(this.activePointerId)}catch{}this.activePointerId=void 0}},n=()=>{this.clearHoldTimers(),r()};t.addEventListener("pointerup",n),t.addEventListener("pointerleave",n),t.addEventListener("pointercancel",n)};t(this.incrementButton,1),t(this.decrementButton,-1)}bindInputListeners(){const t=()=>{this.props.defaultValue=this.input.value,this.updateDisplay()};this.input.addEventListener("input",t),this.input.addEventListener("change",t)}observeDisabledState(t){const e=()=>{const e=this.input.disabled;this.incrementButton.disabled=e,this.decrementButton.disabled=e,t.classList.toggle("is-disabled",e),e?(this.display.classList.remove(za),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor")):this.updateDisplay()};"undefined"!=typeof MutationObserver&&(this.disabledObserver=new MutationObserver(e),this.disabledObserver.observe(this.input,{attributes:!0,attributeFilter:["disabled"]})),e()}updateDisplay(){const t=this.props.formatDisplay;if(!t)return this.display.textContent="",this.display.classList.remove(za),this.input.style.removeProperty("color"),void this.input.style.removeProperty("caretColor");const e=this.input.value,i=Number.parseFloat(e),r=t(Number.isFinite(i)?i:NaN,e,this.input);r?(this.display.textContent=r,this.display.classList.add(za),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(za),this.input.style.removeProperty("color"),this.input.style.removeProperty("caretColor"))}clearHoldTimers(){void 0!==this.holdTimeoutId&&(window.clearTimeout(this.holdTimeoutId),this.holdTimeoutId=void 0),void 0!==this.holdIntervalId&&(window.clearInterval(this.holdIntervalId),this.holdIntervalId=void 0)}},qa=class extends wa{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?Ks:void 0,"stackDense"===this.variant?ta:void 0,"stackCompact"===this.variant?ea:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?ia:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},Ha=class extends Pa{formatSelect=this.Li(new ya({id:"textmode-export-image-format",options:[{value:"png",label:"PNG (.png)"},{value:"jpg",label:"JPG (.jpg)"},{value:"webp",label:"WEBP (.webp)"}],defaultValue:"png"}));scaleInput=this.Li(new La({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(Ks);const e=new qa("row");e.mount(t);const i=new ba({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new ba({label:"scale",labelFor:"textmode-export-image-scale",variant:"dense"});return r.mount(e.root),this.scaleInput.mount(r.root),this.scaleInput.inputElement.id="textmode-export-image-scale",t}getOptions(){const t=Number.parseFloat(this.scaleInput.value);return{format:this.formatSelect.value,scale:Number.isFinite(t)?t:this.zi.defaultOptions?.scale??1}}setDefaults(t){Object.assign(this.zi.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.scaleInput.refresh()}validate(){const t=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0}applyDefaults(){const t=this.zi.defaultOptions;this.formatSelect.value=t.format??"png",this.scaleInput.value=String(t.scale??1)}},Ga=class extends Pa{layerTarget;includeBackground=this.Li(new Ia({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.Li(new ya({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.Li(new La({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.Li(new Fa({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Ks),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new qa("row");e.mount(t);const i=new ba({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new ba({label:"stroke width",labelFor:"textmode-export-svg-stroke-width",variant:"compact"});return r.mount(e.root),this.strokeWidth.mount(r.root),this.strokeWidth.inputElement.id="textmode-export-svg-stroke-width",this.drawMode.selectElement.addEventListener("change",()=>this.updateStrokeControls()),this.updateStrokeControls(),t}getOptions(){return{layer:this.layerTarget?.layer,includeBackgroundRectangles:this.includeBackground.checked,drawMode:this.drawMode.value,strokeWidth:Number.parseFloat(this.strokeWidth.value)}}setDefaults(t){Object.assign(this.zi.defaultOptions,t),this.reset()}reset(){this.applyDefaults(),this.updateStrokeControls()}validate(){const t=Number.parseFloat(this.strokeWidth.value);return"stroke"!==this.drawMode.value||Number.isFinite(t)&&t>=0}refreshLayerTargets(){this.layerTarget?.refresh()}updateStrokeControls(){const t="stroke"===this.drawMode.value;this.strokeWidth.inputElement.disabled=!t,this.strokeWidth.refresh()}applyDefaults(){const t=this.zi.defaultOptions;this.includeBackground.checked=t.includeBackgroundRectangles??!0,this.drawMode.value=t.drawMode??"fill",this.strokeWidth.value=String(t.strokeWidth??1),this.strokeWidth.refresh()}},Wa={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},Xa=class extends wa{props;container;messageElement;constructor(t){super(),this.props=t}render(){this.container=document.createElement("div"),this.container.classList.add("textmode-export-overlay__status"),"gif"===this.props.context?this.container.classList.add("textmode-export-overlay__status--gif"):"video"===this.props.context&&this.container.classList.add("textmode-export-overlay__status--video");const t=document.createElement("span");return t.classList.add("textmode-export-overlay__status-title"),t.textContent=this.props.title,this.messageElement=document.createElement("span"),this.messageElement.classList.add("textmode-export-overlay__status-value"),this.messageElement.textContent=this.props.message,this.applyVariant(this.props.variant??"neutral"),this.container.appendChild(t),this.container.appendChild(this.messageElement),this.container}setMessage(t,e="neutral"){this.messageElement.textContent=t,this.applyVariant(e)}onUpdate(t){this.props=t,this.setMessage(t.message,t.variant??"neutral")}applyVariant(t){this.messageElement.classList.remove(...Object.values(Wa)),this.messageElement.classList.add(Wa[t])}},Za=class extends Pa{frameCountInput=this.Li(new La({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.Li(new La({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.Li(new La({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.Li(new La({defaultValue:"0",attributes:{min:"0",max:"50",step:"1"},formatDisplay:(t,e)=>Number.isFinite(t)?0===t?"∞":null:""===e.trim()?null:e}));status=this.Li(new Xa({title:"status",message:"ready to record",variant:"neutral",context:"gif"}));recordingState="idle";constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(Ks);const e=new qa("row");e.mount(t);const i=new ba({label:"number of frames",labelFor:"textmode-export-gif-frame-count",variant:"dense"});i.mount(e.root),this.frameCountInput.mount(i.root),this.frameCountInput.inputElement.id="textmode-export-gif-frame-count";const r=new ba({label:"frame rate (fps)",labelFor:"textmode-export-gif-frame-rate",variant:"dense"});r.mount(e.root),this.frameRateInput.mount(r.root),this.frameRateInput.inputElement.id="textmode-export-gif-frame-rate";const n=new qa("row");n.mount(t);const o=new ba({label:"scale",labelFor:"textmode-export-gif-scale",variant:"dense"});o.mount(n.root),this.scaleInput.mount(o.root),this.scaleInput.inputElement.id="textmode-export-gif-scale";const s=new ba({label:"loop count",labelFor:"textmode-export-gif-repeat",variant:"dense"});return s.mount(n.root),this.repeatInput.mount(s.root),this.repeatInput.inputElement.id="textmode-export-gif-repeat",this.status.mount(t),t}getOptions(){const t=this.zi.defaultOptions;return{frameCount:this.safeParseInt(this.frameCountInput.value,t.frameCount??300),frameRate:this.safeParseInt(this.frameRateInput.value,t.frameRate??60),scale:this.safeParseFloat(this.scaleInput.value,t.scale??1),repeat:this.safeParseInt(this.repeatInput.value,t.repeat??0)}}setDefaults(t){Object.assign(this.zi.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.setRecordingState("idle")}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseInt(this.frameRateInput.value,10),i=Number.parseFloat(this.scaleInput.value);return Number.isFinite(t)&&t>0&&Number.isFinite(e)&&e>0&&Number.isFinite(i)&&i>0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;switch(this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.scaleInput.inputElement.disabled=i,this.repeatInput.inputElement.disabled=i,t){case"recording":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`recording ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("recording…","active");break;case"encoding":if(e?.totalFrames){const t=e.frameIndex??0;this.status.setMessage(`encoding ${t}/${e.totalFrames}`,"active")}else this.status.setMessage("encoding…","active");break;case"completed":this.status.setMessage("GIF saved successfully","active");break;case"error":this.status.setMessage(e?.message??"failed to export GIF","alert");break;default:this.status.setMessage("ready to record","neutral")}}handleProgress(t){if("recording"!==t.state&&"encoding"!==t.state||!t.totalFrames)"completed"===t.state?this.status.setMessage("GIF saved successfully","active"):"error"===t.state&&this.status.setMessage(t.message??"failed to export GIF","alert");else{const e="recording"===t.state?"recording":"encoding";this.status.setMessage(`${e} ${t.frameIndex??0}/${t.totalFrames}`,"active")}}applyDefaults(){const t=this.zi.defaultOptions;this.frameCountInput.value=String(t.frameCount??300),this.frameRateInput.value=String(t.frameRate??60),this.scaleInput.value=String(t.scale??1),this.repeatInput.value=String(t.repeat??0),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.scaleInput.refresh(),this.repeatInput.refresh()}safeParseInt(t,e){const i=Number.parseInt(t,10);return Number.isFinite(i)?i:e}safeParseFloat(t,e){const i=Number.parseFloat(t);return Number.isFinite(i)?i:e}},Qa=class extends Pa{formatSelect=this.Li(new ya({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));qualitySelect=this.Li(new ya({id:"textmode-export-video-quality",options:[{value:"very-low",label:"very low"},{value:"low",label:"low"},{value:"medium",label:"medium"},{value:"high",label:"high"},{value:"very-high",label:"very high"}],defaultValue:"medium"}));frameRateInput=this.Li(new La({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.Li(new La({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));hardwareAccelerationSelect=this.Li(new ya({id:"textmode-export-video-hardware-acceleration",options:[{value:"no-preference",label:"no preference"},{value:"prefer-hardware",label:"prefer hardware"},{value:"prefer-software",label:"prefer software"}],defaultValue:"no-preference"}));keyFrameIntervalInput=this.Li(new La({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.Li(new Ia({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.Li(new Xa({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.Li(new Xa({title:"estimate",message:"logical dimensions · duration · size",variant:"neutral",context:"video"}));recordingState="idle";resizeObserver;constructor(t){super(t,{recording:!0})}render(){const t=document.createElement("div");t.classList.add(Ks);const e=new qa("row");e.mount(t);const i=new ba({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new ba({label:"quality",labelFor:"textmode-export-video-quality",variant:"compact"});r.mount(e.root),this.qualitySelect.mount(r.root);const n=new qa("row");n.mount(t);const o=new ba({label:"number of frames",labelFor:"textmode-export-video-frame-count",variant:"compact"});o.mount(n.root),this.frameCountInput.mount(o.root),this.frameCountInput.inputElement.id="textmode-export-video-frame-count";const s=new ba({label:"frame rate (fps)",labelFor:"textmode-export-video-frame-rate",variant:"compact"});s.mount(n.root),this.frameRateInput.mount(s.root),this.frameRateInput.inputElement.id="textmode-export-video-frame-rate";const a=new qa("row");a.mount(t);const h=new ba({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(a.root),this.hardwareAccelerationSelect.mount(h.root);const c=new ba({label:"keyframe interval",labelFor:"textmode-export-video-keyframe-interval",variant:"compact"});return c.mount(a.root),this.keyFrameIntervalInput.mount(c.root),this.keyFrameIntervalInput.inputElement.id="textmode-export-video-keyframe-interval",this.transparencyInput.mount(t),this.formatSelect.selectElement.addEventListener("change",this.handleFormatChange),this.syncTransparencyAvailability(),this.qualitySelect.selectElement.addEventListener("change",this.handleQualityChange),this.frameCountInput.inputElement.addEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.addEventListener("input",this.handleEstimateChange),this.formatSelect.selectElement.addEventListener("change",this.handleEstimateChange),this.estimate.mount(t),this.status.mount(t),this.syncOutputEstimate(),this.zi.videoDimensionsTarget&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.syncOutputEstimate()),this.resizeObserver.observe(this.zi.videoDimensionsTarget)),t}getOptions(){const t=this.zi.defaultOptions,e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value),r=Number.parseFloat(this.keyFrameIntervalInput.value),n=this.formatSelect.value,o={format:n,quality:this.qualitySelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.isFinite(r)?r:t.keyFrameInterval??2,frameCount:Number.isFinite(e)?e:t.frameCount??480,frameRate:Number.isFinite(i)?i:t.frameRate??60};return"webm"===n&&(o.transparent=this.transparencyInput.checked),o}setDefaults(t){Object.assign(this.zi.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.syncReadyStatus()}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseFloat(this.frameRateInput.value),i=Number.parseFloat(this.keyFrameIntervalInput.value);return Number.isFinite(t)&&t>=1&&Number.isFinite(e)&&e>=1&&Number.isFinite(i)&&i>=0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;this.formatSelect.selectElement.disabled=i,this.qualitySelect.selectElement.disabled=i,this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.hardwareAccelerationSelect.selectElement.disabled=i,this.keyFrameIntervalInput.inputElement.disabled=i,this.transparencyInput.inputElement.disabled=i||"webm"!==this.formatSelect.value,this.syncStatus(t,e)}handleProgress(t){this.syncStatus(t.state,t)}syncStatus(t,e){switch(t){case"recording":{const t=e?.frameIndex??0,i=e?.totalFrames??this.resolvePlannedFrameCount();if(i){const e=Math.min(Math.max(0,Math.round(t)),i);this.status.setMessage(`recording ${e}/${i} frames`,"active")}else this.status.setMessage(`recording ${Math.max(0,Math.round(t))} frames`,"active");break}case"encoding":this.status.setMessage("writing"===e?.phase?"writing video to disk":"finalizing video","active");break;case"completed":this.status.setMessage("saved to disk","active");break;case"error":this.status.setMessage(e?.message?`error: ${e.message}`:"recording failed","alert");break;default:this.syncReadyStatus()}}resolvePlannedFrameCount(){const t=Number.parseInt(this.frameCountInput.value,10);return Number.isFinite(t)&&t>0?Math.round(t):void 0}applyDefaults(){const t=this.zi.defaultOptions;this.formatSelect.value=t.format??"mp4",this.qualitySelect.value=this.resolveQuality(t.quality),this.frameCountInput.value=String(t.frameCount??480),this.frameRateInput.value=String(t.frameRate??60),this.hardwareAccelerationSelect.value=t.hardwareAcceleration??"no-preference",this.keyFrameIntervalInput.value=String(t.keyFrameInterval??2),this.transparencyInput.checked=Boolean(t.transparent),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.keyFrameIntervalInput.refresh(),this.syncTransparencyAvailability()}resolveQuality(t){return"very-low"===t||"low"===t||"medium"===t||"high"===t||"very-high"===t?t:"medium"}handleQualityChange=()=>{this.isRecording()||this.syncReadyStatus(),this.syncOutputEstimate()};handleEstimateChange=()=>this.syncOutputEstimate();syncReadyStatus(){this.status.setMessage("constant quality; file size depends on content","neutral")}handleFormatChange=()=>{this.syncTransparencyAvailability(),this.syncOutputEstimate()};syncOutputEstimate(){if(!this.estimate.isMounted())return;const t=this.zi.videoDimensionsProvider?.(),e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value);if(!t||!Number.isFinite(e)||!Number.isFinite(i)||i<=0)return void this.estimate.setMessage("logical dimensions · duration · size","neutral");const r={format:this.formatSelect.value,frameCount:Math.max(1,Math.round(e)),frameRate:i,quality:this.qualitySelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.parseFloat(this.keyFrameIntervalInput.value)||2,pixelDensity:1,width:t.width,height:t.height,transparent:"webm"===this.formatSelect.value&&this.transparencyInput.checked,debugLogging:!1};try{const t=U(r);this.estimate.setMessage(`${t.width}×${t.height} · ${(t.frameCount/t.frameRate).toFixed(1)}s · content-dependent size`,"neutral")}catch{this.estimate.setMessage(`${t.width}×${t.height} · MP4 requires even dimensions`,"alert")}}Fi(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.qualitySelect.selectElement.removeEventListener("change",this.handleQualityChange),this.formatSelect.selectElement.removeEventListener("change",this.handleFormatChange),this.formatSelect.selectElement.removeEventListener("change",this.handleEstimateChange),this.frameCountInput.inputElement.removeEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.removeEventListener("input",this.handleEstimateChange),super.Fi()}syncTransparencyAvailability(){if(!this.transparencyInput.isMounted())return;const t="webm"===this.formatSelect.value;this.transparencyInput.root.style.display=t?"":"none",this.transparencyInput.inputElement.disabled=!t||this.isRecording(),t||(this.transparencyInput.checked=!1)}};function Ya(t){return t.capabilities.recording}var Ja=Object.freeze({format:"txt",txt:Object.freeze({preserveTrailingSpaces:!1,emptyCharacter:" "}),json:Object.freeze({target:"selected",pretty:!0,includeMetadata:!0,colorMode:"hex"}),image:Object.freeze({format:"png",scale:1}),svg:Object.freeze({includeBackgroundRectangles:!0,drawMode:"fill",strokeWidth:1}),gif:Object.freeze({frameCount:300,frameRate:60,scale:1,repeat:0}),video:Object.freeze({format:"mp4",frameCount:480,frameRate:60,quality:"medium",hardwareAcceleration:"no-preference",keyFrameInterval:2,transparent:!1})});function Ka(){return{format:Ja.format,txt:{...Ja.txt},json:{...Ja.json},image:{...Ja.image},svg:{...Ja.svg},gif:{...Ja.gif},video:{...Ja.video}}}function th(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var eh=class{qi;constructor(){this.qi=Ka()}get current(){return this.snapshot()}snapshot(){return{format:(t=this.qi).format,txt:{...t.txt},json:{...t.json},image:{...t.image},svg:{...t.svg},gif:{...t.gif},video:{...t.video}};var t}get(t){return this.qi[t]}merge(t){t.format&&(this.qi.format=t.format),t.txt&&Object.assign(this.qi.txt,t.txt),t.json&&Object.assign(this.qi.json,t.json),t.image&&Object.assign(this.qi.image,t.image),t.svg&&Object.assign(this.qi.svg,t.svg),t.gif&&Object.assign(this.qi.gif,t.gif),t.video&&Object.assign(this.qi.video,t.video)}reset(t){const e=Ka();if(!t)return this.qi.format=e.format,th(this.qi.txt,e.txt),th(this.qi.json,e.json),th(this.qi.image,e.image),th(this.qi.svg,e.svg),th(this.qi.gif,e.gif),void th(this.qi.video,e.video);switch(t){case"format":this.qi.format=e.format;break;case"txt":th(this.qi.txt,e.txt);break;case"json":th(this.qi.json,e.json);break;case"image":th(this.qi.image,e.image);break;case"svg":th(this.qi.svg,e.svg);break;case"gif":th(this.qi.gif,e.gif);break;case"video":th(this.qi.video,e.video)}}},ih=class{T;Hi;gi;Gi;Wi;Xi;Zi;Qi=new Map;Yi=[];Ji;Ki;tr;er;ir;rr;nr=new va;sr=new ba({label:"export format",labelFor:"textmode-export-format",variant:"full"});ar=new ya({id:"textmode-export-format",options:[]});hr=new ga({label:"download file",fullWidth:!0,variant:"primary"});cr=new ga({label:"copy to clipboard",fullWidth:!0,variant:"primary"});lr;dr;ur=()=>{this.pr(this.ar.value)};mr=()=>{this.wr().catch(t=>{console.error("[textmode-export] Export failed",t)})};vr=()=>{this.br().catch(t=>{console.error("[textmode-export] Copy failed",t)})};constructor(t,e,i,r){this.T=t,this.Hi=i;const n=this.yr(i.current.format,r);this.gi=new Ea((t=>({format:t,isBusy:!1}))(n)),this.Gi=new xa,this.Wi=new Ma(e,this.Gi),this.Xi=new ka(e),this.Zi=r,this.lr=n,this.gr(),this.Er()}$mount(){this.Tr(),this.kr(),this.rr=new Sa(this.T,this.Ji,this.tr),this.rr.attachDragHandle(this.nr.dragHandleElement),this.rr.bind(),this._r(this.lr)}show(){this.Ji&&(this.refreshLayerTargets(),this.Ji.style.display="",this.rr?.scheduleUpdate())}hide(){this.Ji&&(this.Ji.style.display="none")}toggle(){this.isVisible()?this.hide():this.show()}isVisible(){return!!this.Ji&&"none"!==this.Ji.style.display}refreshLayerTargets(){this.dr&&this.dr.blade.capabilities.layerTarget&&this.dr.blade.refreshLayerTargets()}resetPosition(){this.rr.resetPosition()}getPosition(){return this.rr.getPosition()}setPosition(t){this.rr.setPosition(t)}setDefaults(t){t.format&&this.Mr(t.format),this.Hi.merge(t),this.Cr(this.Ar(t)),t.format&&this.pr(t.format)}getDefaults(){return this.Hi.current}resetDefaults(t){this.Hi.reset(t),"format"!==t?(this.Cr(t?[t]:void 0),t||this.pr(this.Hi.current.format)):this.pr(this.Hi.current.format)}$dispose(){this.ar.isMounted()&&this.ar.selectElement.removeEventListener("change",this.ur),this.hr.isMounted()&&this.hr.buttonElement.removeEventListener("click",this.mr),this.cr.isMounted()&&this.cr.buttonElement.removeEventListener("click",this.vr);for(const t of this.Yi)t();this.Yi.length=0,this.Gi.$clear();for(const t of this.Qi.values())t.blade.destroy();this.Qi.clear(),this.dr=void 0,this.Ji?.isConnected&&this.Ji.remove(),this.rr?.dispose()}Cr(t){const e=new Set(t??this.Qi.keys());for(const[i,r]of this.Qi)e.has(i)&&(r.blade.isMounted()?(r.blade.reset(),r.needsReset=!1):r.needsReset=!0)}gr(){for(const t of this.Zi){const e=t.createBlade();this.Qi.set(t.format,{definition:t,blade:e,initialized:!1,needsReset:!1})}}yr(t,e){return e.some(e=>e.format===t)?t:e[0]?.format??t}Ar(t){return this.Zi.map(t=>t.format).filter(e=>void 0!==t[e])}Mr(t){if(!this.Qi.has(t))throw new Error(`Unknown export format: ${t}`)}Tr(){this.Ji=document.createElement("div"),this.Ji.dataset.plugin="textmode-export-overlay-host",this.Ji.style.cssText="position: absolute; top: 0; left: 0; pointer-events: none; z-index: 2147483647;",this.Ki=this.Ji.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent="@layer textmode-export-overlay{.textmode-export-overlay{--overlay-bg:#141414cc;--overlay-surface:#282828e6;--overlay-border:#ffffff24;--overlay-border-strong:#fff3;--overlay-border-focus:#a0a0a099;--overlay-focus-shadow:0 0 0 1px #8c8c8c47;--overlay-text:#fff;--overlay-muted:#c8c8c8bd;--overlay-radius:.75rem;--overlay-stack-gap:.55rem;gap:var(--overlay-stack-gap);background:var(--overlay-bg);min-width:236px;max-width:236px;color:var(--overlay-text);border-radius:var(--overlay-radius);border:1px solid var(--overlay-border);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);pointer-events:auto;z-index:2147483647;flex-direction:column;padding:.65rem .8rem;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:.82rem;line-height:1.35;display:flex;position:absolute;top:0;left:0;box-shadow:0 12px 28px #0000004d}.textmode-export-overlay *{box-sizing:border-box}.textmode-export-overlay__header{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__header-title-row{justify-content:space-between;align-items:center;gap:.4rem;display:flex}.textmode-export-overlay__header-identity{align-items:center;gap:.35rem;min-width:0;display:inline-flex}.textmode-export-overlay__header-links{flex:none;align-items:center;gap:.3rem;display:inline-flex}.textmode-export-overlay__grab-handle{color:#d7d7d7b8;cursor:grab;touch-action:none;background:0 0;border:1px solid #0000;border-radius:.45rem;flex:none;justify-content:center;align-items:center;width:1.45rem;height:1.45rem;padding:0;line-height:0;transition:background .18s,color .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__grab-handle:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__grab-handle:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay--dragging,.textmode-export-overlay--dragging .textmode-export-overlay__grab-handle{cursor:grabbing}.textmode-export-overlay__support-link{color:#d7d7d7d1;background:0 0;border:1px solid #0000;border-radius:.45rem;justify-content:center;align-items:center;padding:.2rem;line-height:0;text-decoration:none;transition:background .18s,color .18s,transform .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__support-link:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__support-link:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay__support-icon,.textmode-export-overlay__link-icon{width:1rem;height:1rem;display:block}.textmode-export-overlay__stack{gap:var(--overlay-stack-gap);flex-direction:column;display:flex}.textmode-export-overlay__stack--dense{gap:.3rem}.textmode-export-overlay__stack--compact{gap:.45rem}.textmode-export-overlay__section{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__title{white-space:nowrap;font-size:.92rem;font-weight:600}.textmode-export-overlay__divider{background:#ffffff29;width:100%;height:1px;margin-top:.25rem}.textmode-export-overlay__label{opacity:.9;font-weight:500}.textmode-export-overlay__checkbox{align-items:center;gap:.5rem;display:flex}.textmode-export-overlay__checkbox input[type=checkbox]{accent-color:#646464e6;width:1rem;height:1rem}.textmode-export-overlay__row{flex-wrap:wrap;align-items:flex-start;gap:.6rem;width:100%;display:flex}.textmode-export-overlay__field{flex-direction:column;flex:120px;gap:.3rem;min-width:120px;display:flex}.textmode-export-overlay__field--compact{flex:100px;min-width:100px}.textmode-export-overlay__field--dense{flex:90px;min-width:90px}.textmode-export-overlay__field--channel{flex:1 1 0;min-width:0}.textmode-export-overlay__field--full{flex:100%;width:100%}.textmode-export-overlay__input,.textmode-export-overlay select.textmode-export-overlay__input,.textmode-export-overlay input.textmode-export-overlay__input{border:1px solid var(--overlay-border-strong);background:var(--overlay-surface);width:100%;color:var(--overlay-text);font:inherit;border-radius:.4rem;padding:.35rem .5rem;line-height:1.35;transition:border-color .18s,box-shadow .18s,background .18s}.textmode-export-overlay select.textmode-export-overlay__input{appearance:none;background-image:url(\"data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='rgba(200, 200, 200, 0.74)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e\");background-position:right .5rem center;background-repeat:no-repeat;background-size:1rem;padding-right:2rem}.textmode-export-overlay__input:focus{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);background:#2d2f42eb;outline:none}.textmode-export-overlay__input::placeholder{color:var(--overlay-muted);opacity:.7}.textmode-export-overlay__muted{opacity:.7;font-size:.75rem;display:block}.textmode-export-overlay__button{cursor:pointer;border:none;border-radius:.45rem;justify-content:center;align-items:center;gap:.35rem;padding:.45rem .7rem;font-weight:600;transition:background .2s,transform .2s,box-shadow .2s;display:inline-flex}.textmode-export-overlay__button--primary{color:#fff;background:#505050}.textmode-export-overlay__button--secondary{color:#fff;background:#606060}.textmode-export-overlay__button--full{width:100%}.textmode-export-overlay__button:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 7px 18px #00000073}.textmode-export-overlay__button--primary:hover:not(:disabled){background:#404040}.textmode-export-overlay__button--secondary:hover:not(:disabled){background:#4a4a4a}.textmode-export-overlay__button:disabled{cursor:default;opacity:.55;box-shadow:none;transform:none}.textmode-export-overlay__status{background:#4646462e;border:1px solid #6e6e6e38;border-radius:.45rem;flex-direction:column;gap:.25rem;padding:.45rem .55rem;display:flex}.textmode-export-overlay__status--gif{background:#5050501f;border-color:#78787840}.textmode-export-overlay__status--video{background:#4646461f;border-color:#6e6e6e40}.textmode-export-overlay__status-title{opacity:.85;text-transform:uppercase;letter-spacing:.04em;font-size:.75rem;font-weight:600}.textmode-export-overlay__status-value{color:#dedede;font-size:.82rem;transition:color .18s}.textmode-export-overlay__status-value--neutral{color:#cfcfcf}.textmode-export-overlay__status-value--active{color:#f5f5f5}.textmode-export-overlay__status-value--alert{color:#b8b8b8}.textmode-export-number-input,.textmode-export-overlay .textmode-export-number-input{background:var(--overlay-surface);border:1px solid var(--overlay-border-strong);border-radius:.4rem;align-items:stretch;width:100%;transition:border-color .18s,box-shadow .18s,background .18s;display:flex;position:relative;overflow:hidden}.textmode-export-number-input:focus-within{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow)}.textmode-export-number-input.is-disabled{opacity:.55}.textmode-export-number-input__field{min-width:0;color:var(--overlay-text);font:inherit;appearance:textfield;background:0 0;border:none;flex:auto;padding:.35rem .5rem}.textmode-export-number-input__field::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field:focus{outline:none}.textmode-export-number-input__controls{border-left:1px solid #ffffff1f;flex-direction:column;min-width:1.6rem;display:flex}.textmode-export-number-input__control{color:#d0d0d0;cursor:pointer;background:#32323299;border:none;flex:1;justify-content:center;align-items:center;width:100%;padding:0;font-size:.68rem;line-height:1;transition:background .15s,color .15s;display:flex}.textmode-export-number-input__control:hover:not(:disabled){color:#fff;background:#5a5a5ad9}.textmode-export-number-input__control:disabled{cursor:default;opacity:.4;color:#c8c8c866;background:#28282880}.textmode-export-number-input:focus-within .textmode-export-number-input__control{color:#e8e8e8;background:#3c3c3cbf}.textmode-export-number-input__display{pointer-events:none;color:#f8fafc;opacity:0;align-items:center;padding:.4rem .55rem;transition:opacity .14s;display:flex;position:absolute;inset:0}.textmode-export-number-input__display--visible{opacity:1}}",this.Ki.appendChild(t),this.tr=document.createElement("div"),this.tr.dataset.plugin="textmode-export-overlay",this.tr.classList.add("textmode-export-overlay",Ks),this.Ki.appendChild(this.tr),document.body.appendChild(this.Ji)}kr(){this.nr.mount(this.tr);const t=document.createElement("div");t.classList.add(ia),this.tr.appendChild(t),this.sr.mount(t),this.Sr(),this.ar.mount(this.sr.root),this.ar.selectElement.addEventListener("change",this.ur),this.er=document.createElement("div"),this.er.classList.add(Ks,ea),this.tr.appendChild(this.er),this.hr.mount(this.tr),this.hr.buttonElement.addEventListener("click",this.mr),this.ir=document.createElement("div"),this.ir.classList.add(Ks,ta),this.tr.appendChild(this.ir),this.cr.mount(this.ir),this.cr.buttonElement.dataset.defaultLabel="copy to clipboard",this.cr.buttonElement.addEventListener("click",this.vr)}Sr(){const t=this.Zi.map(t=>({value:t.format,label:t.label}));this.ar.update({options:t,defaultValue:this.lr})}Er(){this.Yi.push(this.Gi.$on("export:request",({format:t})=>{t===this.lr&&(this.gi.$set({isBusy:!0,error:void 0}),this.Pr())}),this.Gi.$on("export:success",({format:t})=>{if(t===this.lr){const e={isBusy:!1};"gif"===t&&(e.gifProgress=void 0),"video"===t&&(e.videoProgress=void 0),this.gi.$set(e),this.Pr()}}),this.Gi.$on("export:error",({format:t,error:e})=>{t===this.lr&&(this.gi.$set({isBusy:!1,error:e}),this.Pr())}),this.Gi.$on("export:progress",({format:t,progress:e})=>{if(e){if("gif"===t){const t=e;this.gi.$set({gifProgress:t}),"gif"===this.dr?.definition.format&&Ya(this.dr.blade)&&this.dr.blade.handleProgress(t)}else if("video"===t){const t=e;this.gi.$set({videoProgress:t}),"video"===this.dr?.definition.format&&Ya(this.dr.blade)&&this.dr.blade.handleProgress(t)}this.Pr()}}))}pr(t){this.lr=t,this.gi.$set({format:t}),this._r(t),this.Gi.$emit("format:change",{format:t})}_r(t){const e=this.Qi.get(t);if(!e)throw new Error(`Unknown export format: ${t}`);this.dr&&this.dr.blade.unmount(),this.er.innerHTML="",e.blade.mount(this.er),e.initialized&&!e.needsReset||(e.blade.reset(),e.initialized=!0,e.needsReset=!1),this.dr=e,this.ar.value=t,this.refreshLayerTargets(),this.Ir(),this.Pr(),this.rr?.scheduleUpdate()}Ir(){const t=this.dr?.definition.supportsClipboard??!1;this.ir.style.display=t?"flex":"none",this.cr.setDisabled(!t)}async wr(){if(!this.dr)return;const t=this.dr.definition.format,e=this.dr.blade.getOptions();if(this.dr.blade.validate()){if(Ya(this.dr.blade)){const r=this.dr.blade;if(r.isRecording())return;r.setRecordingState("recording");try{await this.Wi.$requestExport(t,e,{onGIFProgress:t=>{r.setRecordingState(t.state,t)},onVideoProgress:t=>{r.setRecordingState(t.state,t)}})}catch(i){throw r.setRecordingState("error"),i}return void window.setTimeout(()=>{r.setRecordingState("idle"),this.Pr()},1600)}this.hr.setDisabled(!0),this.hr.setLabel("exporting…");try{await this.Wi.$requestExport(t,e)}finally{this.hr.setDisabled(!1),this.hr.setLabel("download file")}}else console.warn("[textmode-export] Export options failed validation")}async br(){if(!this.dr||!this.dr.definition.supportsClipboard)return;const t=this.dr.definition.format,e=this.dr.blade.getOptions(),i=this.cr.buttonElement.dataset.defaultLabel??"copy to clipboard";this.cr.setDisabled(!0),this.cr.setLabel("copying…");try{switch(t){case"txt":await this.Xi.$copy("txt",e);break;case"json":await this.Xi.$copy("json",e);break;case"svg":await this.Xi.$copy("svg",e);break;case"image":await this.Xi.$copy("image",e);break;default:return}this.cr.setLabel("copied!")}catch(r){console.error("[textmode-export] Failed to copy to clipboard",r),this.cr.setLabel("copy failed!")}finally{window.setTimeout(()=>{this.cr.setLabel(i),this.cr.setDisabled(!1)},1200)}}Pr(){if(!this.dr)return;const t=this.dr.definition.format;if(Ya(this.dr.blade)){const e=this.dr.blade,i="gif"===t?this.gi.snapshot.gifProgress:this.gi.snapshot.videoProgress;if(e.isRecording())if(this.hr.setDisabled(!0),i?.totalFrames){const e=i.frameIndex??0,r="encoding"===i.state?"encoding":"recording";this.hr.setLabel("gif"===t?`${r} ${e}/${i.totalFrames}`:`recording ${e}/${i.totalFrames} frames`)}else this.hr.setLabel("encoding"===i?.state?"encoding…":"recording…");else this.hr.setDisabled(!1),this.hr.setLabel("start recording");return}const e=this.gi.snapshot.isBusy;this.hr.setDisabled(e),this.hr.setLabel(e?"exporting…":"download file")}};var rh=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob","saveZip","toZipBlob"],nh=class{api;k;Br=new Set;Fr=new v;$r;Or;v=!1;constructor(t,e){this.k=e;const i={saveCanvas:async(e={})=>(this.Rr(),(new C).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.Rr(),(new C).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.Rr(),(new C).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.Rr(),(new _).$saveSVG(t,e)},saveStrings:(e={})=>{this.Rr(),(new A).$saveTXT(t,e)},toSVG:(e={})=>(this.Rr(),(new _).$generateSVG(t,e)),toString:(e={})=>(this.Rr(),(new A).$generateTXT(t,e)),toJSON:(e={})=>(this.Rr(),(new Yo).$generateJSONData(t,e)),toJSONString:(e={})=>(this.Rr(),(new Yo).$generateJSONString(t,e)),saveJSON:(e={})=>{this.Rr(),(new Yo).$saveJSON(t,e)},saveGIF:(e={})=>this.Dr("gif",e.signal,i=>new O(t,t=>this.k(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.Dr("gif",e.signal,i=>new O(t,t=>this.k(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.Dr("video",e.signal,i=>new Wo(t,t=>this.k(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.Dr("video",e.signal,i=>new Wo(t,t=>this.k(t)).$generateVideoBlob({...e,signal:i})),saveZip:async e=>this.Dr("zip",e?.signal,i=>new Js(t,t=>this.k(t)).$saveZIP({...e,signal:i}),t=>this.Nr(e,t)),toZipBlob:async e=>this.Dr("zip",e?.signal,i=>new Js(t,t=>this.k(t)).$generateZIPBlob({...e,signal:i}),t=>this.Nr(e,t)),exportOverlay:void 0};this.api=i;const r=function(t,e,i){const r=new eh,n=new ih(t,e,r,function(t,e=(()=>{const t=Ka();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new $a({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new Oa({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new Ha({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Ga({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new Za({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new Qa({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:e("video"),videoDimensionsProvider:i,videoDimensionsTarget:r})}]}(i,t=>r.get(t),()=>{const e=t.pixelDensity?.()??1;return{width:Math.max(1,Math.round(t.canvas.width/e)),height:Math.max(1,Math.round(t.canvas.height/e))}},t.canvas));try{n.$mount()}catch(o){throw n.$dispose(),o}return n}(t,i,function(t){return{getOptions:()=>u(t),getLayerById:e=>u(t).find(t=>t.id===e)?.layer,getDefaultId:()=>"base"}}(t));let n;try{n=this.k(()=>{!this.v&&r.isVisible()&&r.refreshLayerTargets()})}catch(o){throw r.$dispose(),o}this.$r=r,this.Or=n,i.exportOverlay=this.Vr()}dispose(){if(!this.v){this.v=!0;for(const t of this.Br)t.abort();this.Br.clear(),this.Fr.dispose(),this.Or(),this.$r.$dispose()}}Vr(){return{show:()=>{this.Rr(),this.$r.show()},hide:()=>{this.Rr(),this.$r.hide()},toggle:()=>{this.Rr(),this.$r.toggle()},isVisible:()=>(this.Rr(),this.$r.isVisible()),resetPosition:()=>{this.Rr(),this.$r.resetPosition()},getPosition:()=>(this.Rr(),this.$r.getPosition()),setPosition:t=>{this.Rr(),this.$r.setPosition(t)},setDefaults:t=>{this.Rr(),this.$r.setDefaults(t)},getDefaults:()=>(this.Rr(),this.$r.getDefaults()),resetDefaults:t=>{this.Rr(),this.$r.resetDefaults(t)}}}Ur(t,e){this.Rr();const i=new AbortController,r=new AbortController,n=()=>r.abort(),o=()=>r.abort();return t?.addEventListener("abort",n,{once:!0}),i.signal.addEventListener("abort",o,{once:!0}),t?.aborted&&r.abort(),this.Br.add(i),Promise.resolve().then(()=>e(r.signal)).finally(()=>{t?.removeEventListener("abort",n),i.signal.removeEventListener("abort",o),this.Br.delete(i)})}Dr(t,e,i,r){return this.Ur(e,async e=>{let n;try{n=this.Fr.acquire()}catch(o){if("video"===t)throw V(o);if("zip"===t){const t=ts(o);throw r?.(t),t}throw o}try{return await i(e)}finally{n()}})}Nr(t,e){const i=t?.frameCount,r=Number.isInteger(i)&&i>=1&&i<=65534?i:300;t?.onProgress?.({state:"error",frameIndex:0,totalFrames:r,progress:0,message:e.message})}Rr(){if(this.v)throw new Error("Textmode export plugin has been disposed.")}},oh={name:"textmode.export.js",install(t,e){const i=new nh(t,t=>e.on("postDraw",t));try{for(const t of rh)e.defineExtension("textmodifier",t,{value:i.api[t]});e.defineExtension("textmodifier","exportOverlay",{get:()=>i.api.exportOverlay})}catch(r){throw i.dispose(),r}return()=>i.dispose()}};"undefined"!=typeof window&&(window.ExportPlugin=oh),t.ExportPlugin=oh,t.ZIPExportError=Jo});
|