textmode.export.js 1.9.0-beta.2 → 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 -5
- 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 -1
- 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 +10 -5
- package/dist/types/index.d.ts +1 -3
- package/dist/types/types.d.ts +7 -4
- package/package.json +5 -38
- package/dist/textmode.document.esm.js +0 -1
- package/dist/types/document/constants.d.ts +0 -32
- package/dist/types/document/decode-shapes.d.ts +0 -4
- package/dist/types/document/decode.d.ts +0 -5
- package/dist/types/document/index.d.ts +0 -13
- package/dist/types/document/parse.d.ts +0 -3
- package/dist/types/document/types.d.ts +0 -209
- package/dist/types/document/validation.d.ts +0 -37
- package/protocol/textmode-document/2.0/SPECIFICATION.md +0 -233
- package/protocol/textmode-document/2.0/fixture.d.ts +0 -3
- package/protocol/textmode-document/2.0/fixtures/textmode-document-all-v2.json +0 -94
- package/protocol/textmode-document/2.0/fixtures/textmode-document-create-integration-v2.json +0 -112
- package/protocol/textmode-document/2.0/fixtures/textmode-document-selected-v2.json +0 -86
- package/protocol/textmode-document/2.0/fixtures/textmode-layer-all-v1.1.json +0 -46
- package/protocol/textmode-document/2.0/fixtures/textmode-layer-selected-v1.json +0 -38
- package/protocol/textmode-document/2.0/textmode-document-2.0.schema.d.ts +0 -3
- package/protocol/textmode-document/2.0/textmode-document-2.0.schema.json +0 -171
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LayerBlendMode as t}from"textmode.js";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var e=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),i=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},r=new TextEncoder;function n(t,e){let i="",n=0;for(const o of t){const t=r.encode(o).byteLength;if(n+t>e)break;i+=o,n+=t}return i}var o=class{$resolve(t,e,i=/* @__PURE__ */new Date){const n=e.toLowerCase(),o=t?.trim(),s=o?.toLowerCase().endsWith(n)?o.slice(0,-n.length):o;return`${this.$sanitizeStem(s,i,255-r.encode(e).length)}${n}`}$sanitizeStem(t,e=/* @__PURE__ */new Date,i=255){const r=this.$defaultStem(e);return t?.trim()&&n(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,"")||n(r,i)}$defaultStem(t=/* @__PURE__ */new Date){return`textmode-export-${t.toISOString().slice(0,19).replace(/:/g,"-")}`}},s=class{$downloadFile(t,e,i){const r=i?(new o).$resolve(e,i):(new o).$sanitizeStem(e),n=URL.createObjectURL(t),s=document.createElement("a");try{s.href=n,s.download=r,s.style.display="none",s.rel="noopener",document.body.appendChild(s),s.click()}finally{s.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}}},a=/* @__PURE__ */new WeakMap;function h(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function c(t,e){let i=a.get(t);if(!i){i=/* @__PURE__ */new Map;for(const e of t.characters)i.set(h(e.color),e);a.set(t,i)}return i.get(e)}function l(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function d(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:l(t,e),layer:e}))}function u(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:l(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}var f=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 p(){return new f("FRAME_SEQUENCE_ABORTED","Frame-sequence capture was cancelled.")}function m(t){return t instanceof f&&"FRAME_SEQUENCE_ABORTED"===t.code||t instanceof DOMException&&"AbortError"===t.name}var w=class{m=!1;v=!1;acquire(){if(this.v)throw new f("FRAME_SEQUENCE_DISPOSED","The textmode export plugin has been disposed.");if(this.m)throw new f("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}},v=1e6;function b(t,e){const i=Math.round(t*v/e),r=Math.max(i+1,Math.round((t+1)*v/e));return{startSeconds:i/v,centerSeconds:(i+Math.floor((r-i)/2))/v,endSeconds:r/v,durationSeconds:(r-i)/v}}var y=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=b(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(/* @__PURE__ */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(p());let s=!1;const a=t=>{s||(s=!0,clearTimeout(c),i?.removeEventListener("abort",h),t())},h=()=>a(()=>o(p())),c=setTimeout(()=>a(()=>o(function(t){return new f("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 p()}};function g(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var x=class extends i{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=g(t.primaryColorPixels,s),c=g(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}},E=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}},T=class{G;constructor(){this.G=new E}$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=c(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:l}=t.primaryColor,d=`rgba(${s},${a},${h},${l/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.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,"><")}},k=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 x,r=new T,n=this.Z(e),o=u(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 s).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename,".svg")}},_={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},M=class{Z(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}Y(t){if(!(t.format in _))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(/* @__PURE__ */new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},_[e.format])})}async $saveImage(t,e={}){const i=this.Z(e);this.Y(i);const r=await this.$toImageBlob(t,e);(new s).$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({[_[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 r=new i,n=u(t,e.layer),o=r.$extractFramebufferData(n.drawFramebuffer),s=[];let a=0;for(let i=0;i<n.grid.rows;i++){let t="";for(let i=0;i<n.grid.cols;i++){const i=4*a,s=r.$getEncodedCharacterValue(o.characterPixels,i);t+=c(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 s).$downloadFile(n,i.filename,".txt")}},S=/* @__PURE__ */e(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>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=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,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=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth: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}),C='(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',P="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",C],{type:"text/javascript;charset=utf-8"});function I(t){let e;try{if(e=P&&(self.URL||self.webkitURL).createObjectURL(P),!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(C),{name:t?.name})}}var B=class{K;tt=/* @__PURE__ */new Map;et;it=0;v=!1;constructor(t,e,i,r,n){this.K=new I,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()}},F=S(),O=class{T;k;constructor(t,e){this.T=t,this.k=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new s).$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 y(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,F.GIFEncoder)():null,h="undefined"==typeof Worker?null:new B(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,F.quantize)(t,256,{}),s=(0,F.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 $(){return new R("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function D(t,e){return new R("VIDEO_EXPORT_TIMEOUT",t,e)}function N(t){return t instanceof R?t:m(t)?$():t instanceof f&&"FRAME_SEQUENCE_TIMEOUT"===t.code?D(t.message,t):new R("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}function V(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 U(t){if(!t)throw new Error("Assertion failed.")}var z,j=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},L=t=>t&&t[t.length-1],q=t=>t>=0&&t<2**32,G=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)},H=t=>{const e=G(t);return 1&e?e+1>>1:-(e>>1)},W=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),X=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Z=/* #__PURE__ */new TextEncoder,Q={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Y={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},J={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},K=t=>!t||null==t.primaries&&null==t.transfer&&null==t.matrix&&null==t.fullRange,tt=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),et=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}},it=(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},rt=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},nt=t=>{throw new Error(`Unexpected value: ${t}`)},ot=(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},st=(t,e,i)=>Math.max(e,Math.min(i,t)),at=(t,e)=>Math.round(t/e)*e,ht=(t,e)=>Math.round(t*e)/e,ct=(t,e)=>Math.floor(t*e)/e,lt=t=>{let e=0;for(;0!==t;)t&=t-1,e++;return e},dt=/^[a-z]{3}$/,ut=1e6*(1+Number.EPSILON),ft=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},pt=null,mt=()=>null!==pt?pt:pt=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),wt=null,vt=()=>null!==wt?wt:wt="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),bt=null,yt=()=>null!==bt?bt:bt=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),gt=/* #__PURE__ */(async()=>{})().constructor,xt=t=>t instanceof gt||t instanceof Promise||"function"==typeof t?.then,Et=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},Tt=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}},kt=(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},_t=t=>"number"==typeof t&&!Number.isNaN(t),Mt=t=>{U(Number.isInteger(t.num)),U(Number.isInteger(t.den)),U(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=/* @__PURE__ */new Map}on(t,e,i){this.ht.has(t)||this.ht.set(t,/* @__PURE__ */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"}(z||(z={}));var It=class t{constructor(){}static get level(){return t.lt}static set level(e){if(e!==z.Silent&&e!==z.Errors&&e!==z.Warnings&&e!==z.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>=z.Errors&&console.error(...e)}static wt(...e){t.dt.ct("warn",e),t.lt>=z.Warnings&&console.warn(...e)}static vt(...e){t.dt.ct("info",e),t.lt>=z.Info&&console.info(...e)}};It.lt=z.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}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}},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=>{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=Nt.indexOf(n);if(-1===o)throw new TypeError(`Unsupported number of channels: ${t.outputNumberOfChannels}`);let s=16;t.objectType>=32&&(s+=6),15===jt(r)&&(s+=24),e&&(s+=9,15===jt(t.outputSampleRate)&&(s+=24));const a=Math.ceil(s/8),h=new Uint8Array(a),c=new $t(h);return Ut(c,t.objectType),zt(c,r),c.writeBits(4,o),e&&(zt(c,t.outputSampleRate),Ut(c,2)),c.writeBits(3,0),h},Ut=(t,e)=>{e<32?t.writeBits(5,e):(t.writeBits(5,31),t.writeBits(6,e-32))},zt=(t,e)=>{const i=jt(e);t.writeBits(4,i),15===i&&t.writeBits(24,e)},jt=t=>{const e=Dt.indexOf(t);return-1===e?15:e},Lt=[48e3,44100,32e3],qt=[24e3,22050,16e3];!function(t){t[t.NON_IDR_SLICE=1]="NON_IDR_SLICE",t[t.SLICE_DPA=2]="SLICE_DPA",t[t.SLICE_DPB=3]="SLICE_DPB",t[t.SLICE_DPC=4]="SLICE_DPC",t[t.IDR=5]="IDR",t[t.SEI=6]="SEI",t[t.SPS=7]="SPS",t[t.PPS=8]="PPS",t[t.AUD=9]="AUD",t[t.SPS_EXT=13]="SPS_EXT"}(Bt||(Bt={})),function(t){t[t.RASL_N=8]="RASL_N",t[t.RASL_R=9]="RASL_R",t[t.BLA_W_LP=16]="BLA_W_LP",t[t.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",t[t.VPS_NUT=32]="VPS_NUT",t[t.SPS_NUT=33]="SPS_NUT",t[t.PPS_NUT=34]="PPS_NUT",t[t.AUD_NUT=35]="AUD_NUT",t[t.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",t[t.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(Ft||(Ft={}));var Gt,Ht=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})},Wt=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=ot(r,i,!1):(U(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},Xt=t=>31&t,Zt=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)},Qt=(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}}),Yt=t=>{const e=G(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)G(t),G(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},Jt=t=>t>>1&63,Kt=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=/* @__PURE__ */new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},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&&H(t);for(let e=0;e<i;e++)H(t)}else G(t)},ee=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=ie(t,r,e,i)},ie=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(G(t)+1):e-1,t.readBits(1),G(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=G(t),i=G(t);for(let r=0;r<e;r++)G(t),t.readBits(1);for(let r=0;r<i;r++)G(t),t.readBits(1);n=e+i}return n},re=(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=Qt[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)&&(G(t),G(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(G(t),G(t),G(t),G(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&G(t),t.readBits(1)&&ne(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=G(t),G(t),G(t),G(t),G(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},ne=(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?G(t):i=1===t.readBits(1);let s=1;i||(s=G(t)+1),r&&oe(t,s,o),n&&oe(t,s,o)}},oe=(t,e,i)=>{for(let r=0;r<e;r++)G(t),G(t),i&&(G(t),G(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"}(Gt||(Gt={}));var se,ae=t=>{const e=X(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"}(se||(se={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var he,ce=[1,2,3,6],le=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],de=[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],ue=[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],pe=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],me=[32e3,44100,48e3,0],we=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],ve=[512,1024,2048,4096],be=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=me[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*lt(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=we[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}}},ye=t=>{const e=new Uint8Array(20),i=X(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(ve.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},ge=["avc","hevc","vp9","av1","vp8","prores"],xe=["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"],Ee=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Te=[...Ee,...xe],ke=["webvtt"],_e=[{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}],Me=[{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}],Ae=[{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}],Se=[{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}],Ce=["ap4x","ap4h","apch","apcn","apcs","apco"],Pe=["dtsc","dtsh","dtsl","dtse"],Ie=[{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}],Be=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=_e.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??L(_e),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=Me.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??L(Me);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.${(Ae.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??L(Ae)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=Se.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??L(Se);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Ie.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 nt(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Fe=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]},Oe=/^pcm-([usf])(\d+)(be)?$/,Re=t=>{if(U(xe.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=Oe.exec(t);let i;return U(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}},$e=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":Ce.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":Pe.includes(t)?"dts":"ulaw"===t?"ulaw":"alaw"===t?"alaw":Oe.test(t)?t:"webvtt"===t?"webvtt":null,De=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Ce],Ne=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ve=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ue=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ze=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,je=(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(!De.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&&!tt(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(Q);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(Y);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(J);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(!Ve.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(!Ue.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(!ze.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(Ce.some(e=>t.decoderConfig.codec.startsWith(e))&&!Ce.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: ${Ce.join(", ")}.`);if(null!==e&&$e(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}'.`)},Le=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],qe=(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(!Le.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&&!tt(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(!Pe.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: ${Pe.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!xe.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${xe.join(", ")}).`);if(null!==e&&$e(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}'.`)},Ge=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.")},He=/* #__PURE__ */new Uint8Array(0),We=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===He&&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===He}get microsecondTimestamp(){return Math.trunc(ut*this.timestamp)}get microsecondDuration(){return Math.trunc(ut*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)}},Xe=class{constructor(t){this.value=t}},Ze=class{constructor(t){this.value=t}},Qe=class{constructor(t){this.value=t}},Ye=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"}(he||(he={})),he.EBML,he.Segment,he.SeekHead,he.Info,he.Cluster,he.Tracks,he.Cues,he.Attachments,he.Chapters,he.Tags;var Je=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,Ke=t=>t<256n?1:t<65536n?2:t<1n<<24n?3:t<1n<<32n?4:t<1n<<40n?5:t<1n<<48n?6:t<1n<<56n?7:8,ti=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,ei=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap,this.dataOffsets=/* @__PURE__ */new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=Je(t)){let i=0;switch(e){case 6:this.helperView.setUint8(i++,t/2**40|0);case 5:this.helperView.setUint8(i++,t/2**32|0);case 4:this.helperView.setUint8(i++,t>>24);case 3:this.helperView.setUint8(i++,t>>16);case 2:this.helperView.setUint8(i++,t>>8);case 1:this.helperView.setUint8(i++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(t,e=Ke(t)){let i=0;for(let r=e-1;r>=0;r--)this.helperView.setUint8(i++,Number(t>>BigInt(8*r)&255n));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(t,e=ti(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??Je(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??Ke(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if("string"==typeof t.data)this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof Xe)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof Ze)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof Qe){const e=t.size??ti(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Ye){const e=Z.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else nt(t.data)}},ii={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"},ri=t=>{const e=t.filePos,i=new $t(zi(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}},ni=/* @__PURE__ */e((t,e)=>{e.exports={}}),oi=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 si=-1/0,ai=-1/0,hi=null;"undefined"!=typeof FinalizationRegistry&&(hi=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-si>=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."),si=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-ai>=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."),ai=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var ci=class{constructor(){this.bt=0,this.yt=null}},li=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],di=new Set(li),ui=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(ut*this.timestamp)}get microsecondDuration(){return Math.trunc(ut*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||!di.has(i.format))throw new TypeError("init.format must be one of: "+li.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??Ei(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?W(e):W(e).slice(),this.Tt=t,this.colorSpace=new vi(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 vi(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*ut),duration:Math.trunc((i.duration??0)*ut)||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:vt(),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 vi({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof ci))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&&!li.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}),hi?.register(this,{type:"video",data:this.xt},this)}clone(){if(this.gt)throw new Error("VideoSample is closed.");return U(null!==this.xt),this.xt instanceof ci?new t(this.xt,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):bi(this.xt)?new t(this.xt.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this.xt instanceof Uint8Array?(U(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||(hi?.unregister(this),this.xt instanceof ci?(this.xt.bt--,0===this.xt.bt&&this.xt.close()):bi(this.xt)?this.xt.close():this.xt=null,this.gt=!0)}allocationSize(t={}){if(xi(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 bi(this.xt)?this.xt.allocationSize(t):ki(this,t).allocationSize}async copyTo(e,i={}){if(!tt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(xi(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(U(null!==this.xt),bi(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 ci)){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{oi(r)}}}const r=ki(this,i);U(this.format);const n=W(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=Ti(this.format);let s;if(this.xt instanceof ci){let t=this.xt.getDataPlanes();if(xt(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)U(this.Tt),U(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");U(t),s=[{data:W(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(U(null!==this.xt),this.xt instanceof ci){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(xt(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 bi(this.xt)?new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.xt instanceof Uint8Array?(U(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&&gi(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=yi(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?wi(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(U(null!==this.xt),this.xt instanceof ci||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&&gi(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=j(this.rotation+(e.rotate??0)),[r,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=yi(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=at(c,e.roundDimensionsTo??1),l=at(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 fi){let e=t(this,d);if(xt(e)&&(e=await e),null!==e)return e}const{canvas:u,context:f,isNew:p}=wi(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()}},fi=[],pi=[],mi=0,wi=(t,e)=>{for(const n of pi)if(n.canvas.width===t&&n.canvas.height===e)return n.age=mi++,{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 pi.length>=3&&pi.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})(pi,t=>t.age),1),pi.push({canvas:i,context:r,age:mi++}),{canvas:i,context:r,isNew:!0}},vi=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(Q);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(Y);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(J);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}}},bi=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,yi=(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 U(o>=0),U(s>=0),{left:r,top:n,width:o,height:s}},gi=(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.")},xi=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.")}},Ei=(t,e,i)=>{const r=Ti(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},Ti=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:nt(t),U(!1)}},ki=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=_i(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 Ai(n,s,o)},_i=(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(!Mi(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},Mi=(t,e)=>{if(null===t)return!0;const i=Ti(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},Ai=(t,e,i)=>{const r=Ti(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}},Si=/* @__PURE__ */new Map,Ci=(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&&$e(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.")},Pi=t=>{const e=t.bitrateMode,i=t.quality.Mt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Be(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}),U(n.length>0),n},Ii=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 Bi):"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?Bi[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=Fi[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&&(U(void 0!==this.At),o=st(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&&(U(null!==o&&n),r=st((o-n.worst)/(n.best-n.worst),0,1)),h=Ri(t,e,i,Oi(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}Bt(t,e,i){return void 0!==this.Ct?this.Ct:(U(void 0!==this.At),Ri(t,e,i,Oi(this.At)))}Ft(t){if(xe.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=Oi(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)}},Bi={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Fi={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}},Oi=t=>.3*Math.exp(2.5538*t),Ri=(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)},$i=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void U(!1),Di=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,...s}=e;if(!ge.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 Ii))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 Ii)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Ci(t,s);const a=Ni(n,o)??new Ii("medium");let h;try{h=Pi({codec:t,width:i,height:r,quality:a,framerate:void 0,...s,alpha:"discard"})}catch{return!1}const c=JSON.stringify(h),l=Si.get(c);if(l)return l;const d=(async()=>{for(const{config:e}of h)if(Vi.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(!vt())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?$i(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return Si.set(c,d),d},Ni=(t,e)=>void 0!==t?t:void 0!==e?e instanceof Ii?e:new Ii({bitrate:e}):void 0,Vi=[],Ui=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,X(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)}},zi=(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},ji=class{constructor(t){this.mutex=new et,this.trackTimestampInfo=/* @__PURE__ */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)}}},Li=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,qi=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Gi=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")},Hi=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.writer.write(this.helper);t.length%8!=0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{const e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(const n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);U(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}}},Wi=/* #__PURE__ */new Uint8Array(8),Xi=/* #__PURE__ */new DataView(Wi.buffer),Zi=t=>[(t%256+256)%256],Qi=t=>(Xi.setUint16(0,t,!1),[Wi[0],Wi[1]]),Yi=t=>(Xi.setInt16(0,t,!1),[Wi[0],Wi[1]]),Ji=t=>(Xi.setUint32(0,t,!1),[Wi[1],Wi[2],Wi[3]]),Ki=t=>(Xi.setUint32(0,t,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),tr=t=>(Xi.setInt32(0,t,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),er=t=>(Xi.setUint32(0,Math.floor(t/2**32),!1),Xi.setUint32(4,t,!1),[Wi[0],Wi[1],Wi[2],Wi[3],Wi[4],Wi[5],Wi[6],Wi[7]]),ir=t=>(Xi.setInt32(0,Math.floor(t/2**32),!1),Xi.setUint32(4,t,!1),[Wi[0],Wi[1],Wi[2],Wi[3],Wi[4],Wi[5],Wi[6],Wi[7]]),rr=t=>(Xi.setInt16(0,256*t,!1),[Wi[0],Wi[1]]),nr=t=>(Xi.setInt32(0,65536*t,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),or=t=>(Xi.setInt32(0,2**30*t,!1),[Wi[0],Wi[1],Wi[2],Wi[3]]),sr=(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()},ar=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},hr=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]},cr=/* #__PURE__ */hr(0),lr=t=>[nr(t[0]),nr(t[1]),or(t[2]),nr(t[3]),nr(t[4]),or(t[5]),nr(t[6]),nr(t[7]),or(t[8])],dr=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),ur=(t,e,i,r,n)=>dr(t,[Zi(e),Ji(i),r??[]],n),fr=()=>dr("styp",[ar("iso5"),Ki(0),ar("iso5"),ar("iso6"),ar("mp41"),ar("cmfc"),ar("dash")]),pr=(t,e)=>{const i=Math.max(0,t.minWrittenTimestamp);let r=Math.max(0,t.maxWrittenEndTimestamp-i);return Number.isFinite(r)||(r=0),ur("sidx",1,0,[Ki(1),Ki(Un),er(jn(i,Un)),er(0),Qi(0),Qi(1),Ki(2147483647&e),Ki(jn(r,Un)),Ki(0)])},mr=t=>({type:"mdat",largeSize:t}),wr=t=>dr("moov",void 0,[vr(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>yr(e,t.creationTime)),t.isFragmented?nn(t.trackDatas):null,vn(t)]),vr=(t,e)=>{const i=Math.max(0,...e.map(t=>Math.max(0,jn(br(t),Un)+jn(t.startTimestampOffset??0,Un)))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!q(t)||!q(i),o=n?er:Ki;return ur("mvhd",+n,0,[o(t),o(t),Ki(Un),o(i),nr(1),rr(1),Array(10).fill(0),lr(cr),Array(24).fill(0),Ki(r)])},br=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},yr=(t,e)=>{const i=zn(t),r=null!==t.startTimestampOffset&&0!==t.startTimestampOffset;return dr("trak",void 0,[gr(t,e),r?xr(t):null,Er(t,e),void 0!==i.name?dr("udta",void 0,[dr("name",[...Z.encode(i.name)])]):null])},gr=(t,e)=>{const i=Math.max(0,jn(br(t),Un)+jn(t.startTimestampOffset??0,Un)),r=!q(e)||!q(i),n=r?er:Ki;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=hr(e??0)}else o=cr;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:nt(t);return ur("tkhd",+r,s,[n(e),n(e),Ki(t.track.id),Ki(0),n(i),Array(8).fill(0),Qi(0),Qi(a),rr("audio"===t.type?1:0),Qi(0),lr(o),nr("video"===t.type?t.info.width:0),nr("video"===t.type?t.info.height:0)])},xr=t=>{const e=t.startTimestampOffset;if(U(null!==e),e>0){const i=jn(e,Un),r=jn(br(t),Un),n=!q(i)||!q(r),o=n?er:Ki,s=n?ir:tr;return dr("edts",void 0,[ur("elst",n?1:0,0,[Ki(2),o(i),s(-1),nr(1),o(r),s(0),nr(1)])])}{const r=jn(-e,t.timescale),n=Math.max(0,jn(br(t),Un)+jn(e,Un)),o=!((i=r)>=-(2**31)&&i<2**31&&q(n)),s=o?er:Ki,a=o?ir:tr;return dr("edts",void 0,[ur("elst",o?1:0,0,[Ki(1),s(n),a(r),nr(1)])])}var i},Er=(t,e)=>dr("mdia",void 0,[Tr(t,e),Mr(!0,kr[t.type],_r[t.type]),Ar(t)]),Tr=(t,e)=>{const i=jn(br(t),t.timescale),r=!q(e)||!q(i),n=r?er:Ki;return ur("mdhd",+r,0,[n(e),n(e),Ki(t.timescale),n(i),Qi(In(t.track.metadata.languageCode??"und")),Qi(0)])},kr={video:"vide",audio:"soun",subtitle:"text"},_r={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Mr=(t,e,i,r="\0\0\0\0")=>ur("hdlr",0,0,[t?ar("mhlr"):Ki(0),ar(e),ar(r),Ki(0),Ki(0),ar(i,!0)]),Ar=t=>dr("minf",void 0,[Sr[t.type](),Cr(),Br(t)]),Sr={video:()=>ur("vmhd",0,1,[Qi(0),Qi(0),Qi(0),Qi(0)]),audio:()=>ur("smhd",0,0,[Qi(0),Qi(0)]),subtitle:()=>ur("nmhd",0,0)},Cr=()=>dr("dinf",void 0,[Pr()]),Pr=()=>ur("dref",0,0,[Ki(1)],[Ir()]),Ir=()=>ur("url ",0,1),Br=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return dr("stbl",void 0,[Fr(t),Qr(t),e?en(t):null,e?rn(t):null,Jr(t),Kr(t),tn(t),Yr(t)])},Fr=t=>{let e;if("video"===t.type)e=Or(_n(t.track.source.Ot,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=An(t.track.source.Ot,t.info.decoderConfig.codec,t.muxer.isQuickTime);U(i),e=Nr(i,t)}else"subtitle"===t.type&&(e=Zr(Cn[t.track.source.Ot],t));return U(e),ur("stsd",0,0,[Ki(1)],[e])},Or=(t,e)=>dr(t,[Array(6).fill(0),Qi(1),Qi(0),Qi(0),Array(12).fill(0),Qi(e.info.width),Qi(e.info.height),Ki(4718592),Ki(4718592),Ki(0),Qi(1),Zi(10),ar("Mediabunny"),Array(21).fill(0),Qi(e.info.hasAlphaChannel?32:24),Yi(65535)],[Mn[e.track.source.Ot]?.(e)??null,Rr(e),K(e.info.decoderConfig.colorSpace)?null:$r(e)]),Rr=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:dr("pasp",[Ki(t.info.pixelAspectRatio.num),Ki(t.info.pixelAspectRatio.den)]),$r=t=>{const e=t.info.decoderConfig.colorSpace;return dr("colr",[ar(t.muxer.isQuickTime?"nclc":"nclx"),Qi(null!=e?.primaries?Q[e.primaries]:2),Qi(null!=e?.transfer?Y[e.transfer]:2),Qi(null!=e?.matrix?J[e.matrix]:2),t.muxer.isQuickTime?[]:Zi((e?.fullRange?1:0)<<7)])},Dr=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?Q[e.colorSpace.primaries]:1,a=i[6]?Number(i[6]):e.colorSpace?.transfer?Y[e.colorSpace.transfer]:1,h=i[7]?Number(i[7]):e.colorSpace?.matrix?J[e.colorSpace.matrix]:1;return ur("vpcC",1,0,[Zi(r),Zi(n),Zi(o),Zi(s),Zi(a),Zi(h),Qi(0)])},Nr=(t,e)=>{let i,r=0,n=16;const o=xe.includes(e.track.source.Ot);if(o){const t=e.track.source.Ot,{sampleSize:i}=Re(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),Qi(1),Qi(r),Qi(0),Ki(0),Qi(e.info.numberOfChannels),Qi(n),Qi(0),Qi(0),Qi(e.info.sampleRate<65536?e.info.sampleRate:0),Qi(0)];else{const t=o?0:-2;i=[Array(6).fill(0),Qi(1),Qi(r),Qi(0),Ki(0),Qi(e.info.numberOfChannels),Qi(Math.min(n,16)),Yi(t),Qi(0),Qi(e.info.sampleRate<65536?e.info.sampleRate:0),Qi(0),o?[Ki(1),Ki(n/8),Ki(e.info.numberOfChannels*n/8)]:[Ki(0),Ki(0),Ki(0)],Ki(2)]}return dr(t,i,[Sn(e.track.source.Ot,e.muxer.isQuickTime)?.(e)??null])},Vr=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=[...Zi(e),...Zi(21),...Ji(0),...Ki(0),...Ki(0)];if(t.info.decoderConfig.description){const e=W(t.info.decoderConfig.description);i=[...i,...Zi(5),...sr(e.byteLength),...e]}return i=[...Qi(1),...Zi(0),...Zi(4),...sr(i.length),...i,...Zi(6),...Zi(1),...Zi(2)],i=[...Zi(3),...sr(i.length),...i],ur("esds",0,0,i)},Ur=t=>dr("wave",void 0,[zr(t),jr(t),dr("\0\0\0\0")]),zr=t=>dr("frma",[ar(An(t.track.source.Ot,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),jr=t=>{const{littleEndian:e}=Re(t.track.source.Ot);return dr("enda",[Qi(+e)])},Lr=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=/* @__PURE__ */new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){U(a.byteLength>=18);const t=ae(W(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return dr("dOps",[Zi(0),Zi(e),Qi(i),Ki(r),Yi(n),Zi(o),...s])},qr=t=>{const e=t.info.decoderConfig?.description;U(e);const i=W(e);return ur("dfLa",0,0,[...i.subarray(4)])},Gr=t=>{const{littleEndian:e,sampleSize:i}=Re(t.track.source.Ot);return ur("pcmC",0,0,[Zi(+e),Zi(8*i)])},Hr=t=>{U(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=/* @__PURE__ */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),dr("dac3",[...i])},Wr=t=>{U(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=ce[o];let d;return d=n<3?Lt[n]/1e3:qt[s]/1e3,{dataRate:Math.round((r+1)*d/(16*l)),substreams:[{fscod:n,fscod2:s,bsid:c,bsmod:0,acmod:a,lfeon:h,numDepSub:0,chanLoc:0}]}})(t.info.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 dr("dec3",[...n])},Xr=t=>{U(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>=fe.length)return null;const s=le[e.readBits(4)];if(0===s)return null;const a=de[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=ue[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:pe[o]|(l?8:0),amode:o,lfePresent:l,bitRate:a,pcmResolution:c}})(t),i=X(t);let r=e?4*Math.ceil(e.frameSize/4):0,n=null;for(;r+4<=t.length&&1683496997===i.getUint32(r);){const e=be(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 dr("ddts",[...ye(e)])},Zr=(t,e)=>dr(t,[Array(6).fill(0),Qi(1)],[Pn[e.track.source.Ot](e)]),Qr=t=>ur("stts",0,0,[Ki(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[Ki(t.sampleCount),Ki(t.sampleDelta)])]),Yr=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return ur("stss",0,0,[Ki(e.length),e.map(([t])=>Ki(t+1))])},Jr=t=>ur("stsc",0,0,[Ki(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[Ki(t.firstChunk),Ki(t.samplesPerChunk),Ki(1)])]),Kr=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=Re(t.track.source.Ot);return ur("stsz",0,0,[Ki(e*t.info.numberOfChannels),Ki(t.samples.reduce((e,i)=>e+jn(i.duration,t.timescale),0))])}return ur("stsz",0,0,[Ki(0),Ki(t.samples.length),t.samples.map(t=>Ki(t.size))])},tn=t=>t.finalizedChunks.length>0&&L(t.finalizedChunks).offset>=2**32?ur("co64",0,0,[Ki(t.finalizedChunks.length),t.finalizedChunks.map(t=>er(t.offset))]):ur("stco",0,0,[Ki(t.finalizedChunks.length),t.finalizedChunks.map(t=>Ki(t.offset))]),en=t=>ur("ctts",1,0,[Ki(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[Ki(t.sampleCount),tr(t.sampleCompositionTimeOffset)])]),rn=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;U(t.compositionTimeOffsetTable.length>0),U(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,jn(e.timestamp,t.timescale)),n=Math.max(n,jn(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:ur("cslg",0,0,[tr(o),tr(e),tr(i),tr(r),tr(n)])},nn=t=>dr("mvex",void 0,t.map(on)),on=t=>ur("trex",0,0,[Ki(t.track.id),Ki(1),Ki(0),Ki(0),Ki(0)]),sn=(t,e)=>dr("moof",void 0,[an(t),...e.map(cn)]),an=t=>ur("mfhd",0,0,[Ki(t)]),hn=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},cn=t=>dr("traf",void 0,[ln(t),dn(t),un(t)]),ln=t=>{U(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:hn(i)};return ur("tfhd",0,131128,[Ki(t.track.id),Ki(r.duration),Ki(r.size),Ki(r.flags)])},dn=t=>(U(t.currentChunk),ur("tfdt",1,0,[er(jn(t.currentChunk.startTimestamp,t.timescale))])),un=t=>{U(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(hn),n=t.currentChunk.samples.map(e=>jn(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,ur("trun",1,p,[Ki(t.currentChunk.samples.length),Ki(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?Ki(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?Ki(e[o]):[],d?Ki(i[o]):[],u?Ki(r[o]):[],f?tr(n[o]):[]])])},fn=t=>ur("tfra",1,0,[Ki(t.track.id),Ki(63),Ki(t.finalizedChunks.length),t.finalizedChunks.map(e=>[er(jn(e.samples[0].timestamp,t.timescale)),er(e.moofOffset),Ki(e.trafIndex+1),Ki(1),Ki(1)])]),pn=()=>dr("vtte"),mn=(t,e,i,r,n)=>dr("vttc",void 0,[null!==n?dr("vsid",[tr(n)]):null,null!==i?dr("iden",[...Z.encode(i)]):null,null!==e?dr("ctim",[...Z.encode(Gi(e))]):null,null!==r?dr("sttg",[...Z.encode(r)]):null,dr("payl",[...Z.encode(t)])]),wn=t=>dr("vtta",[...Z.encode(t)]),vn=t=>{const e=[],i=t.format.Rt.metadataFormat??"auto",r=t.output.$t;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=En(r);t&&e.push(t)}else if("mdta"===i){const t=Tn(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&bn(e,t.output.$t);return 0===e.length?null:dr("udta",void 0,e)},bn=(t,e)=>{for(const{key:i,value:r}of Et(e))switch(i){case"title":t.push(yn("©nam",r));break;case"description":t.push(yn("©des",r));break;case"artist":t.push(yn("©ART",r));break;case"album":t.push(yn("©alb",r));break;case"albumArtist":t.push(yn("albr",r));break;case"genre":t.push(yn("©gen",r));break;case"date":t.push(yn("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(yn("©cmt",r));break;case"lyrics":t.push(yn("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:nt(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(yn(i,r)):r instanceof Uint8Array&&t.push(dr(i,Array.from(r))))}},yn=(t,e)=>{const i=Z.encode(e);return dr(t,[Qi(i.length),Qi(In("und")),Array.from(i)])},gn={"image/jpeg":13,"image/png":14,"image/bmp":27},xn=(t,e)=>{const i=[];for(const{key:r,value:n}of Et(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:kn(n)});break;case"description":i.push({key:e?"description":"©des",value:kn(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:kn(n)});break;case"album":i.push({key:e?"album":"©alb",value:kn(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:kn(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:kn(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:kn(n)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:kn(n)});break;case"date":i.push({key:e?"date":"©day",value:kn(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:dr("data",[Ki(gn[t.mimeType]??0),Ki(0),Array.from(t.data)])});break;case"trackNumber":if(e){const e=void 0!==t.tracksTotal?`${n}/${t.tracksTotal}`:n.toString();i.push({key:"track",value:kn(e)})}else i.push({key:"trkn",value:dr("data",[Ki(0),Ki(0),Qi(0),Qi(n),Qi(t.tracksTotal??0),Qi(0)])});break;case"discNumber":e||i.push({key:"disc",value:dr("data",[Ki(0),Ki(0),Qi(0),Qi(n),Qi(t.discsTotal??0),Qi(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:nt(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:kn(n)}):n instanceof Uint8Array?i.push({key:r,value:dr("data",[Ki(0),Ki(0),Array.from(n)])}):n instanceof Ot&&i.push({key:r,value:dr("data",[Ki(gn[n.mimeType]??0),Ki(0),Array.from(n.data)])}))}return i},En=t=>{const e=xn(t,!1);return 0===e.length?null:ur("meta",0,0,void 0,[Mr(!1,"mdir","","appl"),dr("ilst",void 0,e.map(t=>dr(t.key,void 0,[t.value])))])},Tn=t=>{const e=xn(t,!0);return 0===e.length?null:dr("meta",void 0,[Mr(!1,"mdta",""),ur("keys",0,0,[Ki(e.length)],e.map(t=>dr("mdta",[...Z.encode(t.key)]))),dr("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...Ki(e+1));return dr(i,void 0,[t.value])}))])},kn=t=>dr("data",[Ki(1),Ki(0),...Z.encode(t)]),_n=(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}},Mn={avc:t=>t.info.decoderConfig&&dr("avcC",[...W(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&dr("hvcC",[...W(t.info.decoderConfig.description)]),vp8:Dr,vp9:Dr,av1:t=>dr("av1C",Fe(t.info.decoderConfig.codec)),prores:null},An=(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"}},Sn=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return Vr;case"opus":return Lr;case"flac":return qr;case"ac3":return Hr;case"eac3":return Wr;case"dts":return Xr}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 Ur}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 Gr}return null},Cn={webvtt:"wvtt"},Pn={webvtt:t=>dr("vttC",[...Z.encode(t.info.config.description)])},In=t=>{U(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},Bn=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(){U(!this.started),this.target.Vt(),this.started=!0}write(t){U(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 U(this.started&&!this.finalized),this.target.zt()}async finalize(){U(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}},Fn=(ni(),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 Nn(this,t)}}),On=65536,Rn=2**32,$n=class extends Fn{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/* @__PURE__ */new ArrayBuffer(0),this.Ht)try{this.Wt=new ArrayBuffer(On,{maxByteLength:Rn})}catch{this.Wt=new ArrayBuffer(On),this.Ht=!1}else this.Wt=new ArrayBuffer(On);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>Rn)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)}},Dn=class extends Fn{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(U(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){U(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||!mt()?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;U(this.ee),await this.ee.ready,await this.ee.close(),this.ct("finalized")}async Qt(){return this.ee?.close()}},Nn=class extends Fn{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)}},Vn=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.")}},Un=57600,zn=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},jn=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},Ln=class extends ji{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new $n,this.auxWriter=new Bn(this.auxTarget,!1),this.auxBoxWriter=new Hi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=rt(),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 co,this.isCmaf=e instanceof ho,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(e instanceof ho?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 $n),this.boxWriter=new Hi(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof $n&&"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 Bn(await this.output.me(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new Hi(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.Ot);{const t=this.initBoxWriter??this.boxWriter;if(U(t),this.formatOptions.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return dr("ftyp",t.isQuickTime?[ar("qt "),Ki(e),ar("qt ")]:t.fragmented?t.cmaf?[ar("iso5"),Ki(e),ar("iso5"),ar("iso6"),ar("mp41"),ar("cmfc"),ar("dash")]:[ar("iso5"),Ki(e),ar("iso5"),ar("iso6"),ar("mp41")]:[ar("isom"),Ki(e),ar("isom"),t.holdsAvc?ar("avc1"):[],ar("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||(U(this.writer),U(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=mr(!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;je(i,t.source.Ot),U(i),U(i.decoderConfig);const n={...i.decoderConfig};U(void 0!==n.codedWidth),U(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 Ht(t)){const o=t.subarray(h.offset,h.offset+h.length),s=Jt(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(Zt(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}=Kt(e,i);G(e);const l=G(e);let d=0;3===l&&(d=e.readBits(1));const u=G(e),f=G(e);let p=u,m=f;if(e.readBits(1)){const t=G(e),i=G(e),r=G(e),n=G(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=G(e),v=G(e);G(e);const b=e.readBits(1)?0:i;let y=0;for(let t=b;t<=i;t++)G(e),y=G(e),G(e);G(e),G(e),G(e),G(e),G(e),G(e),e.readBits(1)&&e.readBits(1)&&te(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),G(e),G(e),e.skipBits(1));const g=G(e);if(ee(e,g),e.readBits(1)){const t=G(e);for(let i=0;i<t;i++)G(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=re(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(Zt(t));e.skipBits(16),G(e),G(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),G(e),G(e),H(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&G(e),H(e),H(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:Jt(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 Ht(t)){const n=t.subarray(s.offset,s.offset+s.length),o=Xt(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=Zt(t),i=new $t(e);if(i.skipBits(1),i.skipBits(2),7!==i.readBits(5))return null;const r=i.readAlignedByte(),n=i.readAlignedByte(),o=i.readAlignedByte();G(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=G(i),3===s&&(c=i.readBits(1)),a=G(i),h=G(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+H(i)+256)%256),r=0===n?r:n}G(i);const l=G(i);if(0===l)G(i);else if(1===l){i.skipBits(1),H(i),H(i);const t=G(i);for(let e=0;e<t;e++)H(i)}G(i),i.skipBits(1);const d=G(i),u=G(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=G(i),e=G(i),r=G(i),n=G(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)}let b=2,y=2,g=2,x=0,E={num:1,den:1},T=null,k=null,_=null,M=null;const A=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=Qt[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)&&(G(i),G(i)),i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.skipBits(1));const t=i.readBits(1);t&&Yt(i);const e=i.readBits(1);e&&Yt(i),(t||e)&&i.skipBits(1),i.skipBits(1),_=i.pos,M=i.readBits(1),M&&(i.skipBits(1),G(i),G(i),G(i),G(i),T=G(i),k=G(i))}if(null===T)if(U(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=_e.find(t=>t.level>=o)??L(_e),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);T=r,k=r}return U(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:A,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:M}}catch(e){return It.ft("Error parsing AVC SPS:",e),null}})(e[0]);U(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)&&null!==t.chromaFormat){U(null!==t.bitDepthLumaMinus8),U(null!==t.bitDepthChromaMinus8),U(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;qe(i,t.source.Ot),U(i),U(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=ri(Ui.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,outputSampleRate:i,outputNumberOfChannels: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&&xe.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;Ge(e),U(e),U(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:null,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...Ht(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=ri(Ui.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=Re(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=jn(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=Re(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;){t.lastCueEndTimestamp??=Math.min(0,t.cueQueue[0].timestamp);const i=/* @__PURE__ */new Set([]);for(const h of t.cueQueue)U(h.timestamp<=e),U(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=pn();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;Li.lastIndex=0;const r=Li.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=wn(i.notes);this.auxBoxWriter.writeBox(t)}const h=mn(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:jn(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){U(!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+=jn(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):L(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=jn(e.timestamp-e.decodeTimestamp,t.timescale),o=jn(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){U(t.lastSample);const i=jn(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(U(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=L(t.timeToSampleTable);if(U(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=L(t.compositionTimeOffsetTable);U(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=jn(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,U(t.lastSample),U(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){U("key"===e.type);const i=jn(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(U(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}),U(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(U(!this.isFragmented),U(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+jn(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&L(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)U(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(U(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(U(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const t=this.initBoxWriter??this.boxWriter;U(t),this.formatOptions.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=wr(this);if(t.writeBox(e),this.formatOptions.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onMoov(e,i)}if(this.isCmaf){U(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.fe(!0),this.boxWriter=new Hi(this.writer);const t=this.boxWriter.measureBox(fr()),e=this.boxWriter.measureBox(pr(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}U(this.writer),U(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=sn(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];U(t.currentChunk),U(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=sn(i,e);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(t,e,a)}U(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const d=mr(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(){U(this.writer),U(this.boxWriter),this.ensureOneEnabledTrack();const t=wr(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;U(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=mr(!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(){U("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;U(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(){U(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(U(this.writer),U(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=mr(!1);for(let i=0;i<2;i++){const e=wr(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)U(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=wr(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)U(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(pr(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,dr("mfra",void 0,[...e.map(fn),ur("mfro",0,0,[Ki(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{U(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);U(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=wr(this);if("reserve"===this.fastStart){U(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()}},qn="Mediabunny",Gn={video:1,audio:2,subtitle:17},Hn=class extends ji{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=rt(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=/* @__PURE__ */new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=e}async start(){const t=await this.mutex.acquire();this.writer=await this.output.fe(!!this.format.Rt.appendOnly),this.ebmlWriter=new ei(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:he.EBML,data:[{id:he.EBMLVersion,data:1},{id:he.EBMLReadVersion,data:1},{id:he.EBMLMaxIDLength,data:4},{id:he.EBMLMaxSizeLength,data:8},{id:he.DocType,data:this.format instanceof uo?"webm":"matroska"},{id:he.DocTypeVersion,data:2},{id:he.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:he.SeekHead,data:[{id:he.Seek,data:[{id:he.SeekID,data:e},{id:he.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:he.Seek,data:[{id:he.SeekID,data:i},{id:he.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:he.Seek,data:[{id:he.SeekID,data:r},{id:he.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:he.Seek,data:[{id:he.SeekID,data:n},{id:he.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:he.Seek,data:[{id:he.SeekID,data:o},{id:he.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const t={id:he.Duration,data:new Ze(0)};this.segmentDuration=t;const e={id:he.Info,data:[{id:he.TimestampScale,data:1e6},{id:he.MuxingApp,data:qn},{id:he.WritingApp,data:qn},this.format.Rt.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:he.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){let i=ii[e.track.source.Ot];U(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=ae(W(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:he.TrackEntry,data:[{id:he.TrackNumber,data:e.track.id},{id:he.TrackUID,data:e.track.id},{id:he.TrackType,data:Gn[e.type]},!1===e.track.metadata.disposition?.default?{id:he.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:he.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:he.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:he.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:he.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:he.FlagCommentary,data:1}:null,{id:he.FlagLacing,data:0},{id:he.Language,data:e.track.metadata.languageCode??"und"},{id:he.CodecID,data:i},e.codecPrivate?{id:he.CodecPrivate,data:W(e.codecPrivate)}:null,{id:he.CodecDelay,data:0},{id:he.SeekPreRoll,data:r},void 0!==e.track.metadata.name?{id:he.Name,data:new Ye(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:he.DefaultDuration,data:1e9/e}:null],n=i?j(-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:he.Video,data:[{id:he.PixelWidth,data:t.info.width},{id:he.PixelHeight,data:t.info.height},o?{id:he.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:he.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:he.DisplayUnit,data:3}:null,t.info.alphaMode?{id:he.AlphaMode,data:1}:null,K(s)?null:{id:he.Colour,data:[{id:he.MatrixCoefficients,data:null!=s?.matrix?J[s.matrix]:2},{id:he.TransferCharacteristics,data:null!=s?.transfer?Y[s.transfer]:2},{id:he.Primaries,data:null!=s?.primaries?Q[s.primaries]:2},{id:he.Range,data:null!=s?.fullRange?s.fullRange?2:1:0}]},n?{id:he.Projection,data:[{id:he.ProjectionType,data:0},{id:he.ProjectionPoseRoll,data:new Xe((n+180)%360-180)}]}:null]};return r.push(a),r}audioSpecificTrackInfo(t){const e=xe.includes(t.track.source.Ot)?Re(t.track.source.Ot):null;return[{id:he.Audio,data:[{id:he.SamplingFrequency,data:new Xe(t.info.sampleRate)},{id:he.Channels,data:t.info.numberOfChannels},e?{id:he.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:he.SimpleTag,data:[{id:he.TagName,data:new Ye(e)},"string"==typeof i?{id:he.TagString,data:new Ye(i)}:{id:he.TagBinary,data:i}]})},i=this.output.$t,r=/* @__PURE__ */new Set;for(const{key:n,value:o}of Et(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:nt(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:he.Tags,data:[{id:he.Tag,data:[{id:he.Targets,data:[{id:he.TargetTypeValue,data:50},{id:he.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.$t,e=[],i=/* @__PURE__ */new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+(Tt(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:he.AttachedFile,data:[void 0!==n.description?{id:he.FileDescription,data:new Ye(n.description)}:null,{id:he.FileName,data:new Ye(r)},{id:he.FileMediaType,data:n.mimeType},{id:he.FileData,data:n.data},{id:he.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&&kt(t.data,o.data))||e.push({id:he.AttachedFile,data:[void 0!==o.description?{id:he.FileDescription,data:new Ye(o.description)}:null,{id:he.FileName,data:new Ye(o.name??"")},{id:he.FileMediaType,data:o.mimeType??""},{id:he.FileData,data:o.data},{id:he.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:he.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:he.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:he.Cues,data:[]}}get segmentDataOffset(){return U(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 uo,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;je(i,t.source.Ot),U(i),U(i.decoderConfig),U(void 0!==i.decoderConfig.codedWidth),U(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(Fe(a.info.decoderConfig.codec)):"prores"===t.source.Ot&&(a.codecPrivate=Z.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;qe(i,t.source.Ot),U(i),U(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=ri(Ui.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,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;Ge(e),U(e),U(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Z.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=ht(s,t.metadata.frameRate),a=ht(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=ri(Ui.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);Li.lastIndex=0,n=n.replace(Li,t=>`<${Gi((t=>{const e=qi.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=Z.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?Z.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){U(null!==this.currentClusterStartMsTimestamp),U(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){if(!this.warnedAboutTooNegativeTimestamp){const t=this.format instanceof uo?"WebM":"Matroska";It.wt(`Packets had to be discarded because their timestamp is too negative to represent in ${t}.`),this.warnedAboutTooNegativeTimestamp=!0}return}const s=/* @__PURE__ */new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:he.BlockGroup,data:[{id:he.Block,data:[s,e.data]},"delta"===e.type?{id:he.ReferenceBlock,data:new Qe(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:he.BlockAdditions,data:[{id:he.BlockMore,data:[{id:he.BlockAddID,data:1},{id:he.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:he.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:he.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.Rt.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:he.Cluster,size:this.format.Rt.appendOnly?-1:5,data:[{id:he.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(U(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){U(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=/* @__PURE__ */new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)U(this.cues),this.cues.data.push({id:he.CuePoint,data:[{id:he.CueTime,data:Math.max(0,r)},...n.map(e=>({id:he.CueTrackPositions,data:[{id:he.CueTrack,data:e.track.id},{id:he.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(),U(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 Ze(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),U(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},Wn=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e},Xn=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}),Zn=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})()}},Qn=class extends Zn{constructor(t){if(super(),this.we=null,!ge.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${ge.join(", ")}.`);this.Ot=t}},Yn=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Jn=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 ft,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&&(U(this.outputWidth),U(this.outputHeight),U("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=ct(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(xt(e)&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof ui?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new ui(i)):o.push(new ui(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 ui&&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),U(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{U(this.encoder);const e=t.toVideoFrame(),i=it(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;U(this.frameRateLastSample);const r=Math.round((t-this.frameRateLastTimestamp)*i);for(let o=1;o<r;o++){const t={stack:[],error:void 0,hasError:!1};try{const r=Wn(t,this.frameRateLastSample.clone(),!1);r.setTimestamp(this.frameRateLastTimestamp+o/i),r.setDuration(1/i),await this.processAndEncode(r,e)}catch(n){t.error=n,t.hasError=!0}finally{Xn(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=Ni(this.encodingConfig.quality,this.encodingConfig.bitrate);U(void 0!==e);const i=Pi({...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=Vi.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=$i(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 We))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.");Yn(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=We.fromEncodedChunk(t,r);const o=it(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&W(e.description)[4]);return Wt(t,i)}return Ht(t)})(i,e)){const e=i[t.offset],r=Xt(e);if(r>=Bt.NON_IDR_SLICE&&r<=Bt.SLICE_DPC)return"delta";if(r===Bt.IDR)return"key";if(r===Bt.SEI&&!yt()){const e=i.subarray(t.offset,t.offset+t.length),r=Zt(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=G(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&W(e.description)[21]);return Wt(t,i)}return Ht(t)})(i,e)){const e=Jt(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)*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);U(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:nt(t),U(!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})),Yn(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=/* @__PURE__ */new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(o,s)=>{if(!this.alphaEncoder)return void n(o,null,s);const a=this.alphaFrameQueue.shift();U(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=/* @__PURE__ */new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(o,s)=>{r--;const a=t.shift();for(U(void 0!==a),n(a.chunk,o,a.meta),i++;e.length>0&&e[0]===i;){e.shift();const i=t.shift();U(void 0!==i),n(i.chunk,null,i.meta)}},error:t=>{t.stack=o,this.setError(t)}}),this.alphaEncoder.configure(s)}}U(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=ct(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}},Kn=null,to=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!Kn){const t=new Blob([`(${eo.toString()})()`],{type:"application/javascript"});Kn=URL.createObjectURL(t)}this.worker=new Worker(Kn),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=rt();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=/* @__PURE__ */new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},eo=()=>{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)}}},io=class extends Qn{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(!ge.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${ge.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 Ii))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof Ii)&&(!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&&gi(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.");Ci(t.codec,t)})(e),super(e.codec),this.Ee=new Jn(this,e),this.Te=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 ui(this.Te,{timestamp:t,duration:e});return this.Ee.add(r,!0,i)}ye(t){return this.Ee.flushAndClose(t)}},ro=class extends Zn{constructor(t){if(super(),this.we=null,!Te.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${Te.join(", ")}.`);this.Ot=t}},no=class extends Zn{constructor(t){if(super(),this.we=null,!ke.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${ke.join(", ")}.`);this.Ot=t}},oo=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>ge.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>Te.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>ke.includes(t))}ke(t){return""}_e(){return!1}},so=class extends oo{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&&(!_t(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}get negativeTimestampSupport(){return"full"}Me(t){return new Ln(t,this)}_e(){return"fragmented"===this.Rt.fastStart}},ao=class extends so{constructor(t){super(t)}get Ae(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ge,...Ee,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ke]}ke(t){return(new co).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},ho=class extends so{constructor(t){super(t)}get Ae(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ge,...Ee,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ke]}},co=class extends so{constructor(t){super(t)}get Ae(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ge,...Te]}ke(t){return(new ao).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},lo=class extends oo{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&&(!_t(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 Hn(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[...ge,...Ee,...xe.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...ke]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},uo=class extends lo{constructor(t){super(t)}getSupportedCodecs(){return[...ge.filter(t=>["vp8","vp9","av1"].includes(t)),...Te.filter(t=>["opus","vorbis"].includes(t)),...ke]}get Ae(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}ke(t){return(new lo).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},fo=["video","audio","subtitle"],po=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}},mo=class extends po{constructor(t,e,i,r){super(t,e,"video",i,r)}},wo=class extends po{constructor(t,e,i,r){super(t,e,"audio",i,r)}},vo=class extends po{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},bo=class t{constructor(){this.Se=/* @__PURE__ */new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this.Se.add(e),e.Se.add(this)}},yo=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&!(t=>dt.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 bo)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof bo))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},go=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(xt(e))throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new bo,this.tracks=[],this.Ie=null,this.Be=/* @__PURE__ */new Set,this.Fe=null,this.Oe=null,this.Re=null,this.$e=null,this.De=new et,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 oo))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof Fn||t.target instanceof Vn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof Fn&&this.Ue(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof Fn)&&"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 Fn&&this.Ue(this.je),this.ge=t.format.Me(this)}Le(t){U(this.ze instanceof Vn);const e=this.ze.getTarget(t),i=t=>{if(!(t instanceof Fn))throw new TypeError("getTarget must return a Target.");return t};return xt(e)?e.then(i):i(e)}async qe(t){U(this.ze instanceof Vn);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(U(null!==this.je),this.je instanceof Fn)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 Fn)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 xt(e)?this.Ce=e.then(i):i(e)}fe(t){return this.Fe??=(async()=>{const e=await this.Pe(),i=new Bn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof Qn))throw new TypeError("source must be a VideoSource.");if(yo(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&&je({decoderConfig:e.decoderConfig},t.Ot),void 0!==e.primingPacket){if(!(e.primingPacket instanceof We))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 mo(this.tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof ro))throw new TypeError("source must be an AudioSource.");if(yo(e),void 0!==e.decoderConfig&&qe({decoderConfig:e.decoderConfig},t.Ot),void 0!==e.primingPacket){if(!(e.primingPacket instanceof We))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 wo(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof no))throw new TypeError("source must be a SubtitleSource.");yo(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.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 Ot||e instanceof Rt||Pt(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.$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 fo)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 fo){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 xo(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o($());let s=!1;const a=setTimeout(()=>h(()=>o(D(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o($()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var Eo=["vp9","vp8"],To=["avc"],ko=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 ao:new uo,s="stream"===r.kind?new Dn(r.writable,{chunked:!0}):new $n,a=new go({format:o,target:s}),h=new io(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 xo(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=b(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 xo(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 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.Je(u);throw i?.({state:"error",message:t.message}),t}}async We(t){const e=V(t),i="mp4"===t.format?new ao:new uo,r="mp4"===t.format?To:Eo,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t));for(const o of n)if(await Di(o,{width:e.width,height:e.height,quality:this.Qe(e),alpha:e.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:e.hardwareAcceleration,contentHint:"text"}))return V(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.`)}Qe(t){return new Ii(t.quality)}He(){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.")}Ye(t,e){return e?new Promise((i,r)=>{if(e.aborted)return void r($());const n=()=>r($());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 $()}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 N(t)}Xe(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},_o=class{Ke;T;k;constructor(t,e){this.Ke=new ko,this.T=t,this.k=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.Z(e,t),r=V(i);if("file-system"===t.destination){const n=await this.ti((new o).$resolve(t.filename,`.${e}`),r.mimeType);try{await this.ei(i,n,t.onProgress)}catch(a){try{await(n.abort?.(a))}catch{}throw a}return}const n=await this.ei(i,{kind:"blob"},t.onProgress);if(!n)throw new R("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new s).$downloadFile(n,t.filename,`.${e}`)}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.Z(e,t);V(i);const r=await this.ei(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 ei(t,e,i){const r=new y(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 f||m(n))throw N(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 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))}}}},Mo=class extends i{$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),l=c(n,a)?.character??" ";i.push({x:t,y:s,character:l,foreground:g(e.primaryColorPixels,r),background:g(e.secondaryColorPixels,r),transform:{invert:h.isInverted,flipX:h.flipHorizontal,flipY:h.flipVertical,rotation:h.rotation}}),o++}return i}},Ao="1.9.0-beta.2",So="textmode.document",Co="2.0.0",Po="object-rows-v1",Io={[t.NORMAL]:"normal",[t.ADDITIVE]:"additive",[t.MULTIPLY]:"multiply",[t.SCREEN]:"screen",[t.SUBTRACT]:"subtract",[t.DARKEN]:"darken",[t.LIGHTEN]:"lighten",[t.OVERLAY]:"overlay",[t.SOFT_LIGHT]:"softLight",[t.HARD_LIGHT]:"hardLight",[t.COLOR_DODGE]:"colorDodge",[t.COLOR_BURN]:"colorBurn",[t.DIFFERENCE]:"difference",[t.EXCLUSION]:"exclusion"},Bo=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:Ao}}: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:Po,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 Mo).$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:Io[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.di(t),cells:this.ui(t,e)}}$generateJSONData(e,i={},r=/* @__PURE__ */new Date){const n=this.Z(i),o=this.hi(n,r);if("all"===n.target){const i=function(e){return[e.layers.base,...e.layers.all].map(i=>{const r=u(e,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??t.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(e),r=i[0].grid;return{format:So,formatVersion:Co,target:"all",...o?{metadata:o}:{},canvas:{width:r.width,height:r.height},layers:i.map(t=>this.fi(t,n))}}const s=u(e,n.layer);return{format:So,formatVersion:Co,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=/* @__PURE__ */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 s).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename,".json")}},Fo=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 Oo(t){return new Fo("ZIP_EXPORT_ABORTED","ZIP frame-sequence export was cancelled.",t)}function Ro(t){if(t instanceof Fo)return t;if(m(t))return Oo(t);if(t instanceof f){if("FRAME_SEQUENCE_TIMEOUT"===t.code)return new Fo("ZIP_EXPORT_TIMEOUT",t.message,t);if("FRAME_SEQUENCE_BUSY"===t.code)return new Fo("ZIP_EXPORT_BUSY",t.message,t);if("FRAME_SEQUENCE_DISPOSED"===t.code)return new Fo("ZIP_EXPORT_DISPOSED",t.message,t)}return new Fo("ZIP_EXPORT_FAILED",t instanceof Error?t.message:"ZIP frame-sequence export failed.",t)}var $o=new TextEncoder;function Do(t){if(!t||"object"!=typeof t||Array.isArray(t))return{};const e={...t};return delete e.filename,delete e.format,e}function No(t){const e=new M;return{extension:`.${t}`,compression:"store",getDimensions({canvas:t,frameOptions:e}){const i=Do(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,{...Do(r),format:t}),o=_[t];if(n.type.toLowerCase()!==o)throw new Fo("ZIP_EXPORT_ENCODING_UNSUPPORTED",`The browser returned '${n.type||"an unknown format"}' instead of '${o}'.`);return new Uint8Array(await n.arrayBuffer())}}}function Vo(t,e){return{extension:`.${t}`,compression:"deflate",getDimensions({frameOptions:i}){const r=Do(i),n="json"===t&&"all"===r.target?u(e):u(e,r.layer);return{width:n.grid.width,height:n.grid.height}},async serialize({frameOptions:i,createdAt:r}){const n=Do(i);let o;return o="svg"===t?(new k).$generateSVG(e,n):"json"===t?(new Bo).$generateJSONString(e,n,r):(new A).$generateTXT(e,n),$o.encode(o)}}}var Uo=Uint8Array,zo=Uint16Array,jo=Int32Array,Lo=new Uo([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]),qo=new Uo([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]),Go=new Uo([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ho=function(t,e){for(var i=new zo(31),r=0;r<31;++r)i[r]=e+=1<<t[r-1];var n=new jo(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}},Wo=Ho(Lo,2),Xo=Wo.b,Zo=Wo.r;Xo[28]=258,Zo[258]=28;for(var Qo=Ho(qo,0),Yo=(Qo.b,Qo.r),Jo=new zo(32768),Ko=0;Ko<32768;++Ko){var ts=(43690&Ko)>>1|(21845&Ko)<<1;ts=(61680&(ts=(52428&ts)>>2|(13107&ts)<<2))>>4|(3855&ts)<<4,Jo[Ko]=((65280&ts)>>8|(255&ts)<<8)>>1}var es=function(t,e,i){for(var r=t.length,n=0,o=new zo(e);n<r;++n)t[n]&&++o[t[n]-1];var s,a=new zo(e);for(n=1;n<e;++n)a[n]=a[n-1]+o[n-1]<<1;if(i){s=new zo(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[Jo[d]>>h]=c}else for(s=new zo(r),n=0;n<r;++n)t[n]&&(s[n]=Jo[a[t[n]-1]++]>>15-t[n]);return s},is=new Uo(288);for(Ko=0;Ko<144;++Ko)is[Ko]=8;for(Ko=144;Ko<256;++Ko)is[Ko]=9;for(Ko=256;Ko<280;++Ko)is[Ko]=7;for(Ko=280;Ko<288;++Ko)is[Ko]=8;var rs=new Uo(32);for(Ko=0;Ko<32;++Ko)rs[Ko]=5;var ns=/*#__PURE__*/es(is,9,0),os=/*#__PURE__*/es(rs,5,0),ss=function(t){return(t+7)/8|0},as=function(t,e,i){return(null==e||e<0)&&(e=0),(null==i||i>t.length)&&(i=t.length),new Uo(t.subarray(e,i))},hs=["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"],cs=function(t,e,i){var r=new Error(e||hs[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,cs),!i)throw r;return r},ls=function(t,e,i){i<<=7&e;var r=e/8|0;t[r]|=i,t[r+1]|=i>>8},ds=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},us=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:ys,l:0};if(1==n){var s=new Uo(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 zo(u+1),p=fs(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 Uo(f),l:p}},fs=function(t,e,i){return-1==t.s?Math.max(fs(t.l,e,i+1),fs(t.r,e,i+1)):e[t.s]=i},ps=function(t){for(var e=t.length;e&&!t[--e];);for(var i=new zo(++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}},ms=function(t,e){for(var i=0,r=0;r<e.length;++r)i+=t[r]*e[r];return i},ws=function(t,e,i){var r=i.length,n=ss(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)},vs=function(t,e,i,r,n,o,s,a,h,c,l){ls(e,l++,i),++n[256];for(var d=us(n,15),u=d.t,f=d.l,p=us(o,15),m=p.t,w=p.l,v=ps(u),b=v.c,y=v.n,g=ps(m),x=g.c,E=g.n,T=new zo(19),k=0;k<b.length;++k)++T[31&b[k]];for(k=0;k<x.length;++k)++T[31&x[k]];for(var _=us(T,7),M=_.t,A=_.l,S=19;S>4&&!M[Go[S-1]];--S);var C,P,I,B,F=c+5<<3,O=ms(n,is)+ms(o,rs)+s,R=ms(n,u)+ms(o,m)+s+14+3*S+ms(T,M)+2*T[16]+3*T[17]+7*T[18];if(h>=0&&F<=O&&F<=R)return ws(e,l,t.subarray(h,h+c));if(ls(e,l,1+(R<O)),l+=2,R<O){C=es(u,f,0),P=u,I=es(m,w,0),B=m;var $=es(M,A,0);for(ls(e,l,y-257),ls(e,l+5,E-1),ls(e,l+10,S-4),l+=14,k=0;k<S;++k)ls(e,l+3*k,M[Go[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];ls(e,l,$[U]),l+=M[U],U>15&&(ls(e,l,V[k]>>5&127),l+=V[k]>>12)}}}else C=ns,P=is,I=os,B=rs;for(k=0;k<a;++k){var z=r[k];if(z>255){ds(e,l,C[257+(U=z>>18&31)]),l+=P[U+257],U>7&&(ls(e,l,z>>23&31),l+=Lo[U]);var j=31&z;ds(e,l,I[j]),l+=B[j],j>3&&(ds(e,l,z>>5&8191),l+=qo[j])}else ds(e,l,C[z]),l+=P[z]}return ds(e,l,C[256]),l+P[256]},bs=/*#__PURE__*/new jo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ys=/*#__PURE__*/new Uo(0),gs=/*#__PURE__*/function(){for(var t=/* @__PURE__ */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}(),xs=function(t,e,i){for(;i;++e)t[e]=i,i>>>=8},Es=/* @__PURE__ */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 Uo(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 Uo(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 Uo(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=bs[e-1],u=d>>13,f=8191&d,p=(1<<i)-1,m=o.p||new zo(32768),w=o.h||new zo(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 jo(25e3),x=new zo(288),E=new zo(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=vs(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|Zo[O]<<18|Yo[R];var H=31&Zo[O],W=31&Yo[R];k+=Lo[H]+qo[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=vs(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=ws(h,l+1,t.subarray(_,X))}o.i=s}return as(a,0,r+ss(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||cs(5),this.s.l&&cs(4);var i=t.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var r=new Uo(-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=ys)},t.prototype.flush=function(t){if(this.ondata||cs(5),this.s.l&&cs(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,t){var e=new Uo(6);e[0]=this.s.r>>3;var i=ws(e,this.s.r,ys);this.s.r=0,this.ondata(e.subarray(0,i>>3),!1)}},t}(),Ts="undefined"!=typeof TextEncoder&&/*#__PURE__*/new TextEncoder,ks="undefined"!=typeof TextDecoder&&/*#__PURE__*/new TextDecoder;try{ks.decode(ys,{stream:!0})}catch(za){}function _s(t,e){if(e){for(var i=new Uo(t.length),r=0;r<t.length;++r)i[r]=t.charCodeAt(r);return i}if(Ts)return Ts.encode(t);var n=t.length,o=new Uo(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 Uo(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 as(o,0,s)}var Ms=function(t){var e=0;if(t)for(var i in t){var r=t[i].length;r>65535&&cs(9),e+=r+4}return e},As=function(t,e,i,r,n,o,s,a){var h=r.length,c=i.extra,l=a&&a.length,d=Ms(c);xs(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)&&cs(10),xs(t,e,f<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,-1!=o&&(xs(t,e,i.crc),xs(t,e+4,o<0?-o-2:o),xs(t,e+8,i.size)),xs(t,e+12,h),xs(t,e+14,d),e+=16,null!=s&&(xs(t,e,l),xs(t,e+6,i.attrs),xs(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;xs(t,e,+p),xs(t,e+2,w),t.set(m,e+4),e+=4+w}return l&&(t.set(a,e),e+=l),e},Ss=/* @__PURE__ */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=gs[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||cs(5),this.c.p(t),this.size+=t.length,e&&(this.crc=this.c.d()),this.process(t,e||!1)},t}(),Cs=/* @__PURE__ */function(){function t(t,e){var i,r=this;e||(e={}),Ss.call(this,t),this.d=new Es(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(za){this.ondata(za,null,e)}},t.prototype.push=function(t,e){Ss.prototype.push.call(this,t,e)},t}(),Ps=/* @__PURE__ */function(){function t(t){this.ondata=t,this.u=[],this.d=1}return t.prototype.add=function(t){var e=this;if(this.ondata||cs(5),2&this.d)this.ondata(cs(4+8*(1&this.d),0,1),null,!1);else{var i=_s(t.filename),r=i.length,n=t.comment,o=n&&_s(n),s=r!=t.filename.length||o&&n.length!=o.length,a=r+Ms(t.extra)+30;r>65535&&this.ondata(cs(11,0,1),null,!1);var h=new Uo(a);As(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 Uo(16);xs(o,0,134695760),xs(o,4,t.crc),xs(o,8,p),xs(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(cs(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+Ms(f.extra)+(f.o?f.o.length:0);for(var o,s,a,h,c,l=new Uo(i+22),d=0,u=this.u;d<u.length;d++){var f=u[d];As(l,t,f,f.f,f.u,-f.c-2,e,f.o),t+=46+f.f.length+Ms(f.extra)+(f.o?f.o.length:0),e+=f.b}o=l,s=t,a=this.u.length,h=i,c=e,xs(o,s,101010256),xs(o,s+8,a),xs(o,s+10,a),xs(o,s+12,h),xs(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}(),Is=class{pi;re=[];mi=/* @__PURE__ */new Set;wi;bi;yi="open";gi=0;xi;Ei;Ti;constructor(t,e=4294967295){this.wi=t,this.bi=e,this.pi=new Ps((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 Fo("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 Fo("ZIP_EXPORT_FAILED",`Duplicate ZIP entry: ${t}`);if(this.mi.size>=65535)throw new Fo("ZIP_EXPORT_TOO_LARGE","Classic ZIP archives cannot contain more than 65,535 entries.");if(e.byteLength>this.bi)throw new Fo("ZIP_EXPORT_TOO_LARGE",`A classic ZIP entry cannot exceed ${this.bi.toLocaleString("en-US")} bytes.`);const r="store"===i?new Ss(t):new Cs(t,{level:6});if(r.mtime=this.wi,this.mi.add(t),this.pi.add(r),(r instanceof Ss||r instanceof Cs)&&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=Oo()){"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 Fo("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 Fo("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)}},Bs=/* @__PURE__ */new Set(["png","jpg","webp","svg","json","txt"]),Fs=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 s).$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=Ro(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 Ro(r)}throw e}}async Ci(t,e){const i=this.Ii(t),r=this.Ai.now?.()??/* @__PURE__ */new Date,n=(new o).$resolve(i.filename,".zip",r),s=n.slice(0,-4);let a,h=!1,c=0;try{this.I(i.signal);const t=(l=this.T,{png:No("png"),jpg:No("jpg"),webp:No("webp"),svg:Vo("svg",l),json:Vo("json",l),txt:Vo("txt",l)}),o=this.Ai.resolveSerializer?.(i.format)??t[i.format];a=this.Ai.createWriter?.(r)??new Is(r);const d=a,u=this.Ai.createDriver?.()??new y(this.T,this.k),f=o.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:Ao},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:o.extension});await d.$addEntry(`${s}/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 o.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}`}(s,t,o.extension),n,o.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=Ro(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 Fo("ZIP_EXPORT_INVALID_OPTIONS","ZIP export options are required.");const e=t.format;if("string"!=typeof e||!Bs.has(e))throw new Fo("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 Fo("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 Fo("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 Oo()}st(t){return new Promise((e,i)=>{if(t?.aborted)return void i(Oo());let r=!1;const n=()=>{r||(r=!0,i(Oo()))};t?.addEventListener("abort",n,{once:!0}),setTimeout(()=>{r||(r=!0,t?.removeEventListener("abort",n),e())},0)})}},Os="textmode-export-overlay__stack",Rs="textmode-export-overlay__stack--dense",$s="textmode-export-overlay__stack--compact",Ds="textmode-export-overlay__section",Ns="textmode-export-overlay--dragging",Vs="textmode-export-overlay__label",Us="textmode-export-overlay__field",zs="textmode-export-overlay__field--compact",js="textmode-export-overlay__field--dense",Ls="textmode-export-overlay__field--full",qs="textmode-export-overlay__field--channel",Gs="textmode-export-overlay__input",Hs="textmode-export-overlay__muted",Ws="textmode-export-overlay__button--primary",Xs="textmode-export-overlay__button--secondary",Zs="textmode-export-overlay__button--full",Qs="textmode-export-overlay__link-icon",Ys=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}},Js=class t extends Ys{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(Os,Rs,"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",Qs,[{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(Qs,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}},Ks=class extends Ys{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(Us),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(Vs),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(Hs),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(Us),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(Vs),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(Hs),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(zs,js,Ls,qs),e){case"compact":t.classList.add(zs);break;case"dense":t.classList.add(js);break;case"full":t.classList.add(Ls);break;case"channel":t.classList.add(qs)}}},ta=class extends Ys{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(Gs),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)}}},ea=class extends Ys{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(Xs):this.button.classList.add(Ws),this.props.fullWidth&&this.button.classList.add(Zs),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(Xs),this.button.classList.remove(Ws)):(this.button.classList.add(Ws),this.button.classList.remove(Xs)),this.button.classList.toggle(Zs,Boolean(t.fullWidth))}},ia=class{ht={};Vi(t){const e=this.ht[t];if(e)return e;const i=/* @__PURE__ */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]}},ra=class{yi;ht=/* @__PURE__ */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)}},na=/* @__PURE__ */new Set(["txt","json","svg","image"]),oa=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 na.has(t)}},sa={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)}},aa=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 sa[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}}},ha=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,ca=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||!ha(e.offsetX)||!ha(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(ha(t)&&ha(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{}}},la=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 ca){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(Ns))}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(Ns),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(Ns),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()}},da=class extends Ys{capabilities;Ui;zi=/* @__PURE__ */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()}},ua=class extends Ys{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)}},fa=class extends Ys{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(Gs),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)}},pa=class extends Ys{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new Ks({label:"layer",labelFor:t.id,variant:"full"}),this.select=new ta({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()}},ma=class extends da{layerTarget;trailingSpaces=this.ji(new ua({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.ji(new fa({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.ji(new pa({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Os),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new Ks({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??" "}},wa=class extends da{layerTarget;layerTargetContainer;target=this.ji(new ta({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.ji(new ua({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.ji(new ua({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.ji(new ta({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 pa({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Os);const e=new Ks({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 Ks({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)}},va="textmode-export-number-input",ba=`${va}__field`,ya=`${va}__controls`,ga=`${va}__control`,xa=`${va}__display`,Ea=`${xa}--visible`,Ta=t=>{const e=document.createElement("button");return e.type="button",e.className=ga,e.textContent=t>0?"▲":"▼",e},ka=class extends Ys{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=/* @__PURE__ */new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=va,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=ba,this.display=document.createElement("div"),this.display.className=xa;const e=document.createElement("div");return e.className=ya,this.incrementButton=Ta(1),this.decrementButton=Ta(-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(Ea),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(Ea),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(Ea),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(Ea),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)}},_a=class extends Ys{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?Os:void 0,"stackDense"===this.variant?Rs:void 0,"stackCompact"===this.variant?$s:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?Ds:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},Ma=class extends da{formatSelect=this.ji(new ta({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 ka({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(Os);const e=new _a("row");e.mount(t);const i=new Ks({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Ks({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)}},Aa=class extends da{layerTarget;includeBackground=this.ji(new ua({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.ji(new ta({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.ji(new ka({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.ji(new pa({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Os),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new _a("row");e.mount(t);const i=new Ks({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new Ks({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()}},Sa={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},Ca=class extends Ys{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(Sa)),this.messageElement.classList.add(Sa[t])}},Pa=class extends da{frameCountInput=this.ji(new ka({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.ji(new ka({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.ji(new ka({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.ji(new ka({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 Ca({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(Os);const e=new _a("row");e.mount(t);const i=new Ks({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 Ks({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 _a("row");n.mount(t);const o=new Ks({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 Ks({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}},Ia=class extends da{formatSelect=this.ji(new ta({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));qualitySelect=this.ji(new ta({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 ka({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.ji(new ka({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));hardwareAccelerationSelect=this.ji(new ta({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 ka({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.ji(new ua({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.ji(new Ca({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.ji(new Ca({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(Os);const e=new _a("row");e.mount(t);const i=new Ks({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Ks({label:"quality",labelFor:"textmode-export-video-quality",variant:"compact"});r.mount(e.root),this.qualitySelect.mount(r.root);const n=new _a("row");n.mount(t);const o=new Ks({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 Ks({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 _a("row");a.mount(t);const h=new Ks({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(a.root),this.hardwareAccelerationSelect.mount(h.root);const c=new Ks({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=V(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 Ba(t){return t.capabilities.recording}var Fa=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 Oa(){return{format:Fa.format,txt:{...Fa.txt},json:{...Fa.json},image:{...Fa.image},svg:{...Fa.svg},gif:{...Fa.gif},video:{...Fa.video}}}function Ra(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var $a=class{Li;constructor(){this.Li=Oa()}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=Oa();if(!t)return this.Li.format=e.format,Ra(this.Li.txt,e.txt),Ra(this.Li.json,e.json),Ra(this.Li.image,e.image),Ra(this.Li.svg,e.svg),Ra(this.Li.gif,e.gif),void Ra(this.Li.video,e.video);switch(t){case"format":this.Li.format=e.format;break;case"txt":Ra(this.Li.txt,e.txt);break;case"json":Ra(this.Li.json,e.json);break;case"image":Ra(this.Li.image,e.image);break;case"svg":Ra(this.Li.svg,e.svg);break;case"gif":Ra(this.Li.gif,e.gif);break;case"video":Ra(this.Li.video,e.video)}}},Da=class{T;qi;yi;Gi;Hi;Wi;Xi;Zi=/* @__PURE__ */new Map;Qi=[];Yi;Ji;Ki;tr;er;ir;rr=new Js;nr=new Ks({label:"export format",labelFor:"textmode-export-format",variant:"full"});sr=new ta({id:"textmode-export-format",options:[]});ar=new ea({label:"download file",fullWidth:!0,variant:"primary"});hr=new ea({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 ra((t=>({format:t,isBusy:!1}))(n)),this.Gi=new ia,this.Hi=new aa(e,this.Gi),this.Wi=new oa(e),this.Xi=r,this.cr=n,this.yr(),this.gr()}$mount(){this.Er(),this.Tr(),this.ir=new la(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",Os),this.Ji.appendChild(this.Ki),document.body.appendChild(this.Yi)}Tr(){this.rr.mount(this.Ki);const t=document.createElement("div");t.classList.add(Ds),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(Os,$s),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(Os,Rs),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&&Ba(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&&Ba(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(Ba(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(Ba(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 Na=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob","saveZip","toZipBlob"],Va=class{api;k;Ir=/* @__PURE__ */new Set;Br=new w;Fr;Or;v=!1;constructor(t,e){this.k=e;const i={saveCanvas:async(e={})=>(this.Rr(),(new M).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.Rr(),(new M).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.Rr(),(new M).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.Rr(),(new k).$saveSVG(t,e)},saveStrings:(e={})=>{this.Rr(),(new A).$saveTXT(t,e)},toSVG:(e={})=>(this.Rr(),(new k).$generateSVG(t,e)),toString:(e={})=>(this.Rr(),(new A).$generateTXT(t,e)),toJSON:(e={})=>(this.Rr(),(new Bo).$generateJSONData(t,e)),toJSONString:(e={})=>(this.Rr(),(new Bo).$generateJSONString(t,e)),saveJSON:(e={})=>{this.Rr(),(new Bo).$saveJSON(t,e)},saveGIF:(e={})=>this.$r("gif",e.signal,i=>new O(t,t=>this.k(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.$r("gif",e.signal,i=>new O(t,t=>this.k(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.$r("video",e.signal,i=>new _o(t,t=>this.k(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.$r("video",e.signal,i=>new _o(t,t=>this.k(t)).$generateVideoBlob({...e,signal:i})),saveZip:async e=>this.$r("zip",e?.signal,i=>new Fs(t,t=>this.k(t)).$saveZIP({...e,signal:i}),t=>this.Dr(e,t)),toZipBlob:async e=>this.$r("zip",e?.signal,i=>new Fs(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 $a,n=new Da(t,e,r,function(t,e=(()=>{const t=Oa();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new ma({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new wa({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new Ma({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Aa({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new Pa({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new Ia({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:()=>d(t),getLayerById:e=>d(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 N(o);if("zip"===t){const t=Ro(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.")}},Ua={name:"textmode.export.js",install(t,e){const i=new Va(t,t=>e.on("postDraw",t));try{for(const t of Na)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=Ua);export{Ua as ExportPlugin,So as TEXTMODE_DOCUMENT_FORMAT,Co as TEXTMODE_DOCUMENT_FORMAT_VERSION,Po as TEXTMODE_OBJECT_ROWS_ENCODING,Fo as ZIPExportError};
|
|
1
|
+
import{LayerBlendMode as t}from"textmode.js";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var e=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),i=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},r=new TextEncoder;function n(t,e){let i="",n=0;for(const o of t){const t=r.encode(o).byteLength;if(n+t>e)break;i+=o,n+=t}return i}var o=class{$resolve(t,e,i=/* @__PURE__ */new Date){const n=e.toLowerCase(),o=t?.trim(),s=o?.toLowerCase().endsWith(n)?o.slice(0,-n.length):o;return`${this.$sanitizeStem(s,i,255-r.encode(e).length)}${n}`}$sanitizeStem(t,e=/* @__PURE__ */new Date,i=255){const r=this.$defaultStem(e);return t?.trim()&&n(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,"")||n(r,i)}$defaultStem(t=/* @__PURE__ */new Date){return`textmode-export-${t.toISOString().slice(0,19).replace(/:/g,"-")}`}},s=class{$downloadFile(t,e,i){const r=i?(new o).$resolve(e,i):(new o).$sanitizeStem(e),n=URL.createObjectURL(t),s=document.createElement("a");try{s.href=n,s.download=r,s.style.display="none",s.rel="noopener",document.body.appendChild(s),s.click()}finally{s.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}}},a=/* @__PURE__ */new WeakMap;function h(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function c(t,e){let i=a.get(t);if(!i){i=/* @__PURE__ */new Map;for(const e of t.characters)i.set(h(e.color),e);a.set(t,i)}return i.get(e)}function l(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function d(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:l(t,e),layer:e}))}function u(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:l(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}var f=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 p(){return new f("FRAME_SEQUENCE_ABORTED","Frame-sequence capture was cancelled.")}function m(t){return t instanceof f&&"FRAME_SEQUENCE_ABORTED"===t.code||t instanceof DOMException&&"AbortError"===t.name}var w=class{m=!1;v=!1;acquire(){if(this.v)throw new f("FRAME_SEQUENCE_DISPOSED","The textmode export plugin has been disposed.");if(this.m)throw new f("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}},v=1e6;function b(t,e){const i=Math.round(t*v/e),r=Math.max(i+1,Math.round((t+1)*v/e));return{startSeconds:i/v,centerSeconds:(i+Math.floor((r-i)/2))/v,endSeconds:r/v,durationSeconds:(r-i)/v}}var y=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=b(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(/* @__PURE__ */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(p());let s=!1;const a=t=>{s||(s=!0,clearTimeout(c),i?.removeEventListener("abort",h),t())},h=()=>a(()=>o(p())),c=setTimeout(()=>a(()=>o(function(t){return new f("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 p()}};function g(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var x=class extends i{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=g(t.primaryColorPixels,s),c=g(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}},E=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}},T=class{H;constructor(){this.H=new E}$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=c(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:l}=t.primaryColor,d=`rgba(${s},${a},${h},${l/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.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,"><")}},k=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 x,r=new T,n=this.Z(e),o=u(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 s).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename,".svg")}},_={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},M=class{Z(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}Y(t){if(!(t.format in _))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(/* @__PURE__ */new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},_[e.format])})}async $saveImage(t,e={}){const i=this.Z(e);this.Y(i);const r=await this.$toImageBlob(t,e);(new s).$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({[_[i.format]]:r});await navigator.clipboard.write([n])}},C=class{Z(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}J(t,e){const r=new i,n=u(t,e.layer),o=r.$extractFramebufferData(n.drawFramebuffer),s=[];let a=0;for(let i=0;i<n.grid.rows;i++){let t="";for(let i=0;i<n.grid.cols;i++){const i=4*a,s=r.$getEncodedCharacterValue(o.characterPixels,i);t+=c(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 s).$downloadFile(n,i.filename,".txt")}},A=/* @__PURE__ */e(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>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=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,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=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth: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}),S='(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',P="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",S],{type:"text/javascript;charset=utf-8"});function I(t){let e;try{if(e=P&&(self.URL||self.webkitURL).createObjectURL(P),!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(S),{name:t?.name})}}var B=class{K;tt=/* @__PURE__ */new Map;et;it=0;v=!1;constructor(t,e,i,r,n){this.K=new I,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()}},F=A(),$=class{T;k;constructor(t,e){this.T=t,this.k=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new s).$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 y(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,F.GIFEncoder)():null,h="undefined"==typeof Worker?null:new B(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,F.quantize)(t,256,{}),s=(0,F.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)})}},O=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function R(){return new O("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function D(t,e){return new O("VIDEO_EXPORT_TIMEOUT",t,e)}function N(t){return t instanceof O?t:m(t)?R():t instanceof f&&"FRAME_SEQUENCE_TIMEOUT"===t.code?D(t.message,t):new O("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}function V(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new O("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 O("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 U(t){if(!t)throw new Error("Assertion failed.")}var z,j=Math.PI/180,L=180/Math.PI,q=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},H=[1,0,0,0,1,0,0,0,1],G=t=>{const e=t*j,i=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[i,r,0,-r,i,0,0,0,1]},W=(t,e)=>[1,0,0,0,1,0,t,e,1],X=(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},Z=t=>t&&t[t.length-1],Q=t=>t>=0&&t<2**32,Y=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)},J=t=>{const e=Y(t);return e%2==0?-e/2:(e+1)/2},K=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),tt=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),et=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)}},it=(/* #__PURE__ */void 0!==globalThis.TextDecoder&&globalThis.TextDecoder,new et),rt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},nt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ot={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},st=t=>!t||null==t.primaries&&null==t.transfer&&null==t.matrix&&null==t.fullRange,at=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),ht=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}},ct=t=>[...t].map(t=>t.toString(16).padStart(2,"0")).join(""),lt=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,dt=(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},ut=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},ft=t=>{throw new Error(`Unexpected value: ${t}`)},pt=(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},mt=(t,e,i)=>Math.max(e,Math.min(i,t)),wt=(t,e)=>Math.round(t/e)*e,vt=(t,e)=>Math.round(t*e)/e,bt=(t,e)=>Math.floor(t*e)/e,yt=t=>{let e=0;for(;0!==t;)t&=t-1,e++;return e},gt=/^[a-z]{3}$/,xt=1e6*(1+Number.EPSILON),Et=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},Tt=null,kt=()=>null!==Tt?Tt:Tt=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),_t=null,Mt=()=>null!==_t?_t:_t="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),Ct=null,At=()=>null!==Ct?Ct:Ct=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),St=null,Pt=/* #__PURE__ */(async()=>{})().constructor,It=t=>t instanceof Pt||t instanceof Promise||"function"==typeof t?.then,Bt=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},Ft=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},Ot=t=>"number"==typeof t&&!Number.isNaN(t),Rt=t=>{U(Number.isInteger(t.num)),U(Number.isInteger(t.den)),U(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}},Dt=(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.`)},Nt=t=>Array.isArray(t)?t:[t],Vt=class{constructor(){this.ht=/* @__PURE__ */new Map}on(t,e,i){this.ht.has(t)||this.ht.set(t,/* @__PURE__ */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)}}},Ut=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"}(z||(z={}));var zt=class t{constructor(){}static get level(){return t.lt}static set level(e){if(e!==z.Silent&&e!==z.Errors&&e!==z.Warnings&&e!==z.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 Vt}static on(e,i,r){return t.dt.on(e,i,r)}static ft(...e){t.dt.ct("error",e),t.lt>=z.Errors&&console.error(...e)}static wt(...e){t.dt.ct("warn",e),t.lt>=z.Warnings&&console.warn(...e)}static vt(...e){t.dt.ct("info",e),t.lt>=z.Info&&console.info(...e)}};zt.lt=z.Info,zt.ut=null;var jt,Lt,qt=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.")}},Ht=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.")}},Gt=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}},Wt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Xt=[-1,1,2,3,4,5,6,8],Zt=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=Xt.indexOf(n);if(-1===o)throw new TypeError(`Unsupported number of channels: ${t.outputNumberOfChannels}`);let s=16;t.objectType>=32&&(s+=6),15===Jt(r)&&(s+=24),e&&(s+=9,15===Jt(t.outputSampleRate)&&(s+=24));const a=Math.ceil(s/8),h=new Uint8Array(a),c=new Gt(h);return Qt(c,t.objectType),Yt(c,r),c.writeBits(4,o),e&&(Yt(c,t.outputSampleRate),Qt(c,2)),c.writeBits(3,0),h},Qt=(t,e)=>{e<32?t.writeBits(5,e):(t.writeBits(5,31),t.writeBits(6,e-32))},Yt=(t,e)=>{const i=Jt(e);t.writeBits(4,i),15===i&&t.writeBits(24,e)},Jt=t=>{const e=Wt.indexOf(t);return-1===e?15:e},Kt=[48e3,44100,32e3],te=[24e3,22050,16e3],ee="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"}(jt||(jt={})),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"}(Lt||(Lt={}));var ie,re=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})},ne=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=pt(r,i,!1):(U(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},oe=t=>31&t,se=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)},ae=(new Uint8Array([0,0,0,1]),t=>{try{const e=[],i=[],r=[];for(const a of re(t)){const n=t.subarray(a.offset,a.offset+a.length),o=oe(n[0]);o===jt.SPS&&e.length<31?e.push(n):o===jt.PPS&&i.length<255?i.push(n):o===jt.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=le(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 zt.ft("Error building AVC Decoder Configuration Record:",e),null}}),he=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){U(null!==t.bitDepthLumaMinus8),U(null!==t.bitDepthChromaMinus8),U(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)},ce={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}},le=t=>{try{const e=se(t),i=new Gt(e);if(i.skipBits(1),i.skipBits(2),7!==i.readBits(5))return null;const r=i.readAlignedByte(),n=i.readAlignedByte(),o=i.readAlignedByte();Y(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=Y(i),3===s&&(c=i.readBits(1)),a=Y(i),h=Y(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+J(i)+256)%256),r=0===n?r:n}Y(i);const l=Y(i);if(0===l)Y(i);else if(1===l){i.skipBits(1),J(i),J(i);const t=Y(i);for(let e=0;e<t;e++)J(i)}Y(i),i.skipBits(1);const d=Y(i),u=Y(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=Y(i),e=Y(i),r=Y(i),n=Y(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=ce[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)&&(Y(i),Y(i)),i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.skipBits(1));const t=i.readBits(1);t&&de(i);const e=i.readBits(1);e&&de(i),(t||e)&&i.skipBits(1),i.skipBits(1),_=i.pos,M=i.readBits(1),M&&(i.skipBits(1),Y(i),Y(i),Y(i),Y(i),T=Math.min(Y(i),16),k=Math.min(Y(i),16))}if(null===T)if(U(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=qe.find(t=>t.level>=o)??Z(qe),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);T=r,k=r}return U(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 zt.ft("Error parsing AVC SPS:",e),null}},de=t=>{const e=Y(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)Y(t),Y(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},ue=t=>t>>1&63,fe=t=>{try{const e=[],i=[],r=[],n=[],o=65535;for(const c of re(t)){const s=t.subarray(c.offset,c.offset+c.length),a=ue(s[0]);a===Lt.VPS_NUT&&e.length<o?e.push(s):a===Lt.SPS_NUT&&i.length<o?i.push(s):a===Lt.PPS_NUT&&r.length<o?r.push(s):(a===Lt.PREFIX_SEI_NUT||a===Lt.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 Gt(se(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}=pe(e,i);Y(e);const l=Y(e);let d=0;3===l&&(d=e.readBits(1));const u=Y(e),f=Y(e);let p=u,m=f;if(e.readBits(1)){const t=Y(e),i=Y(e),r=Y(e),n=Y(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=Y(e),v=Y(e);Y(e);const b=e.readBits(1)?0:i;let y=0;for(let t=b;t<=i;t++)Y(e),y=Y(e),Y(e);Y(e),Y(e),Y(e),Y(e),Y(e),Y(e),e.readBits(1)&&e.readBits(1)&&me(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),Y(e),Y(e),e.skipBits(1));const g=Y(e);if(we(e,g),e.readBits(1)){const t=Y(e);for(let i=0;i<t;i++)Y(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=be(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 zt.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 Gt(se(t));e.skipBits(16),Y(e),Y(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),Y(e),Y(e),J(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&Y(e),J(e),J(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:Lt.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Lt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Lt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ue(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 zt.ft("Error building HEVC Decoder Configuration Record:",e),null}},pe=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=/* @__PURE__ */new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},me=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&&J(t);for(let e=0;e<i;e++)J(t)}else Y(t)},we=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=ve(t,r,e,i)},ve=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(Y(t)+1):e-1,t.readBits(1),Y(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=Y(t),i=Y(t);for(let r=0;r<e;r++)Y(t),t.readBits(1);for(let r=0;r<i;r++)Y(t),t.readBits(1);n=e+i}return n},be=(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=ce[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)&&(Y(t),Y(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(Y(t),Y(t),Y(t),Y(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&Y(t),t.readBits(1)&&ye(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=Y(t),Y(t),Y(t),Y(t),Y(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},ye=(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?Y(t):i=1===t.readBits(1);let s=1;i||(s=Y(t)+1),r&&ge(t,s,o),n&&ge(t,s,o)}},ge=(t,e,i)=>{for(let r=0;r<e;r++)Y(t),Y(t),i&&(Y(t),Y(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"}(ie||(ie={}));var xe,Ee={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}},Te=t=>{const e=new Gt(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=Z(Ge).level;for(const d of Ge)if(h<=d.maxPictureSize){c=d.level;break}const l=Ee[o];return{profile:r,level:c,bitDepth:n,chromaSubsampling:s,videoFullRangeFlag:a,colourPrimaries:l?.colourPrimaries??2,transferCharacteristics:l?.transferCharacteristics??2,matrixCoefficients:l?.matrixCoefficients??2}},ke=function*(t){const e=new Gt(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);U(e.pos%8==0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+s)},e.skipBits(8*s)}},_e=t=>{for(const{type:e,data:i}of ke(t)){if(1!==e)continue;const t=new Gt(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},Me=t=>{if(t.byteLength<19)throw new Error("Invalid Opus identification header: too short.");const e=tt(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"}(xe||(xe={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var Ce,Ae=[1,2,3,6],Se=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Pe=[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],Ie=[16,16,20,20,0,24,24,0],Be=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Fe=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],$e=[32e3,44100,48e3,0],Oe=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Re=[512,1024,2048,4096],De=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 Gt(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=$e[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*yt(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=Oe[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}}},Ne=t=>{const e=new Uint8Array(20),i=tt(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 Gt(e);return n.seekToByte(13),n.writeBits(2,Math.max(Re.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},Ve=["avc","hevc","vp9","av1","vp8","prores"],Ue=["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"],ze=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],je=[...ze,...Ue],Le=["webvtt"],qe=[{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}],He=[{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}],Ge=[{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}],We=[{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}],Xe=["ap4x","ap4h","apch","apcn","apcs","apco"],Ze=["dtsc","dtsh","dtsl","dtse"],Qe=[{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}],Ye=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=qe.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??Z(qe),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=He.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??Z(He);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.${(Ge.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??Z(Ge)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=We.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??Z(We);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Qe.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 ft(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Je=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]},Ke=/^pcm-([usf])(\d+)(be)?$/,ti=t=>{if(U(Ue.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=Ke.exec(t);let i;return U(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}},ei=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":Xe.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":Ze.includes(t)?"dts":"ulaw"===t?"ulaw":"alaw"===t?"alaw":Ke.test(t)?t:"webvtt"===t?"webvtt":null,ii=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Xe],ri=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,ni=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,oi=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,si=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ai=(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(!ii.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&&!at(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(rt);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(nt);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(ot);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(!ri.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(!ni.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(!oi.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(!si.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(Xe.some(e=>t.decoderConfig.codec.startsWith(e))&&!Xe.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: ${Xe.join(", ")}.`);if(null!==e&&ei(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}'.`)},hi=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],ci=(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(!hi.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&&!at(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(!Ze.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: ${Ze.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!Ue.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ue.join(", ")}).`);if(null!==e&&ei(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}'.`)},li=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.")},di=/* #__PURE__ */new Uint8Array(0),ui=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===di&&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===di}get microsecondTimestamp(){return Math.trunc(xt*this.timestamp)}get microsecondDuration(){return Math.trunc(xt*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)}},fi=class{constructor(t){this.value=t}},pi=class{constructor(t){this.value=t}},mi=class{constructor(t){this.value=t}},wi=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"}(Ce||(Ce={})),Ce.EBML,Ce.Segment,Ce.SeekHead,Ce.Info,Ce.Cluster,Ce.Tracks,Ce.Cues,Ce.Attachments,Ce.Chapters,Ce.Tags;var vi=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,bi=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,yi=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,gi=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap,this.dataOffsets=/* @__PURE__ */new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=vi(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=bi(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=yi(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??vi(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??bi(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 fi)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof pi)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof mi){const e=t.size??yi(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof wi){const e=it.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else ft(t.data)}},xi={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"},Ei=t=>{const e=t.filePos;if(t.remainingLength<7)return null;const i=new Gt(ar(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>=Wt.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=hr(t)}return a<t.filePos-e?null:{objectType:n,samplingFrequencyIndex:o,channelConfiguration:s,frameLength:a,numberOfAacFrames:h,crcCheck:c,startPos:e}},Ti=/* @__PURE__ */e((t,e)=>{e.exports={}}),ki=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 _i=-1/0,Mi=-1/0,Ci=null;"undefined"!=typeof FinalizationRegistry&&(Ci=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-_i>=1e3&&(zt.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."),_i=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-Mi>=1e3&&(zt.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."),Mi=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var Ai=class{constructor(){this.bt=0,this.yt=null}},Si=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Pi=new Set(Si),Ii=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(xt*this.timestamp)}get microsecondDuration(){return Math.trunc(xt*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||!Pi.has(i.format))throw new TypeError("init.format must be one of: "+Si.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&&Dt(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??zi(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?K(e):K(e).slice(),this.Tt=t,this.colorSpace=new Ri(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&&Dt(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 Ri({primaries:null!==t&&t in rt?t:null,transfer:null!==r&&r in nt?r:null,matrix:null!==n&&n in ot?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&&Dt(i.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*xt),duration:Math.trunc((i.duration??0)*xt)||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:Mt(),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 Ri({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Ai))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&&!Si.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=Rt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ci?.register(this,{type:"video",data:this.xt},this)}clone(){if(this.gt)throw new Error("VideoSample is closed.");return U(null!==this.xt),this.xt instanceof Ai?new t(this.xt,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Di(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?(U(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||(Ci?.unregister(this),this.xt instanceof Ai?(this.xt.bt--,0===this.xt.bt&&this.xt.close()):Di(this.xt)?this.xt.close():this.xt=null,this.gt=!0)}allocationSize(t={}){if(Ui(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 Di(this.xt)?this.xt.allocationSize(t):Li(this,t).allocationSize}async copyTo(e,i={}){if(!at(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ui(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(U(null!==this.xt),Di(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 Ai)){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{ki(r)}}}const r=Li(this,i);U(this.format);const n=K(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=ji(this.format);let s;if(this.xt instanceof Ai){let t=this.xt.getDataPlanes();if(It(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)U(this.Tt),U(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");U(t),s=[{data:K(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(U(null!==this.xt),this.xt instanceof Ai){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(It(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 Di(this.xt)?new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.xt instanceof Uint8Array?(U(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&&Vi(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=Ni(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?Oi(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(U(null!==this.xt),this.xt instanceof Ai||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&&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{rotation:i,flip:r}=(n=this.rotation,o=this.flip,s=e.rotate??0,a=e.flip??!1,{rotation:q(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=Ni(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=wt(p,e.roundDimensionsTo??1),m=wt(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 Bi){let e=t(this,w);if(It(e)&&(e=await e),null!==e)return e}const{canvas:v,context:b,isNew:y}=Oi(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()}},Bi=[],Fi=[],$i=0,Oi=(t,e)=>{for(const n of Fi)if(n.canvas.width===t&&n.canvas.height===e)return n.age=$i++,{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 Fi.length>=3&&Fi.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})(Fi,t=>t.age),1),Fi.push({canvas:i,context:r,age:$i++}),{canvas:i,context:r,isNew:!0}},Ri=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(rt);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(nt);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(ot);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}}},Di=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,Ni=(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 U(o>=0),U(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.")},Ui=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.")}},zi=(t,e,i)=>{const r=ji(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},ji=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:ft(t),U(!1)}},Li=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=qi(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 Gi(n,s,o)},qi=(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(!Hi(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},Hi=(t,e)=>{if(null===t)return!0;const i=ji(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},Gi=(t,e,i)=>{const r=ji(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}},Wi=/* @__PURE__ */new Map,Xi=(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&&ei(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.")},Zi=t=>{const e=t.bitrateMode,i=t.quality.Mt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Ye(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}),U(n.length>0),n},Qi=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 Yi):"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?Yi[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=Ji[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&&(U(void 0!==this.Ct),o=mt(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&&(U(null!==o&&n),r=mt((o-n.worst)/(n.best-n.worst),0,1)),h=tr(t,e,i,Ki(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}Bt(t,e,i){return void 0!==this.St?this.St:(U(void 0!==this.Ct),tr(t,e,i,Ki(this.Ct)))}Ft(t){if(Ue.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=Ki(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)}},Yi={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Ji={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:((()=>{if(null!==St)return St;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?St=Number(t[1]):null})()??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}},Ki=t=>.3*Math.exp(2.5538*t),tr=(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)},er=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void U(!1),ir=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,frameRate:s,...a}=e;if(!Ve.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 Qi))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 Qi)&&(!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.");Xi(t,a);const h=rr(n,o)??new Qi("medium");let c;try{c=Zi({codec:t,width:i,height:r,quality:h,framerate:s,...a,alpha:"discard"})}catch{return!1}const l=JSON.stringify(c),d=Wi.get(l);if(d)return d;const u=(async()=>{for(const{config:e}of c)if(nr.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(!Mt())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?er(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return Wi.set(l,u),u},rr=(t,e)=>void 0!==t?t:void 0!==e?e instanceof Qi?e:new Qi({bitrate:e}):void 0,nr=[],or=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,tt(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)}},sr=(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.`)},ar=(t,e)=>{sr(t,e);const i=t.bytes.subarray(t.bufferPos,t.bufferPos+e);return t.bufferPos+=e,i},hr=t=>{sr(t,2);const e=t.view.getUint16(t.bufferPos,!1);return t.bufferPos+=2,e},cr=class{constructor(t){this.mutex=new ht,this.trackTimestampInfo=/* @__PURE__ */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)}}},lr=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,dr=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,ur=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")},fr=class{constructor(t){this.writer=t,this.helper=/* @__PURE__ */new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.writer.write(this.helper);t.length%8!=0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{const e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(const n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);U(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}}},pr=/* #__PURE__ */new Uint8Array(8),mr=/* #__PURE__ */new DataView(pr.buffer),wr=t=>[(t%256+256)%256],vr=t=>(mr.setUint16(0,t,!1),[pr[0],pr[1]]),br=t=>(mr.setInt16(0,t,!1),[pr[0],pr[1]]),yr=t=>(mr.setUint32(0,t,!1),[pr[1],pr[2],pr[3]]),gr=t=>(mr.setUint32(0,t,!1),[pr[0],pr[1],pr[2],pr[3]]),xr=t=>(mr.setInt32(0,t,!1),[pr[0],pr[1],pr[2],pr[3]]),Er=t=>(mr.setUint32(0,Math.floor(t/2**32),!1),mr.setUint32(4,t,!1),[pr[0],pr[1],pr[2],pr[3],pr[4],pr[5],pr[6],pr[7]]),Tr=t=>(mr.setInt32(0,Math.floor(t/2**32),!1),mr.setUint32(4,t,!1),[pr[0],pr[1],pr[2],pr[3],pr[4],pr[5],pr[6],pr[7]]),kr=t=>(mr.setInt16(0,256*t,!1),[pr[0],pr[1]]),_r=t=>(mr.setInt32(0,65536*t,!1),[pr[0],pr[1],pr[2],pr[3]]),Mr=t=>(mr.setInt32(0,2**30*t,!1),[pr[0],pr[1],pr[2],pr[3]]),Cr=(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()},Ar=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},Sr=t=>[_r(t[0]),_r(t[1]),Mr(t[2]),_r(t[3]),_r(t[4]),Mr(t[5]),_r(t[6]),_r(t[7]),Mr(t[8])],Pr=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),Ir=(t,e,i,r,n)=>Pr(t,[wr(e),yr(i),r??[]],n),Br=()=>Pr("styp",[Ar("iso5"),gr(0),Ar("iso5"),Ar("iso6"),Ar("mp41"),Ar("cmfc"),Ar("dash")]),Fr=(t,e)=>{const i=Math.max(0,t.minWrittenTimestamp);let r=Math.max(0,t.maxWrittenEndTimestamp-i);return Number.isFinite(r)||(r=0),Ir("sidx",1,0,[gr(1),gr(oo),Er(ao(i,oo)),Er(0),vr(0),vr(1),gr(2147483647&e),gr(ao(r,oo)),gr(0)])},$r=t=>({type:"mdat",largeSize:t}),Or=t=>Pr("moov",void 0,[Rr(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>Dr(e,t.creationTime)),t.isFragmented?Tn(t.trackDatas):null,Rn(t)]),Rr=(t,e)=>{const i=Math.max(0,...e.map(t=>Math.max(0,ao(ho(t),oo)+ao(t.startTimestampOffset??0,oo)))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!Q(t)||!Q(i),o=n?Er:gr;return Ir("mvhd",+n,0,[o(t),o(t),gr(oo),o(i),_r(1),kr(1),Array(10).fill(0),Sr(H),Array(24).fill(0),gr(r)])},Dr=(t,e)=>{const i=so(t),r=null!==t.startTimestampOffset&&0!==t.startTimestampOffset;return Pr("trak",void 0,[Nr(t,e),r?Vr(t):null,Ur(t,e),void 0!==i.name?Pr("udta",void 0,[Pr("name",[...it.encode(i.name)])]):null])},Nr=(t,e)=>{const i=Math.max(0,ao(ho(t),oo)+ao(t.startTimestampOffset??0,oo)),r=!Q(e)||!Q(i),n=r?Er:gr;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 X(X(W(-e/2,-i/2),t),W(a/2,h/2))})(X(G(e??0),(t=>[t,0,0,0,1,0,0,0,1])(i?-1:1)),t.info.width,t.info.height)}else o=H;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:ft(t);return Ir("tkhd",+r,s,[n(e),n(e),gr(t.track.id),gr(0),n(i),Array(8).fill(0),vr(0),vr(a),kr("audio"===t.type?1:0),vr(0),Sr(o),_r("video"===t.type?t.info.width:0),_r("video"===t.type?t.info.height:0)])},Vr=t=>{const e=t.startTimestampOffset;if(U(null!==e),e>0){const i=ao(e,oo),r=ao(ho(t),oo),n=!Q(i)||!Q(r),o=n?Er:gr,s=n?Tr:xr;return Pr("edts",void 0,[Ir("elst",n?1:0,0,[gr(2),o(i),s(-1),_r(1),o(r),s(0),_r(1)])])}{const r=ao(-e,t.timescale),n=Math.max(0,ao(ho(t),oo)+ao(e,oo)),o=!((i=r)>=-(2**31)&&i<2**31&&Q(n)),s=o?Er:gr,a=o?Tr:xr;return Pr("edts",void 0,[Ir("elst",o?1:0,0,[gr(1),s(n),a(r),_r(1)])])}var i},Ur=(t,e)=>Pr("mdia",void 0,[zr(t,e),qr(!0,jr[t.type],Lr[t.type]),Hr(t)]),zr=(t,e)=>{const i=ao(ho(t),t.timescale),r=!Q(e)||!Q(i),n=r?Er:gr;return Ir("mdhd",+r,0,[n(e),n(e),gr(t.timescale),n(i),vr(Qn(t.track.metadata.languageCode??"und")),vr(0)])},jr={video:"vide",audio:"soun",subtitle:"text"},Lr={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},qr=(t,e,i,r="\0\0\0\0")=>Ir("hdlr",0,0,[t?Ar("mhlr"):gr(0),Ar(e),Ar(r),gr(0),gr(0),Ar(i,!0)]),Hr=t=>Pr("minf",void 0,[Gr[t.type](),Wr(),Qr(t)]),Gr={video:()=>Ir("vmhd",0,1,[vr(0),vr(0),vr(0),vr(0)]),audio:()=>Ir("smhd",0,0,[vr(0),vr(0)]),subtitle:()=>Ir("nmhd",0,0)},Wr=()=>Pr("dinf",void 0,[Xr()]),Xr=()=>Ir("dref",0,0,[gr(1)],[Zr()]),Zr=()=>Ir("url ",0,1),Qr=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return Pr("stbl",void 0,[Yr(t),wn(t),e?xn(t):null,e?En(t):null,bn(t),yn(t),gn(t),vn(t)])},Yr=t=>{let e;if("video"===t.type)e=Jr(qn(t.track.source.$t,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=Gn(t.track.source.$t,t.info.decoderConfig.codec,t.muxer.isQuickTime);U(i),e=nn(i,t)}else"subtitle"===t.type&&(e=mn(Xn[t.track.source.$t],t));return U(e),Ir("stsd",0,0,[gr(1)],[e])},Jr=(t,e)=>Pr(t,[Array(6).fill(0),vr(1),vr(0),vr(0),Array(12).fill(0),vr(e.info.width),vr(e.info.height),gr(4718592),gr(4718592),gr(0),vr(1),wr(18),Ar(ee),Array(13).fill(0),vr(e.info.hasAlphaChannel?32:24),br(65535)],[Hn[e.track.source.$t]?.(e)??null,tn(e),st(e.info.decoderConfig.colorSpace)?null:en(e),Kr(e)]),Kr=t=>0===t.avgBitrate&&0===t.maxBitrate?null:Pr("btrt",[gr(0),gr(t.maxBitrate),gr(t.avgBitrate)]),tn=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:Pr("pasp",[gr(t.info.pixelAspectRatio.num),gr(t.info.pixelAspectRatio.den)]),en=t=>{const e=t.info.decoderConfig.colorSpace;return Pr("colr",[Ar(t.muxer.isQuickTime?"nclc":"nclx"),vr(null!=e?.primaries?rt[e.primaries]:2),vr(null!=e?.transfer?nt[e.transfer]:2),vr(null!=e?.matrix?ot[e.matrix]:2),t.muxer.isQuickTime?[]:wr((e?.fullRange?1:0)<<7)])},rn=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?rt[e.colorSpace.primaries]:1,a=i[6]?Number(i[6]):e.colorSpace?.transfer?nt[e.colorSpace.transfer]:1,h=i[7]?Number(i[7]):e.colorSpace?.matrix?ot[e.colorSpace.matrix]:1;return Ir("vpcC",1,0,[wr(r),wr(n),wr(o),wr(s),wr(a),wr(h),vr(0)])},nn=(t,e)=>{let i,r=0,n=16;const o=Ue.includes(e.track.source.$t);if(o){const t=e.track.source.$t,{sampleSize:i}=ti(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),vr(1),vr(r),vr(0),gr(0),vr(e.info.numberOfChannels),vr(n),vr(0),vr(0),vr(e.info.sampleRate<65536?e.info.sampleRate:0),vr(0)];else{const t=o?0:-2;i=[Array(6).fill(0),vr(1),vr(r),vr(0),gr(0),vr(e.info.numberOfChannels),vr(Math.min(n,16)),br(t),vr(0),vr(e.info.sampleRate<65536?e.info.sampleRate:0),vr(0),o?[gr(1),gr(n/8),gr(e.info.numberOfChannels*n/8)]:[gr(0),gr(0),gr(0)],gr(2)]}return Pr(t,i,[Wn(e.track.source.$t,e.muxer.isQuickTime)?.(e)??null,Kr(e)])},on=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=[...wr(e),...wr(21),...yr(0),...gr(t.maxBitrate),...gr(t.avgBitrate)];if(t.info.decoderConfig.description){const e=K(t.info.decoderConfig.description);i=[...i,...wr(5),...Cr(e.byteLength),...e]}return i=[...vr(1),...wr(0),...wr(4),...Cr(i.length),...i,...wr(6),...wr(1),...wr(2)],i=[...wr(3),...Cr(i.length),...i],Ir("esds",0,0,i)},sn=t=>Pr("wave",void 0,[an(t),hn(t),Pr("\0\0\0\0")]),an=t=>Pr("frma",[Ar(Gn(t.track.source.$t,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),hn=t=>{const{littleEndian:e}=ti(t.track.source.$t);return Pr("enda",[vr(+e)])},cn=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=/* @__PURE__ */new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){U(a.byteLength>=18);const t=Me(K(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return Pr("dOps",[wr(0),wr(e),vr(i),gr(r),br(n),wr(o),...s])},ln=t=>{const e=t.info.decoderConfig?.description;U(e);const i=K(e);return Ir("dfLa",0,0,[...i.subarray(4)])},dn=t=>{const{littleEndian:e,sampleSize:i}=ti(t.track.source.$t);return Ir("pcmC",0,0,[wr(+e),wr(8*i)])},un=t=>{U(t.info.primingPacket);const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new Gt(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=/* @__PURE__ */new Uint8Array(3),r=new Gt(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),Pr("dac3",[...i])},fn=t=>{U(t.info.primingPacket);const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new Gt(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=Ae[o];let d;return d=n<3?Kt[n]/1e3:te[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 Gt(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 Pr("dec3",[...n])},pn=t=>{U(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 Gt(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>=Be.length)return null;const s=Se[e.readBits(4)];if(0===s)return null;const a=Pe[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=Ie[e.readBits(3)];if(0===c)return null;const l=0!==h;return{frameSize:n,sampleRate:s,numberOfChannels:Be[o]+(l?1:0),sampleCount:32*r,channelLayout:Fe[o]|(l?8:0),amode:o,lfePresent:l,bitRate:a,pcmResolution:c}})(t),i=tt(t);let r=e?4*Math.ceil(e.frameSize/4):0,n=null;for(;r+4<=t.length&&1683496997===i.getUint32(r);){const e=De(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 Pr("ddts",[...Ne(e)])},mn=(t,e)=>Pr(t,[Array(6).fill(0),vr(1)],[Zn[e.track.source.$t](e),Kr(e)]),wn=t=>Ir("stts",0,0,[gr(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[gr(t.sampleCount),gr(t.sampleDelta)])]),vn=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return Ir("stss",0,0,[gr(e.length),e.map(([t])=>gr(t+1))])},bn=t=>Ir("stsc",0,0,[gr(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[gr(t.firstChunk),gr(t.samplesPerChunk),gr(1)])]),yn=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=ti(t.track.source.$t);return Ir("stsz",0,0,[gr(e*t.info.numberOfChannels),gr(t.samples.reduce((e,i)=>e+ao(i.duration,t.timescale),0))])}return Ir("stsz",0,0,[gr(0),gr(t.samples.length),t.samples.map(t=>gr(t.size))])},gn=t=>t.finalizedChunks.length>0&&Z(t.finalizedChunks).offset>=2**32?Ir("co64",0,0,[gr(t.finalizedChunks.length),t.finalizedChunks.map(t=>Er(t.offset))]):Ir("stco",0,0,[gr(t.finalizedChunks.length),t.finalizedChunks.map(t=>gr(t.offset))]),xn=t=>Ir("ctts",1,0,[gr(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[gr(t.sampleCount),xr(t.sampleCompositionTimeOffset)])]),En=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;U(t.compositionTimeOffsetTable.length>0),U(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,ao(e.timestamp,t.timescale)),n=Math.max(n,ao(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:Ir("cslg",0,0,[xr(o),xr(e),xr(i),xr(r),xr(n)])},Tn=t=>Pr("mvex",void 0,t.map(kn)),kn=t=>Ir("trex",0,0,[gr(t.track.id),gr(1),gr(0),gr(0),gr(0)]),_n=(t,e)=>Pr("moof",void 0,[Mn(t),...e.map(An)]),Mn=t=>Ir("mfhd",0,0,[gr(t)]),Cn=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},An=t=>Pr("traf",void 0,[Sn(t),Pn(t),In(t)]),Sn=t=>{U(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:Cn(i)};return Ir("tfhd",0,131128,[gr(t.track.id),gr(r.duration),gr(r.size),gr(r.flags)])},Pn=t=>(U(t.currentChunk),Ir("tfdt",1,0,[Er(ao(t.currentChunk.startTimestamp,t.timescale))])),In=t=>{U(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(Cn),n=t.currentChunk.samples.map(e=>ao(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,Ir("trun",1,p,[gr(t.currentChunk.samples.length),gr(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?gr(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?gr(e[o]):[],d?gr(i[o]):[],u?gr(r[o]):[],f?xr(n[o]):[]])])},Bn=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([Er(ao(n.timestamp,t.timescale)),Er(i.moofOffset),gr(i.trafIndex+1),gr(1),gr(r+1)])}return Ir("tfra",1,0,[gr(t.track.id),gr(63),gr(e.length),e])},Fn=()=>Pr("vtte"),$n=(t,e,i,r,n)=>Pr("vttc",void 0,[null!==n?Pr("vsid",[xr(n)]):null,null!==i?Pr("iden",[...it.encode(i)]):null,null!==e?Pr("ctim",[...it.encode(ur(e))]):null,null!==r?Pr("sttg",[...it.encode(r)]):null,Pr("payl",[...it.encode(t)])]),On=t=>Pr("vtta",[...it.encode(t)]),Rn=t=>{const e=[],i=t.format.Ot.metadataFormat??"auto",r=t.output.Rt;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=zn(r);t&&e.push(t)}else if("mdta"===i){const t=jn(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&Dn(e,t.output.Rt);return 0===e.length?null:Pr("udta",void 0,e)},Dn=(t,e)=>{for(const{key:i,value:r}of Bt(e))switch(i){case"title":t.push(Nn("©nam",r));break;case"description":t.push(Nn("©des",r));break;case"artist":t.push(Nn("©ART",r));break;case"album":t.push(Nn("©alb",r));break;case"albumArtist":t.push(Nn("albr",r));break;case"genre":t.push(Nn("©gen",r));break;case"date":t.push(Nn("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(Nn("©cmt",r));break;case"lyrics":t.push(Nn("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:ft(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(Nn(i,r)):r instanceof Uint8Array&&t.push(Pr(i,Array.from(r))))}},Nn=(t,e)=>{const i=it.encode(e);return Pr(t,[vr(i.length),vr(Qn("und")),Array.from(i)])},Vn={"image/jpeg":13,"image/png":14,"image/bmp":27},Un=(t,e)=>{const i=[];for(const{key:r,value:n}of Bt(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:Ln(n)});break;case"description":i.push({key:e?"description":"©des",value:Ln(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:Ln(n)});break;case"album":i.push({key:e?"album":"©alb",value:Ln(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:Ln(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:Ln(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:Ln(n)});break;case"beatsPerMinute":e||i.push({key:"tmpo",value:Pr("data",[gr(21),gr(0),vr(n)])});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:Ln(n)});break;case"date":i.push({key:e?"date":"©day",value:Ln(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:Pr("data",[gr(Vn[t.mimeType]??0),gr(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:Ln(e)})}else i.push({key:"trkn",value:Pr("data",[gr(0),gr(0),vr(0),vr(n),vr(t.tracksTotal??0),vr(0)])});break;case"discNumber":e||i.push({key:"disc",value:Pr("data",[gr(0),gr(0),vr(0),vr(n),vr(t.discsTotal??0),vr(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:ft(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:Ln(n)}):n instanceof Uint8Array?i.push({key:r,value:Pr("data",[gr(0),gr(0),Array.from(n)])}):n instanceof qt&&i.push({key:r,value:Pr("data",[gr(Vn[n.mimeType]??0),gr(0),Array.from(n.data)])}))}return i},zn=t=>{const e=Un(t,!1);return 0===e.length?null:Ir("meta",0,0,void 0,[qr(!1,"mdir","","appl"),Pr("ilst",void 0,e.map(t=>Pr(t.key,void 0,[t.value])))])},jn=t=>{const e=Un(t,!0);return 0===e.length?null:Pr("meta",void 0,[qr(!1,"mdta",""),Ir("keys",0,0,[gr(e.length)],e.map(t=>Pr("mdta",[...it.encode(t.key)]))),Pr("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...gr(e+1));return Pr(i,void 0,[t.value])}))])},Ln=t=>Pr("data",[gr(1),gr(0),...it.encode(t)]),qn=(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}},Hn={avc:t=>t.info.decoderConfig&&Pr("avcC",[...K(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&Pr("hvcC",[...K(t.info.decoderConfig.description)]),vp8:rn,vp9:rn,av1:t=>Pr("av1C",Je(t.info.decoderConfig.codec)),prores:null},Gn=(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"}},Wn=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return on;case"opus":return cn;case"flac":return ln;case"ac3":return un;case"eac3":return fn;case"dts":return pn}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 sn}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 dn}return null},Xn={webvtt:"wvtt"},Zn={webvtt:t=>Pr("vttC",[...it.encode(t.info.config.description)])},Qn=t=>{U(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},Yn=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(){U(!this.started),this.target.Vt(),this.started=!0}write(t){U(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 U(this.started&&!this.finalized),this.target.zt()}async finalize(){U(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}},Jn=(Ti(),class extends Vt{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 ro(this,t)}}),Kn=65536,to=2**32,eo=class extends Jn{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/* @__PURE__ */new ArrayBuffer(0),this.Gt)try{this.Wt=new ArrayBuffer(Kn,{maxByteLength:to})}catch{this.Wt=new ArrayBuffer(Kn),this.Gt=!1}else this.Wt=new ArrayBuffer(Kn);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>to)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)}},io=class extends Jn{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(U(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){U(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||!kt()?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;U(this.ee),await this.ee.ready,await this.ee.close(),this.ct("finalized")}async Qt(){return this.ee?.close()}},ro=class extends Jn{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)}},no=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.")}},oo=57600,so=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},ao=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},ho=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},co=class extends cr{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new eo,this.auxWriter=new Yn(this.auxTarget,!1),this.auxBoxWriter=new fr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ut(),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 Io,this.isCmaf=e instanceof Po,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(e instanceof Po?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 eo),this.boxWriter=new fr(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof eo&&"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 Yn(await this.output.me(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new fr(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.$t);{const t=this.initBoxWriter??this.boxWriter;if(U(t),this.formatOptions.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return Pr("ftyp",t.isQuickTime?[Ar("qt "),gr(e),Ar("qt ")]:t.fragmented?t.cmaf?[Ar("iso5"),gr(e),Ar("iso5"),Ar("iso6"),Ar("mp41"),Ar("cmfc"),Ar("dash")]:[Ar("iso5"),gr(e),Ar("iso5"),Ar("iso6"),Ar("mp41")]:[Ar("isom"),gr(e),Ar("isom"),t.holdsAvc?Ar("avc1"):[],Ar("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||(U(this.writer),U(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=$r(!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;ai(i,t.source.$t),U(i),U(i.decoderConfig);const n={...i.decoderConfig};U(void 0!==n.codedWidth),U(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=fe(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=ae(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=he(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}:Rt({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;ci(i,t.source.$t),U(i),U(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=Ei(or.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=Wt[t.samplingFrequencyIndex],r=Xt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Zt({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&&Ue.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;li(e),U(e),U(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:/* @__PURE__ */new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...re(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=Ei(or.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=ti(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=ao(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=ti(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=/* @__PURE__ */new Set([]);for(const h of t.cueQueue)U(h.timestamp<=e),U(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=Fn();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;lr.lastIndex=0;const r=lr.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=On(i.notes);this.auxBoxWriter.writeBox(t)}const h=$n(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:ao(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){U(!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+=ao(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):Z(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=ao(e.timestamp-e.decodeTimestamp,t.timescale),o=ao(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){U(t.lastSample);const i=ao(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(U(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=Z(t.timeToSampleTable);if(U(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=Z(t.compositionTimeOffsetTable);U(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=ao(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,U(t.lastSample),U(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){U("key"===e.type);const i=ao(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(U(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}),U(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(U(!this.isFragmented),U(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+ao(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&Z(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)U(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(U(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(U(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const t=this.initBoxWriter??this.boxWriter;U(t),this.formatOptions.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=Or(this);if(t.writeBox(e),this.formatOptions.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onMoov(e,i)}if(this.isCmaf){U(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.fe(!0),this.boxWriter=new fr(this.writer);const t=this.boxWriter.measureBox(Br()),e=this.boxWriter.measureBox(Fr(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}U(this.writer),U(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=_n(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];U(t.currentChunk),U(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=_n(i,e);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(t,e,a)}U(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const d=$r(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(){U(this.writer),U(this.boxWriter),this.ensureOneEnabledTrack();const t=Or(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;U(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=$r(!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(){U("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;U(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(){U(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=ho(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(U(this.writer),U(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=$r(!1);for(let i=0;i<2;i++){const e=Or(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)U(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=Or(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)U(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(Br()),this.boxWriter.writeBox(Fr(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,Pr("mfra",void 0,[...e.map(Bn),Ir("mfro",0,0,[gr(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{U(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);U(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=Or(this);if("reserve"===this.fastStart){U(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()}},lo={video:1,audio:2,subtitle:17},uo=class extends cr{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=ut(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=/* @__PURE__ */new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.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 gi(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:Ce.EBML,data:[{id:Ce.EBMLVersion,data:1},{id:Ce.EBMLReadVersion,data:1},{id:Ce.EBMLMaxIDLength,data:4},{id:Ce.EBMLMaxSizeLength,data:8},{id:Ce.DocType,data:this.format instanceof Fo?"webm":"matroska"},{id:Ce.DocTypeVersion,data:4},{id:Ce.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:Ce.SeekHead,data:[{id:Ce.Seek,data:[{id:Ce.SeekID,data:i},{id:Ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:Ce.Seek,data:[{id:Ce.SeekID,data:r},{id:Ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:Ce.Seek,data:[{id:Ce.SeekID,data:n},{id:Ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:Ce.Seek,data:[{id:Ce.SeekID,data:o},{id:Ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:Ce.Seek,data:[{id:Ce.SeekID,data:e},{id:Ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=s}createSegmentInfo(){const t={id:Ce.Duration,data:new pi(0)};this.segmentDuration=t;const e={id:Ce.Info,data:[{id:Ce.TimestampScale,data:1e6},{id:Ce.MuxingApp,data:ee},{id:Ce.WritingApp,data:ee},this.format.Ot.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:Ce.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){let i=xi[e.track.source.$t];U(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=Me(K(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:Ce.TrackEntry,data:[{id:Ce.TrackNumber,data:e.track.id},{id:Ce.TrackUID,data:e.track.id},{id:Ce.TrackType,data:lo[e.type]},!1===e.track.metadata.disposition?.default?{id:Ce.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:Ce.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:Ce.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:Ce.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:Ce.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:Ce.FlagCommentary,data:1}:null,{id:Ce.FlagLacing,data:0},{id:Ce.Language,data:e.track.metadata.languageCode??"und"},{id:Ce.CodecID,data:i},e.codecPrivate?{id:Ce.CodecPrivate,data:K(e.codecPrivate)}:null,r>0?{id:Ce.SeekPreRoll,data:r}:null,void 0!==e.track.metadata.name?{id:Ce.Name,data:new wi(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:Ce.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 q(wt(r*L,90))})(i);const t=X(G(-n),i);o=Math.sign(t[0]),s=Math.sign(t[4]),-1===s&&(s=1,o=-o,n=q(n+180))}else n=t.track.metadata.rotation??0,o=t.track.metadata.flip?-1:1,s=1;const a=n?q(-1===o?n:-n):0,h=Math.round(Math.acos(o)*L),c=Math.round(Math.acos(s)*L),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:Ce.Video,data:[{id:Ce.PixelWidth,data:t.info.width},{id:Ce.PixelHeight,data:t.info.height},l?{id:Ce.DisplayWidth,data:t.info.aspectRatio.num}:null,l?{id:Ce.DisplayHeight,data:t.info.aspectRatio.den}:null,l?{id:Ce.DisplayUnit,data:3}:null,t.info.alphaMode?{id:Ce.AlphaMode,data:1}:null,st(d)?null:{id:Ce.Colour,data:[{id:Ce.MatrixCoefficients,data:null!=d?.matrix?ot[d.matrix]:2},{id:Ce.TransferCharacteristics,data:null!=d?.transfer?nt[d.transfer]:2},{id:Ce.Primaries,data:null!=d?.primaries?rt[d.primaries]:2},{id:Ce.Range,data:null!=d?.fullRange?d.fullRange?2:1:0}]},a||h||c?{id:Ce.Projection,data:[{id:Ce.ProjectionType,data:0},h?{id:Ce.ProjectionPoseYaw,data:new fi(h)}:null,c?{id:Ce.ProjectionPosePitch,data:new fi(c)}:null,a?{id:Ce.ProjectionPoseRoll,data:new fi((a+180)%360-180)}:null]}:null]};return r.push(u),r}audioSpecificTrackInfo(t){const e=Ue.includes(t.track.source.$t)?ti(t.track.source.$t):null;return[{id:Ce.Audio,data:[{id:Ce.SamplingFrequency,data:new fi(t.info.sampleRate)},{id:Ce.Channels,data:t.info.numberOfChannels},e?{id:Ce.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:Ce.SimpleTag,data:[{id:Ce.TagName,data:new wi(e)},"string"==typeof i?{id:Ce.TagString,data:new wi(i)}:{id:Ce.TagBinary,data:i}]})},i=this.output.Rt,r=/* @__PURE__ */new Set;for(const{key:n,value:o}of Bt(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:ft(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:Ce.Tags,data:[{id:Ce.Tag,data:[{id:Ce.Targets,data:[{id:Ce.TargetTypeValue,data:50},{id:Ce.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.Rt,e=[],i=/* @__PURE__ */new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+(Ft(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:Ce.AttachedFile,data:[void 0!==n.description?{id:Ce.FileDescription,data:new wi(n.description)}:null,{id:Ce.FileName,data:new wi(r)},{id:Ce.FileMediaType,data:n.mimeType},{id:Ce.FileData,data:n.data},{id:Ce.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof Ht&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&&$t(t.data,o.data))||e.push({id:Ce.AttachedFile,data:[void 0!==o.description?{id:Ce.FileDescription,data:new wi(o.description)}:null,{id:Ce.FileName,data:new wi(o.name??"")},{id:Ce.FileMediaType,data:o.mimeType??""},{id:Ce.FileData,data:o.data},{id:Ce.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:Ce.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:Ce.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:Ce.Cues,data:[]}}get segmentDataOffset(){return U(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 Fo,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;ai(i,t.source.$t),U(i),U(i.decoderConfig),U(void 0!==i.decoderConfig.codedWidth),U(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:Rt({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(Je(a.info.decoderConfig.codec)):"prores"===t.source.$t&&(a.codecPrivate=it.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;ci(i,t.source.$t),U(i),U(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=Ei(or.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=Wt[t.samplingFrequencyIndex],r=Xt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Zt({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;li(e),U(e),U(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:it.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=vt(s,t.metadata.frameRate),a=vt(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=Ei(or.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);lr.lastIndex=0,n=n.replace(lr,t=>`<${ur((t=>{const e=dr.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=it.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?it.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 Gt(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){U(null!==this.currentClusterStartMsTimestamp),U(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 Fo?"WebM":"Matroska";zt.wt(`Packets had to be discarded because their timestamp is too negative to represent in ${t}.`),this.warnedAboutTooNegativeTimestamp=!0}return}const s=/* @__PURE__ */new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:Ce.BlockGroup,data:[{id:Ce.Block,data:[s,e.data]},"delta"===e.type?{id:Ce.ReferenceBlock,data:new mi(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:Ce.BlockAdditions,data:[{id:Ce.BlockMore,data:[{id:Ce.BlockAddID,data:1},{id:Ce.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:Ce.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:Ce.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:Ce.Cluster,size:this.format.Ot.appendOnly?-1:5,data:[{id:Ce.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(U(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){U(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=/* @__PURE__ */new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)U(this.cues),this.cues.data.push({id:Ce.CuePoint,data:[{id:Ce.CueTime,data:Math.max(0,r)},...n.map(e=>({id:Ce.CueTrackPositions,data:[{id:Ce.CueTrack,data:e.track.id},{id:Ce.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(),U(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 pi(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),U(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},fo=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},po=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}),mo=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})()}},wo=class extends mo{constructor(t){if(super(),!Ve.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${Ve.join(", ")}.`);this.$t=t}},vo=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},bo=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 Et,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(t,e,i){const r=t;try{this.checkForEncoderError(),this.source.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&&(U(this.outputWidth),U(this.outputHeight),U("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=bt(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(It(e)&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof Ii?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new Ii(i)):o.push(new Ii(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 Ii&&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),U(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{U(this.encoder);const e=t.toVideoFrame(),i=dt(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 Eo);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;U(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=fo(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{po(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=rr(this.encodingConfig.quality,this.encodingConfig.bitrate);U(void 0!==e);const i=Zi({...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=nr.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=er(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 ui))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.");vo(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&&Mt()&&(this.chunkTimestampsAreShiftedByDuration=await go()),this.createWebCodecsEncoders()),U(this.source.ve),this.muxer=this.source.ve.output.xe,this.encoderInitialized=!0})()}createWebCodecsEncoders(){const t=this.encoderConfig;U(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=/* @__PURE__ */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();U(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=/* @__PURE__ */new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{n--;const s=e.shift();for(U(void 0!==s),this.addPacket(s.chunk,t,s.meta),r++;i.length>0&&i[0]===r;){i.shift();const t=e.shift();U(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=ui.fromEncodedChunk(t,r);const o=this.encoderConfig;if(U(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(U(null!==t.avcType),n){const e=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${t.avcType}.${ct(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}.${ct(i.subarray(1,4))}`}if("hevc"===e){let t,e,r,n,s,a;if(o)t=o.generalProfileSpace,e=o.generalProfileIdc,r=lt(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=tt(i),h=o.getUint8(1);t=h>>6&3,e=31&h,r=lt(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=Z(Ge).level;for(const t of Ge)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=Z(Ge).level;for(const t of Ge)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?rt[r.primaries]:1,d=r?.transfer?nt[r.transfer]:1,u=r?.matrix?ot[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&&ft(e),new TypeError(`Unhandled codec '${e}'.`)})({width:o.width,height:o.height,codec:this.encodingConfig.codec,codecDescription:i.decoderConfig.description?K(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:ae(n.data),hevcCodecInfo:"hevc"!==this.encodingConfig.codec||i.decoderConfig.description?null:fe(n.data),vp9CodecInfo:"vp9"===this.encodingConfig.codec?Te(n.data):null,av1CodecInfo:"av1"===this.encodingConfig.codec?_e(n.data):null,proresFormat:null}),"avc"===this.encodingConfig.codec&&i.decoderConfig.description&&Mt())){const t=(t=>{try{const e=tt(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 zt.ft("Error deserializing AVC Decoder Configuration Record:",e),null}})(K(i.decoderConfig.description));let e=t?.sequenceParameterSets[0];if(e&&e[0]===e[1]){U(t),e=e.subarray(1);let r=t.pictureParameterSets[0];r&&(r=r.subarray(1));const n=he({...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=dt(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&K(e.description)[4]);return ne(t,i)}return re(t)})(i,e)){const e=i[t.offset],r=oe(e);if(r>=jt.NON_IDR_SLICE&&r<=jt.SLICE_DPC)return"delta";if(r===jt.IDR)return"key";if(r===jt.SEI&&!At()){const e=i.subarray(t.offset,t.offset+t.length),r=se(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 Gt(r);t.pos=8*n;let e=-1;try{e=Y(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&K(e.description)[21]);return ne(t,i)}return re(t)})(i,e)){const e=ue(i[t.offset]);if(e<Lt.BLA_W_LP)return"delta";if(e<=Lt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new Gt(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 ke(i))if(1===e){const e=new Gt(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new Gt(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:ft(t),U(!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})),vo(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(){U(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=bt(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}},yo=null,go=()=>yo??=(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})(),xo=null,Eo=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!xo){const t=new Blob([`(${To.toString()})()`],{type:"application/javascript"});xo=URL.createObjectURL(t)}this.worker=new Worker(xo),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=ut();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=/* @__PURE__ */new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},To=()=>{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)}}},ko=class extends wo{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(!Ve.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Ve.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 Qi))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof Qi)&&(!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&&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.");Xi(t.codec,t)})(e),super(e.codec),this.Te=new bo(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 Ii(this.ke,{timestamp:t,duration:e});return this.Te.add(r,!0,i)}ge(t){return this.Te.flushAndClose(t)}},_o=class extends mo{constructor(t){if(super(),!je.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${je.join(", ")}.`);this.$t=t}},Mo=class extends mo{constructor(t){if(super(),!Le.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${Le.join(", ")}.`);this.$t=t}},Co=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>Ve.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>je.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>Le.includes(t))}_e(t){return""}Me(){return!1}},Ao=class extends Co{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&&(!Ot(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 co(t,this)}Me(){return"fragmented"===this.Ot.fastStart}},So=class extends Ao{constructor(t){super(t)}get Ae(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ve,...ze,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Le]}_e(t){return(new Io).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},Po=class extends Ao{constructor(t){super(t)}get Ae(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ve,...ze,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Le]}},Io=class extends Ao{constructor(t){super(t)}get Ae(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Ve,...je]}_e(t){return(new So).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Bo=class extends Co{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&&(!Ot(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 uo(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[...Ve,...ze,...Ue.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...Le]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},Fo=class extends Bo{constructor(t){super(t)}getSupportedCodecs(){return[...Ve.filter(t=>["vp8","vp9","av1"].includes(t)),...je.filter(t=>["opus","vorbis"].includes(t)),...Le]}get Ae(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_e(t){return(new Bo).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},$o=["video","audio","subtitle"],Oo=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=Nt(this.metadata.group),r=Nt(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}},Ro=class extends Oo{constructor(t,e,i,r){super(t,e,"video",i,r)}},Do=class extends Oo{constructor(t,e,i,r){super(t,e,"audio",i,r)}},No=class extends Oo{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},Vo=class t{constructor(){this.Se=/* @__PURE__ */new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this.Se.add(e),e.Se.add(this)}},Uo=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&!(t=>gt.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 Vo)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof Vo))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},zo=class extends Vt{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(It(e))throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new Vo,this.tracks=[],this.Be=null,this.Fe=/* @__PURE__ */new Set,this.$e=null,this.Oe=null,this.Re=null,this.De=null,this.Ne=new ht,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 Co))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof Jn||t.target instanceof no))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof Jn&&this.ze(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof Jn)&&"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 Jn&&this.ze(this.Le),this.xe=t.format.Ce(this)}qe(t){U(this.je instanceof no);const e=this.je.getTarget(t),i=t=>{if(!(t instanceof Jn))throw new TypeError("getTarget must return a Target.");return t};return It(e)?e.then(i):i(e)}async He(t){U(this.je instanceof no);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(U(null!==this.Le),this.Le instanceof Jn)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 Jn)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 It(e)?this.Pe=e.then(i):i(e)}fe(t){return this.$e??=(async()=>{const e=await this.Ie(),i=new Yn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof wo))throw new TypeError("source must be a VideoSource.");if(Uo(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&&ai({decoderConfig:e.decoderConfig},t.$t),void 0!==e.primingPacket){if(!(e.primingPacket instanceof ui))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 Ro(this.tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof _o))throw new TypeError("source must be an AudioSource.");if(Uo(e),void 0!==e.decoderConfig&&ci({decoderConfig:e.decoderConfig},t.$t),void 0!==e.primingPacket){if(!(e.primingPacket instanceof ui))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))}addSubtitleTrack(t,e={}){if(!(t instanceof Mo))throw new TypeError("source must be a SubtitleSource.");Uo(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new No(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 qt||e instanceof Ht||Ut(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 $o)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 $o){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?(zt.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&&zt.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?(zt.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 jo(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(R());let s=!1;const a=setTimeout(()=>h(()=>o(D(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(R()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var Lo=["vp9","vp8"],qo=["avc"],Ho=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 So:new Fo,s="stream"===r.kind?new io(r.writable,{chunked:!0}):new eo,a=new zo({format:o,target:s}),h=new ko(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 jo(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=b(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 jo(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 O("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=V(t),i="mp4"===t.format?new So:new Fo,r="mp4"===t.format?qo:Lo,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t));for(const o of n)if(await ir(o,{width:e.width,height:e.height,quality:this.Ye(e),alpha:e.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:e.hardwareAcceleration,contentHint:"text"}))return V(t,o);throw new O("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 Qi(t.quality)}We(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new O("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(R());const n=()=>r(R());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 R()}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 N(t)}Ze(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},Go=class{ti;T;k;constructor(t,e){this.ti=new Ho,this.T=t,this.k=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.Z(e,t),r=V(i);if("file-system"===t.destination){const n=await this.ei((new o).$resolve(t.filename,`.${e}`),r.mimeType);try{await this.ii(i,n,t.onProgress)}catch(a){try{await(n.abort?.(a))}catch{}throw a}return}const n=await this.ii(i,{kind:"blob"},t.onProgress);if(!n)throw new O("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new s).$downloadFile(n,t.filename,`.${e}`)}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.Z(e,t);V(i);const r=await this.ii(i,{kind:"blob"},t.onProgress);if(!r)throw new O("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async ii(t,e,i){const r=new y(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 f||m(n))throw N(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 O("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))}}}},Wo=class extends i{$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),l=c(n,a)?.character??" ";i.push({x:t,y:s,character:l,foreground:g(e.primaryColorPixels,r),background:g(e.secondaryColorPixels,r),transform:{invert:h.isInverted,flipX:h.flipHorizontal,flipY:h.flipVertical,rotation:h.rotation}}),o++}return i}},Xo="1.9.0",Zo={[t.NORMAL]:"normal",[t.ADDITIVE]:"additive",[t.MULTIPLY]:"multiply",[t.SCREEN]:"screen",[t.SUBTRACT]:"subtract",[t.DARKEN]:"darken",[t.LIGHTEN]:"lighten",[t.OVERLAY]:"overlay",[t.SOFT_LIGHT]:"softLight",[t.HARD_LIGHT]:"hardLight",[t.COLOR_DODGE]:"colorDodge",[t.COLOR_BURN]:"colorBurn",[t.DIFFERENCE]:"difference",[t.EXCLUSION]:"exclusion"},Qo=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:Xo}}: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 Wo).$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:Zo[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.ui(t),cells:this.fi(t,e)}}$generateJSONData(e,i={},r=/* @__PURE__ */new Date){const n=this.Z(i),o=this.ci(n,r),s=function(e,i){return(i??[e.layers.base,...e.layers.all]).map(i=>{const r=u(e,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??t.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(e,"selected"===n.target?[n.layer??e.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=/* @__PURE__ */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 s).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename,".json")}},Yo=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 Jo(t){return new Yo("ZIP_EXPORT_ABORTED","ZIP frame-sequence export was cancelled.",t)}function Ko(t){if(t instanceof Yo)return t;if(m(t))return Jo(t);if(t instanceof f){if("FRAME_SEQUENCE_TIMEOUT"===t.code)return new Yo("ZIP_EXPORT_TIMEOUT",t.message,t);if("FRAME_SEQUENCE_BUSY"===t.code)return new Yo("ZIP_EXPORT_BUSY",t.message,t);if("FRAME_SEQUENCE_DISPOSED"===t.code)return new Yo("ZIP_EXPORT_DISPOSED",t.message,t)}return new Yo("ZIP_EXPORT_FAILED",t instanceof Error?t.message:"ZIP frame-sequence export failed.",t)}var ts=new TextEncoder;function es(t){if(!t||"object"!=typeof t||Array.isArray(t))return{};const e={...t};return delete e.filename,delete e.format,e}function is(t){const e=new M;return{extension:`.${t}`,compression:"store",getDimensions({canvas:t,frameOptions:e}){const i=es(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,{...es(r),format:t}),o=_[t];if(n.type.toLowerCase()!==o)throw new Yo("ZIP_EXPORT_ENCODING_UNSUPPORTED",`The browser returned '${n.type||"an unknown format"}' instead of '${o}'.`);return new Uint8Array(await n.arrayBuffer())}}}function rs(t,e){return{extension:`.${t}`,compression:"deflate",getDimensions({frameOptions:i}){const r=es(i),n="json"===t&&"all"===r.target?u(e):u(e,r.layer);return{width:n.grid.width,height:n.grid.height}},async serialize({frameOptions:i,createdAt:r}){const n=es(i);let o;return o="svg"===t?(new k).$generateSVG(e,n):"json"===t?(new Qo).$generateJSONString(e,n,r):(new C).$generateTXT(e,n),ts.encode(o)}}}var ns=Uint8Array,os=Uint16Array,ss=Int32Array,as=new ns([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]),hs=new ns([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]),cs=new ns([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ls=function(t,e){for(var i=new os(31),r=0;r<31;++r)i[r]=e+=1<<t[r-1];var n=new ss(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}},ds=ls(as,2),us=ds.b,fs=ds.r;us[28]=258,fs[258]=28;for(var ps=ls(hs,0),ms=(ps.b,ps.r),ws=new os(32768),vs=0;vs<32768;++vs){var bs=(43690&vs)>>1|(21845&vs)<<1;bs=(61680&(bs=(52428&bs)>>2|(13107&bs)<<2))>>4|(3855&bs)<<4,ws[vs]=((65280&bs)>>8|(255&bs)<<8)>>1}var ys=function(t,e,i){for(var r=t.length,n=0,o=new os(e);n<r;++n)t[n]&&++o[t[n]-1];var s,a=new os(e);for(n=1;n<e;++n)a[n]=a[n-1]+o[n-1]<<1;if(i){s=new os(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[ws[d]>>h]=c}else for(s=new os(r),n=0;n<r;++n)t[n]&&(s[n]=ws[a[t[n]-1]++]>>15-t[n]);return s},gs=new ns(288);for(vs=0;vs<144;++vs)gs[vs]=8;for(vs=144;vs<256;++vs)gs[vs]=9;for(vs=256;vs<280;++vs)gs[vs]=7;for(vs=280;vs<288;++vs)gs[vs]=8;var xs=new ns(32);for(vs=0;vs<32;++vs)xs[vs]=5;var Es=/*#__PURE__*/ys(gs,9,0),Ts=/*#__PURE__*/ys(xs,5,0),ks=function(t){return(t+7)/8|0},_s=function(t,e,i){return(null==e||e<0)&&(e=0),(null==i||i>t.length)&&(i=t.length),new ns(t.subarray(e,i))},Ms=["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"],Cs=function(t,e,i){var r=new Error(e||Ms[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,Cs),!i)throw r;return r},As=function(t,e,i){i<<=7&e;var r=e/8|0;t[r]|=i,t[r+1]|=i>>8},Ss=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},Ps=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:Ds,l:0};if(1==n){var s=new ns(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 os(u+1),p=Is(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 ns(f),l:p}},Is=function(t,e,i){return-1==t.s?Math.max(Is(t.l,e,i+1),Is(t.r,e,i+1)):e[t.s]=i},Bs=function(t){for(var e=t.length;e&&!t[--e];);for(var i=new os(++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}},Fs=function(t,e){for(var i=0,r=0;r<e.length;++r)i+=t[r]*e[r];return i},$s=function(t,e,i){var r=i.length,n=ks(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)},Os=function(t,e,i,r,n,o,s,a,h,c,l){As(e,l++,i),++n[256];for(var d=Ps(n,15),u=d.t,f=d.l,p=Ps(o,15),m=p.t,w=p.l,v=Bs(u),b=v.c,y=v.n,g=Bs(m),x=g.c,E=g.n,T=new os(19),k=0;k<b.length;++k)++T[31&b[k]];for(k=0;k<x.length;++k)++T[31&x[k]];for(var _=Ps(T,7),M=_.t,C=_.l,A=19;A>4&&!M[cs[A-1]];--A);var S,P,I,B,F=c+5<<3,$=Fs(n,gs)+Fs(o,xs)+s,O=Fs(n,u)+Fs(o,m)+s+14+3*A+Fs(T,M)+2*T[16]+3*T[17]+7*T[18];if(h>=0&&F<=$&&F<=O)return $s(e,l,t.subarray(h,h+c));if(As(e,l,1+(O<$)),l+=2,O<$){S=ys(u,f,0),P=u,I=ys(m,w,0),B=m;var R=ys(M,C,0);for(As(e,l,y-257),As(e,l+5,E-1),As(e,l+10,A-4),l+=14,k=0;k<A;++k)As(e,l+3*k,M[cs[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];As(e,l,R[U]),l+=M[U],U>15&&(As(e,l,V[k]>>5&127),l+=V[k]>>12)}}}else S=Es,P=gs,I=Ts,B=xs;for(k=0;k<a;++k){var z=r[k];if(z>255){Ss(e,l,S[257+(U=z>>18&31)]),l+=P[U+257],U>7&&(As(e,l,z>>23&31),l+=as[U]);var j=31&z;Ss(e,l,I[j]),l+=B[j],j>3&&(Ss(e,l,z>>5&8191),l+=hs[j])}else Ss(e,l,S[z]),l+=P[z]}return Ss(e,l,S[256]),l+P[256]},Rs=/*#__PURE__*/new ss([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ds=/*#__PURE__*/new ns(0),Ns=/*#__PURE__*/function(){for(var t=/* @__PURE__ */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},Us=/* @__PURE__ */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 ns(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 ns(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 ns(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=Rs[e-1],u=d>>13,f=8191&d,p=(1<<i)-1,m=o.p||new os(32768),w=o.h||new os(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 ss(25e3),x=new os(288),E=new os(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=Os(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|fs[$]<<18|ms[O];var G=31&fs[$],W=31&ms[O];k+=as[G]+hs[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=Os(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=$s(h,l+1,t.subarray(_,X))}o.i=s}return _s(a,0,r+ks(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||Cs(5),this.s.l&&Cs(4);var i=t.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var r=new ns(-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=Ds)},t.prototype.flush=function(t){if(this.ondata||Cs(5),this.s.l&&Cs(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,t){var e=new ns(6);e[0]=this.s.r>>3;var i=$s(e,this.s.r,Ds);this.s.r=0,this.ondata(e.subarray(0,i>>3),!1)}},t}(),zs="undefined"!=typeof TextEncoder&&/*#__PURE__*/new TextEncoder,js="undefined"!=typeof TextDecoder&&/*#__PURE__*/new TextDecoder;try{js.decode(Ds,{stream:!0})}catch(oh){}function Ls(t,e){if(e){for(var i=new ns(t.length),r=0;r<t.length;++r)i[r]=t.charCodeAt(r);return i}if(zs)return zs.encode(t);var n=t.length,o=new ns(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 ns(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 _s(o,0,s)}var qs=function(t){var e=0;if(t)for(var i in t){var r=t[i].length;r>65535&&Cs(9),e+=r+4}return e},Hs=function(t,e,i,r,n,o,s,a){var h=r.length,c=i.extra,l=a&&a.length,d=qs(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)&&Cs(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},Gs=/* @__PURE__ */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=Ns[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||Cs(5),this.c.p(t),this.size+=t.length,e&&(this.crc=this.c.d()),this.process(t,e||!1)},t}(),Ws=/* @__PURE__ */function(){function t(t,e){var i,r=this;e||(e={}),Gs.call(this,t),this.d=new Us(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(oh){this.ondata(oh,null,e)}},t.prototype.push=function(t,e){Gs.prototype.push.call(this,t,e)},t}(),Xs=/* @__PURE__ */function(){function t(t){this.ondata=t,this.u=[],this.d=1}return t.prototype.add=function(t){var e=this;if(this.ondata||Cs(5),2&this.d)this.ondata(Cs(4+8*(1&this.d),0,1),null,!1);else{var i=Ls(t.filename),r=i.length,n=t.comment,o=n&&Ls(n),s=r!=t.filename.length||o&&n.length!=o.length,a=r+qs(t.extra)+30;r>65535&&this.ondata(Cs(11,0,1),null,!1);var h=new ns(a);Hs(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 ns(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(Cs(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+qs(f.extra)+(f.o?f.o.length:0);for(var o,s,a,h,c,l=new ns(i+22),d=0,u=this.u;d<u.length;d++){var f=u[d];Hs(l,t,f,f.f,f.u,-f.c-2,e,f.o),t+=46+f.f.length+qs(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}(),Zs=class{mi;re=[];wi=/* @__PURE__ */new Set;bi;yi;gi="open";xi=0;Ei;Ti;ki;constructor(t,e=4294967295){this.bi=t,this.yi=e,this.mi=new Xs((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 Yo("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 Yo("ZIP_EXPORT_FAILED",`Duplicate ZIP entry: ${t}`);if(this.wi.size>=65535)throw new Yo("ZIP_EXPORT_TOO_LARGE","Classic ZIP archives cannot contain more than 65,535 entries.");if(e.byteLength>this.yi)throw new Yo("ZIP_EXPORT_TOO_LARGE",`A classic ZIP entry cannot exceed ${this.yi.toLocaleString("en-US")} bytes.`);const r="store"===i?new Gs(t):new Ws(t,{level:6});if(r.mtime=this.bi,this.wi.add(t),this.mi.add(r),(r instanceof Gs||r instanceof Ws)&&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=Jo()){"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 Yo("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 Yo("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)}},Qs=/* @__PURE__ */new Set(["png","jpg","webp","svg","json","txt"]),Ys=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 s).$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=Ko(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 Ko(r)}throw e}}async Pi(t,e){const i=this.Bi(t),r=this.Ai.now?.()??/* @__PURE__ */new Date,n=(new o).$resolve(i.filename,".zip",r),s=n.slice(0,-4);let a,h=!1,c=0;try{this.I(i.signal);const t=(l=this.T,{png:is("png"),jpg:is("jpg"),webp:is("webp"),svg:rs("svg",l),json:rs("json",l),txt:rs("txt",l)}),o=this.Ai.resolveSerializer?.(i.format)??t[i.format];a=this.Ai.createWriter?.(r)??new Zs(r);const d=a,u=this.Ai.createDriver?.()??new y(this.T,this.k),f=o.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:Xo},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:o.extension});await d.$addEntry(`${s}/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 o.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}`}(s,t,o.extension),n,o.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=Ko(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 Yo("ZIP_EXPORT_INVALID_OPTIONS","ZIP export options are required.");const e=t.format;if("string"!=typeof e||!Qs.has(e))throw new Yo("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 Yo("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 Yo("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 Jo()}st(t){return new Promise((e,i)=>{if(t?.aborted)return void i(Jo());let r=!1;const n=()=>{r||(r=!0,i(Jo()))};t?.addEventListener("abort",n,{once:!0}),setTimeout(()=>{r||(r=!0,t?.removeEventListener("abort",n),e())},0)})}},Js="textmode-export-overlay__stack",Ks="textmode-export-overlay__stack--dense",ta="textmode-export-overlay__stack--compact",ea="textmode-export-overlay__section",ia="textmode-export-overlay--dragging",ra="textmode-export-overlay__label",na="textmode-export-overlay__field",oa="textmode-export-overlay__field--compact",sa="textmode-export-overlay__field--dense",aa="textmode-export-overlay__field--full",ha="textmode-export-overlay__field--channel",ca="textmode-export-overlay__input",la="textmode-export-overlay__muted",da="textmode-export-overlay__button--primary",ua="textmode-export-overlay__button--secondary",fa="textmode-export-overlay__button--full",pa="textmode-export-overlay__link-icon",ma=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}},wa=class t extends ma{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(Js,Ks,"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",pa,[{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(pa,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}},va=class extends ma{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(na),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(ra),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(la),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(na),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(ra),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(la),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(oa,sa,aa,ha),e){case"compact":t.classList.add(oa);break;case"dense":t.classList.add(sa);break;case"full":t.classList.add(aa);break;case"channel":t.classList.add(ha)}}},ba=class extends ma{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(ca),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)}}},ya=class extends ma{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(ua):this.button.classList.add(da),this.props.fullWidth&&this.button.classList.add(fa),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(ua),this.button.classList.remove(da)):(this.button.classList.add(da),this.button.classList.remove(ua)),this.button.classList.toggle(fa,Boolean(t.fullWidth))}},ga=class{ht={};Ui(t){const e=this.ht[t];if(e)return e;const i=/* @__PURE__ */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]}},xa=class{gi;ht=/* @__PURE__ */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)}},Ea=/* @__PURE__ */new Set(["txt","json","svg","image"]),Ta=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 Ea.has(t)}},ka={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)}},_a=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 ka[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}}},Ma=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,Ca=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||!Ma(e.offsetX)||!Ma(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(Ma(t)&&Ma(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{}}},Aa=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 Ca){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(ia))}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(ia),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(ia),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()}},Sa=class extends ma{capabilities;zi;ji=/* @__PURE__ */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()}},Pa=class extends ma{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)}},Ia=class extends ma{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(ca),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)}},Ba=class extends ma{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new va({label:"layer",labelFor:t.id,variant:"full"}),this.select=new ba({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()}},Fa=class extends Sa{layerTarget;trailingSpaces=this.Li(new Pa({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.Li(new Ia({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.Li(new Ba({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Js),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new va({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??" "}},$a=class extends Sa{layerTarget;layerTargetContainer;target=this.Li(new ba({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.Li(new Pa({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.Li(new Pa({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.Li(new ba({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 Ba({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Js);const e=new va({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 va({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)}},Oa="textmode-export-number-input",Ra=`${Oa}__field`,Da=`${Oa}__controls`,Na=`${Oa}__control`,Va=`${Oa}__display`,Ua=`${Va}--visible`,za=t=>{const e=document.createElement("button");return e.type="button",e.className=Na,e.textContent=t>0?"▲":"▼",e},ja=class extends ma{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=/* @__PURE__ */new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=Oa,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=Ra,this.display=document.createElement("div"),this.display.className=Va;const e=document.createElement("div");return e.className=Da,this.incrementButton=za(1),this.decrementButton=za(-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(Ua),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(Ua),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(Ua),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(Ua),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)}},La=class extends ma{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?Js:void 0,"stackDense"===this.variant?Ks:void 0,"stackCompact"===this.variant?ta:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?ea:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},qa=class extends Sa{formatSelect=this.Li(new ba({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 ja({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(Js);const e=new La("row");e.mount(t);const i=new va({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new va({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)}},Ha=class extends Sa{layerTarget;includeBackground=this.Li(new Pa({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.Li(new ba({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.Li(new ja({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.Li(new Ba({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Js),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new La("row");e.mount(t);const i=new va({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new va({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()}},Ga={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},Wa=class extends ma{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(Ga)),this.messageElement.classList.add(Ga[t])}},Xa=class extends Sa{frameCountInput=this.Li(new ja({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.Li(new ja({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.Li(new ja({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.Li(new ja({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 Wa({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(Js);const e=new La("row");e.mount(t);const i=new va({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 va({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 La("row");n.mount(t);const o=new va({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 va({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}},Za=class extends Sa{formatSelect=this.Li(new ba({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));qualitySelect=this.Li(new ba({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 ja({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.Li(new ja({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));hardwareAccelerationSelect=this.Li(new ba({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 ja({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.Li(new Pa({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.Li(new Wa({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.Li(new Wa({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(Js);const e=new La("row");e.mount(t);const i=new va({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new va({label:"quality",labelFor:"textmode-export-video-quality",variant:"compact"});r.mount(e.root),this.qualitySelect.mount(r.root);const n=new La("row");n.mount(t);const o=new va({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 va({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 La("row");a.mount(t);const h=new va({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(a.root),this.hardwareAccelerationSelect.mount(h.root);const c=new va({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=V(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 Qa(t){return t.capabilities.recording}var Ya=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 Ja(){return{format:Ya.format,txt:{...Ya.txt},json:{...Ya.json},image:{...Ya.image},svg:{...Ya.svg},gif:{...Ya.gif},video:{...Ya.video}}}function Ka(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var th=class{qi;constructor(){this.qi=Ja()}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=Ja();if(!t)return this.qi.format=e.format,Ka(this.qi.txt,e.txt),Ka(this.qi.json,e.json),Ka(this.qi.image,e.image),Ka(this.qi.svg,e.svg),Ka(this.qi.gif,e.gif),void Ka(this.qi.video,e.video);switch(t){case"format":this.qi.format=e.format;break;case"txt":Ka(this.qi.txt,e.txt);break;case"json":Ka(this.qi.json,e.json);break;case"image":Ka(this.qi.image,e.image);break;case"svg":Ka(this.qi.svg,e.svg);break;case"gif":Ka(this.qi.gif,e.gif);break;case"video":Ka(this.qi.video,e.video)}}},eh=class{T;Hi;gi;Gi;Wi;Xi;Zi;Qi=/* @__PURE__ */new Map;Yi=[];Ji;Ki;tr;er;ir;rr;nr=new wa;sr=new va({label:"export format",labelFor:"textmode-export-format",variant:"full"});ar=new ba({id:"textmode-export-format",options:[]});hr=new ya({label:"download file",fullWidth:!0,variant:"primary"});cr=new ya({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 xa((t=>({format:t,isBusy:!1}))(n)),this.Gi=new ga,this.Wi=new _a(e,this.Gi),this.Xi=new Ta(e),this.Zi=r,this.lr=n,this.gr(),this.Er()}$mount(){this.Tr(),this.kr(),this.rr=new Aa(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",Js),this.Ki.appendChild(this.tr),document.body.appendChild(this.Ji)}kr(){this.nr.mount(this.tr);const t=document.createElement("div");t.classList.add(ea),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(Js,ta),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(Js,Ks),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&&Qa(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&&Qa(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(Qa(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(Qa(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 ih=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob","saveZip","toZipBlob"],rh=class{api;k;Br=/* @__PURE__ */new Set;Fr=new w;$r;Or;v=!1;constructor(t,e){this.k=e;const i={saveCanvas:async(e={})=>(this.Rr(),(new M).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.Rr(),(new M).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.Rr(),(new M).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.Rr(),(new k).$saveSVG(t,e)},saveStrings:(e={})=>{this.Rr(),(new C).$saveTXT(t,e)},toSVG:(e={})=>(this.Rr(),(new k).$generateSVG(t,e)),toString:(e={})=>(this.Rr(),(new C).$generateTXT(t,e)),toJSON:(e={})=>(this.Rr(),(new Qo).$generateJSONData(t,e)),toJSONString:(e={})=>(this.Rr(),(new Qo).$generateJSONString(t,e)),saveJSON:(e={})=>{this.Rr(),(new Qo).$saveJSON(t,e)},saveGIF:(e={})=>this.Dr("gif",e.signal,i=>new $(t,t=>this.k(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.Dr("gif",e.signal,i=>new $(t,t=>this.k(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.Dr("video",e.signal,i=>new Go(t,t=>this.k(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.Dr("video",e.signal,i=>new Go(t,t=>this.k(t)).$generateVideoBlob({...e,signal:i})),saveZip:async e=>this.Dr("zip",e?.signal,i=>new Ys(t,t=>this.k(t)).$saveZIP({...e,signal:i}),t=>this.Nr(e,t)),toZipBlob:async e=>this.Dr("zip",e?.signal,i=>new Ys(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 th,n=new eh(t,e,r,function(t,e=(()=>{const t=Ja();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new Fa({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new $a({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new qa({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Ha({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new Xa({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new Za({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:()=>d(t),getLayerById:e=>d(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 N(o);if("zip"===t){const t=Ko(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.")}},nh={name:"textmode.export.js",install(t,e){const i=new rh(t,t=>e.on("postDraw",t));try{for(const t of ih)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=nh);export{nh as ExportPlugin,Yo as ZIPExportError};
|