textmode.export.js 1.8.1 → 1.9.0-beta.2

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.
Files changed (54) hide show
  1. package/README.md +11 -2
  2. package/dist/textmode.document.esm.js +1 -0
  3. package/dist/textmode.export.esm.js +1 -1
  4. package/dist/textmode.export.umd.js +1 -1
  5. package/dist/types/document/constants.d.ts +32 -0
  6. package/dist/types/document/decode-shapes.d.ts +4 -0
  7. package/dist/types/document/decode.d.ts +5 -0
  8. package/dist/types/document/index.d.ts +13 -0
  9. package/dist/types/document/parse.d.ts +3 -0
  10. package/dist/types/document/types.d.ts +209 -0
  11. package/dist/types/document/validation.d.ts +37 -0
  12. package/dist/types/exporters/base/FileHandler.d.ts +1 -14
  13. package/dist/types/exporters/base/FilenamePolicy.d.ts +6 -0
  14. package/dist/types/exporters/base/LayerTarget.d.ts +0 -2
  15. package/dist/types/exporters/base/frame-sequence/ExclusiveCaptureGate.d.ts +7 -0
  16. package/dist/types/exporters/{video/VideoFrameSchedule.d.ts → base/frame-sequence/FrameSchedule.d.ts} +2 -2
  17. package/dist/types/exporters/{video/VideoFrameDriver.d.ts → base/frame-sequence/FrameSequenceDriver.d.ts} +5 -11
  18. package/dist/types/exporters/base/frame-sequence/errors.d.ts +12 -0
  19. package/dist/types/exporters/base/frame-sequence/index.d.ts +5 -0
  20. package/dist/types/exporters/base/frame-sequence/types.d.ts +20 -0
  21. package/dist/types/exporters/base/frame-sequence/withAbortableTimeout.d.ts +1 -0
  22. package/dist/types/exporters/base/index.d.ts +3 -0
  23. package/dist/types/exporters/gif/GIFExporter.d.ts +1 -1
  24. package/dist/types/exporters/gif/index.d.ts +0 -1
  25. package/dist/types/exporters/gif/types.d.ts +0 -10
  26. package/dist/types/exporters/image/types.d.ts +0 -2
  27. package/dist/types/exporters/json/JSONExporter.d.ts +2 -2
  28. package/dist/types/exporters/json/types.d.ts +14 -204
  29. package/dist/types/exporters/svg/types.d.ts +1 -3
  30. package/dist/types/exporters/txt/types.d.ts +0 -2
  31. package/dist/types/exporters/video/VideoExporter.d.ts +1 -2
  32. package/dist/types/exporters/video/errors.d.ts +1 -0
  33. package/dist/types/exporters/video/types.d.ts +3 -35
  34. package/dist/types/exporters/zip/FrameSerializerRegistry.d.ts +4 -0
  35. package/dist/types/exporters/zip/ZIPArchiveWriter.d.ts +21 -0
  36. package/dist/types/exporters/zip/ZIPExporter.d.ts +32 -0
  37. package/dist/types/exporters/zip/ZIPManifest.d.ts +12 -0
  38. package/dist/types/exporters/zip/errors.d.ts +13 -0
  39. package/dist/types/exporters/zip/index.d.ts +3 -0
  40. package/dist/types/exporters/zip/types.d.ts +170 -0
  41. package/dist/types/index.d.ts +5 -24
  42. package/dist/types/runtime/TextmodeExportController.d.ts +3 -0
  43. package/dist/types/types.d.ts +43 -24
  44. package/package.json +50 -11
  45. package/protocol/textmode-document/2.0/SPECIFICATION.md +233 -0
  46. package/protocol/textmode-document/2.0/fixture.d.ts +3 -0
  47. package/protocol/textmode-document/2.0/fixtures/textmode-document-all-v2.json +94 -0
  48. package/protocol/textmode-document/2.0/fixtures/textmode-document-create-integration-v2.json +112 -0
  49. package/protocol/textmode-document/2.0/fixtures/textmode-document-selected-v2.json +86 -0
  50. package/protocol/textmode-document/2.0/fixtures/textmode-layer-all-v1.1.json +46 -0
  51. package/protocol/textmode-document/2.0/fixtures/textmode-layer-selected-v1.json +38 -0
  52. package/protocol/textmode-document/2.0/textmode-document-2.0.schema.d.ts +3 -0
  53. package/protocol/textmode-document/2.0/textmode-document-2.0.schema.json +171 -0
  54. package/dist/types/exporters/gif/GIFRecorder.d.ts +0 -23
@@ -1 +1 @@
1
- import{LayerBlendMode as t}from"textmode.js";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var e=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),i=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},r=class{$downloadFile(t,e){try{const i=this.t(e),r=URL.createObjectURL(t),n=document.createElement("a");n.href=r,n.download=i,n.style.display="none",n.rel="noopener",document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}catch(i){console.error("[textmode-export] Failed to download file:",i)}}t(t){if(!t)return this.i();const e=t.trim();return e&&e.replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/_{2,}/g,"_").replace(/^_+|_+$/g,"").substring(0,255)||this.i()}i(){return`textmode-export-${/* @__PURE__ */(new Date).toISOString().slice(0,19).replace(/:/g,"-")}`}},n=/* @__PURE__ */new WeakMap;function o(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function s(t,e){let i=n.get(t);if(!i){i=/* @__PURE__ */new Map;for(const e of t.characters)i.set(o(e.color),e);n.set(t,i)}return i.get(e)}function a(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function h(t){return[{id:"base",layer:t.layers.base},...t.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:a(t,e),layer:e}))}function c(t,e){const i=e??t.layers.base,r=function(t,e){if(e===t.layers.base)return"base";const i=t.layers.all.indexOf(e);if(i>=0)return`layer-${i+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")}(t,i),n=i.grid,o=i.font,s=i.drawFramebuffer;if(!n||!s)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:r,label:a(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}function l(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var d=class extends i{o(t,e,i){return{x:t,y:e,cellX:t*i.cellWidth,cellY:e*i.cellHeight}}$extractSVGCellData(t,e){const i=[];let r=0;for(let n=0;n<e.rows;n++)for(let o=0;o<e.cols;o++){const s=4*r,a=this.$getEncodedCharacterValue(t.characterPixels,s);let h=l(t.primaryColorPixels,s),c=l(t.secondaryColorPixels,s);const d=this.$extractCellTransform(t.characterPixels,s);if(d.isInverted){const t=h;h=c,c=t}const u=this.o(o,n,e);i.push({encodedGlyphSlot:a,primaryColor:h,secondaryColor:c,transform:d,position:u}),r++}return i}},u=class{h(t,e,i,r,n){const o=n/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:i+e.xMin*o,y1:r+-e.yMax*o,x2:i+e.xMax*o,y2:r+-e.yMin*o}),toSVG:()=>this.l(e,i,r,o)}}l(t,e,i,r){if(!t||!t.xs)return"";const{xs:n,ys:o,endPts:s,flags:a}=t;if(!(n&&o&&s&&a))return"";let h="",c=0;for(let l=0;l<s.length;l++){const t=s[l];if(!(t<c)){if(t>=c){const s=e+n[c]*r,l=i-o[c]*r;h+=`M${s.toFixed(2)},${l.toFixed(2)}`;let d=c+1;for(;d<=t;)if(1&a[d]){const t=e+n[d]*r,s=i-o[d]*r;h+=`L${t.toFixed(2)},${s.toFixed(2)}`,d++}else{const s=e+n[d]*r,l=i-o[d]*r,u=d+1>t?c:d+1;if(1&a[u]){const t=e+n[u]*r,a=i-o[u]*r;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u+1}else{const t=(s+(e+n[u]*r))/2,a=(l+(i-o[u]*r))/2;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u}}h+="Z"}c=t+1}}return h}$generatePositionedCharacterPath(t,e,i,r,n,o,s,a){if(!a)return null;const h=e.font,c=s/h.head.unitsPerEm,l=i+(n-a.advanceWidth*c)/2,d=r+h.hhea.ascender*c;return this.h(h,a,l,d,s).toSVG()||null}},f=class{u;constructor(){this.u=new u}$generateSVGHeader(t){const{width:e,height:i}=t;return`<?xml version="1.0" encoding="UTF-8"?><svg width="${e}" height="${i}" viewBox="0 0 ${e} ${i}" xmlns="http://www.w3.org/2000/svg"><title>textmode.js sketch</title>`}$generateSVGFooter(){return"</g></svg>"}p(t,e){const{transform:i,position:r}=t;if(!i.flipHorizontal&&!i.flipVertical&&!i.rotation)return"";const n=r.cellX+e.cellWidth/2,o=r.cellY+e.cellHeight/2,s=[];if(i.flipHorizontal||i.flipVertical){const t=i.flipHorizontal?-1:1,e=i.flipVertical?-1:1;s.push(`translate(${n} ${o})scale(${t} ${e})translate(${-n} ${-o})`)}return i.rotation&&s.push(`rotate(${i.rotation} ${n} ${o})`),` transform="${s.join(" ")}"`}m(t,e,i){if(!i.includeBackgroundRectangles||0===t.secondaryColor.a)return"";const{position:r}=t,{r:n,g:o,b:s,a}=t.secondaryColor,h=`rgba(${n},${o},${s},${a/255})`;return"stroke"===i.drawMode?`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${h}" fill="none" stroke-width="${i.strokeWidth}"/>`:`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${h}"/>`}v(t,e,i,r){const n=s(i,t.encodedGlyphSlot);if(!n)return"";const o=this.u.$generatePositionedCharacterPath(n.character,i,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,i.fontSize,n.glyphData);if(!o)return"";const{r:a,g:h,b:c,a:l}=t.primaryColor,d=`rgba(${a},${h},${c},${l/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.m(t,e,r);o&&n.push(o);const s=this.v(t,e,i,r);if(s){const i=this.p(t,e);n.push(i?`<g${i}>${s}</g>`:s)}return n.join("")}$generateSVGContent(t,e,i,r){const n=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)n.push(this.$generateCellContent(o,e,i,r));return n.push(this.$generateSVGFooter()),n.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}},p=class{T(t){return{includeBackgroundRectangles:t.includeBackgroundRectangles??!0,drawMode:t.drawMode??"fill",strokeWidth:t.strokeWidth??1,filename:t.filename,layer:t.layer}}$generateSVG(t,e={}){const i=new d,r=new f,n=this.T(e),o=c(t,n.layer),s=i.$extractSVGCellData(i.$extractFramebufferData(o.drawFramebuffer),o.grid),a=r.$generateSVGContent(s,o.grid,o.font,n);return r.$optimizeSVGContent(a)}$saveSVG(t,e={}){(new r).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename)}},m={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},w=class{T(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}k(t){if(!(t.format in m))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(/* @__PURE__ */new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},m[e.format])})}async $saveImage(t,e={}){const i=this.T(e);this.k(i);const n=await this.$toImageBlob(t,e);(new r).$downloadFile(n,i.filename)}async $toImageBlob(t,e={}){const i=this.T(e);return this.k(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.T(e);this.k(i);const r=await this.$generateImageBlob(t,i),n=new ClipboardItem({[m[i.format]]:r});await navigator.clipboard.write([n])}},b=class{T(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}M(t,e){const r=new i,n=c(t,e.layer),o=r.$extractFramebufferData(n.drawFramebuffer),a=[];let h=0;for(let i=0;i<n.grid.rows;i++){let t="";for(let i=0;i<n.grid.cols;i++){const i=4*h,a=r.$getEncodedCharacterValue(o.characterPixels,i);t+=s(n.font,a)?.character||e.emptyCharacter,h++}e.preserveTrailingSpaces||(t=t.trimEnd()),a.push(t)}return a.join("\n")}$generateTXT(t,e={}){return this.M(t,this.T(e))}$saveTXT(t,e={}){const i=this.T(e),n=this.M(t,i),o=new Blob([n],{type:"text/plain;charset=utf-8"});(new r).$downloadFile(o,i.filename)}},y=/* @__PURE__ */e(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>_,applyPalette:()=>y,default:()=>B,nearestColor:()=>M,nearestColorIndex:()=>T,nearestColorIndexWithDistance:()=>k,prequantize:()=>b,quantize:()=>f,snapColorsToPalette:()=>x});var i={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function r(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView:()=>i.subarray(0,e),bytes:()=>i.slice(0,e),writeByte(t){r(e+1),i[e]=t,e++},writeBytes(t,n=0,o=t.length){r(e+o);for(let r=0;r<o;r++)i[e++]=t[r+n]},writeBytesView(t,n=0,o=t.byteLength){r(e+o),i.set(t.subarray(n,n+o),e),e+=o}};function r(t){var r=i.length;if(r>=t)return;t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));const n=i;i=new Uint8Array(t),e>0&&i.set(n.subarray(0,e),0)}}var n=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],o=function(t,e,i,o,s=r(512),a=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,b=m,y=(1<<b)-1;const v=1<<p-1,g=v+1;let x=v+2,E=0,T=i[0],k=0;for(let r=l;r<65536;r*=2)++k;k=8-k,s.writeByte(d),_(v);const M=i.length;for(let r=1;r<M;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}_(T),T=t,x<4096?(c[n]=x++,h[n]=e):(h.fill(-1),x=v+2,w=!0,_(v))}return _(T),_(g),s.writeByte(0),s.bytesView();function _(t){for(u&=n[f],f>0?u|=t<<f:u=t,f+=b;f>=8;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;if((x>y||w)&&(w?(b=m,y=(1<<b)-1,w=!1):(++b,y=12===b?1<<b:(1<<b)-1)),t==g){for(;f>0;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;E>0&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0)}}};function s(t,e,i){return t<<8&63488|e<<2&992|i>>3}function a(t,e,i,r){return t>>4|240&e|(240&i)<<4|(240&r)<<8}function h(t,e,i){return t>>4<<8|240&e|i>>4}function c(t,e,i){return t<e?e:t>i?i:t}function l(t){return t*t}function d(t,e,i){var r=0,n=1e100;const o=t[e],s=o.cnt,a=o.ac,h=o.rc,c=o.gc,d=o.bc;for(var u=o.fw;0!=u;u=t[u].fw){const e=t[u],o=e.cnt,p=s*o/(s+o);if(!(p>=n)){var f=0;i&&(f+=p*l(e.ac-a))>=n||(f+=p*l(e.rc-h))>=n||(f+=p*l(e.gc-c))>=n||(f+=p*l(e.bc-d))>=n||(n=f,r=u)}}o.err=n,o.nn=r}function u(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function f(t,e,i={}){const{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:o=0,clearAlphaThreshold:f=0,oneBitAlpha:m=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");const w=new Uint32Array(t.buffer);let b=!1!==i.useSqrt;const y="rgba4444"===r,v=function(t,e){const i=new Array("rgb444"===e?4096:65536),r=t.length;if("rgba4444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>24&255,o=e>>16&255,s=e>>8&255,h=255&e,c=a(h,s,o,r);let l=c in i?i[c]:i[c]=u();l.rc+=h,l.gc+=s,l.bc+=o,l.ac+=r,l.cnt++}else if("rgb444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,s=255&e,a=h(s,o,r);let c=a in i?i[a]:i[a]=u();c.rc+=s,c.gc+=o,c.bc+=r,c.cnt++}else for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,a=255&e,h=s(a,o,r);let c=h in i?i[h]:i[h]=u();c.rc+=a,c.gc+=o,c.bc+=r,c.cnt++}return i}(w,r),g=v.length,x=g-1,E=new Uint32Array(g+1);for(var T=0,k=0;k<g;++k){const t=v[k];if(null!=t){var M=1/t.cnt;y&&(t.ac*=M),t.rc*=M,t.gc*=M,t.bc*=M,v[T++]=t}}var _,C,S;for(l(e)/T<.022&&(b=!1),k=0;k<T-1;++k)v[k].fw=k+1,v[k+1].bk=k,b&&(v[k].cnt=Math.sqrt(v[k].cnt));for(b&&(v[k].cnt=Math.sqrt(v[k].cnt)),k=0;k<T;++k){d(v,k,!1);var A=v[k].err;for(C=++E[0];C>1&&!(v[_=E[S=C>>1]].err<=A);C=S)E[C]=_;E[C]=k}var P=T-e;for(k=0;k<P;){for(var B;;){var I=E[1];if((B=v[I]).tm>=B.mtm&&v[B.nn].mtm<=B.tm)break;for(B.mtm==x?I=E[1]=E[E[0]--]:(d(v,I,!1),B.tm=k),A=v[I].err,C=1;(S=C+C)<=E[0]&&(S<E[0]&&v[E[S]].err>v[E[S+1]].err&&S++,!(A<=v[_=E[S]].err));C=S)E[C]=_;E[C]=I}var F=v[B.nn],$=B.cnt,V=F.cnt;M=1/($+V),y&&(B.ac=M*($*B.ac+V*F.ac)),B.rc=M*($*B.rc+V*F.rc),B.gc=M*($*B.gc+V*F.gc),B.bc=M*($*B.bc+V*F.bc),B.cnt+=F.cnt,B.mtm=++k,v[F.bk].fw=F.fw,v[F.fw].bk=F.bk,F.mtm=x}let R=[];var N=0;for(k=0;;++N){let t=c(Math.round(v[k].rc),0,255),e=c(Math.round(v[k].gc),0,255),i=c(Math.round(v[k].bc),0,255),r=255;y&&(r=c(Math.round(v[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=y?[t,e,i,r]:[t,e,i];if(p(R,s)||R.push(s),0==(k=v[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 b(t,{roundRGB:e=5,roundAlpha:i=10,oneBitAlpha:r=null}={}){const n=new Uint32Array(t.buffer);for(let o=0;o<n.length;o++){const t=n[o];let s=t>>24&255,a=t>>16&255,h=t>>8&255,c=255&t;s=w(s,i),r&&(s=s<=("number"==typeof r?r:127)?0:255),c=w(c,e),h=w(h,e),a=w(a,e),n[o]=s<<24|a<<16|h<<8|c}}function y(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");const r=new Uint32Array(t.buffer),n=r.length,o="rgb444"===i?4096:65536,c=new Uint8Array(n),l=new Array(o);if("rgba4444"===i)for(let s=0;s<n;s++){const t=r[s],i=t>>24&255,n=t>>16&255,o=t>>8&255,h=255&t,d=a(h,o,n,i);c[s]=d in l?l[d]:l[d]=v(h,o,n,i,e)}else{const t="rgb444"===i?h:s;for(let i=0;i<n;i++){const n=r[i],o=n>>16&255,s=n>>8&255,a=255&n,h=t(a,s,o);c[i]=h in l?l[h]:l[h]=g(a,s,o,e)}}return c}function v(t,e,i,r,n){let o=0,s=1e100;for(let a=0;a<n.length;a++){const h=n[a];let c=E(h[3]-r);c>s||(c+=E(h[0]-t),c>s||(c+=E(h[1]-e),c>s||(c+=E(h[2]-i),c>s||(s=c,o=a))))}return o}function g(t,e,i,r){let n=0,o=1e100;for(let s=0;s<r.length;s++){const a=r[s];let h=E(a[0]-t);h>o||(h+=E(a[1]-e),h>o||(h+=E(a[2]-i),h>o||(o=h,n=s)))}return n}function x(t,e,i=5){if(!t.length||!e.length)return;const r=t.map(t=>t.slice(0,3)),n=i*i,o=t[0].length;for(let s=0;s<e.length;s++){let i=e[s];i=i.length<o?[i[0],i[1],i[2],255]:i.length>o?i.slice(0,3):i.slice();const a=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 M(t,e,i=m){return t[T(t,e,i)]}function _(t={}){const{initialCapacity:e=4096,auto:n=!0}=t,s=r(e),a=/* @__PURE__ */new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth:b=8,dispose:y=-1}=r;let v=!1;if(n?l||(v=!0,d(),l=!0):v=Boolean(r.first),e=Math.max(0,Math.floor(e)),i=Math.max(0,Math.floor(i)),v){if(!m)throw new Error("First frame must include a { palette } option");!function(t,e,i,r,n=8){const o=n-1<<4|128|P(r.length)-1;S(t,e),S(t,i),t.writeBytes([o,0,0])}(s,e,i,m,b),C(s,m),w>=0&&function(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),A(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,y,g,u,f);const x=Boolean(m)&&!v;!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&&C(s,m),function(t,e,i,r,n=8,s,a,h){o(i,r,e,n,t,s,a,h)}(s,t,e,i,b,a,h,c)}};function d(){A(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 S(t,e){t.writeByte(255&e),t.writeByte(e>>8&255)}function A(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 B=_}),v=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function g(){return new v("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function x(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(g());let s=!1;const a=setTimeout(()=>h(()=>o(function(t){return new v("VIDEO_EXPORT_TIMEOUT",t,void 0)}(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(g()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var E=1e6;function T(t,e){const i=Math.round(t*E/e),r=Math.max(i+1,Math.round((t+1)*E/e));return{startSeconds:i/E,centerSeconds:(i+Math.floor((r-i)/2))/E,endSeconds:r/E,durationSeconds:(r-i)/E}}var k=class{canvas;_;C;S;A;P=null;B=0;I=0;constructor(t,e,i,r){this._=t,this.C=e,this.A=t.canvas,this.canvas=this.F(i,r);const n=this.canvas.getContext("2d");if(!n)throw new Error("Video export requires a 2D canvas context for staging frames.");n.imageSmoothingEnabled=!1,this.S=n}async $render(t){const e=this._,i=Math.max(1,Math.round(t.frameCount)),r=Math.max(Number.EPSILON,Math.abs(t.frameRate)),n=1e3/r,o=e.isLooping(),s=e.frameCount,a=e.millis,h="secs"in e,c=e.secs,l=this.$(),d=this.V(),u=this.C(()=>{this.R()});try{e.noLoop(),this.B=s,this.I=a,this.N(h),this.D(r,n),this.O();for(let e=0;e<i;e++){this.U(t.signal);const n=T(e,r);this.B=s+e+1,this.I=1e3*n.startSeconds,await(t.prepareFrame?.({frameIndex:e,frameCount:i,startSeconds:n.startSeconds,centerSeconds:n.centerSeconds,endSeconds:n.endSeconds,timeSeconds:n.startSeconds,frameRate:r,signal:t.signal})),this.U(t.signal),await this.j(e,t.signal),this.U(t.signal),await t.onFrame({frameIndex:e,canvas:this.canvas})}}finally{u(),this.P?.reject(/* @__PURE__ */new Error("Video export frame rendering was interrupted.")),this.P=null,this.L(d),this.H(l),e.frameCount=s,e.millis=a,h&&void 0!==c&&(e.secs=c),o?e.loop():e.noLoop()}}j(t,e){if(this.P)throw new Error("A video export frame is already pending.");const i=this._;return x(new Promise((e,r)=>{this.P={frameIndex:t,resolve:e,reject:r};try{i.redraw(1)}catch(n){this.P=null,r(n)}}),`Video export frame ${t+1} did not render within 30000ms.`,e,3e4).catch(e=>{throw this.P?.frameIndex===t&&(this.P=null),e})}R(){const t=this.P;if(t)try{this.S.clearRect(0,0,this.canvas.width,this.canvas.height),this.S.drawImage(this.A,0,0,this.A.width,this.A.height,0,0,this.canvas.width,this.canvas.height),this.P=null,t.resolve()}catch(e){this.P=null,t.reject(e)}}F(t,e){const i=document.createElement("canvas");return i.width=Math.max(1,Math.round(t)),i.height=Math.max(1,Math.round(e)),i}$(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._,t),value:this._[t]}))}V(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this._,t),descriptor:Object.getOwnPropertyDescriptor(this._,t)}))}N(t){Object.defineProperty(this._,"frameCount",{configurable:!0,enumerable:!0,get:()=>this.B,set:t=>{this.B=t}}),Object.defineProperty(this._,"millis",{configurable:!0,enumerable:!0,get:()=>this.I,set:t=>{this.I=t}}),t&&Object.defineProperty(this._,"secs",{configurable:!0,enumerable:!0,get:()=>this.I/1e3,set:t=>{this.I=1e3*t}})}D(t,e){const i=this._,r=i.frameRate;i.deltaTime=()=>e,i.frameRate=function(e){return void 0===e?t:r.call(this,e)}}O(){this._.resizeCanvas=()=>{}}H(t){const e=this._;for(const i of t)i.hadOwnProperty?e[i.key]=i.value:delete e[i.key]}L(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this._,e.key,e.descriptor):delete this._[e.key]}U(t){if(t?.aborted)throw g()}},M='(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',_="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",M],{type:"text/javascript;charset=utf-8"});function C(t){let e;try{if(e=_&&(self.URL||self.webkitURL).createObjectURL(_),!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(M),{name:t?.name})}}var S=class{q;G=/* @__PURE__ */new Map;W;X=0;Y=!1;constructor(t,e,i,r,n){this.q=new C,this.q.addEventListener("message",this.J),this.q.addEventListener("error",this.K),n?.addEventListener("abort",this.dispose,{once:!0}),this.W=this.Z({type:"init",width:t,height:e,delay:Math.round(1e3/i),repeat:r})}async encodeFrame(t,e){await this.W,await this.Z({type:"frame",buffer:t,frameIndex:e},[t])}async finish(){await this.W;const t=await this.Z({type:"finish"});if(!t.buffer)throw new Error("GIF worker returned no encoded output.");return t.buffer}dispose=()=>{if(!this.Y){this.Y=!0,this.q.terminate();for(const t of this.G.values())t.reject(new DOMException("GIF export was cancelled.","AbortError"));this.G.clear()}};Z(t,e=[]){if(this.Y)return Promise.reject(new DOMException("GIF export was cancelled.","AbortError"));const i=++this.X;return new Promise((r,n)=>{this.G.set(i,{resolve:r,reject:n}),this.q.postMessage({...t,id:i},e)})}J=t=>{const e=t.data,i=this.G.get(e.id);i&&(this.G.delete(e.id),"error"!==e.type?i.resolve(e):i.reject(new Error(e.message??"GIF worker failed")))};K=t=>{const e=new Error(t.message||"GIF worker failed");for(const i of this.G.values())i.reject(e);this.G.clear()}},A=y(),P=class{_;C;constructor(t,e){this._=t,this.C=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new r).$downloadFile(e,t.filename)}async $generateGIFBlob(t={}){const e=this.T(t),i=this._.canvas,r=Math.max(1,Math.round(i.width*e.scale)),n=Math.max(1,Math.round(i.height*e.scale)),o=new k(this._,this.C,r,n),s=o.canvas.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("GIF export requires a 2D canvas context.");const a="undefined"==typeof Worker?(0,A.GIFEncoder)():null,h="undefined"==typeof Worker?null:new S(r,n,e.frameRate,e.repeat,e.signal);try{let i;if(this.U(e.signal),await o.$render({frameCount:e.frameCount,frameRate:e.frameRate,signal:e.signal,prepareFrame:e.prepareFrame,onFrame:async({frameIndex:i,canvas:r})=>{this.U(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,A.quantize)(t,256,{}),s=(0,A.applyPalette)(t,o);a.writeFrame(s,r.width,r.height,{palette:o,delay:Math.round(1e3/e.frameRate),repeat:0===i?e.repeat:-1})}t.onProgress?.({state:"encoding",frameIndex:i+1,totalFrames:e.frameCount}),(i+1)%2==0&&await this.tt(e.signal)}}),this.U(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()}}T(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}}U(t){if(t?.aborted)throw new DOMException("GIF export was cancelled.","AbortError")}tt(t){return new Promise((e,i)=>{t?.aborted?i(new DOMException("GIF export was cancelled.","AbortError")):setTimeout(e,0)})}};function B(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new v("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const i=Math.max(1,Math.round(t.width)),r=Math.max(1,Math.round(t.height));if("mp4"===t.format&&(i%2!=0||r%2!=0))throw new v("VIDEO_DIMENSIONS_UNSUPPORTED",`MP4/H.264 requires even dimensions; received ${i}x${r}. Increase pixel density or choose WebM.`);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 I(t){if(!t)throw new Error("Assertion failed.")}var F,$=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},V=t=>t&&t[t.length-1],R=t=>t>=0&&t<2**32,N=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)},D=t=>{const e=N(t);return 1&e?e+1>>1:-(e>>1)},O=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),U=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),z=/* #__PURE__ */new TextEncoder,j={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},L={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},H={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},q=t=>!!(t&&t.primaries&&t.transfer&&t.matrix&&void 0!==t.fullRange),G=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),W=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}},X=(t,e,i)=>{let r=0,n=t.length-1,o=-1;for(;r<=n;){const s=r+(n-r+1)/2|0;i(t[s])<=e?(o=s,r=s+1):n=s-1}return o},Q=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},Y=t=>{throw new Error(`Unexpected value: ${t}`)},J=(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},K=(t,e,i)=>Math.max(e,Math.min(i,t)),Z=(t,e)=>Math.round(t/e)*e,tt=(t,e)=>Math.round(t*e)/e,et=(t,e)=>Math.floor(t*e)/e,it=t=>{let e=0;for(;0!==t;)t&=t-1,e++;return e},rt=/^[a-z]{3}$/,nt=1e6*(1+Number.EPSILON),ot=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},st=null,at=()=>null!==st?st:st=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),ht=null,ct=()=>null!==ht?ht:ht="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),lt=null,dt=()=>null!==lt?lt:lt=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),ut=null,ft=()=>{if(null!==ut)return ut;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?ut=Number(t[1]):null},pt=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},mt=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}},wt=(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},bt=t=>{I(Number.isInteger(t.num)),I(Number.isInteger(t.den)),I(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}},yt=(t,e)=>{if("object"!=typeof t||!t)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(t.left)||t.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(t.top)||t.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(t.width)||t.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(t.height)||t.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},vt=t=>Array.isArray(t)?t:[t],gt=class{constructor(){this.et=/* @__PURE__ */new Map}on(t,e,i){this.et.has(t)||this.et.set(t,/* @__PURE__ */new Set);const r={fn:e,once:i?.once??!1};return this.et.get(t).add(r),()=>{this.et.get(t)?.delete(r)}}it(...t){const[e,i]=t,r=this.et.get(e);if(r)for(const o of r){try{o.fn(i)}catch(n){console.error(n)}o.once&&r.delete(o)}}},xt=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"}(F||(F={}));var Et=class t{constructor(){}static get level(){return t.rt}static set level(e){if(e!==F.Silent&&e!==F.Errors&&e!==F.Warnings&&e!==F.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");t.rt=e}static get nt(){return t.ot??=new gt}static on(e,i,r){return t.nt.on(e,i,r)}static st(...e){t.nt.it("error",e),t.rt>=F.Errors&&console.error(...e)}static ht(...e){t.nt.it("warn",e),t.rt>=F.Warnings&&console.warn(...e)}static ct(...e){t.nt.it("info",e),t.rt>=F.Info&&console.info(...e)}};Et.rt=F.Info,Et.ot=null;var Tt,kt,Mt=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.")}},_t=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.")}},Ct=class t{constructor(t){this.bytes=t,this.pos=0}seekToByte(t){this.pos=8*t}readBit(){const t=Math.floor(this.pos/8),e=this.bytes[t]??0,i=7-(7&this.pos),r=(e&1<<i)>>i;return this.pos++,r}readBits(t){if(1===t)return this.readBit();let e=0;for(let i=0;i<t;i++)e<<=1,e|=this.readBit();return e}writeBits(t,e){const i=this.pos+t;for(let r=this.pos;r<i;r++){const t=Math.floor(r/8);let n=this.bytes[t];const o=7-(7&r);n&=~(1<<o),n|=(e&1<<i-r-1)>>i-r-1<<o,this.bytes[t]=n}this.pos=i}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new t(this.bytes);return e.pos=this.pos,e}},St=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],At=[-1,1,2,3,4,5,6,8],Pt=t=>{let e=St.indexOf(t.sampleRate),i=null;-1===e&&(e=15,i=t.sampleRate);const r=At.indexOf(t.numberOfChannels);if(-1===r)throw new TypeError(`Unsupported number of channels: ${t.numberOfChannels}`);let n=13;t.objectType>=32&&(n+=6),15===e&&(n+=24);const o=Math.ceil(n/8),s=new Uint8Array(o),a=new Ct(s);return t.objectType<32?a.writeBits(5,t.objectType):(a.writeBits(5,31),a.writeBits(6,t.objectType-32)),a.writeBits(4,e),15===e&&a.writeBits(24,i),a.writeBits(4,r),s},Bt=["avc","hevc","vp9","av1","vp8","prores"],It=["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"],Ft=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],$t=[...Ft,...It],Vt=["webvtt"],Rt=[{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}],Nt=[{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}],Dt=[{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}],Ot=[{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}],Ut=["ap4x","ap4h","apch","apcn","apcs","apco"],zt=["dtsc","dtsh","dtsl","dtse"],jt=[{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}],Lt=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=Rt.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??V(Rt),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=Nt.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??V(Nt);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.${(Dt.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??V(Dt)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=Ot.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??V(Ot);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=jt.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 Y(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Ht=t=>{const e=t.split("."),i=Number(e[1]),r=e[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(e[3])?0:1)<<6)+0+((e[4]?Number(e[4]):0)<<4)+((e[5]?Number(e[5][0]):1)<<3)+((e[5]?Number(e[5][1]):1)<<2)+(e[5]?Number(e[5][2]):0),0]},qt=/^pcm-([usf])(\d+)(be)?$/,Gt=t=>{if(I(It.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=qt.exec(t);let i;return I(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}},Wt=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":Ut.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":zt.includes(t)?"dts":"ulaw"===t?"ulaw":"alaw"===t?"alaw":qt.test(t)?t:"webvtt"===t?"webvtt":null,Xt=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Ut],Qt=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Yt=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Jt=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Kt=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Zt=(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(!Xt.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&&!G(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(j);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(L);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(H);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(!Qt.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(!Yt.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(!Jt.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(!Kt.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(Ut.some(e=>t.decoderConfig.codec.startsWith(e))&&!Ut.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: ${Ut.join(", ")}.`);if(null!==e&&Wt(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}'.`)},te=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],ee=(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(!te.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&&!G(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(!zt.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: ${zt.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!It.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${It.join(", ")}).`);if(null!==e&&Wt(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}'.`)},ie=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.")},re=[48e3,44100,32e3],ne=[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"}(Tt||(Tt={})),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"}(kt||(kt={}));var oe,se=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})},ae=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=J(r,i,!1):(I(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},he=t=>31&t,ce=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)},le=(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}}),de=t=>{const e=N(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)N(t),N(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},ue=t=>t>>1&63,fe=(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}},pe=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&&D(t);for(let e=0;e<i;e++)D(t)}else N(t)},me=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=we(t,r,e,i)},we=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(N(t)+1):e-1,t.readBits(1),N(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=N(t),i=N(t);for(let r=0;r<e;r++)N(t),t.readBits(1);for(let r=0;r<i;r++)N(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=le[e];t&&(a=t)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),o=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(N(t),N(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(N(t),N(t),N(t),N(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&N(t),t.readBits(1)&&ye(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=N(t),N(t),N(t),N(t),N(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?N(t):i=1===t.readBits(1);let s=1;i||(s=N(t)+1),r&&ve(t,s,o),n&&ve(t,s,o)}},ve=(t,e,i)=>{for(let r=0;r<e;r++)N(t),N(t),i&&(N(t),N(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"}(oe||(oe={}));var ge,xe=t=>{const e=U(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"}(ge||(ge={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var Ee,Te=[1,2,3,6],ke=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Me=[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],_e=[16,16,20,20,0,24,24,0],Ce=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Se=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Ae=[32e3,44100,48e3,0],Pe=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Be=[512,1024,2048,4096],Ie=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 Ct(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=Ae[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 b=0;b<l;b++)u.push(e.readBits(i+1));for(const b of u)e.skipBits(8*it(b));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 b=0;b<d;b++)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=Pe[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}}},Fe=t=>{const e=new Uint8Array(20),i=U(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 Ct(e);return n.seekToByte(13),n.writeBits(2,Math.max(Be.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},$e=/* #__PURE__ */new Uint8Array(0),Ve=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===$e&&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===$e}get microsecondTimestamp(){return Math.trunc(nt*this.timestamp)}get microsecondDuration(){return Math.trunc(nt*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)}},Re=class{constructor(t){this.value=t}},Ne=class{constructor(t){this.value=t}},De=class{constructor(t){this.value=t}},Oe=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"}(Ee||(Ee={})),Ee.EBML,Ee.Segment,Ee.SeekHead,Ee.Info,Ee.Cluster,Ee.Tracks,Ee.Cues,Ee.Attachments,Ee.Chapters,Ee.Tags;var Ue=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,ze=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,je=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,Le=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=Ue(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=ze(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=je(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??Ue(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??ze(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 Re)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof Ne)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof De){const e=t.size??je(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Oe){const e=z.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else Y(t.data)}},He={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"},qe=t=>{const e=t.filePos,i=new Ct(Ai(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}},Ge=/* @__PURE__ */e((t,e)=>{e.exports={}}),We=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 Xe=-1/0,Qe=-1/0,Ye=null;"undefined"!=typeof FinalizationRegistry&&(Ye=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-Xe>=1e3&&(Et.st("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Xe=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-Qe>=1e3&&(Et.st("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Qe=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var Je=class{constructor(){this.lt=0,this.dt=null}},Ke=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Ze=new Set(Ke),ti=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(nt*this.timestamp)}get microsecondDuration(){return Math.trunc(nt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,i){if(this.ut=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0===i.format||!Ze.has(i.format))throw new TypeError("init.format must be one of: "+Ke.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&&yt(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??li(i.format,i.codedWidth,i.codedHeight);let r=i.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},void 0!==i.displayWidth?(this.squarePixelWidth=this.rotation%180==0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180==0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this.ft=i.wt?O(e):O(e).slice(),this.bt=t,this.colorSpace=new oi(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&&yt(i.visibleRect,"init.visibleRect"),this.ft=e,this.bt=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=i?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=i?.timestamp??e.timestamp/1e6,this.duration=i?.duration??(e.duration??0)/1e6,this.colorSpace=new oi(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&&yt(i.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*nt),duration:Math.trunc((i.duration??0)*nt)||void 0,visibleRect:i.visibleRect&&{x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height}}),i);let r=0,n=0;if("naturalWidth"in e?(r=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,n=e.videoHeight):"width"in e&&(r=Number(e.width),n=Number(e.height)),!r||!n)throw new TypeError("Could not determine dimensions.");const o=i.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(o.width,o.height),a=s.getContext("2d",{alpha:ct(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-o.left,-o.top),this.ft=s,this.bt=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 oi({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Je))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0!==i.rotation&&![0,90,180,270].includes(i.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(i.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==i.duration&&(!Number.isFinite(i.duration)||i.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this.ft=e,e.lt++,this.format=e.getFormat(),null!==this.format&&!Ke.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=bt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ye?.register(this,{type:"video",data:this.ft},this)}clone(){if(this.ut)throw new Error("VideoSample is closed.");return I(null!==this.ft),this.ft instanceof Je?new t(this.ft,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):si(this.ft)?new t(this.ft.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this.ft instanceof Uint8Array?(I(this.bt),new t(this.ft,{format:this.format,layout:this.bt,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,wt:!0})):new t(this.ft,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this.ut||(Ye?.unregister(this),this.ft instanceof Je?(this.ft.lt--,0===this.ft.lt&&this.ft.close()):si(this.ft)?this.ft.close():this.ft=null,this.ut=!0)}allocationSize(t={}){if(ci(t),this.ut)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot get allocation size when format is null.");return si(this.ft)?this.ft.allocationSize(t):ui(this,t).allocationSize}async copyTo(e,i={}){if(!G(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ci(i),this.ut)throw new Error("VideoSample is closed.");if(null==(i.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(I(null!==this.ft),si(this.ft))return this.ft.copyTo(e,i);if(i.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(i.format)){if(!(this.ft instanceof Je)){if("undefined"==typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const t=this.toVideoFrame(),r=await t.copyTo(e,i);return t.close(),r}{const r={stack:[],error:void 0,hasError:!1};try{const n=function(t,e,i){if(null!=e){if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(t){return Promise.reject(t)}}),t.stack.push({value:e,dispose:r,async:i})}else i&&t.stack.push({async:!0});return e}(r,await this.ft.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},i.colorSpace??"srgb"),!1);if(!(n instanceof t))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return await n.copyTo(e,i)}catch(c){r.error=c,r.hasError=!0}finally{We(r)}}}const r=ui(this,i);I(this.format);const n=O(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=di(this.format);let s;if(this.ft instanceof Je){let t=this.ft.getDataPlanes();if(t instanceof Promise&&(t=await t),!Array.isArray(t)||t.some(t=>!(t.data instanceof Uint8Array)||!Number.isInteger(t.stride)||t.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=t}else if(this.ft instanceof Uint8Array)I(this.bt),I(this.bt.length===o.length),s=this.bt.map((t,e)=>{const i=Math.ceil(this.codedHeight/o[e].heightDivisor);return{data:this.ft.subarray(t.offset,t.offset+t.stride*i),stride:t.stride}});else{const t=this.ft.getContext("2d");I(t),s=[{data:O(t.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const a=[],h=o.length;for(let t=0;t<h;t++){const e=r.computedLayouts[t],i=s[t].stride,o=s[t].data;let h=e.sourceTop*i;h+=e.sourceLeftBytes;let c=e.destinationOffset;const l=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let t=0;t<e.sourceHeight;t++){if(h+l>o.byteLength)throw new Error("Source buffer OOB read.");if(c+l>n.byteLength)throw new Error("Destination buffer OOB write.");const t=o.subarray(h,h+l);n.set(t,c),h+=i,c+=e.destinationStride}a.push(d)}if(void 0!==i.format){const t=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),e=this.format.includes("X")&&i.format.includes("A");if(t||e)for(let i=0;i<r.allocationSize;i+=4){if(t){const t=n[i];n[i]=n[i+2],n[i+2]=t}e&&(n[i+3]=255)}}return a}toVideoFrame(){if(this.ut)throw new Error("VideoSample is closed.");if(I(null!==this.ft),this.ft instanceof Je){if(null===this.format)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const t=this.ft.getDataPlanes();if(t instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const e=t.reduce((t,e)=>t+e.data.byteLength,0),i=new Uint8Array(e);let r=0;const n=[];for(const o of t)i.set(o.data,r),n.push(r),r+=o.data.byteLength;return new VideoFrame(i,{format:this.format,layout:t.map((t,e)=>({offset:n[e],stride:t.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return si(this.ft)?new VideoFrame(this.ft,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.ft instanceof Uint8Array?(I(this.bt),new VideoFrame(this.ft,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this.bt,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this.ft,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,r,n,o,s,a,h){let c=0,l=0,d=this.displayWidth,u=this.displayHeight,f=0,p=0,m=this.displayWidth,w=this.displayHeight;if(void 0!==o?(c=e,l=i,d=r,u=n,f=o,p=s,void 0!==a?(m=a,w=h):(m=d,w=u)):(f=e,p=i,void 0!==r&&(m=r,w=n)),!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this.ut)throw new Error("VideoSample is closed.");({sx:c,sy:l,sWidth:d,sHeight:u}=this.yt(c,l,d,u,this.rotation));const b=this.toCanvasImageSource();t.save();const y=f+m/2,v=p+w/2;t.translate(y,v),t.rotate(this.rotation*Math.PI/180);const g=this.rotation%180==0?1:m/w;t.scale(1/g,g),t.drawImage(b,c,l,d,u,-m/2,-w/2,m,w),t.restore()}drawWithFit(t,e){if(!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==e.crop&&hi(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=ai(d,o,s));const{sx:u,sy:f,sWidth:p,sHeight:m}=this.yt(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??s,n);if("fill"===e.fit)a=0,h=0,c=i,l=r;else{const[t,n]=e.crop?[e.crop.width,e.crop.height]:[o,s],d="contain"===e.fit?Math.min(i/t,r/n):Math.max(i/t,r/n);c=t*d,l=n*d,a=(i-c)/2,h=(r-l)/2}t.save();const w=n%180==0?1:c/l;t.translate(i/2,r/2),t.rotate(n*Math.PI/180),t.scale(1/w,w),t.translate(-i/2,-r/2),t.drawImage(this.toCanvasImageSource(),u,f,p,m,a,h,c,l),t.restore()}yt(t,e,i,r,n){return 90===n?[t,e,i,r]=[e,this.squarePixelHeight-t-i,r,i]:180===n?[t,e]=[this.squarePixelWidth-t-i,this.squarePixelHeight-e-r]:270===n&&([t,e,i,r]=[this.squarePixelWidth-e-r,t,r,i]),{sx:t,sy:e,sWidth:i,sHeight:r}}vt(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?ni(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.ut)throw new Error("VideoSample is closed.");if(I(null!==this.ft),this.ft instanceof Je||this.ft instanceof Uint8Array){const t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}return this.ft}async transform(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&hi(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=$(this.rotation+(e.rotate??0)),[r,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=ai(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=Z(c,e.roundDimensionsTo??1),l=Z(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 ei){let e=t(this,d);if(e instanceof Promise&&(e=await e),null!==e)return e}const{canvas:u,context:f,isNew:p}=ni(d.width,d.height);return this.vt(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()}},ei=[],ii=[],ri=0,ni=(t,e)=>{for(const n of ii)if(n.canvas.width===t&&n.canvas.height===e)return n.age=ri++,{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 ii.length>=3&&ii.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})(ii,t=>t.age),1),ii.push({canvas:i,context:r,age:ri++}),{canvas:i,context:r,isNew:!0}},oi=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(j);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(L);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(H);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}}},si=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,ai=(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 I(o>=0),I(s>=0),{left:r,top:n,width:o,height:s}},hi=(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.")},ci=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.")}},li=(t,e,i)=>{const r=di(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},di=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:Y(t),I(!1)}},ui=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=fi(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 mi(n,s,o)},fi=(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(!pi(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},pi=(t,e)=>{if(null===t)return!0;const i=di(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},mi=(t,e,i)=>{const r=di(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,bi=(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&&Wt(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.")},yi=t=>{const e=t.bitrateMode,i=t.quality.gt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Lt(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}),I(n.length>0),n},vi=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 gi):"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.xt="string"==typeof t.quality?gi[t.quality]:t.quality,this.Et=t.preferBitrate??!1,this.Tt=void 0,this.kt=void 0}else{if(void 0!==t.bitrate&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(void 0!==t.quantizer&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(void 0===t.bitrate&&void 0===t.quantizer)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this.xt=void 0,this.Et=!1,this.Tt=t.bitrate,this.kt=t.quantizer}this.Mt=t.bitrateMode}gt(t,e,i,r){const n=xi[t];let o=null,s=this.Mt??r??"variable";if(void 0!==this.kt){if(n)if(this.kt<n.min||this.kt>n.max){if(void 0===this.Tt)throw new Error(`Quantizer ${this.kt} is out of range for codec '${t}'; must be between ${n.min} and ${n.max}.`)}else o=this.kt,void 0===this.Tt&&(s="quantizer");else if(void 0===this.Tt)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.Tt&&n&&!this.Et&&(I(void 0!==this.xt),o=K(Math.round((a=n.worst)+(n.best-a)*this.xt),n.min,n.max));var a;let h;if(void 0!==this.Tt)h=this.Tt;else{let r=this.xt;void 0===r&&(I(null!==o&&n),r=K((o-n.worst)/(n.best-n.worst),0,1)),h=Ti(t,e,i,Ei(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}_t(t,e,i){return void 0!==this.Tt?this.Tt:(I(void 0!==this.xt),Ti(t,e,i,Ei(this.xt)))}Ct(t){if(It.includes(t)||"flac"===t)return;if(void 0!==this.Tt)return this.Tt;if(void 0===this.xt)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");const e=Ei(this.xt),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)}},gi={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},xi={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}},Ei=t=>.3*Math.exp(2.5538*t),Ti=(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)},ki=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void I(!1),Mi=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,...s}=e;if(!Bt.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 vi))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 vi)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");bi(t,s);const a=_i(n,o)??new vi("medium");let h;try{h=yi({codec:t,width:i,height:r,quality:a,framerate:void 0,...s,alpha:"discard"})}catch{return!1}const c=JSON.stringify(h),l=wi.get(c);if(l)return l;const d=(async()=>{for(const{config:e}of h)if(Ci.some(i=>i.supports(t,e)))return!0;if("undefined"==typeof VideoEncoder)return!1;if(!(i%2!=1&&r%2!=1||"avc"!==t&&"hevc"!==t))return!1;for(const{config:e,quantizer:n}of h){try{if(!(await VideoEncoder.isConfigSupported(e)).supported)continue}catch{continue}if(!ct())return!0;if(await new Promise(async o=>{try{const s=new VideoEncoder({output:()=>{},error:()=>o(!1)});s.configure(e);const a=new Uint8Array(i*r*4),h=new VideoFrame(a,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});s.encode(h,null!==n?ki(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return wi.set(c,d),d},_i=(t,e)=>void 0!==t?t:void 0!==e?e instanceof vi?e:new vi({bitrate:e}):void 0,Ci=[],Si=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,U(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)}},Ai=(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},Pi=class{constructor(t){this.mutex=new W,this.trackTimestampInfo=/* @__PURE__ */new WeakMap,this.output=t}onTrackClose(t){}validateTimestamp(t,e,i){if(e<0)throw new Error(`Timestamps must be non-negative (got ${e}s).`);let r=this.trackTimestampInfo.get(t);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,r)}}},Bi=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ii=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Fi=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")},$i=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);I(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}}},Vi=/* #__PURE__ */new Uint8Array(8),Ri=/* #__PURE__ */new DataView(Vi.buffer),Ni=t=>[(t%256+256)%256],Di=t=>(Ri.setUint16(0,t,!1),[Vi[0],Vi[1]]),Oi=t=>(Ri.setInt16(0,t,!1),[Vi[0],Vi[1]]),Ui=t=>(Ri.setUint32(0,t,!1),[Vi[1],Vi[2],Vi[3]]),zi=t=>(Ri.setUint32(0,t,!1),[Vi[0],Vi[1],Vi[2],Vi[3]]),ji=t=>(Ri.setInt32(0,t,!1),[Vi[0],Vi[1],Vi[2],Vi[3]]),Li=t=>(Ri.setUint32(0,Math.floor(t/2**32),!1),Ri.setUint32(4,t,!1),[Vi[0],Vi[1],Vi[2],Vi[3],Vi[4],Vi[5],Vi[6],Vi[7]]),Hi=t=>(Ri.setInt32(0,Math.floor(t/2**32),!1),Ri.setUint32(4,t,!1),[Vi[0],Vi[1],Vi[2],Vi[3],Vi[4],Vi[5],Vi[6],Vi[7]]),qi=t=>(Ri.setInt16(0,256*t,!1),[Vi[0],Vi[1]]),Gi=t=>(Ri.setInt32(0,65536*t,!1),[Vi[0],Vi[1],Vi[2],Vi[3]]),Wi=t=>(Ri.setInt32(0,2**30*t,!1),[Vi[0],Vi[1],Vi[2],Vi[3]]),Xi=(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()},Qi=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},Yi=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]},Ji=/* #__PURE__ */Yi(0),Ki=t=>[Gi(t[0]),Gi(t[1]),Wi(t[2]),Gi(t[3]),Gi(t[4]),Wi(t[5]),Gi(t[6]),Gi(t[7]),Wi(t[8])],Zi=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),tr=(t,e,i,r,n)=>Zi(t,[Ni(e),Ui(i),r??[]],n),er=()=>Zi("styp",[Qi("iso5"),zi(0),Qi("iso5"),Qi("iso6"),Qi("mp41"),Qi("cmfc"),Qi("dash")]),ir=(t,e)=>{let i=t.maxWrittenEndTimestamp-t.minWrittenTimestamp;return Number.isFinite(i)||(i=0),tr("sidx",1,0,[zi(1),zi(Sn),Li(Pn(t.minWrittenTimestamp,Sn)),Li(0),Di(0),Di(1),zi(2147483647&e),zi(Pn(i,Sn)),zi(0)])},rr=t=>({type:"mdat",largeSize:t}),nr=t=>Zi("moov",void 0,[or(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>ar(e,t.creationTime)),t.isFragmented?qr(t.trackDatas):null,on(t)]),or=(t,e)=>{const i=Math.max(0,...e.map(t=>Pn(sr(t),Sn)+Pn(t.startTimestampOffset??0,Sn))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!R(t)||!R(i),o=n?Li:zi;return tr("mvhd",+n,0,[o(t),o(t),zi(Sn),o(i),Gi(1),qi(1),Array(10).fill(0),Ki(Ji),Array(24).fill(0),zi(r)])},sr=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},ar=(t,e)=>{const i=An(t),r=null!==t.startTimestampOffset&&t.startTimestampOffset>0;return Zi("trak",void 0,[hr(t,e),r?cr(t,t.startTimestampOffset):null,lr(t,e),void 0!==i.name?Zi("udta",void 0,[Zi("name",[...z.encode(i.name)])]):null])},hr=(t,e)=>{const i=Pn(sr(t),Sn)+Pn(t.startTimestampOffset??0,Sn),r=!R(e)||!R(i),n=r?Li:zi;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=Yi(e??0)}else o=Ji;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:Y(t);return tr("tkhd",+r,s,[n(e),n(e),zi(t.track.id),zi(0),n(i),Array(8).fill(0),Di(0),Di(a),qi("audio"===t.type?1:0),Di(0),Ki(o),Gi("video"===t.type?t.info.width:0),Gi("video"===t.type?t.info.height:0)])},cr=(t,e)=>{const i=Pn(e,Sn),r=Pn(sr(t),Sn),n=!R(i)||!R(r),o=n?Li:zi,s=n?Hi:ji;return Zi("edts",void 0,[tr("elst",n?1:0,0,[zi(2),o(i),s(-1),Gi(1),o(r),s(0),Gi(1)])])},lr=(t,e)=>Zi("mdia",void 0,[dr(t,e),pr(!0,ur[t.type],fr[t.type]),mr(t)]),dr=(t,e)=>{const i=Pn(sr(t),t.timescale),r=!R(e)||!R(i),n=r?Li:zi;return tr("mdhd",+r,0,[n(e),n(e),zi(t.timescale),n(i),Di(vn(t.track.metadata.languageCode??"und")),Di(0)])},ur={video:"vide",audio:"soun",subtitle:"text"},fr={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},pr=(t,e,i,r="\0\0\0\0")=>tr("hdlr",0,0,[t?Qi("mhlr"):zi(0),Qi(e),Qi(r),zi(0),zi(0),Qi(i,!0)]),mr=t=>Zi("minf",void 0,[wr[t.type](),br(),gr(t)]),wr={video:()=>tr("vmhd",0,1,[Di(0),Di(0),Di(0),Di(0)]),audio:()=>tr("smhd",0,0,[Di(0),Di(0)]),subtitle:()=>tr("nmhd",0,0)},br=()=>Zi("dinf",void 0,[yr()]),yr=()=>tr("dref",0,0,[zi(1)],[vr()]),vr=()=>tr("url ",0,1),gr=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return Zi("stbl",void 0,[xr(t),Dr(t),e?Lr(t):null,e?Hr(t):null,Ur(t),zr(t),jr(t),Or(t)])},xr=t=>{let e;if("video"===t.type)e=Er(fn(t.track.source.St,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=mn(t.track.source.St,t.info.decoderConfig.codec,t.muxer.isQuickTime);I(i),e=_r(i,t)}else"subtitle"===t.type&&(e=Nr(bn[t.track.source.St],t));return I(e),tr("stsd",0,0,[zi(1)],[e])},Er=(t,e)=>Zi(t,[Array(6).fill(0),Di(1),Di(0),Di(0),Array(12).fill(0),Di(e.info.width),Di(e.info.height),zi(4718592),zi(4718592),zi(0),Di(1),Ni(10),Qi("Mediabunny"),Array(21).fill(0),Di(e.info.hasAlphaChannel?32:24),Oi(65535)],[pn[e.track.source.St]?.(e)??null,Tr(e),q(e.info.decoderConfig.colorSpace)?kr(e):null]),Tr=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:Zi("pasp",[zi(t.info.pixelAspectRatio.num),zi(t.info.pixelAspectRatio.den)]),kr=t=>Zi("colr",[Qi(t.muxer.isQuickTime?"nclc":"nclx"),Di(j[t.info.decoderConfig.colorSpace.primaries]),Di(L[t.info.decoderConfig.colorSpace.transfer]),Di(H[t.info.decoderConfig.colorSpace.matrix]),t.muxer.isQuickTime?[]:Ni((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Mr=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?j[e.colorSpace.primaries]:2,a=i[6]?Number(i[6]):e.colorSpace?.transfer?L[e.colorSpace.transfer]:2,h=i[7]?Number(i[7]):e.colorSpace?.matrix?H[e.colorSpace.matrix]:2;return tr("vpcC",1,0,[Ni(r),Ni(n),Ni(o),Ni(s),Ni(a),Ni(h),Di(0)])},_r=(t,e)=>{let i,r=0,n=16;const o=It.includes(e.track.source.St);if(o){const t=e.track.source.St,{sampleSize:i}=Gt(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),Di(1),Di(r),Di(0),zi(0),Di(e.info.numberOfChannels),Di(n),Di(0),Di(0),Di(e.info.sampleRate<65536?e.info.sampleRate:0),Di(0)];else{const t=o?0:-2;i=[Array(6).fill(0),Di(1),Di(r),Di(0),zi(0),Di(e.info.numberOfChannels),Di(Math.min(n,16)),Oi(t),Di(0),Di(e.info.sampleRate<65536?e.info.sampleRate:0),Di(0),o?[zi(1),zi(n/8),zi(e.info.numberOfChannels*n/8)]:[zi(0),zi(0),zi(0)],zi(2)]}return Zi(t,i,[wn(e.track.source.St,e.muxer.isQuickTime)?.(e)??null])},Cr=t=>{let e;switch(t.track.source.St){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.St}`)}let i=[...Ni(e),...Ni(21),...Ui(0),...zi(0),...zi(0)];if(t.info.decoderConfig.description){const e=O(t.info.decoderConfig.description);i=[...i,...Ni(5),...Xi(e.byteLength),...e]}return i=[...Di(1),...Ni(0),...Ni(4),...Xi(i.length),...i,...Ni(6),...Ni(1),...Ni(2)],i=[...Ni(3),...Xi(i.length),...i],tr("esds",0,0,i)},Sr=t=>Zi("wave",void 0,[Ar(t),Pr(t),Zi("\0\0\0\0")]),Ar=t=>Zi("frma",[Qi(mn(t.track.source.St,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),Pr=t=>{const{littleEndian:e}=Gt(t.track.source.St);return Zi("enda",[Di(+e)])},Br=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){I(a.byteLength>=18);const t=xe(O(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return Zi("dOps",[Ni(0),Ni(e),Di(i),zi(r),Oi(n),Ni(o),...s])},Ir=t=>{const e=t.info.decoderConfig?.description;I(e);const i=O(e);return tr("dfLa",0,0,[...i.subarray(4)])},Fr=t=>{const{littleEndian:e,sampleSize:i}=Gt(t.track.source.St);return tr("pcmC",0,0,[Ni(+e),Ni(8*i)])},$r=t=>{I(t.info.primingPacket);const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new Ct(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 Ct(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),Zi("dac3",[...i])},Vr=t=>{I(t.info.primingPacket);const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new Ct(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=Te[o];let d;return d=n<3?re[n]/1e3:ne[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 Ct(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 Zi("dec3",[...n])},Rr=t=>{I(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 Ct(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>=Ce.length)return null;const s=ke[e.readBits(4)];if(0===s)return null;const a=Me[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=_e[e.readBits(3)];if(0===c)return null;const l=0!==h;return{frameSize:n,sampleRate:s,numberOfChannels:Ce[o]+(l?1:0),sampleCount:32*r,channelLayout:Se[o]|(l?8:0),amode:o,lfePresent:l,bitRate:a,pcmResolution:c}})(t),i=U(t);let r=e?4*Math.ceil(e.frameSize/4):0,n=null;for(;r+4<=t.length&&1683496997===i.getUint32(r);){const e=Ie(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 Zi("ddts",[...Fe(e)])},Nr=(t,e)=>Zi(t,[Array(6).fill(0),Di(1)],[yn[e.track.source.St](e)]),Dr=t=>tr("stts",0,0,[zi(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[zi(t.sampleCount),zi(t.sampleDelta)])]),Or=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return tr("stss",0,0,[zi(e.length),e.map(([t])=>zi(t+1))])},Ur=t=>tr("stsc",0,0,[zi(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[zi(t.firstChunk),zi(t.samplesPerChunk),zi(1)])]),zr=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=Gt(t.track.source.St);return tr("stsz",0,0,[zi(e*t.info.numberOfChannels),zi(t.samples.reduce((e,i)=>e+Pn(i.duration,t.timescale),0))])}return tr("stsz",0,0,[zi(0),zi(t.samples.length),t.samples.map(t=>zi(t.size))])},jr=t=>t.finalizedChunks.length>0&&V(t.finalizedChunks).offset>=2**32?tr("co64",0,0,[zi(t.finalizedChunks.length),t.finalizedChunks.map(t=>Li(t.offset))]):tr("stco",0,0,[zi(t.finalizedChunks.length),t.finalizedChunks.map(t=>zi(t.offset))]),Lr=t=>tr("ctts",1,0,[zi(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[zi(t.sampleCount),ji(t.sampleCompositionTimeOffset)])]),Hr=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;I(t.compositionTimeOffsetTable.length>0),I(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,Pn(e.timestamp,t.timescale)),n=Math.max(n,Pn(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:tr("cslg",0,0,[ji(o),ji(e),ji(i),ji(r),ji(n)])},qr=t=>Zi("mvex",void 0,t.map(Gr)),Gr=t=>tr("trex",0,0,[zi(t.track.id),zi(1),zi(0),zi(0),zi(0)]),Wr=(t,e)=>Zi("moof",void 0,[Xr(t),...e.map(Yr)]),Xr=t=>tr("mfhd",0,0,[zi(t)]),Qr=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},Yr=t=>Zi("traf",void 0,[Jr(t),Kr(t),Zr(t)]),Jr=t=>{I(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:Qr(i)};return tr("tfhd",0,131128,[zi(t.track.id),zi(r.duration),zi(r.size),zi(r.flags)])},Kr=t=>(I(t.currentChunk),tr("tfdt",1,0,[Li(Pn(t.currentChunk.startTimestamp,t.timescale))])),Zr=t=>{I(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(Qr),n=t.currentChunk.samples.map(e=>Pn(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,tr("trun",1,p,[zi(t.currentChunk.samples.length),zi(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?zi(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?zi(e[o]):[],d?zi(i[o]):[],u?zi(r[o]):[],f?ji(n[o]):[]])])},tn=t=>tr("tfra",1,0,[zi(t.track.id),zi(63),zi(t.finalizedChunks.length),t.finalizedChunks.map(e=>[Li(Pn(e.samples[0].timestamp,t.timescale)),Li(e.moofOffset),zi(e.trafIndex+1),zi(1),zi(1)])]),en=()=>Zi("vtte"),rn=(t,e,i,r,n)=>Zi("vttc",void 0,[null!==n?Zi("vsid",[ji(n)]):null,null!==i?Zi("iden",[...z.encode(i)]):null,null!==e?Zi("ctim",[...z.encode(Fi(e))]):null,null!==r?Zi("sttg",[...z.encode(r)]):null,Zi("payl",[...z.encode(t)])]),nn=t=>Zi("vtta",[...z.encode(t)]),on=t=>{const e=[],i=t.format.At.metadataFormat??"auto",r=t.output.Pt;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=ln(r);t&&e.push(t)}else if("mdta"===i){const t=dn(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&sn(e,t.output.Pt);return 0===e.length?null:Zi("udta",void 0,e)},sn=(t,e)=>{for(const{key:i,value:r}of pt(e))switch(i){case"title":t.push(an("©nam",r));break;case"description":t.push(an("©des",r));break;case"artist":t.push(an("©ART",r));break;case"album":t.push(an("©alb",r));break;case"albumArtist":t.push(an("albr",r));break;case"genre":t.push(an("©gen",r));break;case"date":t.push(an("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(an("©cmt",r));break;case"lyrics":t.push(an("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:Y(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(an(i,r)):r instanceof Uint8Array&&t.push(Zi(i,Array.from(r))))}},an=(t,e)=>{const i=z.encode(e);return Zi(t,[Di(i.length),Di(vn("und")),Array.from(i)])},hn={"image/jpeg":13,"image/png":14,"image/bmp":27},cn=(t,e)=>{const i=[];for(const{key:r,value:n}of pt(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:un(n)});break;case"description":i.push({key:e?"description":"©des",value:un(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:un(n)});break;case"album":i.push({key:e?"album":"©alb",value:un(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:un(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:un(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:un(n)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:un(n)});break;case"date":i.push({key:e?"date":"©day",value:un(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:Zi("data",[zi(hn[t.mimeType]??0),zi(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:un(e)})}else i.push({key:"trkn",value:Zi("data",[zi(0),zi(0),Di(0),Di(n),Di(t.tracksTotal??0),Di(0)])});break;case"discNumber":e||i.push({key:"disc",value:Zi("data",[zi(0),zi(0),Di(0),Di(n),Di(t.discsTotal??0),Di(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:Y(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:un(n)}):n instanceof Uint8Array?i.push({key:r,value:Zi("data",[zi(0),zi(0),Array.from(n)])}):n instanceof Mt&&i.push({key:r,value:Zi("data",[zi(hn[n.mimeType]??0),zi(0),Array.from(n.data)])}))}return i},ln=t=>{const e=cn(t,!1);return 0===e.length?null:tr("meta",0,0,void 0,[pr(!1,"mdir","","appl"),Zi("ilst",void 0,e.map(t=>Zi(t.key,void 0,[t.value])))])},dn=t=>{const e=cn(t,!0);return 0===e.length?null:Zi("meta",void 0,[pr(!1,"mdta",""),tr("keys",0,0,[zi(e.length)],e.map(t=>Zi("mdta",[...z.encode(t.key)]))),Zi("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...zi(e+1));return Zi(i,void 0,[t.value])}))])},un=t=>Zi("data",[zi(1),zi(0),...z.encode(t)]),fn=(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}},pn={avc:t=>t.info.decoderConfig&&Zi("avcC",[...O(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&Zi("hvcC",[...O(t.info.decoderConfig.description)]),vp8:Mr,vp9:Mr,av1:t=>Zi("av1C",Ht(t.info.decoderConfig.codec)),prores:null},mn=(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 Cr;case"opus":return Br;case"flac":return Ir;case"ac3":return $r;case"eac3":return Vr;case"dts":return Rr}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 Sr}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 Fr}return null},bn={webvtt:"wvtt"},yn={webvtt:t=>Zi("vttC",[...z.encode(t.info.config.description)])},vn=t=>{I(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},gn=class{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t.Bt)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t.It(e),t.Bt=!0}start(){I(!this.started),this.target.Ft(),this.started=!0}write(t){I(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target.$t(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return I(this.started&&!this.finalized),this.target.Vt()}async finalize(){I(this.started&&!this.finalized),await this.target.Rt(),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}},xn=(Ge(),class extends gt{constructor(){super(...arguments),this.Bt=!1,this.Nt=null,this.onwrite=null}It(t){!1!==this.Nt&&(this.Nt=t)}Dt(t,e){this.onwrite?.(t,e),this.it("write",{start:t,end:e})}slice(t){if(!Number.isInteger(t)||t<0)throw new TypeError("offset must be a non-negative integer.");return new _n(this,t)}}),En=65536,Tn=2**32,kn=class extends xn{constructor(t={}){if(super(),this.buffer=null,this.Ot=0,!t||"object"!=typeof t)throw new TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");if(this.At=t,this.Ut="resize"in/* @__PURE__ */new ArrayBuffer(0),this.Ut)try{this.zt=new ArrayBuffer(En,{maxByteLength:Tn})}catch{this.zt=new ArrayBuffer(En),this.Ut=!1}else this.zt=new ArrayBuffer(En);this.jt=new Uint8Array(this.zt)}Lt(t){let e=this.zt.byteLength;for(;e<t;)e*=2;if(e!==this.zt.byteLength){if(e>Tn)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.Ut)this.zt.resize(e);else{const t=new ArrayBuffer(e),i=new Uint8Array(t);i.set(this.jt,0),this.zt=t,this.jt=i}}}Ft(){}$t(t,e){this.Lt(e+t.byteLength),this.jt.set(t,e),this.Ot=Math.max(this.Ot,e+t.byteLength),this.Dt(e,e+t.byteLength)}async Vt(){}async Rt(){this.buffer=this.zt.slice(0,this.Ot),this.At.onFinalize&&await this.At.onFinalize(this.buffer),this.it("finalized")}async Ht(){}qt(t,e){return this.jt.slice(t,e)}},Mn=class extends xn{constructor(t,e={}){if(super(),this.Gt=[],this.Wt=0,this.Xt=0,this.Qt=null,this.Yt=null,this.Jt=[],!(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.Kt=t,this.At=e,this.Zt=e.chunked??!1,this.te=e.chunkSize??16777216}Ft(){this.Qt=this.Kt.getWriter()}$t(t,e){if(e>this.Wt){const t=e-this.Wt;this.$t(new Uint8Array(t),this.Wt)}this.Gt.push({data:t.slice(),start:e}),this.Wt=Math.max(this.Wt,e+t.byteLength),this.Dt(e,e+t.byteLength)}async Vt(){if(null!==this.Yt)throw this.Yt;if(I(this.Qt),0===this.Gt.length)return;const t=[],e=[...this.Gt].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){const r=t[t.length-1],n=e[i];n.start<=r.start+r.size?r.size=Math.max(r.size,n.start+n.data.byteLength-r.start):t.push({start:n.start,size:n.data.byteLength})}for(const i of t){i.data=new Uint8Array(i.size);for(const t of this.Gt)i.start<=t.start&&t.start<i.start+i.size&&i.data.set(t.data,t.start-i.start);if(null!==this.Qt.desiredSize&&this.Qt.desiredSize<=0&&await this.Qt.ready,this.Zt)this.ee(i.data,i.start),this.ie();else{if(!0===this.Nt&&i.start!==this.Xt)throw new Error("Internal error: Monotonicity violation.");this.Qt.write({type:"write",data:i.data,position:i.start}).catch(t=>{this.Yt??=t}),this.Xt=i.start+i.data.byteLength}}this.Gt.length=0}ee(t,e){let i=this.Jt.findIndex(t=>t.start<=e&&e<t.start+this.te);-1===i&&(i=this.re(e));const r=this.Jt[i],n=e-r.start,o=t.subarray(0,Math.min(this.te-n,t.byteLength));r.data.set(o,n);const s={start:n,end:n+o.byteLength};if(this.ne(r,s),0===r.written[0].start&&r.written[0].end===this.te&&(r.shouldFlush=!0),this.Jt.length>2){for(let t=0;t<this.Jt.length-1;t++)this.Jt[t].shouldFlush=!0;this.ie()}o.byteLength<t.byteLength&&this.ee(t.subarray(o.byteLength),e+o.byteLength)}ne(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)}re(t){const e={start:Math.floor(t/this.te)*this.te,data:new Uint8Array(this.te),written:[],shouldFlush:!1};return this.Jt.push(e),this.Jt.sort((t,e)=>t.start-e.start),this.Jt.indexOf(e)}ie(t=!1){I(this.Qt);for(let e=0;e<this.Jt.length;e++){const i=this.Jt[e];if(i.shouldFlush||t){for(const t of i.written){const e=i.start+t.start;if(!0===this.Nt&&e!==this.Xt)throw new Error("Internal error: Monotonicity violation.");let r;r=0===t.start&&t.end===i.data.byteLength||!at()?i.data.subarray(t.start,t.end):i.data.slice(t.start,t.end),this.Qt.write({type:"write",data:r,position:e}).catch(t=>{this.Yt??=t}),this.Xt=i.start+t.end}this.Jt.splice(e--,1)}}}async Rt(){if(this.Zt&&this.ie(!0),null!==this.Yt)throw this.Yt;I(this.Qt),await this.Qt.ready,await this.Qt.close(),this.it("finalized")}async Ht(){return this.Qt?.close()}},_n=class extends xn{constructor(t,e){super(),this.oe=t,this.se=e}Ft(){}$t(t,e){this.oe.$t(t,this.se+e),this.Dt(e,e+t.byteLength)}Vt(){return this.oe.Vt()}async Rt(){this.it("finalized")}async Ht(){}It(t){super.It(t),this.oe.It(t)}},Cn=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.")}},Sn=57600,An=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},Pn=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},Bn=class extends Pi{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new kn,this.auxWriter=new gn(this.auxTarget,!1),this.auxBoxWriter=new $i(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Q(),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.At},this.isQuickTime=e instanceof Jn,this.isCmaf=e instanceof Yn,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(e instanceof Yn?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.ae(t=>void 0!==this.formatOptions.fastStart?"fragmented"===this.formatOptions.fastStart:t instanceof kn),this.boxWriter=new $i(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof kn&&"in-memory"),this.isFragmented="fragmented"===this.fastStart),this.isCmaf){if(!this.output.he())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 gn(await this.output.ce(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new $i(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.St);{const t=this.initBoxWriter??this.boxWriter;if(I(t),this.formatOptions.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return Zi("ftyp",t.isQuickTime?[Qi("qt "),zi(e),Qi("qt ")]:t.fragmented?t.cmaf?[Qi("iso5"),zi(e),Qi("iso5"),Qi("iso6"),Qi("mp41"),Qi("cmfc"),Qi("dash")]:[Qi("iso5"),zi(e),Qi("iso5"),Qi("iso6"),Qi("mp41")]:[Qi("isom"),zi(e),Qi("isom"),t.holdsAvc?Qi("avc1"):[],Qi("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||(I(this.writer),I(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=rr(!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.ut&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.St]);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;Zt(i,t.source.St),I(i),I(i.decoderConfig);const n={...i.decoderConfig};I(void 0!==n.codedWidth),I(void 0!==n.codedHeight);let o=!1;if("avc"!==t.source.St||n.description){if("hevc"===t.source.St&&!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 se(t)){const o=t.subarray(h.offset,h.offset+h.length),s=ue(o[0]);s===kt.VPS_NUT?e.push(o):s===kt.SPS_NUT?i.push(o):s===kt.PPS_NUT?r.push(o):s!==kt.PREFIX_SEI_NUT&&s!==kt.SUFFIX_SEI_NUT||n.push(o)}if(0===i.length||0===r.length)return null;const o=(t=>{try{const e=new Ct(ce(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}=fe(e,i);N(e);const l=N(e);let d=0;3===l&&(d=e.readBits(1));const u=N(e),f=N(e);let p=u,m=f;if(e.readBits(1)){const t=N(e),i=N(e),r=N(e),n=N(e);let o=1,s=1;const a=0===d?l:0;1===a?(o=2,s=2):2===a&&(o=2,s=1),p-=(t+i)*o,m-=(r+n)*s}const w=N(e),b=N(e);N(e);const y=e.readBits(1)?0:i;let v=0;for(let t=y;t<=i;t++)N(e),v=N(e),N(e);N(e),N(e),N(e),N(e),N(e),N(e),e.readBits(1)&&e.readBits(1)&&pe(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),N(e),N(e),e.skipBits(1));const g=N(e);if(me(e,g),e.readBits(1)){const t=N(e);for(let i=0;i<t;i++)N(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,E=2,T=2,k=0,M=0,_={num:1,den:1};if(e.readBits(1)){const t=be(e,i);_=t.pixelAspectRatio,x=t.colourPrimaries,E=t.transferCharacteristics,T=t.matrixCoefficients,k=t.fullRangeFlag,M=t.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:m,pixelAspectRatio:_,colourPrimaries:x,transferCharacteristics:E,matrixCoefficients:T,fullRangeFlag:k,maxDecFrameBuffering:v+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:a,generalConstraintIndicatorFlags:h,generalLevelIdc:c,chromaFormatIdc:l,bitDepthLumaMinus8:w,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:M}}catch(e){return Et.st("Error parsing HEVC SPS:",e),null}})(i[0]);if(!o)return null;let s=0;if(r.length>0){const t=r[0],e=new Ct(ce(t));e.skipBits(16),N(e),N(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),N(e),N(e),D(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&N(e),D(e),D(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:kt.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:kt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:kt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ue(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 Et.st("Error building HEVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push((3&t.generalProfileSpace)<<6|(1&t.generalTierFlag)<<5|31&t.generalProfileIdc),e.push(t.generalProfileCompatibilityFlags>>>24&255),e.push(t.generalProfileCompatibilityFlags>>>16&255),e.push(t.generalProfileCompatibilityFlags>>>8&255),e.push(255&t.generalProfileCompatibilityFlags),e.push(...t.generalConstraintIndicatorFlags),e.push(255&t.generalLevelIdc),e.push(240|t.minSpatialSegmentationIdc>>8&15),e.push(255&t.minSpatialSegmentationIdc),e.push(252|3&t.parallelismType),e.push(252|3&t.chromaFormatIdc),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.avgFrameRate>>8&255),e.push(255&t.avgFrameRate),e.push((3&t.constantFrameRate)<<6|(7&t.numTemporalLayers)<<3|(1&t.temporalIdNested)<<2|3&t.lengthSizeMinusOne),e.push(255&t.arrays.length);for(const i of t.arrays){e.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),e.push(i.nalUnits.length>>8&255),e.push(255&i.nalUnits.length);for(const t of i.nalUnits){e.push(t.length>>8&255),e.push(255&t.length);for(let i=0;i<t.length;i++)e.push(t[i])}}return new Uint8Array(e)})(t),o=!0}}else{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 se(t)){const n=t.subarray(s.offset,s.offset+s.length),o=he(n[0]);o===Tt.SPS?e.push(n):o===Tt.PPS?i.push(n):o===Tt.SPS_EXT&&r.push(n)}if(0===e.length)return null;if(0===i.length)return null;const n=(t=>{try{const e=new Ct(ce(t));if(e.skipBits(1),e.skipBits(2),7!==e.readBits(5))return null;const i=e.readAlignedByte(),r=e.readAlignedByte(),n=e.readAlignedByte();N(e);let o=1,s=0,a=0,h=0;if((100===i||110===i||122===i||244===i||44===i||83===i||86===i||118===i||128===i)&&(o=N(e),3===o&&(h=e.readBits(1)),s=N(e),a=N(e),e.skipBits(1),e.readBits(1)))for(let t=0;t<(3!==o?8:12);t++)if(e.readBits(1)){const i=t<6?16:64;let r=8,n=8;for(let t=0;t<i;t++)0!==n&&(n=(r+D(e)+256)%256),r=0===n?r:n}N(e);const c=N(e);if(0===c)N(e);else if(1===c){e.skipBits(1),D(e),D(e);const t=N(e);for(let i=0;i<t;i++)D(e)}N(e),e.skipBits(1);const l=N(e),d=N(e),u=16*(l+1),f=16*(d+1);let p=u,m=f;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const t=N(e),i=N(e),r=N(e),n=N(e);let s,a;0===(0===h?o:0)?(s=1,a=2-w):(s=3===o?1:2,a=(1===o?2:1)*(2-w)),p-=s*(t+i),m-=a*(r+n)}let b=2,y=2,v=2,g=0,x={num:1,den:1},E=null,T=null;if(e.readBits(1)){if(e.readBits(1)){const t=e.readBits(8);if(255===t)x={num:e.readBits(16),den:e.readBits(16)};else{const e=le[t];e&&(x=e)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),g=e.readBits(1),e.readBits(1)&&(b=e.readBits(8),y=e.readBits(8),v=e.readBits(8))),e.readBits(1)&&(N(e),N(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const t=e.readBits(1);t&&de(e);const i=e.readBits(1);i&&de(e),(t||i)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),N(e),N(e),N(e),N(e),E=N(e),T=N(e))}if(null===E)if(I(null===T),(44===i||86===i||100===i||110===i||122===i||244===i)&&16&r)E=0,T=0;else{const t=l+1,e=(2-w)*(d+1),i=Rt.find(t=>t.level>=n)??V(Rt),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);E=r,T=r}return I(null!==T),{profileIdc:i,constraintFlags:r,levelIdc:n,frameMbsOnlyFlag:w,chromaFormatIdc:o,bitDepthLumaMinus8:s,bitDepthChromaMinus8:a,codedWidth:u,codedHeight:f,displayWidth:p,displayHeight:m,pixelAspectRatio:x,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:y,fullRangeFlag:g,numReorderFrames:E,maxDecFrameBuffering:T}}catch(e){return Et.st("Error parsing AVC SPS:",e),null}})(e[0]);I(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 Et.st("Error building AVC Decoder Configuration Record:",e),null}})(e.data);if(!t)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=(t=>{const e=[];e.push(t.configurationVersion),e.push(t.avcProfileIndication),e.push(t.profileCompatibility),e.push(t.avcLevelIndication),e.push(252|3&t.lengthSizeMinusOne),e.push(224|31&t.sequenceParameterSets.length);for(const i of t.sequenceParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}e.push(t.pictureParameterSets.length);for(const i of t.pictureParameterSets){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}if(100===t.avcProfileIndication||110===t.avcProfileIndication||122===t.avcProfileIndication||144===t.avcProfileIndication){I(null!==t.chromaFormat),I(null!==t.bitDepthLumaMinus8),I(null!==t.bitDepthChromaMinus8),I(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}:bt({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;ee(i,t.source.St),I(i),I(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.St&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=qe(Si.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=St[t.samplingFrequencyIndex],r=At[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Pt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}if(!e){if("ac3"===t.source.St||"eac3"===t.source.St)throw new Error("AC-3/E-AC-3 require a priming packet.");if("dts"===t.source.St)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&&It.includes(t.source.St),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;ie(e),I(e),I(e.config);const r={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...se(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=qe(Si.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=Gt(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=Pn(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=Gt(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.St&&(r.cueQueue.push(e),await this.processWebVTTCues(r,e.timestamp))}finally{r()}}async processWebVTTCues(t,e){for(;t.cueQueue.length>0;){const i=/* @__PURE__ */new Set([]);for(const h of t.cueQueue)I(h.timestamp<=e),I(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=en();this.auxBoxWriter.writeBox(e);const i=this.auxTarget.qt(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;Bi.lastIndex=0;const r=Bi.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=nn(i.notes);this.auxBoxWriter.writeBox(t)}const h=rn(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.qt(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:Pn(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){this.isFragmented||(t.startTimestampOffset??=t.timestampProcessingQueue[0].timestamp);let e=0;for(let i=0;i<t.timestampProcessingQueue.length;i++){const r=t.timestampProcessingQueue[i];e+=Pn(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):V(t.timeToSampleTable).sampleCount+=e,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(t=>t.timestamp).sort((t,e)=>t-e);this.isFragmented||(t.startTimestampOffset??=i[0]);for(let r=0;r<t.timestampProcessingQueue.length;r++){const e=t.timestampProcessingQueue[r];e.decodeTimestamp=i[r];const n=Pn(e.timestamp-e.decodeTimestamp,t.timescale),o=Pn(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){I(t.lastSample);const i=Pn(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(I(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=V(t.timeToSampleTable);if(I(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=V(t.compositionTimeOffsetTable);I(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=Pn(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,I(t.lastSample),I(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){I("key"===e.type);const i=Pn(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(I(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}),I(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(I(!this.isFragmented),I(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+Pn(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&V(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)I(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(I(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(I(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const t=this.initBoxWriter??this.boxWriter;I(t),this.formatOptions.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=nr(this);if(t.writeBox(e),this.formatOptions.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onMoov(e,i)}if(this.isCmaf){I(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.ae(!0),this.boxWriter=new $i(this.writer);const t=this.boxWriter.measureBox(er()),e=this.boxWriter.measureBox(ir(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}I(this.writer),I(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=Wr(i,e),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let s=o+8,a=1/0;for(let u=0;u<e.length;u++){const t=e[u];t.currentChunk.offset=s,t.currentChunk.moofOffset=n,t.currentChunk.trafIndex=u;for(const e of t.currentChunk.samples)s+=e.size;a=Math.min(a,t.currentChunk.startTimestamp)}const h=s-o,c=h>=2**32;if(c)for(const u of e)u.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const l=Wr(i,e);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(t,e,a)}I(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const d=rr(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(){I(this.writer),I(this.boxWriter),this.ensureOneEnabledTrack();const t=nr(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;I(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=rr(!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(){I("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;I(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.St&&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(){I(this.isFragmented);const t=await this.mutex.acquire();try{for(const t of this.trackDatas)"subtitle"===t.type&&"webvtt"===t.track.source.St&&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.St&&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(I(this.writer),I(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=rr(!1);for(let i=0;i<2;i++){const e=nr(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)I(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=nr(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)I(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(er()),this.boxWriter.writeBox(ir(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,Zi("mfra",void 0,[...e.map(tn),tr("mfro",0,0,[zi(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{I(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);I(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=nr(this);if("reserve"===this.fastStart){I(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()}},In="Mediabunny",Fn={video:1,audio:2,subtitle:17},$n=class extends Pi{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=Q(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=/* @__PURE__ */new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=e}async start(){const t=await this.mutex.acquire();this.writer=await this.output.ae(!!this.format.At.appendOnly),this.ebmlWriter=new Le(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.At.onEbmlHeader&&this.writer.startTrackingWrites();const t={id:Ee.EBML,data:[{id:Ee.EBMLVersion,data:1},{id:Ee.EBMLReadVersion,data:1},{id:Ee.EBMLMaxIDLength,data:4},{id:Ee.EBMLMaxSizeLength,data:8},{id:Ee.DocType,data:this.format instanceof Zn?"webm":"matroska"},{id:Ee.DocTypeVersion,data:2},{id:Ee.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(t),this.format.At.onEbmlHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onEbmlHeader(t,e)}}maybeCreateSeekHead(t){if(this.format.At.appendOnly)return;const e=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),s={id:Ee.SeekHead,data:[{id:Ee.Seek,data:[{id:Ee.SeekID,data:e},{id:Ee.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:Ee.Seek,data:[{id:Ee.SeekID,data:i},{id:Ee.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:Ee.Seek,data:[{id:Ee.SeekID,data:r},{id:Ee.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:Ee.Seek,data:[{id:Ee.SeekID,data:n},{id:Ee.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:Ee.Seek,data:[{id:Ee.SeekID,data:o},{id:Ee.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const t={id:Ee.Duration,data:new Ne(0)};this.segmentDuration=t;const e={id:Ee.Info,data:[{id:Ee.TimestampScale,data:1e6},{id:Ee.MuxingApp,data:In},{id:Ee.WritingApp,data:In},this.format.At.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:Ee.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){let i=He[e.track.source.St];I(i),"audio"===e.type&&"dts"===e.track.source.St&&("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.St){r=8e7;const t=e.info.decoderConfig.description;if(t){const e=xe(O(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:Ee.TrackEntry,data:[{id:Ee.TrackNumber,data:e.track.id},{id:Ee.TrackUID,data:e.track.id},{id:Ee.TrackType,data:Fn[e.type]},!1===e.track.metadata.disposition?.default?{id:Ee.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:Ee.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:Ee.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:Ee.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:Ee.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:Ee.FlagCommentary,data:1}:null,{id:Ee.FlagLacing,data:0},{id:Ee.Language,data:e.track.metadata.languageCode??"und"},{id:Ee.CodecID,data:i},e.codecPrivate?{id:Ee.CodecPrivate,data:O(e.codecPrivate)}:null,{id:Ee.CodecDelay,data:0},{id:Ee.SeekPreRoll,data:r},void 0!==e.track.metadata.name?{id:Ee.Name,data:new Oe(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:Ee.DefaultDuration,data:1e9/e}:null],n=i?$(-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:Ee.Video,data:[{id:Ee.PixelWidth,data:t.info.width},{id:Ee.PixelHeight,data:t.info.height},o?{id:Ee.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:Ee.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:Ee.DisplayUnit,data:3}:null,t.info.alphaMode?{id:Ee.AlphaMode,data:1}:null,q(s)?{id:Ee.Colour,data:[{id:Ee.MatrixCoefficients,data:H[s.matrix]},{id:Ee.TransferCharacteristics,data:L[s.transfer]},{id:Ee.Primaries,data:j[s.primaries]},{id:Ee.Range,data:s.fullRange?2:1}]}:null,n?{id:Ee.Projection,data:[{id:Ee.ProjectionType,data:0},{id:Ee.ProjectionPoseRoll,data:new Re((n+180)%360-180)}]}:null]};return r.push(a),r}audioSpecificTrackInfo(t){const e=It.includes(t.track.source.St)?Gt(t.track.source.St):null;return[{id:Ee.Audio,data:[{id:Ee.SamplingFrequency,data:new Re(t.info.sampleRate)},{id:Ee.Channels,data:t.info.numberOfChannels},e?{id:Ee.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:Ee.SimpleTag,data:[{id:Ee.TagName,data:new Oe(e)},"string"==typeof i?{id:Ee.TagString,data:new Oe(i)}:{id:Ee.TagBinary,data:i}]})},i=this.output.Pt,r=/* @__PURE__ */new Set;for(const{key:n,value:o}of pt(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:Y(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:Ee.Tags,data:[{id:Ee.Tag,data:[{id:Ee.Targets,data:[{id:Ee.TargetTypeValue,data:50},{id:Ee.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.Pt,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")+(mt(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:Ee.AttachedFile,data:[void 0!==n.description?{id:Ee.FileDescription,data:new Oe(n.description)}:null,{id:Ee.FileName,data:new Oe(r)},{id:Ee.FileMediaType,data:n.mimeType},{id:Ee.FileData,data:n.data},{id:Ee.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof _t&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&&wt(t.data,o.data))||e.push({id:Ee.AttachedFile,data:[void 0!==o.description?{id:Ee.FileDescription,data:new Oe(o.description)}:null,{id:Ee.FileName,data:new Oe(o.name??"")},{id:Ee.FileMediaType,data:o.mimeType??""},{id:Ee.FileData,data:o.data},{id:Ee.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:Ee.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:Ee.Segment,size:this.format.At.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=t,this.format.At.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(t),this.format.At.onSegmentHeader){const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onSegmentHeader(t,e)}}createCues(){this.cues={id:Ee.Cues,data:[]}}get segmentDataOffset(){return I(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.ut&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.St]);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 Zn,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;Zt(i,t.source.St),I(i),I(i.decoderConfig),I(void 0!==i.decoderConfig.codedWidth),I(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:bt({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.St?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.St?a.codecPrivate=new Uint8Array(Ht(a.info.decoderConfig.codec)):"prores"===t.source.St&&(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;ee(i,t.source.St),I(i),I(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.St&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=qe(Si.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=St[t.samplingFrequencyIndex],r=At[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Pt({objectType:t.objectType,sampleRate:i,numberOfChannels:r}),o=!0}const s={track:t,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.description??null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(t,e){const i=this.trackDatas.find(e=>e.track===t);if(i)return i;ie(e),I(e),I(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.St){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=tt(s,t.metadata.frameRate),a=tt(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.St&&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=qe(Si.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);Bi.lastIndex=0,n=n.replace(Bi,t=>`<${Fi((t=>{const e=Ii.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 Ct(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){I(null!==this.currentClusterStartMsTimestamp),I(null!==this.currentClusterMaxMsTimestamp);const t=i-this.currentClusterStartMsTimestamp;n=r&&i>this.currentClusterMaxMsTimestamp&&t>=1e3*(this.format.At.minimumClusterDuration??1)||t>32767}else n=!0;n&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768)return;const s=/* @__PURE__ */new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:Ee.BlockGroup,data:[{id:Ee.Block,data:[s,e.data]},"delta"===e.type?{id:Ee.ReferenceBlock,data:new De(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:Ee.BlockAdditions,data:[{id:Ee.BlockMore,data:[{id:Ee.BlockAddID,data:1},{id:Ee.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:Ee.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:Ee.SimpleBlock,data:[s,e.data]};this.ebmlWriter.writeEBML(t)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+h),t.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(t){this.currentCluster&&this.finalizeCurrentCluster(),this.format.At.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:Ee.Cluster,size:this.format.At.appendOnly?-1:5,data:[{id:Ee.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(I(this.currentCluster),!this.format.At.appendOnly){const t=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),e=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(t,5),this.writer.seek(e)}if(this.format.At.onCluster){I(null!==this.currentClusterStartMsTimestamp);const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.At.onCluster(t,e,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=/* @__PURE__ */new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)I(this.cues),this.cues.data.push({id:Ee.CuePoint,data:[{id:Ee.CueTime,data:r},...n.map(e=>({id:Ee.CueTrackPositions,data:[{id:Ee.CueTrack,data:e.track.id},{id:Ee.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(),I(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format.At.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6);const e=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Ne(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),I(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},Vn=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},Rn=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}),Nn=class{constructor(){this.le=null,this.de=null,this.ut=!1}ue(){if(!this.le)throw new Error("Source is not connected to an output track.");if("canceled"===this.le.output.state)throw new Error("Output has been canceled.");if("finalizing"===this.le.output.state||"finalized"===this.le.output.state)throw new Error("Output has been finalized.");if("pending"===this.le.output.state)throw new Error("Output has not started.");if(this.ut)throw new Error("Source is closed.")}async Ft(){}async fe(t){}close(){if(this.de)return;const t=this.le;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.de=(async()=>{await this.fe(!1),this.ut=!0,"finalizing"!==t.output.state&&"finalized"!==t.output.state&&t.output.pe.onTrackClose(t)})()}async me(t){return this.de??=(async()=>{await this.fe(t),this.ut=!0})()}},Dn=class extends Nn{constructor(t){if(super(),this.le=null,!Bt.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${Bt.join(", ")}.`);this.St=t}},On=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Un=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 ot,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.ue();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&&(I(this.outputWidth),I(this.outputHeight),I("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=et(t.timestamp,a);if(null!==this.frameRateLastSample){if(o<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=n);await this.padFrameRate(o,i)}t===r&&(t=t.clone(),e=!0),t.setTimestamp(o),t.setDuration(1/a),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=o,this.frameRateLastEndTimestamp=n}await this.processAndEncode(t,i)}finally{e&&t.close()}}async processAndEncode(t,e){const i=this.encodingConfig;let r;if(i.transform?.process){let e=i.transform.process(t);if(e instanceof Promise&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof ti?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new ti(i)):o.push(new ti(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 ti&&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),I(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{I(this.encoder);const e=t.toVideoFrame(),i=X(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 jn);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;I(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=Vn(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{Rn(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=_i(this.encodingConfig.quality,this.encodingConfig.bitrate);I(void 0!==e);const i=yi({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source.le?.metadata.frameRate});let r,n=null;for(const t of i){const e=t.config;if(this.encodingConfig.onEncoderConfig?.(e),r=Ci.find(t=>t.supports(this.encodingConfig.codec,e)),r){n=t;break}if("undefined"!=typeof VideoEncoder){if(e.alpha="discard","keep"===this.encodingConfig.alpha&&(e.latencyMode="quality"),!(e.width%2!=1&&e.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw new Error(`The dimensions ${e.width}x${e.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);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=ki(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 Ve))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.");On(this.source.le,t),this.encodingConfig.onEncodedPacket?.(t,e),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.le,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=Ve.fromEncodedChunk(t,r);const o=X(this.preciseTimings,t.timestamp,t=>t.microsecondTimestamp),s=-1!==o?this.preciseTimings[o]:null;let a=null;0===this.emittedEncoderPackets&&"delta"===n.type&&i?.decoderConfig&&(a=((t,e,i)=>{switch(t){case"avc":for(const t of((t,e)=>{if(e.description){const i=1+(3&O(e.description)[4]);return ae(t,i)}return se(t)})(i,e)){const e=i[t.offset],r=he(e);if(r>=Tt.NON_IDR_SLICE&&r<=Tt.SLICE_DPC)return"delta";if(r===Tt.IDR)return"key";if(r===Tt.SEI&&(!dt()||ft()>=144)){const e=i.subarray(t.offset,t.offset+t.length),r=ce(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 Ct(r);t.pos=8*n;const e=N(t),i=t.readBits(1);if(0===e&&1===i)return"key"}n+=e}while(n<r.length-1)}}return"delta";case"hevc":for(const t of((t,e)=>{if(e.description){const i=1+(3&O(e.description)[21]);return ae(t,i)}return se(t)})(i,e)){const e=ue(i[t.offset]);if(e<kt.BLA_W_LP)return"delta";if(e<=kt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new Ct(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 Ct(t),i=()=>{let t=0;for(let i=0;i<8;i++){const r=e.readAlignedByte();if(t|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return t>=2**32-1?null:t};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),n=e.readBits(1),o=e.readBits(1);let s;if(e.skipBits(1),n&&e.skipBits(8),o){const t=i();if(null===t)return;s=t}else s=Math.floor(e.getBitsLeft()/8);I(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 Ct(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new Ct(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:Y(t),I(!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})),On(this.source.le,n),this.encodingConfig.onEncodedPacket?.(n,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.le,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();I(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(I(void 0!==a),n(a.chunk,o,a.meta),i++;e.length>0&&e[0]===i;){e.shift();const i=t.shift();I(void 0!==i),n(i.chunk,null,i.meta)}},error:t=>{t.stack=o,this.setError(t)}}),this.alphaEncoder.configure(s)}}I(this.source.le),this.muxer=this.source.le.output.pe,this.encoderInitialized=!0})()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,e=et(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}},zn=null,jn=class{constructor(){this.worker=null,this.pendingRequests=/* @__PURE__ */new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!zn){const t=new Blob([`(${Ln.toString()})()`],{type:"application/javascript"});zn=URL.createObjectURL(t)}this.worker=new Worker(zn),this.worker.addEventListener("message",t=>{const e=t.data,i=this.pendingRequests.get(e.id);i&&(this.pendingRequests.delete(e.id),"error"in e?i.reject(new Error(e.error)):i.resolve({colorFrame:e.colorFrame,alphaFrame:e.alphaFrame}))}),this.worker.addEventListener("error",t=>{const e=new Error(t.message||"Color/alpha splitter worker error.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()})}const e=this.nextRequestId++,i=Q();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=/* @__PURE__ */new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Ln=()=>{let t=null,e=Promise.resolve();self.addEventListener("message",t=>{const{id:r,sourceFrame:n}=t.data;e=e.then(async()=>{try{const{colorFrame:t,alphaFrame:e}=await i(n);self.postMessage({id:r,colorFrame:t,alphaFrame:e},{transfer:[t,e]})}catch(t){self.postMessage({id:r,error:t.message})}finally{n.close()}})});const i=async e=>{const i=e.format;if(!i)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=e.allocationSize();if(t&&t.byteLength===o||(t=new Uint8Array(o)),await e.copyTo(t),"RGBA"===i||"BGRA"===i)return r(t,i,e);if("I420A"===i||"I420AP10"===i||"I420AP12"===i||"I422A"===i||"I422AP10"===i||"I422AP12"===i||"I444A"===i||"I444AP10"===i||"I444AP12"===i)return n(t,i,e);throw new Error(`CPU color/alpha splitting does not support format '${i}'.`)},r=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=r*n,s=o+Math.ceil(r/2)*Math.ceil(n/2)*2,a=new Uint8Array(s);for(let l=0,d=3;l<o;l++,d+=4)a[l]=t[d];a.fill(128,o);const h=new VideoFrame(t,{format:"RGBA"===e?"RGBX":"BGRX",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),c={format:"I420",codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[a.buffer]};return{colorFrame:h,alphaFrame:new VideoFrame(a,c)}},n=(t,e,i)=>{const r=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=e.includes("P10"),s=e.includes("P12"),a=o||s?2:1;let h,c;e.startsWith("I420")?(h=Math.ceil(r/2),c=Math.ceil(n/2)):e.startsWith("I422")?(h=Math.ceil(r/2),c=n):(h=r,c=n);const l=r*n,d=l*a,u=l*a+h*c*a*2,f=e.replace("A",""),p=Math.ceil(r/2)*Math.ceil(n/2),m=new Uint8Array(d+p*a*2),w=u;m.set(t.subarray(w,w+d),0);const b=d,y=o?512:s?2048:128;1===a?m.fill(y,b):new Uint16Array(m.buffer,b,2*p).fill(y);const v=o?"I420P10":s?"I420P12":"I420",g=new VideoFrame(t.subarray(0,u),{format:f,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),x={format:v,codedWidth:r,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[m.buffer]};return{colorFrame:g,alphaFrame:new VideoFrame(m,x)}}},Hn=class extends Dn{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(!Bt.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${Bt.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 vi))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof vi)&&(!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&&hi(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.");bi(t.codec,t)})(e),super(e.codec),this.we=new Un(this,e),this.be=t}add(t,e=0,i){if(!Number.isFinite(t)||t<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");const r=new ti(this.be,{timestamp:t,duration:e});return this.we.add(r,!0,i)}fe(t){return this.we.flushAndClose(t)}},qn=class extends Nn{constructor(t){if(super(),this.le=null,!$t.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${$t.join(", ")}.`);this.St=t}},Gn=class extends Nn{constructor(t){if(super(),this.le=null,!Vt.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${Vt.join(", ")}.`);this.St=t}},Wn=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>Bt.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>$t.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>Vt.includes(t))}ye(t){return""}ve(){return!1}},Xn=class extends Wn{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==t.minimumFragmentDuration&&(!Number.isFinite(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==t.onFtyp&&"function"!=typeof t.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==t.onMoov&&"function"!=typeof t.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==t.onMdat&&"function"!=typeof t.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==t.onMoof&&"function"!=typeof t.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==t.metadataFormat&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this.At=t}getSupportedTrackCounts(){const t=2**32-1;return{video:{min:0,max:t},audio:{min:0,max:t},subtitle:{min:0,max:t},total:{min:0,max:t}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}ge(t){return new Bn(t,this)}ve(){return"fragmented"===this.At.fastStart}},Qn=class extends Xn{constructor(t){super(t)}get xe(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Bt,...Ft,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Vt]}ye(t){return(new Jn).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},Yn=class extends Xn{constructor(t){super(t)}get xe(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Bt,...Ft,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Vt]}},Jn=class extends Xn{constructor(t){super(t)}get xe(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Bt,...$t]}ye(t){return(new Qn).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Kn=class extends Wn{constructor(t={}){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.appendOnly&&"boolean"!=typeof t.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==t.minimumClusterDuration&&(!Number.isFinite(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==t.onEbmlHeader&&"function"!=typeof t.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==t.onSegmentHeader&&"function"!=typeof t.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==t.onCluster&&"function"!=typeof t.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this.At=t}ge(t){return new $n(t,this)}get xe(){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[...Bt,...Ft,...It.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...Vt]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},Zn=class extends Kn{constructor(t){super(t)}getSupportedCodecs(){return[...Bt.filter(t=>["vp8","vp9","av1"].includes(t)),...$t.filter(t=>["opus","vorbis"].includes(t)),...Vt]}get xe(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}ye(t){return(new Kn).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},to=["video","audio","subtitle"],eo=class t{constructor(t,e,i,r,n){this.id=t,this.output=e,this.type=i,this.source=r,this.metadata=n}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const i=vt(this.metadata.group),r=vt(e.metadata.group);for(const t of i){if(this.type!==e.type&&r.some(e=>t===e))return!0;if(r.some(e=>t.Ee.has(e)))return!0}return!1}},io=class extends eo{constructor(t,e,i,r){super(t,e,"video",i,r)}},ro=class extends eo{constructor(t,e,i,r){super(t,e,"audio",i,r)}},no=class extends eo{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},oo=class t{constructor(){this.Ee=/* @__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.Ee.add(e),e.Ee.add(this)}},so=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&(e=t.languageCode,!rt.test(e)))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");var e;if(void 0!==t.name&&"string"!=typeof t.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==t.disposition&&(t=>{if(!t||"object"!=typeof t)throw new TypeError("disposition must be an object.");if(void 0!==t.default&&"boolean"!=typeof t.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==t.primary&&"boolean"!=typeof t.primary)throw new TypeError("disposition.primary must be a boolean.");if(void 0!==t.forced&&"boolean"!=typeof t.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==t.original&&"boolean"!=typeof t.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==t.commentary&&"boolean"!=typeof t.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==t.hearingImpaired&&"boolean"!=typeof t.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==t.visuallyImpaired&&"boolean"!=typeof t.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(t.disposition),void 0!==t.maximumPacketCount&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==t.group&&!(t.group instanceof oo)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof oo))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},ao=class extends gt{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this.Te)throw new TypeError(t);const e=this.ke();if(e instanceof Promise)throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new oo,this.tracks=[],this.Me=null,this._e=/* @__PURE__ */new Set,this.Ce=null,this.Se=null,this.Ae=null,this.Pe=null,this.Be=new W,this.Pt={},this.Ie=null,this.Te=null,this.Fe=null,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!(t.format instanceof Wn))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof xn||t.target instanceof Cn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof xn&&this.$e(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof xn)&&"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.Ve=t.target,this.Me=t.onFinalize??null,this.Re=t.initTarget??null,this.Re instanceof xn&&this.$e(this.Re),this.pe=t.format.ge(this)}Ne(t){I(this.Ve instanceof Cn);const e=this.Ve.getTarget(t),i=t=>{if(!(t instanceof xn))throw new TypeError("getTarget must return a Target.");return t};return e instanceof Promise?e.then(i):i(e)}async De(t){I(this.Ve instanceof Cn);const e=await this.Ne(t);return this.it("target",{target:e,request:t,isRoot:t.isRoot}),"canceled"===this.state?await e.Ht():this.$e(e),e}$e(t){this._e.add(t),t.on("finalized",()=>this._e.delete(t),{once:!0})}async ce(){if(I(null!==this.Re),this.Re instanceof xn)return this.Re;const t=await this.Re();return"canceled"===this.state?await t.Ht():this.$e(t),t}he(){return null!==this.Re}ke(){if(this.Ie)return this.Ie;if(this.Te)return this.Te;if(this.Ve instanceof xn)return this.it("target",{target:this.Ve,request:null,isRoot:!0}),this.Ie=this.Ve,this.Ve;const t={path:this.Ve.rootPath,isRoot:!0,mimeType:this.format.mimeType},e=this.Ne(t),i=e=>("canceled"===this.state?e.Ht():this.$e(e),this.it("target",{target:e,request:t,isRoot:!0}),this.Ie=e,e);return e instanceof Promise?this.Te=e.then(i):i(e)}ae(t){return this.Ce??=(async()=>{const e=await this.ke(),i=new gn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof Dn))throw new TypeError("source must be a VideoSource.");if(so(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.xe} 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&&Zt({decoderConfig:e.decoderConfig},t.St),void 0!==e.primingPacket){if(!(e.primingPacket instanceof Ve))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.Oe(new io(this.tracks.length+1,this,t,i))}addAudioTrack(t,e={}){if(!(t instanceof qn))throw new TypeError("source must be an AudioSource.");if(so(e),void 0!==e.decoderConfig&&ee({decoderConfig:e.decoderConfig},t.St),void 0!==e.primingPacket){if(!(e.primingPacket instanceof Ve))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.Oe(new ro(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof Gn))throw new TypeError("source must be a SubtitleSource.");so(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Oe(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.lyrics&&"string"!=typeof t.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==t.images){if(!Array.isArray(t.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of t.images){if(!e||"object"!=typeof e)throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof e.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==t.comment&&"string"!=typeof t.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==t.raw){if(!t.raw||"object"!=typeof t.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(t.raw))if(!(null===e||"string"==typeof e||e instanceof Uint8Array||e instanceof Mt||e instanceof _t||xt(e)))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}})(t),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this.Pt=t}Oe(t){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t.source.le)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.xe} does not support ${t.type} tracks.`:`${this.format.xe} 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.xe} 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.xe} does not support video tracks.`+this.format.ye(t.source.St));if(!e.includes(t.source.St))throw new Error(`Codec '${t.source.St}' cannot be contained within ${this.format.xe}. Supported video codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.ye(t.source.St))}else if(t.isAudioTrack()){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format.xe} does not support audio tracks.`+this.format.ye(t.source.St));if(!e.includes(t.source.St))throw new Error(`Codec '${t.source.St}' cannot be contained within ${this.format.xe}. Supported audio codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.ye(t.source.St))}else if(t.isSubtitleTrack()){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format.xe} does not support subtitle tracks.`+this.format.ye(t.source.St));if(!e.includes(t.source.St))throw new Error(`Codec '${t.source.St}' cannot be contained within ${this.format.xe}. Supported subtitle codecs are: ${e.map(t=>`'${t}'`).join(", ")}.`+this.format.ye(t.source.St))}return this.tracks.push(t),t.source.le=t,t}hasEnoughTracks(){const t=this.format.getSupportedTrackCounts();for(const i of to)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 to){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.xe} requires exactly ${r} ${i} track${1===r?"":"s"}.`:`${this.format.xe} 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.xe} requires exactly ${e} track${1===e?"":"s"}.`:`${this.format.xe} requires at least ${e} track${1===e?"":"s"}.`);if("canceled"===this.state)throw new Error("Output has been canceled.");return this.Se?(Et.ht("Output has already been started."),this.Se):this.Se=(async()=>{this.state="started";const t=this.Be.acquire();try{await this.pe.start();const t=this.tracks.map(t=>t.source.Ft());await Promise.all(t)}finally{(await t)()}})()}getMimeType(){return this.pe.getMimeType()}async cancel(){return this.Ae?(Et.ht("Output has already been canceled."),this.Ae):"finalizing"!==this.state&&"finalized"!==this.state?this.Ae=(async()=>{this.state="canceled";const t=await this.Be.acquire();try{const t=this.tracks.map(t=>t.source.me(!0));await Promise.all(t),await Promise.all([...this._e].map(t=>t.Ht())),this._e.clear()}finally{t()}})():void("finalized"===this.state&&Et.ht("Output has already been finalized."))}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this.Pe?(Et.ht("Output has already been finalized."),this.Pe):this.Pe=(async()=>{this.state="finalizing";const t=await this.Be.acquire();try{const t=this.tracks.map(t=>t.source.me(!1));if(await Promise.all(t),await this.pe.finalize(),this.Ce){const t=await this.Ce;t.finalized||(await t.flush(),await t.finalize())}this.Me&&await this.Me(),this.state="finalized"}finally{await Promise.all([...this._e].map(t=>t.Ht().catch(()=>{}))),this._e.clear(),t()}})()}},ho=["vp9","vp8"],co=["avc"],lo=class{async $record(t,e,i,r={kind:"blob"}){this.U(t.signal),this.Ue();const n=await this.ze(t);this.je(t,"video export plan",n),this.Le(i,"recording","probing",0,n.frameCount,n);const o="mp4"===n.format?new Qn:new Zn,s="stream"===r.kind?new Mn(r.writable,{chunked:!0}):new kn,a=new ao({format:o,target:s}),h=new Hn(e.canvas,{codec:n.codec,quality:this.He(n),alpha:n.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:n.hardwareAcceleration,keyFrameInterval:n.keyFrameInterval,sizeChangeBehavior:"deny",contentHint:"text",onEncoderConfig:e=>this.je(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 x(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.U(t.signal);const r=T(e,n.frameRate);await this.qe(h.add(r.startSeconds,r.durationSeconds),t.signal),this.Le(i,"recording","capturing",e+1,n.frameCount,n)}}),this.U(t.signal),d(),this.Le(i,"encoding","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),await x(a.finalize(),"Video output did not finalize within 30000ms.",t.signal,3e4),this.Le(i,"completed","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),"stream"===r.kind)return;const o=s;if(!o.buffer)throw new v("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:n.mimeType})}catch(u){d(),await(async()=>{if(!l){l=!0;try{await a.cancel()}catch{}}})();const t=this.Ge(u);throw i?.({state:"error",message:t.message}),t}}async ze(t){const e=B(t),i="mp4"===t.format?new Qn:new Zn,r="mp4"===t.format?co:ho,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t));for(const o of n)if(await Mi(o,{width:e.width,height:e.height,quality:this.He(e),alpha:e.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:e.hardwareAcceleration,contentHint:"text"}))return B(t,o);throw new v("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.`)}He(t){return new vi(t.quality)}Ue(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new v("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}qe(t,e){return e?new Promise((i,r)=>{if(e.aborted)return void r(g());const n=()=>r(g());e.addEventListener("abort",n,{once:!0}),t.then(t=>{e.removeEventListener("abort",n),i(t)},t=>{e.removeEventListener("abort",n),r(t)})}):t}U(t){if(t?.aborted)throw g()}Le(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})}Ge(t){return t instanceof v?t:new v("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}je(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},uo=class{We;_;C;constructor(t,e){this.We=new lo,this._=t,this.C=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.T(e,t),n=B(i);if("file-system"===t.destination){const r=await this.Xe(this.Qe(t.filename,`.${e}`)??`textmode-export.${e}`,n.mimeType);try{await this.Ye(i,r,t.onProgress)}catch(s){try{await(r.abort?.(s))}catch{}throw s}return}const o=await this.Ye(i,{kind:"blob"},t.onProgress);if(!o)throw new v("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new r).$downloadFile(o,this.Qe(t.filename,`.${e}`))}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.T(e,t);B(i);const r=await this.Ye(i,{kind:"blob"},t.onProgress);if(!r)throw new v("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async Ye(t,e,i){const r=new k(this._,this.C,t.width,t.height);try{return await this.We.$record(t,r,i,e)}catch(n){throw i?.({state:"error",message:n instanceof Error?n.message:`${t.format.toUpperCase()} export failed`}),n}}T(t,e){const i=this.Je(e.frameRate,60),r=this.Ke(e.frameCount,300),n=this.Je(e.pixelDensity,1),o=this.Ze(),s=Math.max(1,Math.round(this._.canvas.width/o*n)),a=Math.max(1,Math.round(this._.canvas.height/o*n));return{filename:e.filename,format:t,frameRate:i,frameCount:r,quality:this.xt(e.quality),hardwareAcceleration:this.ti(e.hardwareAcceleration),keyFrameInterval:this.ei(e.keyFrameInterval),pixelDensity:n,width:s,height:a,transparent:Boolean(e.transparent),debugLogging:Boolean(e.debugLogging),signal:e.signal,prepareFrame:e.prepareFrame}}Ke(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}Je(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}xt(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.ii(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}}ii(t){return"constant"===t||"variable"===t}ti(t){return"prefer-hardware"===t||"prefer-software"===t||"no-preference"===t?t:"no-preference"}ei(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}Ze(){const t=this._.pixelDensity?.();return"number"==typeof t&&Number.isFinite(t)&&t>0?t:1}Qe(t,e){if(!t)return;const i=t.trim();return i?i.toLowerCase().endsWith(e)?i:`${i}${e}`:void 0}async Xe(t,e){const i=globalThis;if(!i.showSaveFilePicker)throw new v("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))}}}},fo=class extends i{$extractCellData(t){const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],r=t.grid,n=t.font;let o=0;for(let a=0;a<r.rows;a++)for(let t=0;t<r.cols;t++){const r=4*o,h=this.$getEncodedCharacterValue(e.characterPixels,r),c=this.$extractCellTransform(e.characterPixels,r),d=s(n,h)?.character??" ";i.push({x:t,y:a,character:d,foreground:l(e.primaryColorPixels,r),background:l(e.secondaryColorPixels,r),transform:{invert:c.isInverted,flipX:c.flipHorizontal,flipY:c.flipVertical,rotation:c.rotation}}),o++}return i}},po="textmode.document",mo="2.0.0",wo={[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{T(t){return{target:t.target??"selected",pretty:t.pretty??!0,colorMode:t.colorMode??"hex",includeMetadata:t.includeMetadata??!0,filename:t.filename,layer:t.layer}}ri(t){return t.includeMetadata?{createdAt:/* @__PURE__ */(new Date).toISOString(),generator:{name:"textmode.export.js",version:"1.8.1"}}:void 0}ni(t,e){return"rgba"===e?{...t}:`#${[t.r,t.g,t.b,t.a].map(t=>t.toString(16).padStart(2,"0")).join("")}`}oi(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.ni(t.foreground,r),background:this.ni(t.background,r),transform:{...t.transform}}));n.push(s)}return{encoding:"object-rows-v1",rows:n}}si(t){return{cols:t.grid.cols,rows:t.grid.rows,cellWidth:t.grid.cellWidth,cellHeight:t.grid.cellHeight}}ai(t,e){const i=(new fo).$extractCellData(t);return this.oi(i,t.grid.cols,t.grid.rows,e.colorMode)}hi(t,e){return{id:t.id,visible:t.visible,opacity:t.opacity,blendMode:wo[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.si(t),cells:this.ai(t,e)}}$generateJSONData(e,i={}){const r=this.T(i),n=this.ri(r);if("all"===r.target){const i=function(e){return[e.layers.base,...e.layers.all].map(i=>{const r=c(e,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??t.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(e),o=i[0].grid;return{format:po,formatVersion:mo,target:"all",...n?{metadata:n}:{},canvas:{width:o.width,height:o.height},layers:i.map(t=>this.hi(t,r))}}const o=c(e,r.layer);return{format:po,formatVersion:mo,target:"selected",...n?{metadata:n}:{},canvas:{width:o.grid.width,height:o.grid.height},grid:this.si(o),layer:{id:o.id,cells:this.ai(o,r)}}}$generateJSONString(t,e={}){const i=this.T(e),r=this.$generateJSONData(t,i),n="number"==typeof i.pretty?i.pretty:i.pretty?2:0;return JSON.stringify(r,null,n)}$saveJSON(t,e={}){const i=this.T(e);(new r).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename)}},yo="textmode-export-overlay__stack",vo="textmode-export-overlay__stack--dense",go="textmode-export-overlay__stack--compact",xo="textmode-export-overlay__section",Eo="textmode-export-overlay--dragging",To="textmode-export-overlay__label",ko="textmode-export-overlay__field",Mo="textmode-export-overlay__field--compact",_o="textmode-export-overlay__field--dense",Co="textmode-export-overlay__field--full",So="textmode-export-overlay__field--channel",Ao="textmode-export-overlay__input",Po="textmode-export-overlay__muted",Bo="textmode-export-overlay__button--primary",Io="textmode-export-overlay__button--secondary",Fo="textmode-export-overlay__button--full",$o="textmode-export-overlay__link-icon",Vo=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.ci(),this.element.remove(),this.element=void 0,this.mounted=!1)}destroy(){this.destroyed||(this.unmount(),this.li(),this.destroyed=!0)}update(t){this.mounted&&this.onUpdate(t)}onMount(){}ci(){}li(){}onUpdate(t){}get root(){if(!this.element)throw new Error("Component is not mounted yet");return this.element}isMounted(){return this.mounted}},Ro=class t extends Vo{static di="http://www.w3.org/2000/svg";ui;get dragHandleElement(){if(!this.ui)throw new Error("Header drag handle is not mounted yet");return this.ui}render(){this.ui=void 0;const t=document.createElement("div");t.classList.add(yo,vo,"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.fi("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.ui=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.pi("https://github.com/humanbydefinition/textmode.export.js","View repository on GitHub",$o,[{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.pi("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}fi(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.mi($o,i)),r}pi(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.mi(i,r)),n}mi(e,i){const r=document.createElementNS(t.di,"svg");r.setAttribute("xmlns",t.di),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.di,"path");for(const[t,i]of Object.entries(n))e.setAttribute(t,i);r.appendChild(e)}return r}},No=class extends Vo{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(ko),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(To),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(Po),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(ko),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(To),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(Po),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(Mo,_o,Co,So),e){case"compact":t.classList.add(Mo);break;case"dense":t.classList.add(_o);break;case"full":t.classList.add(Co);break;case"channel":t.classList.add(So)}}},Do=class extends Vo{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(Ao),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}ci(){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)}}},Oo=class extends Vo{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(Io):this.button.classList.add(Bo),this.props.fullWidth&&this.button.classList.add(Fo),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(Io),this.button.classList.remove(Bo)):(this.button.classList.add(Bo),this.button.classList.remove(Io)),this.button.classList.toggle(Fo,Boolean(t.fullWidth))}},Uo=class{et={};wi(t){const e=this.et[t];if(e)return e;const i=/* @__PURE__ */new Set;return this.et[t]=i,i}$on(t,e){const i=this.wi(t);return i.add(e),()=>{i.delete(e),0===i.size&&delete this.et[t]}}$emit(t,e){const i=this.et[t];if(i)for(const n of[...i])try{n(e)}catch(r){console.error("[textmode-export] Event handler failed",r)}}$clear(){for(const t of Object.keys(this.et))delete this.et[t]}},zo=class{bi;et=/* @__PURE__ */new Set;constructor(t){this.bi=t}get snapshot(){return Object.freeze({...this.bi})}$set(t){const e=Object.keys(t);if(0===e.length)return;let i=!1;for(const o of e)if(this.bi[o]!==t[o]){i=!0;break}if(!i)return;this.bi=Object.assign({},this.bi,t);const r=this.snapshot;for(const o of[...this.et])try{o(r)}catch(n){console.error("[textmode-export] State listener failed",n)}}$subscribe(t){return this.et.add(t),t(this.snapshot),()=>{this.et.delete(t)}}$reset(t){this.bi=t;const e=this.snapshot;for(const i of[...this.et])i(e)}},jo=/* @__PURE__ */new Set(["txt","json","svg","image"]),Lo=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 jo.has(t)}},Ho={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)}},qo=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 Ho[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}}},Go=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,Wo=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||!Go(e.offsetX)||!Go(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(Go(t)&&Go(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{}}},Xo=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 Wo){this.modifier=t,this.host=e,this.surface=i,this.storage=r,this.handleUpdate=()=>this.scheduleUpdate();const n=this.storage.load();this.position=n?{mode:"custom",offsetX:n.offsetX,offsetY:n.offsetY}:{mode:"auto",offsetX:8,offsetY:8},this.renderedOffset={offsetX:this.position.offsetX,offsetY:this.position.offsetY}}getPosition(){return Object.freeze({...this.position})}setPosition(t,e={}){Number.isFinite(t.offsetX)&&Number.isFinite(t.offsetY)&&(this.position={mode:"custom",offsetX:t.offsetX,offsetY:t.offsetY},this.scheduleUpdate(),(e.persist??1)&&this.storage.save(this.position.offsetX,this.position.offsetY))}resetPosition(){this.position={mode:"auto",offsetX:8,offsetY:8},this.storage.clear(),this.scheduleUpdate()}scheduleUpdate(){null!==this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.animationFrameId=requestAnimationFrame(()=>this.update())}bind(){this.bound||(window.addEventListener("resize",this.handleUpdate),window.addEventListener("scroll",this.handleUpdate,!0),this.bound=!0,this.handleUpdate())}attachDragHandle(t){this.dragHandle!==t&&(this.detachDragHandle(),this.dragHandle=t,t.addEventListener("pointerdown",this.handlePointerDown),t.addEventListener("keydown",this.handleKeyDown))}detachDragHandle(){this.dragHandle&&(this.dragHandle.removeEventListener("pointerdown",this.handlePointerDown),this.dragHandle.removeEventListener("keydown",this.handleKeyDown),this.dragHandle.removeEventListener("pointermove",this.handlePointerMove),this.dragHandle.removeEventListener("pointerup",this.handlePointerUp),this.dragHandle.removeEventListener("pointercancel",this.handlePointerUp),this.dragHandle=void 0,this.dragState=void 0,this.surface.classList.remove(Eo))}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(Eo),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(Eo),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()}},Qo=class extends Vo{capabilities;yi;gi=/* @__PURE__ */new Set;constructor(t,e){super(),this.yi=t,this.capabilities={clipboard:t.supportsClipboard,layerTarget:!!t.layerTargetProvider,recording:!1,...e}}xi(t){return this.gi.add(t),t}ci(){for(const t of this.gi)t.unmount()}li(){for(const t of this.gi)t.destroy();this.gi.clear()}},Yo=class extends Vo{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}ci(){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)}},Jo=class extends Vo{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(Ao),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}ci(){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)}},Ko=class extends Vo{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new No({label:"layer",labelFor:t.id,variant:"full"}),this.select=new Do({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}ci(){this.select.unmount(),this.field.unmount()}li(){this.select.destroy(),this.field.destroy()}},Zo=class extends Qo{layerTarget;trailingSpaces=this.xi(new Yo({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.xi(new Jo({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.xi(new Ko({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(yo),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new No({label:"empty character",labelFor:"textmode-export-empty-character",variant:"full"});return e.mount(t),this.emptyCharacter.mount(e.root),t}getOptions(){const t=this.yi.defaultOptions,e=this.emptyCharacter.value||t.emptyCharacter;return{layer:this.layerTarget?.layer,preserveTrailingSpaces:this.trailingSpaces.checked,emptyCharacter:e}}setDefaults(t){Object.assign(this.yi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return this.emptyCharacter.value.length<=1}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.yi.defaultOptions;this.trailingSpaces.checked=t.preserveTrailingSpaces??!1,this.emptyCharacter.value=t.emptyCharacter??" "}},ts=class extends Qo{layerTarget;layerTargetContainer;target=this.xi(new Do({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.xi(new Yo({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.xi(new Yo({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.xi(new Do({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.xi(new Ko({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(yo);const e=new No({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 No({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.yi.defaultOptions,t),this.reset()}reset(){this.applyDefaults()}validate(){return!0}refreshLayerTargets(){this.layerTarget?.refresh()}applyDefaults(){const t=this.yi.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)}},es="textmode-export-number-input",is=`${es}__field`,rs=`${es}__controls`,ns=`${es}__control`,os=`${es}__display`,ss=`${os}--visible`,as=t=>{const e=document.createElement("button");return e.type="button",e.className=ns,e.textContent=t>0?"▲":"▼",e},hs=class extends Vo{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=es,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=is,this.display=document.createElement("div"),this.display.className=os;const e=document.createElement("div");return e.className=rs,this.incrementButton=as(1),this.decrementButton=as(-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()}li(){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(ss),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(ss),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(ss),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(ss),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)}},cs=class extends Vo{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?yo:void 0,"stackDense"===this.variant?vo:void 0,"stackCompact"===this.variant?go:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?xo:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},ls=class extends Qo{formatSelect=this.xi(new Do({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.xi(new hs({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(yo);const e=new cs("row");e.mount(t);const i=new No({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new No({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.yi.defaultOptions?.scale??1}}setDefaults(t){Object.assign(this.yi.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.yi.defaultOptions;this.formatSelect.value=t.format??"png",this.scaleInput.value=String(t.scale??1)}},ds=class extends Qo{layerTarget;includeBackground=this.xi(new Yo({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.xi(new Do({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.xi(new hs({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.xi(new Ko({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(yo),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new cs("row");e.mount(t);const i=new No({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new No({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.yi.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.yi.defaultOptions;this.includeBackground.checked=t.includeBackgroundRectangles??!0,this.drawMode.value=t.drawMode??"fill",this.strokeWidth.value=String(t.strokeWidth??1),this.strokeWidth.refresh()}},us={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},fs=class extends Vo{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(us)),this.messageElement.classList.add(us[t])}},ps=class extends Qo{frameCountInput=this.xi(new hs({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.xi(new hs({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.xi(new hs({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.xi(new hs({defaultValue:"0",attributes:{min:"0",max:"50",step:"1"},formatDisplay:(t,e)=>Number.isFinite(t)?0===t?"∞":null:""===e.trim()?null:e}));status=this.xi(new fs({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(yo);const e=new cs("row");e.mount(t);const i=new No({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 No({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 cs("row");n.mount(t);const o=new No({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 No({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.yi.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.yi.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.yi.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}},ms=class extends Qo{formatSelect=this.xi(new Do({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));qualitySelect=this.xi(new Do({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.xi(new hs({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.xi(new hs({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));hardwareAccelerationSelect=this.xi(new Do({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.xi(new hs({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.xi(new Yo({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.xi(new fs({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.xi(new fs({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(yo);const e=new cs("row");e.mount(t);const i=new No({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new No({label:"quality",labelFor:"textmode-export-video-quality",variant:"compact"});r.mount(e.root),this.qualitySelect.mount(r.root);const n=new cs("row");n.mount(t);const o=new No({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 No({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 cs("row");a.mount(t);const h=new No({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(a.root),this.hardwareAccelerationSelect.mount(h.root);const c=new No({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.yi.videoDimensionsTarget&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.syncOutputEstimate()),this.resizeObserver.observe(this.yi.videoDimensionsTarget)),t}getOptions(){const t=this.yi.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.yi.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.yi.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.yi.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=B(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")}}ci(){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.ci()}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 ws(t){return t.capabilities.recording}var bs=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 ys(){return{format:bs.format,txt:{...bs.txt},json:{...bs.json},image:{...bs.image},svg:{...bs.svg},gif:{...bs.gif},video:{...bs.video}}}function vs(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var gs=class{Ei;constructor(){this.Ei=ys()}get current(){return this.snapshot()}snapshot(){return{format:(t=this.Ei).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.Ei[t]}merge(t){t.format&&(this.Ei.format=t.format),t.txt&&Object.assign(this.Ei.txt,t.txt),t.json&&Object.assign(this.Ei.json,t.json),t.image&&Object.assign(this.Ei.image,t.image),t.svg&&Object.assign(this.Ei.svg,t.svg),t.gif&&Object.assign(this.Ei.gif,t.gif),t.video&&Object.assign(this.Ei.video,t.video)}reset(t){const e=ys();if(!t)return this.Ei.format=e.format,vs(this.Ei.txt,e.txt),vs(this.Ei.json,e.json),vs(this.Ei.image,e.image),vs(this.Ei.svg,e.svg),vs(this.Ei.gif,e.gif),void vs(this.Ei.video,e.video);switch(t){case"format":this.Ei.format=e.format;break;case"txt":vs(this.Ei.txt,e.txt);break;case"json":vs(this.Ei.json,e.json);break;case"image":vs(this.Ei.image,e.image);break;case"svg":vs(this.Ei.svg,e.svg);break;case"gif":vs(this.Ei.gif,e.gif);break;case"video":vs(this.Ei.video,e.video)}}},xs=class{_;Ti;bi;ki;Mi;_i;Ci;Si=/* @__PURE__ */new Map;Ai=[];Pi;Bi;Ii;Fi;$i;Vi;Ri=new Ro;Ni=new No({label:"export format",labelFor:"textmode-export-format",variant:"full"});Di=new Do({id:"textmode-export-format",options:[]});Oi=new Oo({label:"download file",fullWidth:!0,variant:"primary"});Ui=new Oo({label:"copy to clipboard",fullWidth:!0,variant:"primary"});zi;ji;Li=()=>{this.Hi(this.Di.value)};qi=()=>{this.Gi().catch(t=>{console.error("[textmode-export] Export failed",t)})};Wi=()=>{this.Xi().catch(t=>{console.error("[textmode-export] Copy failed",t)})};constructor(t,e,i,r){this._=t,this.Ti=i;const n=this.Qi(i.current.format,r);this.bi=new zo((t=>({format:t,isBusy:!1}))(n)),this.ki=new Uo,this.Mi=new qo(e,this.ki),this._i=new Lo(e),this.Ci=r,this.zi=n,this.Yi(),this.Ji()}$mount(){this.Ki(),this.Zi(),this.Vi=new Xo(this._,this.Pi,this.Ii),this.Vi.attachDragHandle(this.Ri.dragHandleElement),this.Vi.bind(),this.tr(this.zi)}show(){this.Pi&&(this.refreshLayerTargets(),this.Pi.style.display="",this.Vi?.scheduleUpdate())}hide(){this.Pi&&(this.Pi.style.display="none")}toggle(){this.isVisible()?this.hide():this.show()}isVisible(){return!!this.Pi&&"none"!==this.Pi.style.display}refreshLayerTargets(){this.ji&&this.ji.blade.capabilities.layerTarget&&this.ji.blade.refreshLayerTargets()}resetPosition(){this.Vi.resetPosition()}getPosition(){return this.Vi.getPosition()}setPosition(t){this.Vi.setPosition(t)}setDefaults(t){t.format&&this.er(t.format),this.Ti.merge(t),this.ir(this.rr(t)),t.format&&this.Hi(t.format)}getDefaults(){return this.Ti.current}resetDefaults(t){this.Ti.reset(t),"format"!==t?(this.ir(t?[t]:void 0),t||this.Hi(this.Ti.current.format)):this.Hi(this.Ti.current.format)}$dispose(){this.Di.isMounted()&&this.Di.selectElement.removeEventListener("change",this.Li),this.Oi.isMounted()&&this.Oi.buttonElement.removeEventListener("click",this.qi),this.Ui.isMounted()&&this.Ui.buttonElement.removeEventListener("click",this.Wi);for(const t of this.Ai)t();this.Ai.length=0,this.ki.$clear();for(const t of this.Si.values())t.blade.destroy();this.Si.clear(),this.ji=void 0,this.Pi?.isConnected&&this.Pi.remove(),this.Vi?.dispose()}ir(t){const e=new Set(t??this.Si.keys());for(const[i,r]of this.Si)e.has(i)&&(r.blade.isMounted()?(r.blade.reset(),r.needsReset=!1):r.needsReset=!0)}Yi(){for(const t of this.Ci){const e=t.createBlade();this.Si.set(t.format,{definition:t,blade:e,initialized:!1,needsReset:!1})}}Qi(t,e){return e.some(e=>e.format===t)?t:e[0]?.format??t}rr(t){return this.Ci.map(t=>t.format).filter(e=>void 0!==t[e])}er(t){if(!this.Si.has(t))throw new Error(`Unknown export format: ${t}`)}Ki(){this.Pi=document.createElement("div"),this.Pi.dataset.plugin="textmode-export-overlay-host",this.Pi.style.cssText="position: absolute; top: 0; left: 0; pointer-events: none; z-index: 2147483647;",this.Bi=this.Pi.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent="@layer textmode-export-overlay{.textmode-export-overlay{--overlay-bg:#141414cc;--overlay-surface:#282828e6;--overlay-border:#ffffff24;--overlay-border-strong:#fff3;--overlay-border-focus:#a0a0a099;--overlay-focus-shadow:0 0 0 1px #8c8c8c47;--overlay-text:#fff;--overlay-muted:#c8c8c8bd;--overlay-radius:.75rem;--overlay-stack-gap:.55rem;gap:var(--overlay-stack-gap);background:var(--overlay-bg);min-width:236px;max-width:236px;color:var(--overlay-text);border-radius:var(--overlay-radius);border:1px solid var(--overlay-border);-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);pointer-events:auto;z-index:2147483647;flex-direction:column;padding:.65rem .8rem;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:.82rem;line-height:1.35;display:flex;position:absolute;top:0;left:0;box-shadow:0 12px 28px #0000004d}.textmode-export-overlay *{box-sizing:border-box}.textmode-export-overlay__header{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__header-title-row{justify-content:space-between;align-items:center;gap:.4rem;display:flex}.textmode-export-overlay__header-identity{align-items:center;gap:.35rem;min-width:0;display:inline-flex}.textmode-export-overlay__header-links{flex:none;align-items:center;gap:.3rem;display:inline-flex}.textmode-export-overlay__grab-handle{color:#d7d7d7b8;cursor:grab;touch-action:none;background:0 0;border:1px solid #0000;border-radius:.45rem;flex:none;justify-content:center;align-items:center;width:1.45rem;height:1.45rem;padding:0;line-height:0;transition:background .18s,color .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__grab-handle:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__grab-handle:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay--dragging,.textmode-export-overlay--dragging .textmode-export-overlay__grab-handle{cursor:grabbing}.textmode-export-overlay__support-link{color:#d7d7d7d1;background:0 0;border:1px solid #0000;border-radius:.45rem;justify-content:center;align-items:center;padding:.2rem;line-height:0;text-decoration:none;transition:background .18s,color .18s,transform .18s,border-color .18s;display:inline-flex}.textmode-export-overlay__support-link:hover{color:#fff;background:#5a5a5a4d;border-color:#c8c8c824}.textmode-export-overlay__support-link:focus-visible{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);outline:none}.textmode-export-overlay__support-icon,.textmode-export-overlay__link-icon{width:1rem;height:1rem;display:block}.textmode-export-overlay__stack{gap:var(--overlay-stack-gap);flex-direction:column;display:flex}.textmode-export-overlay__stack--dense{gap:.3rem}.textmode-export-overlay__stack--compact{gap:.45rem}.textmode-export-overlay__section{flex-direction:column;gap:.4rem;display:flex}.textmode-export-overlay__title{white-space:nowrap;font-size:.92rem;font-weight:600}.textmode-export-overlay__divider{background:#ffffff29;width:100%;height:1px;margin-top:.25rem}.textmode-export-overlay__label{opacity:.9;font-weight:500}.textmode-export-overlay__checkbox{align-items:center;gap:.5rem;display:flex}.textmode-export-overlay__checkbox input[type=checkbox]{accent-color:#646464e6;width:1rem;height:1rem}.textmode-export-overlay__row{flex-wrap:wrap;align-items:flex-start;gap:.6rem;width:100%;display:flex}.textmode-export-overlay__field{flex-direction:column;flex:120px;gap:.3rem;min-width:120px;display:flex}.textmode-export-overlay__field--compact{flex:100px;min-width:100px}.textmode-export-overlay__field--dense{flex:90px;min-width:90px}.textmode-export-overlay__field--channel{flex:1 1 0;min-width:0}.textmode-export-overlay__field--full{flex:100%;width:100%}.textmode-export-overlay__input,.textmode-export-overlay select.textmode-export-overlay__input,.textmode-export-overlay input.textmode-export-overlay__input{border:1px solid var(--overlay-border-strong);background:var(--overlay-surface);width:100%;color:var(--overlay-text);font:inherit;border-radius:.4rem;padding:.35rem .5rem;line-height:1.35;transition:border-color .18s,box-shadow .18s,background .18s}.textmode-export-overlay select.textmode-export-overlay__input{appearance:none;background-image:url(\"data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='rgba(200, 200, 200, 0.74)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e\");background-position:right .5rem center;background-repeat:no-repeat;background-size:1rem;padding-right:2rem}.textmode-export-overlay__input:focus{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow);background:#2d2f42eb;outline:none}.textmode-export-overlay__input::placeholder{color:var(--overlay-muted);opacity:.7}.textmode-export-overlay__muted{opacity:.7;font-size:.75rem;display:block}.textmode-export-overlay__button{cursor:pointer;border:none;border-radius:.45rem;justify-content:center;align-items:center;gap:.35rem;padding:.45rem .7rem;font-weight:600;transition:background .2s,transform .2s,box-shadow .2s;display:inline-flex}.textmode-export-overlay__button--primary{color:#fff;background:#505050}.textmode-export-overlay__button--secondary{color:#fff;background:#606060}.textmode-export-overlay__button--full{width:100%}.textmode-export-overlay__button:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 7px 18px #00000073}.textmode-export-overlay__button--primary:hover:not(:disabled){background:#404040}.textmode-export-overlay__button--secondary:hover:not(:disabled){background:#4a4a4a}.textmode-export-overlay__button:disabled{cursor:default;opacity:.55;box-shadow:none;transform:none}.textmode-export-overlay__status{background:#4646462e;border:1px solid #6e6e6e38;border-radius:.45rem;flex-direction:column;gap:.25rem;padding:.45rem .55rem;display:flex}.textmode-export-overlay__status--gif{background:#5050501f;border-color:#78787840}.textmode-export-overlay__status--video{background:#4646461f;border-color:#6e6e6e40}.textmode-export-overlay__status-title{opacity:.85;text-transform:uppercase;letter-spacing:.04em;font-size:.75rem;font-weight:600}.textmode-export-overlay__status-value{color:#dedede;font-size:.82rem;transition:color .18s}.textmode-export-overlay__status-value--neutral{color:#cfcfcf}.textmode-export-overlay__status-value--active{color:#f5f5f5}.textmode-export-overlay__status-value--alert{color:#b8b8b8}.textmode-export-number-input,.textmode-export-overlay .textmode-export-number-input{background:var(--overlay-surface);border:1px solid var(--overlay-border-strong);border-radius:.4rem;align-items:stretch;width:100%;transition:border-color .18s,box-shadow .18s,background .18s;display:flex;position:relative;overflow:hidden}.textmode-export-number-input:focus-within{border-color:var(--overlay-border-focus);box-shadow:var(--overlay-focus-shadow)}.textmode-export-number-input.is-disabled{opacity:.55}.textmode-export-number-input__field{min-width:0;color:var(--overlay-text);font:inherit;appearance:textfield;background:0 0;border:none;flex:auto;padding:.35rem .5rem}.textmode-export-number-input__field::-webkit-outer-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}.textmode-export-number-input__field:focus{outline:none}.textmode-export-number-input__controls{border-left:1px solid #ffffff1f;flex-direction:column;min-width:1.6rem;display:flex}.textmode-export-number-input__control{color:#d0d0d0;cursor:pointer;background:#32323299;border:none;flex:1;justify-content:center;align-items:center;width:100%;padding:0;font-size:.68rem;line-height:1;transition:background .15s,color .15s;display:flex}.textmode-export-number-input__control:hover:not(:disabled){color:#fff;background:#5a5a5ad9}.textmode-export-number-input__control:disabled{cursor:default;opacity:.4;color:#c8c8c866;background:#28282880}.textmode-export-number-input:focus-within .textmode-export-number-input__control{color:#e8e8e8;background:#3c3c3cbf}.textmode-export-number-input__display{pointer-events:none;color:#f8fafc;opacity:0;align-items:center;padding:.4rem .55rem;transition:opacity .14s;display:flex;position:absolute;inset:0}.textmode-export-number-input__display--visible{opacity:1}}",this.Bi.appendChild(t),this.Ii=document.createElement("div"),this.Ii.dataset.plugin="textmode-export-overlay",this.Ii.classList.add("textmode-export-overlay",yo),this.Bi.appendChild(this.Ii),document.body.appendChild(this.Pi)}Zi(){this.Ri.mount(this.Ii);const t=document.createElement("div");t.classList.add(xo),this.Ii.appendChild(t),this.Ni.mount(t),this.nr(),this.Di.mount(this.Ni.root),this.Di.selectElement.addEventListener("change",this.Li),this.Fi=document.createElement("div"),this.Fi.classList.add(yo,go),this.Ii.appendChild(this.Fi),this.Oi.mount(this.Ii),this.Oi.buttonElement.addEventListener("click",this.qi),this.$i=document.createElement("div"),this.$i.classList.add(yo,vo),this.Ii.appendChild(this.$i),this.Ui.mount(this.$i),this.Ui.buttonElement.dataset.defaultLabel="copy to clipboard",this.Ui.buttonElement.addEventListener("click",this.Wi)}nr(){const t=this.Ci.map(t=>({value:t.format,label:t.label}));this.Di.update({options:t,defaultValue:this.zi})}Ji(){this.Ai.push(this.ki.$on("export:request",({format:t})=>{t===this.zi&&(this.bi.$set({isBusy:!0,error:void 0}),this.sr())}),this.ki.$on("export:success",({format:t})=>{if(t===this.zi){const e={isBusy:!1};"gif"===t&&(e.gifProgress=void 0),"video"===t&&(e.videoProgress=void 0),this.bi.$set(e),this.sr()}}),this.ki.$on("export:error",({format:t,error:e})=>{t===this.zi&&(this.bi.$set({isBusy:!1,error:e}),this.sr())}),this.ki.$on("export:progress",({format:t,progress:e})=>{if(e){if("gif"===t){const t=e;this.bi.$set({gifProgress:t}),"gif"===this.ji?.definition.format&&ws(this.ji.blade)&&this.ji.blade.handleProgress(t)}else if("video"===t){const t=e;this.bi.$set({videoProgress:t}),"video"===this.ji?.definition.format&&ws(this.ji.blade)&&this.ji.blade.handleProgress(t)}this.sr()}}))}Hi(t){this.zi=t,this.bi.$set({format:t}),this.tr(t),this.ki.$emit("format:change",{format:t})}tr(t){const e=this.Si.get(t);if(!e)throw new Error(`Unknown export format: ${t}`);this.ji&&this.ji.blade.unmount(),this.Fi.innerHTML="",e.blade.mount(this.Fi),e.initialized&&!e.needsReset||(e.blade.reset(),e.initialized=!0,e.needsReset=!1),this.ji=e,this.Di.value=t,this.refreshLayerTargets(),this.ar(),this.sr(),this.Vi?.scheduleUpdate()}ar(){const t=this.ji?.definition.supportsClipboard??!1;this.$i.style.display=t?"flex":"none",this.Ui.setDisabled(!t)}async Gi(){if(!this.ji)return;const t=this.ji.definition.format,e=this.ji.blade.getOptions();if(this.ji.blade.validate()){if(ws(this.ji.blade)){const r=this.ji.blade;if(r.isRecording())return;r.setRecordingState("recording");try{await this.Mi.$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.sr()},1600)}this.Oi.setDisabled(!0),this.Oi.setLabel("exporting…");try{await this.Mi.$requestExport(t,e)}finally{this.Oi.setDisabled(!1),this.Oi.setLabel("download file")}}else console.warn("[textmode-export] Export options failed validation")}async Xi(){if(!this.ji||!this.ji.definition.supportsClipboard)return;const t=this.ji.definition.format,e=this.ji.blade.getOptions(),i=this.Ui.buttonElement.dataset.defaultLabel??"copy to clipboard";this.Ui.setDisabled(!0),this.Ui.setLabel("copying…");try{switch(t){case"txt":await this._i.$copy("txt",e);break;case"json":await this._i.$copy("json",e);break;case"svg":await this._i.$copy("svg",e);break;case"image":await this._i.$copy("image",e);break;default:return}this.Ui.setLabel("copied!")}catch(r){console.error("[textmode-export] Failed to copy to clipboard",r),this.Ui.setLabel("copy failed!")}finally{window.setTimeout(()=>{this.Ui.setLabel(i),this.Ui.setDisabled(!1)},1200)}}sr(){if(!this.ji)return;const t=this.ji.definition.format;if(ws(this.ji.blade)){const e=this.ji.blade,i="gif"===t?this.bi.snapshot.gifProgress:this.bi.snapshot.videoProgress;if(e.isRecording())if(this.Oi.setDisabled(!0),i?.totalFrames){const e=i.frameIndex??0,r="encoding"===i.state?"encoding":"recording";this.Oi.setLabel("gif"===t?`${r} ${e}/${i.totalFrames}`:`recording ${e}/${i.totalFrames} frames`)}else this.Oi.setLabel("encoding"===i?.state?"encoding…":"recording…");else this.Oi.setDisabled(!1),this.Oi.setLabel("start recording");return}const e=this.bi.snapshot.isBusy;this.Oi.setDisabled(e),this.Oi.setLabel(e?"exporting…":"download file")}};var Es=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob"],Ts=class{api;C;hr=/* @__PURE__ */new Set;cr;lr;Y=!1;constructor(t,e){this.C=e;const i={saveCanvas:async(e={})=>(this.dr(),(new w).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.dr(),(new w).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.dr(),(new w).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.dr(),(new p).$saveSVG(t,e)},saveStrings:(e={})=>{this.dr(),(new b).$saveTXT(t,e)},toSVG:(e={})=>(this.dr(),(new p).$generateSVG(t,e)),toString:(e={})=>(this.dr(),(new b).$generateTXT(t,e)),toJSON:(e={})=>(this.dr(),(new bo).$generateJSONData(t,e)),toJSONString:(e={})=>(this.dr(),(new bo).$generateJSONString(t,e)),saveJSON:(e={})=>{this.dr(),(new bo).$saveJSON(t,e)},saveGIF:(e={})=>this.ur(e.signal,i=>new P(t,t=>this.C(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.ur(e.signal,i=>new P(t,t=>this.C(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.ur(e.signal,i=>new uo(t,t=>this.C(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.ur(e.signal,i=>new uo(t,t=>this.C(t)).$generateVideoBlob({...e,signal:i})),exportOverlay:void 0};this.api=i;const r=function(t,e,i){const r=new gs,n=new xs(t,e,r,function(t,e=(()=>{const t=ys();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new Zo({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new ts({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new ls({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new ds({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new ps({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new ms({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:e("video"),videoDimensionsProvider:i,videoDimensionsTarget:r})}]}(i,t=>r.get(t),()=>{const e=t.pixelDensity?.()??1;return{width:Math.max(1,Math.round(t.canvas.width/e)),height:Math.max(1,Math.round(t.canvas.height/e))}},t.canvas));try{n.$mount()}catch(o){throw n.$dispose(),o}return n}(t,i,function(t){return{getOptions:()=>h(t),getLayerById:e=>h(t).find(t=>t.id===e)?.layer,getDefaultId:()=>"base"}}(t));let n;try{n=this.C(()=>{!this.Y&&r.isVisible()&&r.refreshLayerTargets()})}catch(o){throw r.$dispose(),o}this.cr=r,this.lr=n,i.exportOverlay=this.pr()}dispose(){if(!this.Y){this.Y=!0;for(const t of this.hr)t.abort();this.hr.clear(),this.lr(),this.cr.$dispose()}}pr(){return{show:()=>{this.dr(),this.cr.show()},hide:()=>{this.dr(),this.cr.hide()},toggle:()=>{this.dr(),this.cr.toggle()},isVisible:()=>(this.dr(),this.cr.isVisible()),resetPosition:()=>{this.dr(),this.cr.resetPosition()},getPosition:()=>(this.dr(),this.cr.getPosition()),setPosition:t=>{this.dr(),this.cr.setPosition(t)},setDefaults:t=>{this.dr(),this.cr.setDefaults(t)},getDefaults:()=>(this.dr(),this.cr.getDefaults()),resetDefaults:t=>{this.dr(),this.cr.resetDefaults(t)}}}ur(t,e){this.dr();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.hr.add(i),Promise.resolve().then(()=>e(r.signal)).finally(()=>{t?.removeEventListener("abort",n),i.signal.removeEventListener("abort",o),this.hr.delete(i)})}dr(){if(this.Y)throw new Error("Textmode export plugin has been disposed.")}},ks={name:"textmode.export.js",install(t,e){const i=new Ts(t,t=>e.on("postDraw",t));try{for(const t of Es)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=ks);export{ks as ExportPlugin};
1
+ import{LayerBlendMode as t}from"textmode.js";Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var e=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),i=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},r=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};