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
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("textmode.js")):"function"==typeof define&&define.amd?define(["exports","textmode.js"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TextmodeExport={},t.textmode)}(this,function(t,e){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var i=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),r=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},n=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-${(new Date).toISOString().slice(0,19).replace(/:/g,"-")}`}},o=new WeakMap;function s(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function a(t,e){let i=o.get(t);if(!i){i=new Map;for(const e of t.characters)i.set(s(e.color),e);o.set(t,i)}return i.get(e)}function h(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function c(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:h(t,e),layer:e}))}function l(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:h(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}function d(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var u=class extends r{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=d(t.primaryColorPixels,s),c=d(t.secondaryColorPixels,s);const l=this.$extractCellTransform(t.characterPixels,s);if(l.isInverted){const t=h;h=c,c=t}const u=this.o(o,n,e);i.push({encodedGlyphSlot:a,primaryColor:h,secondaryColor:c,transform:l,position:u}),r++}return i}},f=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}},p=class{u;constructor(){this.u=new f}$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=a(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:s,g:h,b:c,a:l}=t.primaryColor,d=`rgba(${s},${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,"><")}},m=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 u,r=new p,n=this.T(e),o=l(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 n).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename)}},w={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},b=class{T(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}k(t){if(!(t.format in w))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},w[e.format])})}async $saveImage(t,e={}){const i=this.T(e);this.k(i);const r=await this.$toImageBlob(t,e);(new n).$downloadFile(r,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({[w[i.format]]:r});await navigator.clipboard.write([n])}},y=class{T(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}M(t,e){const i=new r,n=l(t,e.layer),o=i.$extractFramebufferData(n.drawFramebuffer),s=[];let h=0;for(let r=0;r<n.grid.rows;r++){let t="";for(let r=0;r<n.grid.cols;r++){const r=4*h,s=i.$getEncodedCharacterValue(o.characterPixels,r);t+=a(n.font,s)?.character||e.emptyCharacter,h++}e.preserveTrailingSpaces||(t=t.trimEnd()),s.push(t)}return s.join("\n")}$generateTXT(t,e={}){return this.M(t,this.T(e))}$saveTXT(t,e={}){const i=this.T(e),r=this.M(t,i),o=new Blob([r],{type:"text/plain;charset=utf-8"});(new n).$downloadFile(o,i.filename)}},v=i(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>_,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=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=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=_}),g=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function x(){return new g("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function E(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(x());let s=!1;const a=setTimeout(()=>h(()=>o(function(t){return new g("VIDEO_EXPORT_TIMEOUT",t,void 0)}(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(x()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var T=1e6;function k(t,e){const i=Math.round(t*T/e),r=Math.max(i+1,Math.round((t+1)*T/e));return{startSeconds:i/T,centerSeconds:(i+Math.floor((r-i)/2))/T,endSeconds:r/T,durationSeconds:(r-i)/T}}var M=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=k(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(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 E(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 x()}},_='(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',C="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",_],{type:"text/javascript;charset=utf-8"});function S(t){let e;try{if(e=C&&(self.URL||self.webkitURL).createObjectURL(C),!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(_),{name:t?.name})}}var A=class{q;G=new Map;W;X=0;Y=!1;constructor(t,e,i,r,n){this.q=new S,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()}},P=v(),B=class{_;C;constructor(t,e){this._=t,this.C=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new n).$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 M(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,P.GIFEncoder)():null,h="undefined"==typeof Worker?null:new A(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,P.quantize)(t,256,{}),s=(0,P.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 I(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new g("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 g("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 F(t){if(!t)throw new Error("Assertion failed.")}var $,V=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},R=t=>t&&t[t.length-1],N=t=>t>=0&&t<2**32,D=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)},O=t=>{const e=D(t);return 1&e?e+1>>1:-(e>>1)},U=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),z=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),j=new TextEncoder,L={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},H={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},q={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},G=t=>!!(t&&t.primaries&&t.transfer&&t.matrix&&void 0!==t.fullRange),W=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),X=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}},Q=(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},Y=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},J=t=>{throw new Error(`Unexpected value: ${t}`)},K=(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},Z=(t,e,i)=>Math.max(e,Math.min(i,t)),tt=(t,e)=>Math.round(t/e)*e,et=(t,e)=>Math.round(t*e)/e,it=(t,e)=>Math.floor(t*e)/e,rt=t=>{let e=0;for(;0!==t;)t&=t-1,e++;return e},nt=/^[a-z]{3}$/,ot=1e6*(1+Number.EPSILON),st=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},at=null,ht=()=>null!==at?at:at=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),ct=null,lt=()=>null!==ct?ct:ct="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),dt=null,ut=()=>null!==dt?dt:dt=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),ft=null,pt=()=>{if(null!==ft)return ft;if("undefined"==typeof navigator)return null;const t=/\bChrome\/(\d+)/.exec(navigator.userAgent);return t?ft=Number(t[1]):null},mt=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},wt=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}},bt=(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},yt=t=>{F(Number.isInteger(t.num)),F(Number.isInteger(t.den)),F(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}},vt=(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.`)},gt=t=>Array.isArray(t)?t:[t],xt=class{constructor(){this.et=new Map}on(t,e,i){this.et.has(t)||this.et.set(t,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)}}},Et=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"}($||($={}));var Tt=class t{constructor(){}static get level(){return t.rt}static set level(e){if(e!==$.Silent&&e!==$.Errors&&e!==$.Warnings&&e!==$.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 xt}static on(e,i,r){return t.nt.on(e,i,r)}static st(...e){t.nt.it("error",e),t.rt>=$.Errors&&console.error(...e)}static ht(...e){t.nt.it("warn",e),t.rt>=$.Warnings&&console.warn(...e)}static ct(...e){t.nt.it("info",e),t.rt>=$.Info&&console.info(...e)}};Tt.rt=$.Info,Tt.ot=null;var kt,Mt,_t=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.")}},Ct=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.")}},St=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}},At=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Pt=[-1,1,2,3,4,5,6,8],Bt=t=>{let e=At.indexOf(t.sampleRate),i=null;-1===e&&(e=15,i=t.sampleRate);const r=Pt.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 St(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},It=["avc","hevc","vp9","av1","vp8","prores"],Ft=["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"],$t=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Vt=[...$t,...Ft],Rt=["webvtt"],Nt=[{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}],Dt=[{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}],Ot=[{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}],Ut=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],zt=["ap4x","ap4h","apch","apcn","apcs","apco"],jt=["dtsc","dtsh","dtsl","dtse"],Lt=[{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}],Ht=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=Nt.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??R(Nt),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=Dt.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??R(Dt);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.${(Ot.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??R(Ot)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=Ut.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??R(Ut);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Lt.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 J(t),new TypeError(`Unhandled codec '${String(t)}'.`)},qt=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]},Gt=/^pcm-([usf])(\d+)(be)?$/,Wt=t=>{if(F(Ft.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=Gt.exec(t);let i;return F(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}},Xt=t=>t.startsWith("avc1")||t.startsWith("avc3")?"avc":t.startsWith("hev1")||t.startsWith("hvc1")?"hevc":"vp8"===t?"vp8":t.startsWith("vp09")?"vp9":t.startsWith("av01")?"av1":zt.includes(t)?"prores":"mp3"===t||"mp4a.69"===t||"mp4a.6B"===t||"mp4a.6b"===t||"mp4a.40.34"===t?"mp3":t.startsWith("mp4a.40.")||"mp4a.67"===t?"aac":"opus"===t?"opus":"vorbis"===t?"vorbis":"flac"===t?"flac":"ac-3"===t||"ac3"===t?"ac3":"ec-3"===t||"eac3"===t?"eac3":jt.includes(t)?"dts":"ulaw"===t?"ulaw":"alaw"===t?"alaw":Gt.test(t)?t:"webvtt"===t?"webvtt":null,Qt=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...zt],Yt=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Jt=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Kt=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Zt=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,te=(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(!Qt.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&&!W(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(L);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(H);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(q);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(!Yt.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(t.decoderConfig.codec.startsWith("hev1")||t.decoderConfig.codec.startsWith("hvc1")){if(!Jt.test(t.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(t.decoderConfig.codec.startsWith("vp8")){if("vp8"!==t.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(t.decoderConfig.codec.startsWith("vp09")){if(!Kt.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(!Zt.test(t.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(zt.some(e=>t.decoderConfig.codec.startsWith(e))&&!zt.some(e=>t.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${zt.join(", ")}.`);if(null!==e&&Xt(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}'.`)},ee=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],ie=(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(!ee.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&&!W(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(!jt.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: ${jt.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!Ft.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ft.join(", ")}).`);if(null!==e&&Xt(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}'.`)},re=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.")},ne=[48e3,44100,32e3],oe=[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"}(kt||(kt={})),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"}(Mt||(Mt={}));var se,ae=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})},he=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=K(r,i,!1):(F(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},ce=t=>31&t,le=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)},de=(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}}),ue=t=>{const e=D(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)D(t),D(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},fe=t=>t>>1&63,pe=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},me=t=>{for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBits(1)){const i=Math.min(64,1<<4+(e<<1));e>1&&O(t);for(let e=0;e<i;e++)O(t)}else D(t)},we=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=be(t,r,e,i)},be=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(D(t)+1):e-1,t.readBits(1),D(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=D(t),i=D(t);for(let r=0;r<e;r++)D(t),t.readBits(1);for(let r=0;r<i;r++)D(t),t.readBits(1);n=e+i}return n},ye=(t,e)=>{let i=2,r=2,n=2,o=0,s=0,a={num:1,den:1};if(t.readBits(1)){const e=t.readBits(8);if(255===e)a={num:t.readBits(16),den:t.readBits(16)};else{const t=de[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)&&(D(t),D(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(D(t),D(t),D(t),D(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&D(t),t.readBits(1)&&ve(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=D(t),D(t),D(t),D(t),D(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},ve=(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?D(t):i=1===t.readBits(1);let s=1;i||(s=D(t)+1),r&&ge(t,s,o),n&&ge(t,s,o)}},ge=(t,e,i)=>{for(let r=0;r<e;r++)D(t),D(t),i&&(D(t),D(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"}(se||(se={}));var xe,Ee=t=>{const e=z(t),i=e.getUint8(9),r=e.getUint16(10,!0),n=e.getUint32(12,!0),o=e.getInt16(16,!0),s=e.getUint8(18);let a=null;return s&&(a=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:o,channelMappingFamily:s,channelMappingTable:a}};!function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"}(xe||(xe={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var Te,ke=[1,2,3,6],Me=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],_e=[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],Ce=[16,16,20,20,0,24,24,0],Se=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ae=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Pe=[32e3,44100,48e3,0],Be=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ie=[512,1024,2048,4096],Fe=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 St(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=Pe[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*rt(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=Be[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}}},$e=t=>{const e=new Uint8Array(20),i=z(e);i.setUint32(0,t.sampleRate),i.setUint32(4,t.bitRate),i.setUint32(8,t.bitRate),e[12]=t.pcmResolution;const r=t.core&&!t.hasExtensions?1:0,n=new St(e);return n.seekToByte(13),n.writeBits(2,Math.max(Ie.indexOf(t.sampleCount),0)),n.writeBits(5,r),n.writeBits(1,t.core?.lfePresent?1:0),n.writeBits(6,t.core?.amode??0),n.writeBits(14,t.core?t.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,t.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),e},Ve=new Uint8Array(0),Re=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===Ve&&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===Ve}get microsecondTimestamp(){return Math.trunc(ot*this.timestamp)}get microsecondDuration(){return Math.trunc(ot*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)}},Ne=class{constructor(t){this.value=t}},De=class{constructor(t){this.value=t}},Oe=class{constructor(t){this.value=t}},Ue=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"}(Te||(Te={})),Te.EBML,Te.Segment,Te.SeekHead,Te.Info,Te.Cluster,Te.Tracks,Te.Cues,Te.Attachments,Te.Chapters,Te.Tags;var ze=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,je=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,Le=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,He=class{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=ze(t)){let i=0;switch(e){case 6:this.helperView.setUint8(i++,t/2**40|0);case 5:this.helperView.setUint8(i++,t/2**32|0);case 4:this.helperView.setUint8(i++,t>>24);case 3:this.helperView.setUint8(i++,t>>16);case 2:this.helperView.setUint8(i++,t>>8);case 1:this.helperView.setUint8(i++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(t,e=je(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=Le(t)){t<0&&(t+=2**(8*e)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=(t=>{if(t<127)return 1;if(t<16383)return 2;if(t<2097151)return 3;if(t<268435455)return 4;if(t<2**35-1)return 5;if(t<2**42-1)return 6;throw new Error("EBML varint size not supported "+t)})(t)){let i=0;switch(e){case 1:this.helperView.setUint8(i++,128|t);break;case 2:this.helperView.setUint8(i++,64|t>>8),this.helperView.setUint8(i++,t);break;case 3:this.helperView.setUint8(i++,32|t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 4:this.helperView.setUint8(i++,16|t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 5:this.helperView.setUint8(i++,8|t/2**32&7),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;case 6:this.helperView.setUint8(i++,4|t/2**40&3),this.helperView.setUint8(i++,t/2**32|0),this.helperView.setUint8(i++,t>>24),this.helperView.setUint8(i++,t>>16),this.helperView.setUint8(i++,t>>8),this.helperView.setUint8(i++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(t=>t.charCodeAt(0))))}writeEBML(t){if(null!==t)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(const e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data)){const e=this.writer.getPos(),i=-1===t.size?1:t.size??4;-1===t.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const r=this.writer.getPos();if(this.dataOffsets.set(t,r),this.writeEBML(t.data),-1!==t.size){const t=this.writer.getPos()-r,n=this.writer.getPos();this.writer.seek(e),this.writeVarInt(t,i),this.writer.seek(n)}}else if("number"==typeof t.data){const e=t.size??ze(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??je(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 Ne)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof De)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof Oe){const e=t.size??Le(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Ue){const e=j.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else J(t.data)}},qe={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"},Ge=t=>{const e=t.filePos,i=new St(Pi(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}},We=i((t,e)=>{e.exports={}}),Xe=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 Qe=-1/0,Ye=-1/0,Je=null;"undefined"!=typeof FinalizationRegistry&&(Je=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-Qe>=1e3&&(Tt.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."),Qe=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-Ye>=1e3&&(Tt.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."),Ye=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var Ke=class{constructor(){this.lt=0,this.dt=null}},Ze=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ti=new Set(Ze),ei=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(ot*this.timestamp)}get microsecondDuration(){return Math.trunc(ot*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||!ti.has(i.format))throw new TypeError("init.format must be one of: "+Ze.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&&vt(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??di(i.format,i.codedWidth,i.codedHeight);let r=i.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},void 0!==i.displayWidth?(this.squarePixelWidth=this.rotation%180==0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180==0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this.ft=i.wt?U(e):U(e).slice(),this.bt=t,this.colorSpace=new si(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&&vt(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 si(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&&vt(i.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*ot),duration:Math.trunc((i.duration??0)*ot)||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:lt(),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 si({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Ke))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&&!Ze.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=yt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Je?.register(this,{type:"video",data:this.ft},this)}clone(){if(this.ut)throw new Error("VideoSample is closed.");return F(null!==this.ft),this.ft instanceof Ke?new t(this.ft,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):ai(this.ft)?new t(this.ft.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this.ft instanceof Uint8Array?(F(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||(Je?.unregister(this),this.ft instanceof Ke?(this.ft.lt--,0===this.ft.lt&&this.ft.close()):ai(this.ft)?this.ft.close():this.ft=null,this.ut=!0)}allocationSize(t={}){if(li(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 ai(this.ft)?this.ft.allocationSize(t):fi(this,t).allocationSize}async copyTo(e,i={}){if(!W(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(li(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(F(null!==this.ft),ai(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 Ke)){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{Xe(r)}}}const r=fi(this,i);F(this.format);const n=U(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=ui(this.format);let s;if(this.ft instanceof Ke){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)F(this.bt),F(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");F(t),s=[{data:U(t.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const a=[],h=o.length;for(let t=0;t<h;t++){const e=r.computedLayouts[t],i=s[t].stride,o=s[t].data;let h=e.sourceTop*i;h+=e.sourceLeftBytes;let c=e.destinationOffset;const l=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let t=0;t<e.sourceHeight;t++){if(h+l>o.byteLength)throw new Error("Source buffer OOB read.");if(c+l>n.byteLength)throw new Error("Destination buffer OOB write.");const t=o.subarray(h,h+l);n.set(t,c),h+=i,c+=e.destinationStride}a.push(d)}if(void 0!==i.format){const t=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),e=this.format.includes("X")&&i.format.includes("A");if(t||e)for(let i=0;i<r.allocationSize;i+=4){if(t){const t=n[i];n[i]=n[i+2],n[i+2]=t}e&&(n[i+3]=255)}}return a}toVideoFrame(){if(this.ut)throw new Error("VideoSample is closed.");if(F(null!==this.ft),this.ft instanceof Ke){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 ai(this.ft)?new VideoFrame(this.ft,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.ft instanceof Uint8Array?(F(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&&ci(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=hi(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?oi(l,d):{canvas:t,context:e,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,l,d)):p||f.clearRect(0,0,l,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,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(F(null!==this.ft),this.ft instanceof Ke||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&&ci(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=V(this.rotation+(e.rotate??0)),[r,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=hi(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=tt(c,e.roundDimensionsTo??1),l=tt(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 ii){let e=t(this,d);if(e instanceof Promise&&(e=await e),null!==e)return e}const{canvas:u,context:f,isNew:p}=oi(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()}},ii=[],ri=[],ni=0,oi=(t,e)=>{for(const n of ri)if(n.canvas.width===t&&n.canvas.height===e)return n.age=ni++,{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 ri.length>=3&&ri.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})(ri,t=>t.age),1),ri.push({canvas:i,context:r,age:ni++}),{canvas:i,context:r,isNew:!0}},si=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(L);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(H);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(q);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}}},ai=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,hi=(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 F(o>=0),F(s>=0),{left:r,top:n,width:o,height:s}},ci=(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.")},li=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.")}},di=(t,e,i)=>{const r=ui(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},ui=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:J(t),F(!1)}},fi=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=pi(i,r,t.codedWidth,t.codedHeight,t.format),o=e.layout;let s;if(e.format&&e.format!==t.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(e.format))throw new Error("NotSupportedError: Invalid destination format.");s=e.format}else s=t.format;return wi(n,s,o)},pi=(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=ui(t);for(let r=0;r<i.length;r++){const t=i[r],n=t.widthDivisor,o=t.heightDivisor;if((e.x||0)%n!==0)return!1;if((e.y||0)%o!==0)return!1}return!0},wi=(t,e,i)=>{const r=ui(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}},bi=new Map,yi=(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&&Xt(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.")},vi=t=>{const e=t.bitrateMode,i=t.quality.gt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Ht(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}),F(n.length>0),n},gi=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 xi):"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?xi[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=Ei[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&&(F(void 0!==this.xt),o=Z(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&&(F(null!==o&&n),r=Z((o-n.worst)/(n.best-n.worst),0,1)),h=ki(t,e,i,Ti(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}_t(t,e,i){return void 0!==this.Tt?this.Tt:(F(void 0!==this.xt),ki(t,e,i,Ti(this.xt)))}Ct(t){if(Ft.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=Ti(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)}},xi={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Ei={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}},Ti=t=>.3*Math.exp(2.5538*t),ki=(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)},Mi=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void F(!1),_i=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,...s}=e;if(!It.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 gi))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 gi)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");yi(t,s);const a=Ci(n,o)??new gi("medium");let h;try{h=vi({codec:t,width:i,height:r,quality:a,framerate:void 0,...s,alpha:"discard"})}catch{return!1}const c=JSON.stringify(h),l=bi.get(c);if(l)return l;const d=(async()=>{for(const{config:e}of h)if(Si.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(!lt())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?Mi(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return bi.set(c,d),d},Ci=(t,e)=>void 0!==t?t:void 0!==e?e instanceof gi?e:new gi({bitrate:e}):void 0,Si=[],Ai=class t{constructor(t,e,i,r,n){this.bytes=t,this.view=e,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new t(e,z(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(e,i=this.end-e){if(e<this.start||e+i>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+i)}},Pi=(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},Bi=class{constructor(t){this.mutex=new X,this.trackTimestampInfo=new WeakMap,this.output=t}onTrackClose(t){}validateTimestamp(t,e,i){if(e<0)throw new Error(`Timestamps must be non-negative (got ${e}s).`);let r=this.trackTimestampInfo.get(t);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,r)}}},Ii=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Fi=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,$i=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")},Vi=class{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.writer.write(this.helper);t.length%8!=0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{const e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(const n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);F(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}}},Ri=new Uint8Array(8),Ni=new DataView(Ri.buffer),Di=t=>[(t%256+256)%256],Oi=t=>(Ni.setUint16(0,t,!1),[Ri[0],Ri[1]]),Ui=t=>(Ni.setInt16(0,t,!1),[Ri[0],Ri[1]]),zi=t=>(Ni.setUint32(0,t,!1),[Ri[1],Ri[2],Ri[3]]),ji=t=>(Ni.setUint32(0,t,!1),[Ri[0],Ri[1],Ri[2],Ri[3]]),Li=t=>(Ni.setInt32(0,t,!1),[Ri[0],Ri[1],Ri[2],Ri[3]]),Hi=t=>(Ni.setUint32(0,Math.floor(t/2**32),!1),Ni.setUint32(4,t,!1),[Ri[0],Ri[1],Ri[2],Ri[3],Ri[4],Ri[5],Ri[6],Ri[7]]),qi=t=>(Ni.setInt32(0,Math.floor(t/2**32),!1),Ni.setUint32(4,t,!1),[Ri[0],Ri[1],Ri[2],Ri[3],Ri[4],Ri[5],Ri[6],Ri[7]]),Gi=t=>(Ni.setInt16(0,256*t,!1),[Ri[0],Ri[1]]),Wi=t=>(Ni.setInt32(0,65536*t,!1),[Ri[0],Ri[1],Ri[2],Ri[3]]),Xi=t=>(Ni.setInt32(0,2**30*t,!1),[Ri[0],Ri[1],Ri[2],Ri[3]]),Qi=(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()},Yi=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},Ji=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]},Ki=Ji(0),Zi=t=>[Wi(t[0]),Wi(t[1]),Xi(t[2]),Wi(t[3]),Wi(t[4]),Xi(t[5]),Wi(t[6]),Wi(t[7]),Xi(t[8])],tr=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),er=(t,e,i,r,n)=>tr(t,[Di(e),zi(i),r??[]],n),ir=()=>tr("styp",[Yi("iso5"),ji(0),Yi("iso5"),Yi("iso6"),Yi("mp41"),Yi("cmfc"),Yi("dash")]),rr=(t,e)=>{let i=t.maxWrittenEndTimestamp-t.minWrittenTimestamp;return Number.isFinite(i)||(i=0),er("sidx",1,0,[ji(1),ji(An),Hi(Bn(t.minWrittenTimestamp,An)),Hi(0),Oi(0),Oi(1),ji(2147483647&e),ji(Bn(i,An)),ji(0)])},nr=t=>({type:"mdat",largeSize:t}),or=t=>tr("moov",void 0,[sr(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>hr(e,t.creationTime)),t.isFragmented?Gr(t.trackDatas):null,sn(t)]),sr=(t,e)=>{const i=Math.max(0,...e.map(t=>Bn(ar(t),An)+Bn(t.startTimestampOffset??0,An))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!N(t)||!N(i),o=n?Hi:ji;return er("mvhd",+n,0,[o(t),o(t),ji(An),o(i),Wi(1),Gi(1),Array(10).fill(0),Zi(Ki),Array(24).fill(0),ji(r)])},ar=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},hr=(t,e)=>{const i=Pn(t),r=null!==t.startTimestampOffset&&t.startTimestampOffset>0;return tr("trak",void 0,[cr(t,e),r?lr(t,t.startTimestampOffset):null,dr(t,e),void 0!==i.name?tr("udta",void 0,[tr("name",[...j.encode(i.name)])]):null])},cr=(t,e)=>{const i=Bn(ar(t),An)+Bn(t.startTimestampOffset??0,An),r=!N(e)||!N(i),n=r?Hi:ji;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=Ji(e??0)}else o=Ki;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:J(t);return er("tkhd",+r,s,[n(e),n(e),ji(t.track.id),ji(0),n(i),Array(8).fill(0),Oi(0),Oi(a),Gi("audio"===t.type?1:0),Oi(0),Zi(o),Wi("video"===t.type?t.info.width:0),Wi("video"===t.type?t.info.height:0)])},lr=(t,e)=>{const i=Bn(e,An),r=Bn(ar(t),An),n=!N(i)||!N(r),o=n?Hi:ji,s=n?qi:Li;return tr("edts",void 0,[er("elst",n?1:0,0,[ji(2),o(i),s(-1),Wi(1),o(r),s(0),Wi(1)])])},dr=(t,e)=>tr("mdia",void 0,[ur(t,e),mr(!0,fr[t.type],pr[t.type]),wr(t)]),ur=(t,e)=>{const i=Bn(ar(t),t.timescale),r=!N(e)||!N(i),n=r?Hi:ji;return er("mdhd",+r,0,[n(e),n(e),ji(t.timescale),n(i),Oi(gn(t.track.metadata.languageCode??"und")),Oi(0)])},fr={video:"vide",audio:"soun",subtitle:"text"},pr={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},mr=(t,e,i,r="\0\0\0\0")=>er("hdlr",0,0,[t?Yi("mhlr"):ji(0),Yi(e),Yi(r),ji(0),ji(0),Yi(i,!0)]),wr=t=>tr("minf",void 0,[br[t.type](),yr(),xr(t)]),br={video:()=>er("vmhd",0,1,[Oi(0),Oi(0),Oi(0),Oi(0)]),audio:()=>er("smhd",0,0,[Oi(0),Oi(0)]),subtitle:()=>er("nmhd",0,0)},yr=()=>tr("dinf",void 0,[vr()]),vr=()=>er("dref",0,0,[ji(1)],[gr()]),gr=()=>er("url ",0,1),xr=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return tr("stbl",void 0,[Er(t),Or(t),e?Hr(t):null,e?qr(t):null,zr(t),jr(t),Lr(t),Ur(t)])},Er=t=>{let e;if("video"===t.type)e=Tr(pn(t.track.source.St,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=wn(t.track.source.St,t.info.decoderConfig.codec,t.muxer.isQuickTime);F(i),e=Cr(i,t)}else"subtitle"===t.type&&(e=Dr(yn[t.track.source.St],t));return F(e),er("stsd",0,0,[ji(1)],[e])},Tr=(t,e)=>tr(t,[Array(6).fill(0),Oi(1),Oi(0),Oi(0),Array(12).fill(0),Oi(e.info.width),Oi(e.info.height),ji(4718592),ji(4718592),ji(0),Oi(1),Di(10),Yi("Mediabunny"),Array(21).fill(0),Oi(e.info.hasAlphaChannel?32:24),Ui(65535)],[mn[e.track.source.St]?.(e)??null,kr(e),G(e.info.decoderConfig.colorSpace)?Mr(e):null]),kr=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:tr("pasp",[ji(t.info.pixelAspectRatio.num),ji(t.info.pixelAspectRatio.den)]),Mr=t=>tr("colr",[Yi(t.muxer.isQuickTime?"nclc":"nclx"),Oi(L[t.info.decoderConfig.colorSpace.primaries]),Oi(H[t.info.decoderConfig.colorSpace.transfer]),Oi(q[t.info.decoderConfig.colorSpace.matrix]),t.muxer.isQuickTime?[]:Di((t.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),_r=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?L[e.colorSpace.primaries]:2,a=i[6]?Number(i[6]):e.colorSpace?.transfer?H[e.colorSpace.transfer]:2,h=i[7]?Number(i[7]):e.colorSpace?.matrix?q[e.colorSpace.matrix]:2;return er("vpcC",1,0,[Di(r),Di(n),Di(o),Di(s),Di(a),Di(h),Oi(0)])},Cr=(t,e)=>{let i,r=0,n=16;const o=Ft.includes(e.track.source.St);if(o){const t=e.track.source.St,{sampleSize:i}=Wt(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),Oi(1),Oi(r),Oi(0),ji(0),Oi(e.info.numberOfChannels),Oi(n),Oi(0),Oi(0),Oi(e.info.sampleRate<65536?e.info.sampleRate:0),Oi(0)];else{const t=o?0:-2;i=[Array(6).fill(0),Oi(1),Oi(r),Oi(0),ji(0),Oi(e.info.numberOfChannels),Oi(Math.min(n,16)),Ui(t),Oi(0),Oi(e.info.sampleRate<65536?e.info.sampleRate:0),Oi(0),o?[ji(1),ji(n/8),ji(e.info.numberOfChannels*n/8)]:[ji(0),ji(0),ji(0)],ji(2)]}return tr(t,i,[bn(e.track.source.St,e.muxer.isQuickTime)?.(e)??null])},Sr=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=[...Di(e),...Di(21),...zi(0),...ji(0),...ji(0)];if(t.info.decoderConfig.description){const e=U(t.info.decoderConfig.description);i=[...i,...Di(5),...Qi(e.byteLength),...e]}return i=[...Oi(1),...Di(0),...Di(4),...Qi(i.length),...i,...Di(6),...Di(1),...Di(2)],i=[...Di(3),...Qi(i.length),...i],er("esds",0,0,i)},Ar=t=>tr("wave",void 0,[Pr(t),Br(t),tr("\0\0\0\0")]),Pr=t=>tr("frma",[Yi(wn(t.track.source.St,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),Br=t=>{const{littleEndian:e}=Wt(t.track.source.St);return tr("enda",[Oi(+e)])},Ir=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){F(a.byteLength>=18);const t=Ee(U(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return tr("dOps",[Di(0),Di(e),Oi(i),ji(r),Ui(n),Di(o),...s])},Fr=t=>{const e=t.info.decoderConfig?.description;F(e);const i=U(e);return er("dfLa",0,0,[...i.subarray(4)])},$r=t=>{const{littleEndian:e,sampleSize:i}=Wt(t.track.source.St);return er("pcmC",0,0,[Di(+e),Di(8*i)])},Vr=t=>{F(t.info.primingPacket);const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new St(t);e.skipBits(16),e.skipBits(16);const i=e.readBits(2);if(3===i)return null;const r=e.readBits(6),n=e.readBits(5);if(n>8)return null;const o=e.readBits(3),s=e.readBits(3);return 1&s&&1!==s&&e.skipBits(2),4&s&&e.skipBits(2),2===s&&e.skipBits(2),{fscod:i,bsid:n,bsmod:o,acmod:s,lfeon:e.readBits(1),bitRateCode:Math.floor(r/2)}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const i=new Uint8Array(3),r=new St(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),tr("dac3",[...i])},Rr=t=>{F(t.info.primingPacket);const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new St(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=ke[o];let d;return d=n<3?ne[n]/1e3:oe[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 St(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 tr("dec3",[...n])},Nr=t=>{F(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 St(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>=Se.length)return null;const s=Me[e.readBits(4)];if(0===s)return null;const a=_e[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=Ce[e.readBits(3)];if(0===c)return null;const l=0!==h;return{frameSize:n,sampleRate:s,numberOfChannels:Se[o]+(l?1:0),sampleCount:32*r,channelLayout:Ae[o]|(l?8:0),amode:o,lfePresent:l,bitRate:a,pcmResolution:c}})(t),i=z(t);let r=e?4*Math.ceil(e.frameSize/4):0,n=null;for(;r+4<=t.length&&1683496997===i.getUint32(r);){const e=Fe(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 tr("ddts",[...$e(e)])},Dr=(t,e)=>tr(t,[Array(6).fill(0),Oi(1)],[vn[e.track.source.St](e)]),Or=t=>er("stts",0,0,[ji(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[ji(t.sampleCount),ji(t.sampleDelta)])]),Ur=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return er("stss",0,0,[ji(e.length),e.map(([t])=>ji(t+1))])},zr=t=>er("stsc",0,0,[ji(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[ji(t.firstChunk),ji(t.samplesPerChunk),ji(1)])]),jr=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=Wt(t.track.source.St);return er("stsz",0,0,[ji(e*t.info.numberOfChannels),ji(t.samples.reduce((e,i)=>e+Bn(i.duration,t.timescale),0))])}return er("stsz",0,0,[ji(0),ji(t.samples.length),t.samples.map(t=>ji(t.size))])},Lr=t=>t.finalizedChunks.length>0&&R(t.finalizedChunks).offset>=2**32?er("co64",0,0,[ji(t.finalizedChunks.length),t.finalizedChunks.map(t=>Hi(t.offset))]):er("stco",0,0,[ji(t.finalizedChunks.length),t.finalizedChunks.map(t=>ji(t.offset))]),Hr=t=>er("ctts",1,0,[ji(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[ji(t.sampleCount),Li(t.sampleCompositionTimeOffset)])]),qr=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;F(t.compositionTimeOffsetTable.length>0),F(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,Bn(e.timestamp,t.timescale)),n=Math.max(n,Bn(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:er("cslg",0,0,[Li(o),Li(e),Li(i),Li(r),Li(n)])},Gr=t=>tr("mvex",void 0,t.map(Wr)),Wr=t=>er("trex",0,0,[ji(t.track.id),ji(1),ji(0),ji(0),ji(0)]),Xr=(t,e)=>tr("moof",void 0,[Qr(t),...e.map(Jr)]),Qr=t=>er("mfhd",0,0,[ji(t)]),Yr=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},Jr=t=>tr("traf",void 0,[Kr(t),Zr(t),tn(t)]),Kr=t=>{F(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:Yr(i)};return er("tfhd",0,131128,[ji(t.track.id),ji(r.duration),ji(r.size),ji(r.flags)])},Zr=t=>(F(t.currentChunk),er("tfdt",1,0,[Hi(Bn(t.currentChunk.startTimestamp,t.timescale))])),tn=t=>{F(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(Yr),n=t.currentChunk.samples.map(e=>Bn(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,er("trun",1,p,[ji(t.currentChunk.samples.length),ji(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?ji(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?ji(e[o]):[],d?ji(i[o]):[],u?ji(r[o]):[],f?Li(n[o]):[]])])},en=t=>er("tfra",1,0,[ji(t.track.id),ji(63),ji(t.finalizedChunks.length),t.finalizedChunks.map(e=>[Hi(Bn(e.samples[0].timestamp,t.timescale)),Hi(e.moofOffset),ji(e.trafIndex+1),ji(1),ji(1)])]),rn=()=>tr("vtte"),nn=(t,e,i,r,n)=>tr("vttc",void 0,[null!==n?tr("vsid",[Li(n)]):null,null!==i?tr("iden",[...j.encode(i)]):null,null!==e?tr("ctim",[...j.encode($i(e))]):null,null!==r?tr("sttg",[...j.encode(r)]):null,tr("payl",[...j.encode(t)])]),on=t=>tr("vtta",[...j.encode(t)]),sn=t=>{const e=[],i=t.format.At.metadataFormat??"auto",r=t.output.Pt;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=dn(r);t&&e.push(t)}else if("mdta"===i){const t=un(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&an(e,t.output.Pt);return 0===e.length?null:tr("udta",void 0,e)},an=(t,e)=>{for(const{key:i,value:r}of mt(e))switch(i){case"title":t.push(hn("©nam",r));break;case"description":t.push(hn("©des",r));break;case"artist":t.push(hn("©ART",r));break;case"album":t.push(hn("©alb",r));break;case"albumArtist":t.push(hn("albr",r));break;case"genre":t.push(hn("©gen",r));break;case"date":t.push(hn("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(hn("©cmt",r));break;case"lyrics":t.push(hn("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:J(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(hn(i,r)):r instanceof Uint8Array&&t.push(tr(i,Array.from(r))))}},hn=(t,e)=>{const i=j.encode(e);return tr(t,[Oi(i.length),Oi(gn("und")),Array.from(i)])},cn={"image/jpeg":13,"image/png":14,"image/bmp":27},ln=(t,e)=>{const i=[];for(const{key:r,value:n}of mt(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:fn(n)});break;case"description":i.push({key:e?"description":"©des",value:fn(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:fn(n)});break;case"album":i.push({key:e?"album":"©alb",value:fn(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:fn(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:fn(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:fn(n)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:fn(n)});break;case"date":i.push({key:e?"date":"©day",value:fn(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:tr("data",[ji(cn[t.mimeType]??0),ji(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:fn(e)})}else i.push({key:"trkn",value:tr("data",[ji(0),ji(0),Oi(0),Oi(n),Oi(t.tracksTotal??0),Oi(0)])});break;case"discNumber":e||i.push({key:"disc",value:tr("data",[ji(0),ji(0),Oi(0),Oi(n),Oi(t.discsTotal??0),Oi(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:J(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:fn(n)}):n instanceof Uint8Array?i.push({key:r,value:tr("data",[ji(0),ji(0),Array.from(n)])}):n instanceof _t&&i.push({key:r,value:tr("data",[ji(cn[n.mimeType]??0),ji(0),Array.from(n.data)])}))}return i},dn=t=>{const e=ln(t,!1);return 0===e.length?null:er("meta",0,0,void 0,[mr(!1,"mdir","","appl"),tr("ilst",void 0,e.map(t=>tr(t.key,void 0,[t.value])))])},un=t=>{const e=ln(t,!0);return 0===e.length?null:tr("meta",void 0,[mr(!1,"mdta",""),er("keys",0,0,[ji(e.length)],e.map(t=>tr("mdta",[...j.encode(t.key)]))),tr("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...ji(e+1));return tr(i,void 0,[t.value])}))])},fn=t=>tr("data",[ji(1),ji(0),...j.encode(t)]),pn=(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&&tr("avcC",[...U(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&tr("hvcC",[...U(t.info.decoderConfig.description)]),vp8:_r,vp9:_r,av1:t=>tr("av1C",qt(t.info.decoderConfig.codec)),prores:null},wn=(t,e,i)=>{switch(t){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return e}if(i)switch(t){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(t){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},bn=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return Sr;case"opus":return Ir;case"flac":return Fr;case"ac3":return Vr;case"eac3":return Rr;case"dts":return Nr}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 Ar}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 $r}return null},yn={webvtt:"wvtt"},vn={webvtt:t=>tr("vttC",[...j.encode(t.info.config.description)])},gn=t=>{F(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},xn=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(){F(!this.started),this.target.Ft(),this.started=!0}write(t){F(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 F(this.started&&!this.finalized),this.target.Vt()}async finalize(){F(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}},En=(We(),class extends xt{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 Cn(this,t)}}),Tn=65536,kn=2**32,Mn=class extends En{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 new ArrayBuffer(0),this.Ut)try{this.zt=new ArrayBuffer(Tn,{maxByteLength:kn})}catch{this.zt=new ArrayBuffer(Tn),this.Ut=!1}else this.zt=new ArrayBuffer(Tn);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>kn)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)}},_n=class extends En{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(F(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){F(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||!ht()?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;F(this.Qt),await this.Qt.ready,await this.Qt.close(),this.it("finalized")}async Ht(){return this.Qt?.close()}},Cn=class extends En{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)}},Sn=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.")}},An=57600,Pn=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},Bn=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},In=class extends Bi{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Mn,this.auxWriter=new xn(this.auxTarget,!1),this.auxBoxWriter=new Vi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Y(),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 Kn,this.isCmaf=e instanceof Jn,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(e instanceof Jn?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 Mn),this.boxWriter=new Vi(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Mn&&"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 xn(await this.output.ce(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new Vi(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.St);{const t=this.initBoxWriter??this.boxWriter;if(F(t),this.formatOptions.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return tr("ftyp",t.isQuickTime?[Yi("qt "),ji(e),Yi("qt ")]:t.fragmented?t.cmaf?[Yi("iso5"),ji(e),Yi("iso5"),Yi("iso6"),Yi("mp41"),Yi("cmfc"),Yi("dash")]:[Yi("iso5"),ji(e),Yi("iso5"),Yi("iso6"),Yi("mp41")]:[Yi("isom"),ji(e),Yi("isom"),t.holdsAvc?Yi("avc1"):[],Yi("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||(F(this.writer),F(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=nr(!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;te(i,t.source.St),F(i),F(i.decoderConfig);const n={...i.decoderConfig};F(void 0!==n.codedWidth),F(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 ae(t)){const o=t.subarray(h.offset,h.offset+h.length),s=fe(o[0]);s===Mt.VPS_NUT?e.push(o):s===Mt.SPS_NUT?i.push(o):s===Mt.PPS_NUT?r.push(o):s!==Mt.PREFIX_SEI_NUT&&s!==Mt.SUFFIX_SEI_NUT||n.push(o)}if(0===i.length||0===r.length)return null;const o=(t=>{try{const e=new St(le(t));e.skipBits(16),e.readBits(4);const i=e.readBits(3),r=e.readBits(1),{general_profile_space:n,general_tier_flag:o,general_profile_idc:s,general_profile_compatibility_flags:a,general_constraint_indicator_flags:h,general_level_idc:c}=pe(e,i);D(e);const l=D(e);let d=0;3===l&&(d=e.readBits(1));const u=D(e),f=D(e);let p=u,m=f;if(e.readBits(1)){const t=D(e),i=D(e),r=D(e),n=D(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=D(e),b=D(e);D(e);const y=e.readBits(1)?0:i;let v=0;for(let t=y;t<=i;t++)D(e),v=D(e),D(e);D(e),D(e),D(e),D(e),D(e),D(e),e.readBits(1)&&e.readBits(1)&&me(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),D(e),D(e),e.skipBits(1));const g=D(e);if(we(e,g),e.readBits(1)){const t=D(e);for(let i=0;i<t;i++)D(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=ye(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 Tt.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 St(le(t));e.skipBits(16),D(e),D(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),D(e),D(e),O(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&D(e),O(e),O(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:Mt.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Mt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Mt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:fe(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 Tt.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 ae(t)){const n=t.subarray(s.offset,s.offset+s.length),o=ce(n[0]);o===kt.SPS?e.push(n):o===kt.PPS?i.push(n):o===kt.SPS_EXT&&r.push(n)}if(0===e.length)return null;if(0===i.length)return null;const n=(t=>{try{const e=new St(le(t));if(e.skipBits(1),e.skipBits(2),7!==e.readBits(5))return null;const i=e.readAlignedByte(),r=e.readAlignedByte(),n=e.readAlignedByte();D(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=D(e),3===o&&(h=e.readBits(1)),s=D(e),a=D(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+O(e)+256)%256),r=0===n?r:n}D(e);const c=D(e);if(0===c)D(e);else if(1===c){e.skipBits(1),O(e),O(e);const t=D(e);for(let i=0;i<t;i++)O(e)}D(e),e.skipBits(1);const l=D(e),d=D(e),u=16*(l+1),f=16*(d+1);let p=u,m=f;const w=e.readBits(1);if(w||e.skipBits(1),e.skipBits(1),e.readBits(1)){const t=D(e),i=D(e),r=D(e),n=D(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=de[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)&&(D(e),D(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const t=e.readBits(1);t&&ue(e);const i=e.readBits(1);i&&ue(e),(t||i)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),D(e),D(e),D(e),D(e),E=D(e),T=D(e))}if(null===E)if(F(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=Nt.find(t=>t.level>=n)??R(Nt),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);E=r,T=r}return F(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 Tt.st("Error parsing AVC SPS:",e),null}})(e[0]);F(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 Tt.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){F(null!==t.chromaFormat),F(null!==t.bitDepthLumaMinus8),F(null!==t.bitDepthChromaMinus8),F(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}:yt({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;ie(i,t.source.St),F(i),F(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=Ge(Ai.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=At[t.samplingFrequencyIndex],r=Pt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Bt({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&&Ft.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;re(e),F(e),F(e.config);const r={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...ae(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=Ge(Ai.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=Wt(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=Bn(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=Wt(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=new Set([]);for(const h of t.cueQueue)F(h.timestamp<=e),F(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=rn();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;Ii.lastIndex=0;const r=Ii.test(i.text),s=i.timestamp+i.duration;let a=t.cueToSourceId.get(i);if(void 0===a&&o<s&&(a=t.nextSourceId++,t.cueToSourceId.set(i,a)),i.notes){const t=on(i.notes);this.auxBoxWriter.writeBox(t)}const h=nn(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:Bn(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+=Bn(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):R(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=Bn(e.timestamp-e.decodeTimestamp,t.timescale),o=Bn(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){F(t.lastSample);const i=Bn(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(F(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=R(t.timeToSampleTable);if(F(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=R(t.compositionTimeOffsetTable);F(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=Bn(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,F(t.lastSample),F(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){F("key"===e.type);const i=Bn(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(F(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}),F(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(F(!this.isFragmented),F(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+Bn(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&R(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)F(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(F(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(F(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const t=this.initBoxWriter??this.boxWriter;F(t),this.formatOptions.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=or(this);if(t.writeBox(e),this.formatOptions.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onMoov(e,i)}if(this.isCmaf){F(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.ae(!0),this.boxWriter=new Vi(this.writer);const t=this.boxWriter.measureBox(ir()),e=this.boxWriter.measureBox(rr(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}F(this.writer),F(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=Xr(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=Xr(i,e);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(t,e,a)}F(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const d=nr(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(){F(this.writer),F(this.boxWriter),this.ensureOneEnabledTrack();const t=or(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;F(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=nr(!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(){F("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;F(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(){F(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(F(this.writer),F(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=nr(!1);for(let i=0;i<2;i++){const e=or(this),i=this.boxWriter.measureBox(e);t=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+t;for(const n of this.finalizedChunks){n.offset=r;for(const{data:e}of n.samples)F(e),r+=e.byteLength,t+=e.byteLength}if(r<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const e=or(this);if(this.boxWriter.writeBox(e),this.formatOptions.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(t,e)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const t of i.samples)F(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(ir()),this.boxWriter.writeBox(rr(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,tr("mfra",void 0,[...e.map(en),er("mfro",0,0,[ji(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{F(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);F(void 0!==t);const e=this.writer.getPos()-t;if(this.mdat.size=e,this.mdat.largeSize=e>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}const i=or(this);if("reserve"===this.fastStart){F(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()}},Fn="Mediabunny",$n={video:1,audio:2,subtitle:17},Vn=class extends Bi{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=Y(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=e}async start(){const t=await this.mutex.acquire();this.writer=await this.output.ae(!!this.format.At.appendOnly),this.ebmlWriter=new He(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:Te.EBML,data:[{id:Te.EBMLVersion,data:1},{id:Te.EBMLReadVersion,data:1},{id:Te.EBMLMaxIDLength,data:4},{id:Te.EBMLMaxSizeLength,data:8},{id:Te.DocType,data:this.format instanceof to?"webm":"matroska"},{id:Te.DocTypeVersion,data:2},{id:Te.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:Te.SeekHead,data:[{id:Te.Seek,data:[{id:Te.SeekID,data:e},{id:Te.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:Te.Seek,data:[{id:Te.SeekID,data:i},{id:Te.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:Te.Seek,data:[{id:Te.SeekID,data:r},{id:Te.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:Te.Seek,data:[{id:Te.SeekID,data:n},{id:Te.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:Te.Seek,data:[{id:Te.SeekID,data:o},{id:Te.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const t={id:Te.Duration,data:new De(0)};this.segmentDuration=t;const e={id:Te.Info,data:[{id:Te.TimestampScale,data:1e6},{id:Te.MuxingApp,data:Fn},{id:Te.WritingApp,data:Fn},this.format.At.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:Te.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){let i=qe[e.track.source.St];F(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=Ee(U(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:Te.TrackEntry,data:[{id:Te.TrackNumber,data:e.track.id},{id:Te.TrackUID,data:e.track.id},{id:Te.TrackType,data:$n[e.type]},!1===e.track.metadata.disposition?.default?{id:Te.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:Te.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:Te.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:Te.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:Te.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:Te.FlagCommentary,data:1}:null,{id:Te.FlagLacing,data:0},{id:Te.Language,data:e.track.metadata.languageCode??"und"},{id:Te.CodecID,data:i},e.codecPrivate?{id:Te.CodecPrivate,data:U(e.codecPrivate)}:null,{id:Te.CodecDelay,data:0},{id:Te.SeekPreRoll,data:r},void 0!==e.track.metadata.name?{id:Te.Name,data:new Ue(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:Te.DefaultDuration,data:1e9/e}:null],n=i?V(-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:Te.Video,data:[{id:Te.PixelWidth,data:t.info.width},{id:Te.PixelHeight,data:t.info.height},o?{id:Te.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:Te.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:Te.DisplayUnit,data:3}:null,t.info.alphaMode?{id:Te.AlphaMode,data:1}:null,G(s)?{id:Te.Colour,data:[{id:Te.MatrixCoefficients,data:q[s.matrix]},{id:Te.TransferCharacteristics,data:H[s.transfer]},{id:Te.Primaries,data:L[s.primaries]},{id:Te.Range,data:s.fullRange?2:1}]}:null,n?{id:Te.Projection,data:[{id:Te.ProjectionType,data:0},{id:Te.ProjectionPoseRoll,data:new Ne((n+180)%360-180)}]}:null]};return r.push(a),r}audioSpecificTrackInfo(t){const e=Ft.includes(t.track.source.St)?Wt(t.track.source.St):null;return[{id:Te.Audio,data:[{id:Te.SamplingFrequency,data:new Ne(t.info.sampleRate)},{id:Te.Channels,data:t.info.numberOfChannels},e?{id:Te.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:Te.SimpleTag,data:[{id:Te.TagName,data:new Ue(e)},"string"==typeof i?{id:Te.TagString,data:new Ue(i)}:{id:Te.TagBinary,data:i}]})},i=this.output.Pt,r=new Set;for(const{key:n,value:o}of mt(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:J(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:Te.Tags,data:[{id:Te.Tag,data:[{id:Te.Targets,data:[{id:Te.TargetTypeValue,data:50},{id:Te.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.Pt,e=[],i=new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+(wt(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:Te.AttachedFile,data:[void 0!==n.description?{id:Te.FileDescription,data:new Ue(n.description)}:null,{id:Te.FileName,data:new Ue(r)},{id:Te.FileMediaType,data:n.mimeType},{id:Te.FileData,data:n.data},{id:Te.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof Ct&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&&bt(t.data,o.data))||e.push({id:Te.AttachedFile,data:[void 0!==o.description?{id:Te.FileDescription,data:new Ue(o.description)}:null,{id:Te.FileName,data:new Ue(o.name??"")},{id:Te.FileMediaType,data:o.mimeType??""},{id:Te.FileData,data:o.data},{id:Te.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:Te.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:Te.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:Te.Cues,data:[]}}get segmentDataOffset(){return F(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 to,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;te(i,t.source.St),F(i),F(i.decoderConfig),F(void 0!==i.decoderConfig.codedWidth),F(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:yt({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(qt(a.info.decoderConfig.codec)):"prores"===t.source.St&&(a.codecPrivate=j.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;ie(i,t.source.St),F(i),F(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=Ge(Ai.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=At[t.samplingFrequencyIndex],r=Pt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Bt({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;re(e),F(e),F(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:j.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=et(s,t.metadata.frameRate),a=et(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=Ge(Ai.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);Ii.lastIndex=0,n=n.replace(Ii,t=>`<${$i((t=>{const e=Fi.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=j.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?j.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 St(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){F(null!==this.currentClusterStartMsTimestamp),F(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=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:Te.BlockGroup,data:[{id:Te.Block,data:[s,e.data]},"delta"===e.type?{id:Te.ReferenceBlock,data:new Oe(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:Te.BlockAdditions,data:[{id:Te.BlockMore,data:[{id:Te.BlockAddID,data:1},{id:Te.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:Te.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:Te.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:Te.Cluster,size:this.format.At.appendOnly?-1:5,data:[{id:Te.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(F(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){F(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=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)F(this.cues),this.cues.data.push({id:Te.CuePoint,data:[{id:Te.CueTime,data:r},...n.map(e=>({id:Te.CueTrackPositions,data:[{id:Te.CueTrack,data:e.track.id},{id:Te.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(),F(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 De(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),F(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},Rn=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},Nn=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}),Dn=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})()}},On=class extends Dn{constructor(t){if(super(),this.le=null,!It.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${It.join(", ")}.`);this.St=t}},Un=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},zn=class{setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}constructor(t,e){this.source=t,this.encodingConfig=e,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new st,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&&(F(this.outputWidth),F(this.outputHeight),F("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=it(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 ei?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new ei(i)):o.push(new ei(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 ei&&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),F(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{F(this.encoder);const e=t.toVideoFrame(),i=Q(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 Ln);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;F(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=Rn(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{Nn(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=Ci(this.encodingConfig.quality,this.encodingConfig.bitrate);F(void 0!==e);const i=vi({...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=Si.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=Mi(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 Re))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.");Un(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=Re.fromEncodedChunk(t,r);const o=Q(this.preciseTimings,t.timestamp,t=>t.microsecondTimestamp),s=-1!==o?this.preciseTimings[o]:null;let a=null;0===this.emittedEncoderPackets&&"delta"===n.type&&i?.decoderConfig&&(a=((t,e,i)=>{switch(t){case"avc":for(const t of((t,e)=>{if(e.description){const i=1+(3&U(e.description)[4]);return he(t,i)}return ae(t)})(i,e)){const e=i[t.offset],r=ce(e);if(r>=kt.NON_IDR_SLICE&&r<=kt.SLICE_DPC)return"delta";if(r===kt.IDR)return"key";if(r===kt.SEI&&(!ut()||pt()>=144)){const e=i.subarray(t.offset,t.offset+t.length),r=le(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 St(r);t.pos=8*n;const e=D(t),i=t.readBits(1);if(0===e&&1===i)return"key"}n+=e}while(n<r.length-1)}}return"delta";case"hevc":for(const t of((t,e)=>{if(e.description){const i=1+(3&U(e.description)[21]);return he(t,i)}return ae(t)})(i,e)){const e=fe(i[t.offset]);if(e<Mt.BLA_W_LP)return"delta";if(e<=Mt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new St(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 St(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);F(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 St(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new St(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:J(t),F(!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})),Un(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=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();F(void 0!==a),a?(this.alphaEncoder.encode(a,{...this.defaultEncodeOptions,keyFrame:"key"===o.type}),r++,a.close(),t.push({chunk:o,meta:s})):0===r?n(o,null,s):(e.push(i+r),t.push({chunk:o,meta:s}))},error:t=>{t.stack=o,this.setError(t)}}),this.encoder.configure(s),"keep"===this.encodingConfig.alpha){const o=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(o,s)=>{r--;const a=t.shift();for(F(void 0!==a),n(a.chunk,o,a.meta),i++;e.length>0&&e[0]===i;){e.shift();const i=t.shift();F(void 0!==i),n(i.chunk,null,i.meta)}},error:t=>{t.stack=o,this.setError(t)}}),this.alphaEncoder.configure(s)}}F(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=it(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}},jn=null,Ln=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!jn){const t=new Blob([`(${Hn.toString()})()`],{type:"application/javascript"});jn=URL.createObjectURL(t)}this.worker=new Worker(jn),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=Y();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},Hn=()=>{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)}}},qn=class extends On{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(!It.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${It.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 gi))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof gi)&&(!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&&ci(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.");yi(t.codec,t)})(e),super(e.codec),this.we=new zn(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 ei(this.be,{timestamp:t,duration:e});return this.we.add(r,!0,i)}fe(t){return this.we.flushAndClose(t)}},Gn=class extends Dn{constructor(t){if(super(),this.le=null,!Vt.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${Vt.join(", ")}.`);this.St=t}},Wn=class extends Dn{constructor(t){if(super(),this.le=null,!Rt.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${Rt.join(", ")}.`);this.St=t}},Xn=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>It.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>Vt.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>Rt.includes(t))}ye(t){return""}ve(){return!1}},Qn=class extends Xn{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 In(t,this)}ve(){return"fragmented"===this.At.fastStart}},Yn=class extends Qn{constructor(t){super(t)}get xe(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...It,...$t,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Rt]}ye(t){return(new Kn).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},Jn=class extends Qn{constructor(t){super(t)}get xe(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...It,...$t,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Rt]}},Kn=class extends Qn{constructor(t){super(t)}get xe(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...It,...Vt]}ye(t){return(new Yn).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Zn=class extends Xn{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 Vn(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[...It,...$t,...Ft.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...Rt]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},to=class extends Zn{constructor(t){super(t)}getSupportedCodecs(){return[...It.filter(t=>["vp8","vp9","av1"].includes(t)),...Vt.filter(t=>["opus","vorbis"].includes(t)),...Rt]}get xe(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}ye(t){return(new Zn).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},eo=["video","audio","subtitle"],io=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=gt(this.metadata.group),r=gt(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}},ro=class extends io{constructor(t,e,i,r){super(t,e,"video",i,r)}},no=class extends io{constructor(t,e,i,r){super(t,e,"audio",i,r)}},oo=class extends io{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},so=class t{constructor(){this.Ee=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)}},ao=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&(e=t.languageCode,!nt.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 so)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof so))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},ho=class extends xt{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 so,this.tracks=[],this.Me=null,this._e=new Set,this.Ce=null,this.Se=null,this.Ae=null,this.Pe=null,this.Be=new X,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 Xn))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof En||t.target instanceof Sn))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof En&&this.$e(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof En)&&"function"!=typeof t.initTarget)throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=t.format,this.Ve=t.target,this.Me=t.onFinalize??null,this.Re=t.initTarget??null,this.Re instanceof En&&this.$e(this.Re),this.pe=t.format.ge(this)}Ne(t){F(this.Ve instanceof Sn);const e=this.Ve.getTarget(t),i=t=>{if(!(t instanceof En))throw new TypeError("getTarget must return a Target.");return t};return e instanceof Promise?e.then(i):i(e)}async De(t){F(this.Ve instanceof Sn);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(F(null!==this.Re),this.Re instanceof En)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 En)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 xn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof On))throw new TypeError("source must be a VideoSource.");if(ao(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&&te({decoderConfig:e.decoderConfig},t.St),void 0!==e.primingPacket){if(!(e.primingPacket instanceof Re))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))}addAudioTrack(t,e={}){if(!(t instanceof Gn))throw new TypeError("source must be an AudioSource.");if(ao(e),void 0!==e.decoderConfig&&ie({decoderConfig:e.decoderConfig},t.St),void 0!==e.primingPacket){if(!(e.primingPacket instanceof Re))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 no(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof Wn))throw new TypeError("source must be a SubtitleSource.");ao(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Oe(new oo(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 _t||e instanceof Ct||Et(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 eo)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 eo){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?(Tt.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?(Tt.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&&Tt.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?(Tt.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()}})()}},co=["vp9","vp8"],lo=["avc"],uo=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 Yn:new to,s="stream"===r.kind?new _n(r.writable,{chunked:!0}):new Mn,a=new ho({format:o,target:s}),h=new qn(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 E(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=k(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 E(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 g("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=I(t),i="mp4"===t.format?new Yn:new to,r="mp4"===t.format?lo:co,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t));for(const o of n)if(await _i(o,{width:e.width,height:e.height,quality:this.He(e),alpha:e.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:e.hardwareAcceleration,contentHint:"text"}))return I(t,o);throw new g("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 gi(t.quality)}Ue(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new g("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(x());const n=()=>r(x());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 x()}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 g?t:new g("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}je(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},fo=class{We;_;C;constructor(t,e){this.We=new uo,this._=t,this.C=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.T(e,t),r=I(i);if("file-system"===t.destination){const n=await this.Xe(this.Qe(t.filename,`.${e}`)??`textmode-export.${e}`,r.mimeType);try{await this.Ye(i,n,t.onProgress)}catch(s){try{await(n.abort?.(s))}catch{}throw s}return}const o=await this.Ye(i,{kind:"blob"},t.onProgress);if(!o)throw new g("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new n).$downloadFile(o,this.Qe(t.filename,`.${e}`))}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.T(e,t);I(i);const r=await this.Ye(i,{kind:"blob"},t.onProgress);if(!r)throw new g("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async Ye(t,e,i){const r=new M(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 g("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))}}}},po=class extends r{$extractCellData(t){const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],r=t.grid,n=t.font;let o=0;for(let s=0;s<r.rows;s++)for(let t=0;t<r.cols;t++){const r=4*o,h=this.$getEncodedCharacterValue(e.characterPixels,r),c=this.$extractCellTransform(e.characterPixels,r),l=a(n,h)?.character??" ";i.push({x:t,y:s,character:l,foreground:d(e.primaryColorPixels,r),background:d(e.secondaryColorPixels,r),transform:{invert:c.isInverted,flipX:c.flipHorizontal,flipY:c.flipVertical,rotation:c.rotation}}),o++}return i}},mo="textmode.document",wo="2.0.0",bo={[e.LayerBlendMode.NORMAL]:"normal",[e.LayerBlendMode.ADDITIVE]:"additive",[e.LayerBlendMode.MULTIPLY]:"multiply",[e.LayerBlendMode.SCREEN]:"screen",[e.LayerBlendMode.SUBTRACT]:"subtract",[e.LayerBlendMode.DARKEN]:"darken",[e.LayerBlendMode.LIGHTEN]:"lighten",[e.LayerBlendMode.OVERLAY]:"overlay",[e.LayerBlendMode.SOFT_LIGHT]:"softLight",[e.LayerBlendMode.HARD_LIGHT]:"hardLight",[e.LayerBlendMode.COLOR_DODGE]:"colorDodge",[e.LayerBlendMode.COLOR_BURN]:"colorBurn",[e.LayerBlendMode.DIFFERENCE]:"difference",[e.LayerBlendMode.EXCLUSION]:"exclusion"},yo=class{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:(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 po).$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:bo[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.si(t),cells:this.ai(t,e)}}$generateJSONData(t,i={}){const r=this.T(i),n=this.ri(r);if("all"===r.target){const i=function(t){return[t.layers.base,...t.layers.all].map(i=>{const r=l(t,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??e.LayerBlendMode.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(t),o=i[0].grid;return{format:mo,formatVersion:wo,target:"all",...n?{metadata:n}:{},canvas:{width:o.width,height:o.height},layers:i.map(t=>this.hi(t,r))}}const o=l(t,r.layer);return{format:mo,formatVersion:wo,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 n).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename)}},vo="textmode-export-overlay__stack",go="textmode-export-overlay__stack--dense",xo="textmode-export-overlay__stack--compact",Eo="textmode-export-overlay__section",To="textmode-export-overlay--dragging",ko="textmode-export-overlay__label",Mo="textmode-export-overlay__field",_o="textmode-export-overlay__field--compact",Co="textmode-export-overlay__field--dense",So="textmode-export-overlay__field--full",Ao="textmode-export-overlay__field--channel",Po="textmode-export-overlay__input",Bo="textmode-export-overlay__muted",Io="textmode-export-overlay__button--primary",Fo="textmode-export-overlay__button--secondary",$o="textmode-export-overlay__button--full",Vo="textmode-export-overlay__link-icon",Ro=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}},No=class t extends Ro{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(vo,go,"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",Vo,[{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(Vo,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}},Do=class extends Ro{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(Mo),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(ko),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(Bo),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(Mo),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(ko),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(Bo),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(_o,Co,So,Ao),e){case"compact":t.classList.add(_o);break;case"dense":t.classList.add(Co);break;case"full":t.classList.add(So);break;case"channel":t.classList.add(Ao)}}},Oo=class extends Ro{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(Po),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)}}},Uo=class extends Ro{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(Fo):this.button.classList.add(Io),this.props.fullWidth&&this.button.classList.add($o),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(Fo),this.button.classList.remove(Io)):(this.button.classList.add(Io),this.button.classList.remove(Fo)),this.button.classList.toggle($o,Boolean(t.fullWidth))}},zo=class{et={};wi(t){const e=this.et[t];if(e)return e;const i=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]}},jo=class{bi;et=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)}},Lo=new Set(["txt","json","svg","image"]),Ho=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 Lo.has(t)}},qo={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)}},Go=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 qo[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}}},Wo=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,Xo=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||!Wo(e.offsetX)||!Wo(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(Wo(t)&&Wo(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{}}},Qo=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 Xo){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(To))}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(To),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(To),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()}},Yo=class extends Ro{capabilities;yi;gi=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()}},Jo=class extends Ro{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)}},Ko=class extends Ro{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(Po),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)}},Zo=class extends Ro{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new Do({label:"layer",labelFor:t.id,variant:"full"}),this.select=new Oo({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()}},ts=class extends Yo{layerTarget;trailingSpaces=this.xi(new Jo({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.xi(new Ko({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.xi(new Zo({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(vo),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new Do({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??" "}},es=class extends Yo{layerTarget;layerTargetContainer;target=this.xi(new Oo({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.xi(new Jo({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.xi(new Jo({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.xi(new Oo({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 Zo({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(vo);const e=new Do({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 Do({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)}},is="textmode-export-number-input",rs=`${is}__field`,ns=`${is}__controls`,os=`${is}__control`,ss=`${is}__display`,as=`${ss}--visible`,hs=t=>{const e=document.createElement("button");return e.type="button",e.className=os,e.textContent=t>0?"▲":"▼",e},cs=class extends Ro{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=is,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=rs,this.display=document.createElement("div"),this.display.className=ss;const e=document.createElement("div");return e.className=ns,this.incrementButton=hs(1),this.decrementButton=hs(-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(as),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(as),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(as),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(as),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)}},ls=class extends Ro{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?vo:void 0,"stackDense"===this.variant?go:void 0,"stackCompact"===this.variant?xo:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?Eo:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},ds=class extends Yo{formatSelect=this.xi(new Oo({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 cs({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(vo);const e=new ls("row");e.mount(t);const i=new Do({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Do({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)}},us=class extends Yo{layerTarget;includeBackground=this.xi(new Jo({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.xi(new Oo({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.xi(new cs({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.xi(new Zo({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(vo),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new ls("row");e.mount(t);const i=new Do({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new Do({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()}},fs={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},ps=class extends Ro{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(fs)),this.messageElement.classList.add(fs[t])}},ms=class extends Yo{frameCountInput=this.xi(new cs({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.xi(new cs({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.xi(new cs({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.xi(new cs({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 ps({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(vo);const e=new ls("row");e.mount(t);const i=new Do({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 Do({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 ls("row");n.mount(t);const o=new Do({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 Do({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}},ws=class extends Yo{formatSelect=this.xi(new Oo({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));qualitySelect=this.xi(new Oo({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 cs({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.xi(new cs({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));hardwareAccelerationSelect=this.xi(new Oo({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 cs({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.xi(new Jo({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.xi(new ps({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.xi(new ps({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(vo);const e=new ls("row");e.mount(t);const i=new Do({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new Do({label:"quality",labelFor:"textmode-export-video-quality",variant:"compact"});r.mount(e.root),this.qualitySelect.mount(r.root);const n=new ls("row");n.mount(t);const o=new Do({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 Do({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 ls("row");a.mount(t);const h=new Do({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(a.root),this.hardwareAccelerationSelect.mount(h.root);const c=new Do({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=I(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 bs(t){return t.capabilities.recording}var ys=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 vs(){return{format:ys.format,txt:{...ys.txt},json:{...ys.json},image:{...ys.image},svg:{...ys.svg},gif:{...ys.gif},video:{...ys.video}}}function gs(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var xs=class{Ei;constructor(){this.Ei=vs()}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=vs();if(!t)return this.Ei.format=e.format,gs(this.Ei.txt,e.txt),gs(this.Ei.json,e.json),gs(this.Ei.image,e.image),gs(this.Ei.svg,e.svg),gs(this.Ei.gif,e.gif),void gs(this.Ei.video,e.video);switch(t){case"format":this.Ei.format=e.format;break;case"txt":gs(this.Ei.txt,e.txt);break;case"json":gs(this.Ei.json,e.json);break;case"image":gs(this.Ei.image,e.image);break;case"svg":gs(this.Ei.svg,e.svg);break;case"gif":gs(this.Ei.gif,e.gif);break;case"video":gs(this.Ei.video,e.video)}}},Es=class{_;Ti;bi;ki;Mi;_i;Ci;Si=new Map;Ai=[];Pi;Bi;Ii;Fi;$i;Vi;Ri=new No;Ni=new Do({label:"export format",labelFor:"textmode-export-format",variant:"full"});Di=new Oo({id:"textmode-export-format",options:[]});Oi=new Uo({label:"download file",fullWidth:!0,variant:"primary"});Ui=new Uo({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 jo((t=>({format:t,isBusy:!1}))(n)),this.ki=new zo,this.Mi=new Go(e,this.ki),this._i=new Ho(e),this.Ci=r,this.zi=n,this.Yi(),this.Ji()}$mount(){this.Ki(),this.Zi(),this.Vi=new Qo(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",vo),this.Bi.appendChild(this.Ii),document.body.appendChild(this.Pi)}Zi(){this.Ri.mount(this.Ii);const t=document.createElement("div");t.classList.add(Eo),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(vo,xo),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(vo,go),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&&bs(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&&bs(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(bs(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(bs(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 Ts=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob"],ks=class{api;C;hr=new Set;cr;lr;Y=!1;constructor(t,e){this.C=e;const i={saveCanvas:async(e={})=>(this.dr(),(new b).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.dr(),(new b).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.dr(),(new b).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.dr(),(new m).$saveSVG(t,e)},saveStrings:(e={})=>{this.dr(),(new y).$saveTXT(t,e)},toSVG:(e={})=>(this.dr(),(new m).$generateSVG(t,e)),toString:(e={})=>(this.dr(),(new y).$generateTXT(t,e)),toJSON:(e={})=>(this.dr(),(new yo).$generateJSONData(t,e)),toJSONString:(e={})=>(this.dr(),(new yo).$generateJSONString(t,e)),saveJSON:(e={})=>{this.dr(),(new yo).$saveJSON(t,e)},saveGIF:(e={})=>this.ur(e.signal,i=>new B(t,t=>this.C(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.ur(e.signal,i=>new B(t,t=>this.C(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.ur(e.signal,i=>new fo(t,t=>this.C(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.ur(e.signal,i=>new fo(t,t=>this.C(t)).$generateVideoBlob({...e,signal:i})),exportOverlay:void 0};this.api=i;const r=function(t,e,i){const r=new xs,n=new Es(t,e,r,function(t,e=(()=>{const t=vs();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new ts({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new es({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new ds({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new us({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new ms({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new ws({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:()=>c(t),getLayerById:e=>c(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.")}},Ms={name:"textmode.export.js",install(t,e){const i=new ks(t,t=>e.on("postDraw",t));try{for(const t of Ts)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=Ms),t.ExportPlugin=Ms});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("textmode.js")):"function"==typeof define&&define.amd?define(["exports","textmode.js"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).TextmodeExport={},t.textmode)}(this,function(t,e){Object.defineProperty(t,Symbol.toStringTag,{value:"Module"});Object.create,Object.defineProperty,Object.getOwnPropertyDescriptor,Object.getOwnPropertyNames,Object.getPrototypeOf,Object.prototype.hasOwnProperty;var i=(t,e)=>()=>(e||(t((e={exports:{}}).exports,e),t=null),e.exports),r=class{$extractFramebufferData(t){return{characterPixels:t.readPixels(0),primaryColorPixels:t.readPixels(1),secondaryColorPixels:t.readPixels(2)}}$getEncodedCharacterValue(t,e){return t[e]+(t[e+1]<<8)}$getCharacterIndex(t,e){return this.$getEncodedCharacterValue(t,e)}$extractCellTransform(t,e){const i=t[e+2],r=t[e+3]/255;return{isInverted:!!(1&i),flipHorizontal:!!(2&i),flipVertical:!!(4&i),rotation:Math.round(360*r*100)/100}}},n=new TextEncoder;function o(t,e){let i="",r=0;for(const o of t){const t=n.encode(o).byteLength;if(r+t>e)break;i+=o,r+=t}return i}var s=class{$resolve(t,e,i=new Date){const r=e.toLowerCase(),o=t?.trim(),s=o?.toLowerCase().endsWith(r)?o.slice(0,-r.length):o;return`${this.$sanitizeStem(s,i,255-n.encode(e).length)}${r}`}$sanitizeStem(t,e=new Date,i=255){const r=this.$defaultStem(e);return t?.trim()&&o(Array.from(t.normalize("NFC"),t=>{const e=t.codePointAt(0)??0;return e<32||127===e?"_":t}).join("").trim().replace(/[<>:"/\\|?*]/g,"_").replace(/\s+/g,"_").replace(/\.{2,}/g,"_").replace(/_+/g,"_").replace(/^[._]+|[._]+$/g,""),i).replace(/[._]+$/g,"")||o(r,i)}$defaultStem(t=new Date){return`textmode-export-${t.toISOString().slice(0,19).replace(/:/g,"-")}`}},a=class{$downloadFile(t,e,i){const r=i?(new s).$resolve(e,i):(new s).$sanitizeStem(e),n=URL.createObjectURL(t),o=document.createElement("a");try{o.href=n,o.download=r,o.style.display="none",o.rel="noopener",document.body.appendChild(o),o.click()}finally{o.remove(),setTimeout(()=>URL.revokeObjectURL(n),0)}}},h=new WeakMap;function c(t){return Math.round(255*t[0])+(Math.round(255*t[1])<<8)}function l(t,e){let i=h.get(t);if(!i){i=new Map;for(const e of t.characters)i.set(c(e.color),e);h.set(t,i)}return i.get(e)}function d(t,e){const i="base"===t?"Base layer":`Layer ${Number.parseInt(t.replace("layer-",""),10)}`;return e.isVisible()?i:`${i} (hidden)`}function u(t){return[{id:"base",layer:t.layers.base},...t.layers.all.map((t,e)=>({id:`layer-${e+1}`,layer:t}))].map(({id:t,layer:e})=>({id:t,label:d(t,e),layer:e}))}function f(t,e){const i=e??t.layers.base,r=function(t,e){if(e===t.layers.base)return"base";const i=t.layers.all.indexOf(e);if(i>=0)return`layer-${i+1}`;throw new Error("[textmode-export] Cannot export a layer that is not managed by this Textmodifier instance.")}(t,i),n=i.grid,o=i.font,s=i.drawFramebuffer;if(!n||!s)throw new Error("[textmode-export] Cannot export an uninitialized layer.");return{id:r,label:d(r,i),layer:i,grid:n,font:o,drawFramebuffer:s}}var p=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="FRAME_SEQUENCE_ABORTED"===t?"AbortError":"FrameSequenceError",this.code=t,this.cause=i}};function m(){return new p("FRAME_SEQUENCE_ABORTED","Frame-sequence capture was cancelled.")}function w(t){return t instanceof p&&"FRAME_SEQUENCE_ABORTED"===t.code||t instanceof DOMException&&"AbortError"===t.name}var v=class{m=!1;v=!1;acquire(){if(this.v)throw new p("FRAME_SEQUENCE_DISPOSED","The textmode export plugin has been disposed.");if(this.m)throw new p("FRAME_SEQUENCE_BUSY","Another deterministic frame capture is already active for this textmode instance.");this.m=!0;let t=!1;return()=>{t||(t=!0,this.m=!1)}}dispose(){this.v=!0}},b=1e6;function y(t,e){const i=Math.round(t*b/e),r=Math.max(i+1,Math.round((t+1)*b/e));return{startSeconds:i/b,centerSeconds:(i+Math.floor((r-i)/2))/b,endSeconds:r/b,durationSeconds:(r-i)/b}}var g=class{canvas;T;k;_;M;A=null;S=0;C=0;constructor(t,e,i){if(this.T=t,this.k=e,this.M=t.canvas,this.canvas=i?this.P(i):this.M,i){const t=this.canvas.getContext("2d");if(!t)throw new Error("Frame-sequence export requires a 2D canvas context for staging frames.");t.imageSmoothingEnabled=!1,this._=t}else this._=null}async $render(t){this.I(t.signal);const e=this.T,i=e.isLooping(),r=e.frameCount,n=e.millis,o="secs"in e,s=e.frameRate(),a=this.B(),h=this.F(),c=this.k(()=>this.O());try{e.noLoop(),this.S=r,this.C=n,this.R(o),this.$(t.frameRate,1e3/t.frameRate),this.D();for(let e=0;e<t.frameCount;e++){this.I(t.signal);const i=y(e,t.frameRate);this.S=r+e+1,this.C=1e3*i.startSeconds,await(t.prepareFrame?.({frameIndex:e,frameCount:t.frameCount,startSeconds:i.startSeconds,centerSeconds:i.centerSeconds,endSeconds:i.endSeconds,timeSeconds:i.startSeconds,frameRate:t.frameRate,signal:t.signal})),this.I(t.signal),await this.N(e,t.signal),this.I(t.signal),await t.onFrame({frameIndex:e,canvas:this.canvas}),this.I(t.signal)}}finally{try{c()}catch{}this.A?.reject(new Error("Frame-sequence rendering was interrupted.")),this.A=null,this.V(h),this.U(a),"number"==typeof s&&e.frameRate(s),i?e.loop():e.noLoop()}}N(t,e){if(this.A)throw new Error("A frame-sequence render is already pending.");return function(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(m());let s=!1;const a=t=>{s||(s=!0,clearTimeout(c),i?.removeEventListener("abort",h),t())},h=()=>a(()=>o(m())),c=setTimeout(()=>a(()=>o(function(t){return new p("FRAME_SEQUENCE_TIMEOUT",t,void 0)}(e))),r);i?.addEventListener("abort",h,{once:!0}),t.then(t=>a(()=>n(t)),t=>a(()=>o(t)))})}(new Promise((e,i)=>{this.A={frameIndex:t,resolve:e,reject:i};try{this.T.redraw(1)}catch(r){this.A=null,i(r)}}),`Frame ${t+1} did not render within 30000ms.`,e,3e4).catch(e=>{throw this.A?.frameIndex===t&&(this.A=null),e})}O(){const t=this.A;if(t)try{this._&&(this._.clearRect(0,0,this.canvas.width,this.canvas.height),this._.drawImage(this.M,0,0,this.M.width,this.M.height,0,0,this.canvas.width,this.canvas.height)),this.A=null,t.resolve()}catch(e){this.A=null,t.reject(e)}}P(t){const e=document.createElement("canvas");return e.width=Math.max(1,Math.round(t.width)),e.height=Math.max(1,Math.round(t.height)),e}B(){return["deltaTime","frameRate","resizeCanvas"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this.T,t),value:this.T[t]}))}F(){return["frameCount","millis","secs"].map(t=>({key:t,hadOwnProperty:Object.prototype.hasOwnProperty.call(this.T,t),descriptor:Object.getOwnPropertyDescriptor(this.T,t)}))}R(t){Object.defineProperty(this.T,"frameCount",{configurable:!0,enumerable:!0,get:()=>this.S,set:t=>{this.S=t}}),Object.defineProperty(this.T,"millis",{configurable:!0,enumerable:!0,get:()=>this.C,set:t=>{this.C=t}}),t&&Object.defineProperty(this.T,"secs",{configurable:!0,enumerable:!0,get:()=>this.C/1e3,set:t=>{this.C=1e3*t}})}$(t,e){const i=this.T.frameRate;this.T.deltaTime=()=>e,this.T.frameRate=function(e){return void 0===e?t:i.call(this,e)}}D(){this.T.resizeCanvas=()=>{}}U(t){const e=this.T;for(const i of t)i.hadOwnProperty?e[i.key]=i.value:delete e[i.key]}V(t){for(const e of t)e.hadOwnProperty&&e.descriptor?Object.defineProperty(this.T,e.key,e.descriptor):delete this.T[e.key]}I(t){if(t?.aborted)throw m()}};function x(t,e){return{r:t[e],g:t[e+1],b:t[e+2],a:t[e+3]}}var E=class extends r{j(t,e,i){return{x:t,y:e,cellX:t*i.cellWidth,cellY:e*i.cellHeight}}$extractSVGCellData(t,e){const i=[];let r=0;for(let n=0;n<e.rows;n++)for(let o=0;o<e.cols;o++){const s=4*r,a=this.$getEncodedCharacterValue(t.characterPixels,s);let h=x(t.primaryColorPixels,s),c=x(t.secondaryColorPixels,s);const l=this.$extractCellTransform(t.characterPixels,s);if(l.isInverted){const t=h;h=c,c=t}const d=this.j(o,n,e);i.push({encodedGlyphSlot:a,primaryColor:h,secondaryColor:c,transform:l,position:d}),r++}return i}},T=class{L(t,e,i,r,n){const o=n/t.head.unitsPerEm;return{getBoundingBox:()=>({x1:i+e.xMin*o,y1:r+-e.yMax*o,x2:i+e.xMax*o,y2:r+-e.yMin*o}),toSVG:()=>this.q(e,i,r,o)}}q(t,e,i,r){if(!t||!t.xs)return"";const{xs:n,ys:o,endPts:s,flags:a}=t;if(!(n&&o&&s&&a))return"";let h="",c=0;for(let l=0;l<s.length;l++){const t=s[l];if(!(t<c)){if(t>=c){const s=e+n[c]*r,l=i-o[c]*r;h+=`M${s.toFixed(2)},${l.toFixed(2)}`;let d=c+1;for(;d<=t;)if(1&a[d]){const t=e+n[d]*r,s=i-o[d]*r;h+=`L${t.toFixed(2)},${s.toFixed(2)}`,d++}else{const s=e+n[d]*r,l=i-o[d]*r,u=d+1>t?c:d+1;if(1&a[u]){const t=e+n[u]*r,a=i-o[u]*r;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u+1}else{const t=(s+(e+n[u]*r))/2,a=(l+(i-o[u]*r))/2;h+=`Q${s.toFixed(2)},${l.toFixed(2)} ${t.toFixed(2)},${a.toFixed(2)}`,d=u}}h+="Z"}c=t+1}}return h}$generatePositionedCharacterPath(t,e,i,r,n,o,s,a){if(!a)return null;const h=e.font,c=s/h.head.unitsPerEm,l=i+(n-a.advanceWidth*c)/2,d=r+h.hhea.ascender*c;return this.L(h,a,l,d,s).toSVG()||null}},k=class{G;constructor(){this.G=new T}$generateSVGHeader(t){const{width:e,height:i}=t;return`<?xml version="1.0" encoding="UTF-8"?><svg width="${e}" height="${i}" viewBox="0 0 ${e} ${i}" xmlns="http://www.w3.org/2000/svg"><title>textmode.js sketch</title>`}$generateSVGFooter(){return"</g></svg>"}H(t,e){const{transform:i,position:r}=t;if(!i.flipHorizontal&&!i.flipVertical&&!i.rotation)return"";const n=r.cellX+e.cellWidth/2,o=r.cellY+e.cellHeight/2,s=[];if(i.flipHorizontal||i.flipVertical){const t=i.flipHorizontal?-1:1,e=i.flipVertical?-1:1;s.push(`translate(${n} ${o})scale(${t} ${e})translate(${-n} ${-o})`)}return i.rotation&&s.push(`rotate(${i.rotation} ${n} ${o})`),` transform="${s.join(" ")}"`}W(t,e,i){if(!i.includeBackgroundRectangles||0===t.secondaryColor.a)return"";const{position:r}=t,{r:n,g:o,b:s,a}=t.secondaryColor,h=`rgba(${n},${o},${s},${a/255})`;return"stroke"===i.drawMode?`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" stroke="${h}" fill="none" stroke-width="${i.strokeWidth}"/>`:`<rect x="${r.cellX}" y="${r.cellY}" width="${e.cellWidth}" height="${e.cellHeight}" fill="${h}"/>`}X(t,e,i,r){const n=l(i,t.encodedGlyphSlot);if(!n)return"";const o=this.G.$generatePositionedCharacterPath(n.character,i,t.position.cellX,t.position.cellY,e.cellWidth,e.cellHeight,i.fontSize,n.glyphData);if(!o)return"";const{r:s,g:a,b:h,a:c}=t.primaryColor,d=`rgba(${s},${a},${h},${c/255})`;return"stroke"===r.drawMode?`<path d="${o}" stroke="${d}" stroke-width="${r.strokeWidth}" fill="none"/>`:`<path d="${o}" fill="${d}"/>`}$generateCellContent(t,e,i,r){const n=[],o=this.W(t,e,r);o&&n.push(o);const s=this.X(t,e,i,r);if(s){const i=this.H(t,e);n.push(i?`<g${i}>${s}</g>`:s)}return n.join("")}$generateSVGContent(t,e,i,r){const n=[this.$generateSVGHeader(e),'<g id="ascii-cells">'];for(const o of t)n.push(this.$generateCellContent(o,e,i,r));return n.push(this.$generateSVGFooter()),n.join("")}$optimizeSVGContent(t){return t.replace(/\s+/g," ").replace(/> </g,"><")}},_=class{Z(t){return{includeBackgroundRectangles:t.includeBackgroundRectangles??!0,drawMode:t.drawMode??"fill",strokeWidth:t.strokeWidth??1,filename:t.filename,layer:t.layer}}$generateSVG(t,e={}){const i=new E,r=new k,n=this.Z(e),o=f(t,n.layer),s=i.$extractSVGCellData(i.$extractFramebufferData(o.drawFramebuffer),o.grid),a=r.$generateSVGContent(s,o.grid,o.font,n);return r.$optimizeSVGContent(a)}$saveSVG(t,e={}){(new a).$downloadFile(new Blob([this.$generateSVG(t,e)],{type:"image/svg+xml;charset=utf-8"}),e.filename,".svg")}},M={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},A=class{Z(t){return{format:t.format??"png",scale:Math.abs(t.scale??1),filename:t.filename}}Y(t){if(!(t.format in M))throw new Error(`Saving '${t.format}' files is not supported`)}async $generateImageBlob(t,e){const i=t,r=document.createElement("canvas"),n=r.getContext("2d"),o=Math.round(i.width*e.scale),s=Math.round(i.height*e.scale);return r.width=o,r.height=s,n.imageSmoothingEnabled=!1,n.clearRect(0,0,o,s),n.drawImage(i,0,0,i.width,i.height,0,0,o,s),await new Promise((t,i)=>{r.toBlob(r=>{r?t(r):i(new Error(`Failed to generate ${e.format.toUpperCase()} blob`))},M[e.format])})}async $saveImage(t,e={}){const i=this.Z(e);this.Y(i);const r=await this.$toImageBlob(t,e);(new a).$downloadFile(r,i.filename,`.${i.format}`)}async $toImageBlob(t,e={}){const i=this.Z(e);return this.Y(i),this.$generateImageBlob(t,i)}async $copyImageToClipboard(t,e={}){if("undefined"==typeof navigator||!navigator.clipboard||"function"!=typeof navigator.clipboard.write)throw new Error("Clipboard API is not available in this environment");const i=this.Z(e);this.Y(i);const r=await this.$generateImageBlob(t,i),n=new ClipboardItem({[M[i.format]]:r});await navigator.clipboard.write([n])}},S=class{Z(t){return{preserveTrailingSpaces:t.preserveTrailingSpaces??!1,emptyCharacter:t.emptyCharacter??" ",filename:t.filename,layer:t.layer}}J(t,e){const i=new r,n=f(t,e.layer),o=i.$extractFramebufferData(n.drawFramebuffer),s=[];let a=0;for(let r=0;r<n.grid.rows;r++){let t="";for(let r=0;r<n.grid.cols;r++){const r=4*a,s=i.$getEncodedCharacterValue(o.characterPixels,r);t+=l(n.font,s)?.character||e.emptyCharacter,a++}e.preserveTrailingSpaces||(t=t.trimEnd()),s.push(t)}return s.join("\n")}$generateTXT(t,e={}){return this.J(t,this.Z(e))}$saveTXT(t,e={}){const i=this.Z(e),r=this.J(t,i),n=new Blob([r],{type:"text/plain;charset=utf-8"});(new a).$downloadFile(n,i.filename,".txt")}},C=i(t=>{var e=Object.defineProperty;e(t,"__esModule",{value:!0}),((t,i)=>{for(var r in i)e(t,r,{get:i[r],enumerable:!0})})(t,{GIFEncoder:()=>M,applyPalette:()=>b,default:()=>I,nearestColor:()=>_,nearestColorIndex:()=>T,nearestColorIndexWithDistance:()=>k,prequantize:()=>v,quantize:()=>f,snapColorsToPalette:()=>x});var i={signature:"GIF",version:"89a",trailer:59,extensionIntroducer:33,applicationExtensionLabel:255,graphicControlExtensionLabel:249,imageSeparator:44,signatureSize:3,versionSize:3,globalColorTableFlagMask:128,colorResolutionMask:112,sortFlagMask:8,globalColorTableSizeMask:7,applicationIdentifierSize:8,applicationAuthCodeSize:3,disposalMethodMask:28,userInputFlagMask:2,transparentColorFlagMask:1,localColorTableFlagMask:128,interlaceFlagMask:64,idSortFlagMask:32,localColorTableSizeMask:7};function r(t=256){let e=0,i=new Uint8Array(t);return{get buffer(){return i.buffer},reset(){e=0},bytesView:()=>i.subarray(0,e),bytes:()=>i.slice(0,e),writeByte(t){r(e+1),i[e]=t,e++},writeBytes(t,n=0,o=t.length){r(e+o);for(let r=0;r<o;r++)i[e++]=t[r+n]},writeBytesView(t,n=0,o=t.byteLength){r(e+o),i.set(t.subarray(n,n+o),e),e+=o}};function r(t){var r=i.length;if(r>=t)return;t=Math.max(t,r*(r<1048576?2:1.125)>>>0),0!=r&&(t=Math.max(t,256));const n=i;i=new Uint8Array(t),e>0&&i.set(n.subarray(0,e),0)}}var n=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],o=function(t,e,i,o,s=r(512),a=new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003)){const l=h.length,d=Math.max(2,o);a.fill(0),c.fill(0),h.fill(-1);let u=0,f=0;const p=d+1,m=p;let w=!1,v=m,b=(1<<v)-1;const y=1<<p-1,g=y+1;let x=y+2,E=0,T=i[0],k=0;for(let r=l;r<65536;r*=2)++k;k=8-k,s.writeByte(d),M(y);const _=i.length;for(let r=1;r<_;r++)t:{const t=i[r],e=(t<<12)+T;let n=t<<k^T;if(h[n]===e){T=c[n];break t}const o=0===n?1:l-n;for(;h[n]>=0;)if(n-=o,n<0&&(n+=l),h[n]===e){T=c[n];break t}M(T),T=t,x<4096?(c[n]=x++,h[n]=e):(h.fill(-1),x=y+2,w=!0,M(y))}return M(T),M(g),s.writeByte(0),s.bytesView();function M(t){for(u&=n[f],f>0?u|=t<<f:u=t,f+=v;f>=8;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;if((x>b||w)&&(w?(v=m,b=(1<<v)-1,w=!1):(++v,b=12===v?1<<v:(1<<v)-1)),t==g){for(;f>0;)a[E++]=255&u,E>=254&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0),u>>=8,f-=8;E>0&&(s.writeByte(E),s.writeBytesView(a,0,E),E=0)}}};function s(t,e,i){return t<<8&63488|e<<2&992|i>>3}function a(t,e,i,r){return t>>4|240&e|(240&i)<<4|(240&r)<<8}function h(t,e,i){return t>>4<<8|240&e|i>>4}function c(t,e,i){return t<e?e:t>i?i:t}function l(t){return t*t}function d(t,e,i){var r=0,n=1e100;const o=t[e],s=o.cnt,a=o.ac,h=o.rc,c=o.gc,d=o.bc;for(var u=o.fw;0!=u;u=t[u].fw){const e=t[u],o=e.cnt,p=s*o/(s+o);if(!(p>=n)){var f=0;i&&(f+=p*l(e.ac-a))>=n||(f+=p*l(e.rc-h))>=n||(f+=p*l(e.gc-c))>=n||(f+=p*l(e.bc-d))>=n||(n=f,r=u)}}o.err=n,o.nn=r}function u(){return{ac:0,rc:0,gc:0,bc:0,cnt:0,nn:0,fw:0,bk:0,tm:0,mtm:0,err:0}}function f(t,e,i={}){const{format:r="rgb565",clearAlpha:n=!0,clearAlphaColor:o=0,clearAlphaThreshold:f=0,oneBitAlpha:m=!1}=i;if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");const w=new Uint32Array(t.buffer);let v=!1!==i.useSqrt;const b="rgba4444"===r,y=function(t,e){const i=new Array("rgb444"===e?4096:65536),r=t.length;if("rgba4444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>24&255,o=e>>16&255,s=e>>8&255,h=255&e,c=a(h,s,o,r);let l=c in i?i[c]:i[c]=u();l.rc+=h,l.gc+=s,l.bc+=o,l.ac+=r,l.cnt++}else if("rgb444"===e)for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,s=255&e,a=h(s,o,r);let c=a in i?i[a]:i[a]=u();c.rc+=s,c.gc+=o,c.bc+=r,c.cnt++}else for(let n=0;n<r;++n){const e=t[n],r=e>>16&255,o=e>>8&255,a=255&e,h=s(a,o,r);let c=h in i?i[h]:i[h]=u();c.rc+=a,c.gc+=o,c.bc+=r,c.cnt++}return i}(w,r),g=y.length,x=g-1,E=new Uint32Array(g+1);for(var T=0,k=0;k<g;++k){const t=y[k];if(null!=t){var _=1/t.cnt;b&&(t.ac*=_),t.rc*=_,t.gc*=_,t.bc*=_,y[T++]=t}}var M,A,S;for(l(e)/T<.022&&(v=!1),k=0;k<T-1;++k)y[k].fw=k+1,y[k+1].bk=k,v&&(y[k].cnt=Math.sqrt(y[k].cnt));for(v&&(y[k].cnt=Math.sqrt(y[k].cnt)),k=0;k<T;++k){d(y,k,!1);var C=y[k].err;for(A=++E[0];A>1&&!(y[M=E[S=A>>1]].err<=C);A=S)E[A]=M;E[A]=k}var P=T-e;for(k=0;k<P;){for(var I;;){var B=E[1];if((I=y[B]).tm>=I.mtm&&y[I.nn].mtm<=I.tm)break;for(I.mtm==x?B=E[1]=E[E[0]--]:(d(y,B,!1),I.tm=k),C=y[B].err,A=1;(S=A+A)<=E[0]&&(S<E[0]&&y[E[S]].err>y[E[S+1]].err&&S++,!(C<=y[M=E[S]].err));A=S)E[A]=M;E[A]=B}var F=y[I.nn],O=I.cnt,R=F.cnt;_=1/(O+R),b&&(I.ac=_*(O*I.ac+R*F.ac)),I.rc=_*(O*I.rc+R*F.rc),I.gc=_*(O*I.gc+R*F.gc),I.bc=_*(O*I.bc+R*F.bc),I.cnt+=F.cnt,I.mtm=++k,y[F.bk].fw=F.fw,y[F.fw].bk=F.bk,F.mtm=x}let $=[];var D=0;for(k=0;;++D){let t=c(Math.round(y[k].rc),0,255),e=c(Math.round(y[k].gc),0,255),i=c(Math.round(y[k].bc),0,255),r=255;b&&(r=c(Math.round(y[k].ac),0,255),m&&(r=r<=("number"==typeof m?m:127)?0:255),n&&r<=f&&(t=e=i=o,r=0));const s=b?[t,e,i,r]:[t,e,i];if(p($,s)||$.push(s),0==(k=y[k].fw))break}return $}function p(t,e){for(let i=0;i<t.length;i++){const r=t[i];let n=r[0]===e[0]&&r[1]===e[1]&&r[2]===e[2],o=!(r.length>=4&&e.length>=4)||r[3]===e[3];if(n&&o)return!0}return!1}function m(t,e){var i,r=0;for(i=0;i<t.length;i++){const n=t[i]-e[i];r+=n*n}return r}function w(t,e){return e>1?Math.round(t/e)*e:t}function v(t,{roundRGB:e=5,roundAlpha:i=10,oneBitAlpha:r=null}={}){const n=new Uint32Array(t.buffer);for(let o=0;o<n.length;o++){const t=n[o];let s=t>>24&255,a=t>>16&255,h=t>>8&255,c=255&t;s=w(s,i),r&&(s=s<=("number"==typeof r?r:127)?0:255),c=w(c,e),h=w(h,e),a=w(a,e),n[o]=s<<24|a<<16|h<<8|c}}function b(t,e,i="rgb565"){if(!t||!t.buffer)throw new Error("quantize() expected RGBA Uint8Array data");if(!(t instanceof Uint8Array||t instanceof Uint8ClampedArray))throw new Error("quantize() expected RGBA Uint8Array data");if(e.length>256)throw new Error("applyPalette() only works with 256 colors or less");const r=new Uint32Array(t.buffer),n=r.length,o="rgb444"===i?4096:65536,c=new Uint8Array(n),l=new Array(o);if("rgba4444"===i)for(let s=0;s<n;s++){const t=r[s],i=t>>24&255,n=t>>16&255,o=t>>8&255,h=255&t,d=a(h,o,n,i);c[s]=d in l?l[d]:l[d]=y(h,o,n,i,e)}else{const t="rgb444"===i?h:s;for(let i=0;i<n;i++){const n=r[i],o=n>>16&255,s=n>>8&255,a=255&n,h=t(a,s,o);c[i]=h in l?l[h]:l[h]=g(a,s,o,e)}}return c}function y(t,e,i,r,n){let o=0,s=1e100;for(let a=0;a<n.length;a++){const h=n[a];let c=E(h[3]-r);c>s||(c+=E(h[0]-t),c>s||(c+=E(h[1]-e),c>s||(c+=E(h[2]-i),c>s||(s=c,o=a))))}return o}function g(t,e,i,r){let n=0,o=1e100;for(let s=0;s<r.length;s++){const a=r[s];let h=E(a[0]-t);h>o||(h+=E(a[1]-e),h>o||(h+=E(a[2]-i),h>o||(o=h,n=s)))}return n}function x(t,e,i=5){if(!t.length||!e.length)return;const r=t.map(t=>t.slice(0,3)),n=i*i,o=t[0].length;for(let s=0;s<e.length;s++){let i=e[s];i=i.length<o?[i[0],i[1],i[2],255]:i.length>o?i.slice(0,3):i.slice();const a=k(r,i.slice(0,3),m),h=a[0],c=a[1];c>0&&c<=n&&(t[h]=i)}}function E(t){return t*t}function T(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return n}function k(t,e,i=m){let r=1/0,n=-1;for(let o=0;o<t.length;o++){const s=i(e,t[o]);s<r&&(r=s,n=o)}return[n,r]}function _(t,e,i=m){return t[T(t,e,i)]}function M(t={}){const{initialCapacity:e=4096,auto:n=!0}=t,s=r(e),a=new Uint8Array(256),h=new Int32Array(5003),c=new Int32Array(5003);let l=!1;return{reset(){s.reset(),l=!1},finish(){s.writeByte(i.trailer)},bytes:()=>s.bytes(),bytesView:()=>s.bytesView(),get buffer(){return s.buffer},get stream(){return s},writeHeader:d,writeFrame(t,e,i,r={}){const{transparent:u=!1,transparentIndex:f=0,delay:p=0,palette:m=null,repeat:w=0,colorDepth:v=8,dispose:b=-1}=r;let y=!1;if(n?l||(y=!0,d(),l=!0):y=Boolean(r.first),e=Math.max(0,Math.floor(e)),i=Math.max(0,Math.floor(i)),y){if(!m)throw new Error("First frame must include a { palette } option");!function(t,e,i,r,n=8){const o=n-1<<4|128|P(r.length)-1;S(t,e),S(t,i),t.writeBytes([o,0,0])}(s,e,i,m,v),A(s,m),w>=0&&function(t,e){t.writeByte(33),t.writeByte(255),t.writeByte(11),C(t,"NETSCAPE2.0"),t.writeByte(3),t.writeByte(1),S(t,e),t.writeByte(0)}(s,w)}const g=Math.round(p/10);!function(t,e,i,r,n){var o,s;t.writeByte(33),t.writeByte(249),t.writeByte(4),n<0&&(n=0,r=!1),r?(o=1,s=2):(o=0,s=0),e>=0&&(s=7&e),s<<=2,t.writeByte(0|s|o),S(t,i),t.writeByte(n||0),t.writeByte(0)}(s,b,g,u,f);const x=Boolean(m)&&!y;!function(t,e,i,r){if(t.writeByte(44),S(t,0),S(t,0),S(t,e),S(t,i),r){const e=P(r.length)-1;t.writeByte(128|e)}else t.writeByte(0)}(s,e,i,x?m:null),x&&A(s,m),function(t,e,i,r,n=8,s,a,h){o(i,r,e,n,t,s,a,h)}(s,t,e,i,v,a,h,c)}};function d(){C(s,"GIF89a")}}function A(t,e){const i=1<<P(e.length);for(let r=0;r<i;r++){let i=[0,0,0];r<e.length&&(i=e[r]),t.writeByte(i[0]),t.writeByte(i[1]),t.writeByte(i[2])}}function S(t,e){t.writeByte(255&e),t.writeByte(e>>8&255)}function C(t,e){for(var i=0;i<e.length;i++)t.writeByte(e.charCodeAt(i))}function P(t){return Math.max(Math.ceil(Math.log2(t)),1)}var I=M}),P='(function() {\n\tvar r = ((t, r) => () => (r || (t((r = { exports: {} }).exports, r), t = null), r.exports))((t) => {\n\t\tvar r = Object.defineProperty;\n\t\tr(t, "__esModule", { value: !0 }), ((t, e) => {\n\t\t\tfor (var n in e) r(t, n, {\n\t\t\t\tget: e[n],\n\t\t\t\tenumerable: !0\n\t\t\t});\n\t\t})(t, {\n\t\t\tGIFEncoder: () => I,\n\t\t\tapplyPalette: () => b,\n\t\t\tdefault: () => x,\n\t\t\tnearestColor: () => C,\n\t\t\tnearestColorIndex: () => k,\n\t\t\tnearestColorIndexWithDistance: () => U,\n\t\t\tprequantize: () => A,\n\t\t\tquantize: () => y,\n\t\t\tsnapColorsToPalette: () => v\n\t\t});\n\t\tvar e = {\n\t\t\tsignature: "GIF",\n\t\t\tversion: "89a",\n\t\t\ttrailer: 59,\n\t\t\textensionIntroducer: 33,\n\t\t\tapplicationExtensionLabel: 255,\n\t\t\tgraphicControlExtensionLabel: 249,\n\t\t\timageSeparator: 44,\n\t\t\tsignatureSize: 3,\n\t\t\tversionSize: 3,\n\t\t\tglobalColorTableFlagMask: 128,\n\t\t\tcolorResolutionMask: 112,\n\t\t\tsortFlagMask: 8,\n\t\t\tglobalColorTableSizeMask: 7,\n\t\t\tapplicationIdentifierSize: 8,\n\t\t\tapplicationAuthCodeSize: 3,\n\t\t\tdisposalMethodMask: 28,\n\t\t\tuserInputFlagMask: 2,\n\t\t\ttransparentColorFlagMask: 1,\n\t\t\tlocalColorTableFlagMask: 128,\n\t\t\tinterlaceFlagMask: 64,\n\t\t\tidSortFlagMask: 32,\n\t\t\tlocalColorTableSizeMask: 7\n\t\t};\n\t\tfunction n(t = 256) {\n\t\t\tlet r = 0, e = new Uint8Array(t);\n\t\t\treturn {\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn e.buffer;\n\t\t\t\t},\n\t\t\t\treset() {\n\t\t\t\t\tr = 0;\n\t\t\t\t},\n\t\t\t\tbytesView: () => e.subarray(0, r),\n\t\t\t\tbytes: () => e.slice(0, r),\n\t\t\t\twriteByte(t) {\n\t\t\t\t\tn(r + 1), e[r] = t, r++;\n\t\t\t\t},\n\t\t\t\twriteBytes(t, o = 0, a = t.length) {\n\t\t\t\t\tn(r + a);\n\t\t\t\t\tfor (let n = 0; n < a; n++) e[r++] = t[n + o];\n\t\t\t\t},\n\t\t\t\twriteBytesView(t, o = 0, a = t.byteLength) {\n\t\t\t\t\tn(r + a), e.set(t.subarray(o, o + a), r), r += a;\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction n(t) {\n\t\t\t\tvar n = e.length;\n\t\t\t\tif (n >= t) return;\n\t\t\t\tt = Math.max(t, n * (n < 1048576 ? 2 : 1.125) >>> 0), 0 != n && (t = Math.max(t, 256));\n\t\t\t\tconst o = e;\n\t\t\t\te = new Uint8Array(t), r > 0 && e.set(o.subarray(0, r), 0);\n\t\t\t}\n\t\t}\n\t\tvar o = [\n\t\t\t0,\n\t\t\t1,\n\t\t\t3,\n\t\t\t7,\n\t\t\t15,\n\t\t\t31,\n\t\t\t63,\n\t\t\t127,\n\t\t\t255,\n\t\t\t511,\n\t\t\t1023,\n\t\t\t2047,\n\t\t\t4095,\n\t\t\t8191,\n\t\t\t16383,\n\t\t\t32767,\n\t\t\t65535\n\t\t], a = function(t, r, e, a, i = n(512), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003)) {\n\t\t\tconst s = c.length, u = Math.max(2, a);\n\t\t\tl.fill(0), f.fill(0), c.fill(-1);\n\t\t\tlet p = 0, y = 0;\n\t\t\tconst h = u + 1, w = h;\n\t\t\tlet d = !1, A = w, b = (1 << A) - 1;\n\t\t\tconst M = 1 << h - 1, g = M + 1;\n\t\t\tlet v = M + 2, m = 0, k = e[0], U = 0;\n\t\t\tfor (let n = s; n < 65536; n *= 2) ++U;\n\t\t\tU = 8 - U, i.writeByte(u), I(M);\n\t\t\tconst C = e.length;\n\t\t\tfor (let n = 1; n < C; n++) t: {\n\t\t\t\tconst t = e[n], r = (t << 12) + k;\n\t\t\t\tlet o = t << U ^ k;\n\t\t\t\tif (c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tconst a = 0 === o ? 1 : s - o;\n\t\t\t\tfor (; c[o] >= 0;) if (o -= a, o < 0 && (o += s), c[o] === r) {\n\t\t\t\t\tk = f[o];\n\t\t\t\t\tbreak t;\n\t\t\t\t}\n\t\t\t\tI(k), k = t, v < 4096 ? (f[o] = v++, c[o] = r) : (c.fill(-1), v = M + 2, d = !0, I(M));\n\t\t\t}\n\t\t\treturn I(k), I(g), i.writeByte(0), i.bytesView();\n\t\t\tfunction I(t) {\n\t\t\t\tfor (p &= o[y], y > 0 ? p |= t << y : p = t, y += A; y >= 8;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\tif ((v > b || d) && (d ? (A = w, b = (1 << A) - 1, d = !1) : (++A, b = 12 === A ? 1 << A : (1 << A) - 1)), t == g) {\n\t\t\t\t\tfor (; y > 0;) l[m++] = 255 & p, m >= 254 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0), p >>= 8, y -= 8;\n\t\t\t\t\tm > 0 && (i.writeByte(m), i.writeBytesView(l, 0, m), m = 0);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\t\tfunction i(t, r, e) {\n\t\t\treturn t << 8 & 63488 | r << 2 & 992 | e >> 3;\n\t\t}\n\t\tfunction l(t, r, e, n) {\n\t\t\treturn t >> 4 | 240 & r | (240 & e) << 4 | (240 & n) << 8;\n\t\t}\n\t\tfunction c(t, r, e) {\n\t\t\treturn t >> 4 << 8 | 240 & r | e >> 4;\n\t\t}\n\t\tfunction f(t, r, e) {\n\t\t\treturn t < r ? r : t > e ? e : t;\n\t\t}\n\t\tfunction s(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction u(t, r, e) {\n\t\t\tvar n = 0, o = 1e100;\n\t\t\tconst a = t[r], i = a.cnt, l = a.ac, c = a.rc, f = a.gc, u = a.bc;\n\t\t\tfor (var p = a.fw; 0 != p; p = t[p].fw) {\n\t\t\t\tconst r = t[p], a = r.cnt, h = i * a / (i + a);\n\t\t\t\tif (!(h >= o)) {\n\t\t\t\t\tvar y = 0;\n\t\t\t\t\te && (y += h * s(r.ac - l)) >= o || (y += h * s(r.rc - c)) >= o || (y += h * s(r.gc - f)) >= o || (y += h * s(r.bc - u)) >= o || (o = y, n = p);\n\t\t\t\t}\n\t\t\t}\n\t\t\ta.err = o, a.nn = n;\n\t\t}\n\t\tfunction p() {\n\t\t\treturn {\n\t\t\t\tac: 0,\n\t\t\t\trc: 0,\n\t\t\t\tgc: 0,\n\t\t\t\tbc: 0,\n\t\t\t\tcnt: 0,\n\t\t\t\tnn: 0,\n\t\t\t\tfw: 0,\n\t\t\t\tbk: 0,\n\t\t\t\ttm: 0,\n\t\t\t\tmtm: 0,\n\t\t\t\terr: 0\n\t\t\t};\n\t\t}\n\t\tfunction y(t, r, e = {}) {\n\t\t\tconst { format: n = "rgb565", clearAlpha: o = !0, clearAlphaColor: a = 0, clearAlphaThreshold: y = 0, oneBitAlpha: w = !1 } = e;\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tconst d = new Uint32Array(t.buffer);\n\t\t\tlet A = !1 !== e.useSqrt;\n\t\t\tconst b = "rgba4444" === n, M = function(t, r) {\n\t\t\t\tconst e = new Array("rgb444" === r ? 4096 : 65536), n = t.length;\n\t\t\t\tif ("rgba4444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 24 & 255, a = r >> 16 & 255, i = r >> 8 & 255, c = 255 & r, f = l(c, i, a, n);\n\t\t\t\t\tlet s = f in e ? e[f] : e[f] = p();\n\t\t\t\t\ts.rc += c, s.gc += i, s.bc += a, s.ac += n, s.cnt++;\n\t\t\t\t}\n\t\t\t\telse if ("rgb444" === r) for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, i = 255 & r, l = c(i, a, n);\n\t\t\t\t\tlet f = l in e ? e[l] : e[l] = p();\n\t\t\t\t\tf.rc += i, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\telse for (let o = 0; o < n; ++o) {\n\t\t\t\t\tconst r = t[o], n = r >> 16 & 255, a = r >> 8 & 255, l = 255 & r, c = i(l, a, n);\n\t\t\t\t\tlet f = c in e ? e[c] : e[c] = p();\n\t\t\t\t\tf.rc += l, f.gc += a, f.bc += n, f.cnt++;\n\t\t\t\t}\n\t\t\t\treturn e;\n\t\t\t}(d, n), g = M.length, v = g - 1, m = new Uint32Array(g + 1);\n\t\t\tfor (var k = 0, U = 0; U < g; ++U) {\n\t\t\t\tconst t = M[U];\n\t\t\t\tif (null != t) {\n\t\t\t\t\tvar C = 1 / t.cnt;\n\t\t\t\t\tb && (t.ac *= C), t.rc *= C, t.gc *= C, t.bc *= C, M[k++] = t;\n\t\t\t\t}\n\t\t\t}\n\t\t\tvar I, F, z;\n\t\t\tfor (s(r) / k < .022 && (A = !1), U = 0; U < k - 1; ++U) M[U].fw = U + 1, M[U + 1].bk = U, A && (M[U].cnt = Math.sqrt(M[U].cnt));\n\t\t\tfor (A && (M[U].cnt = Math.sqrt(M[U].cnt)), U = 0; U < k; ++U) {\n\t\t\t\tu(M, U, !1);\n\t\t\t\tvar B = M[U].err;\n\t\t\t\tfor (F = ++m[0]; F > 1 && !(M[I = m[z = F >> 1]].err <= B); F = z) m[F] = I;\n\t\t\t\tm[F] = U;\n\t\t\t}\n\t\t\tvar E = k - r;\n\t\t\tfor (U = 0; U < E;) {\n\t\t\t\tfor (var x;;) {\n\t\t\t\t\tvar G = m[1];\n\t\t\t\t\tif ((x = M[G]).tm >= x.mtm && M[x.nn].mtm <= x.tm) break;\n\t\t\t\t\tfor (x.mtm == v ? G = m[1] = m[m[0]--] : (u(M, G, !1), x.tm = U), B = M[G].err, F = 1; (z = F + F) <= m[0] && (z < m[0] && M[m[z]].err > M[m[z + 1]].err && z++, !(B <= M[I = m[z]].err)); F = z) m[F] = I;\n\t\t\t\t\tm[F] = G;\n\t\t\t\t}\n\t\t\t\tvar S = M[x.nn], T = x.cnt, q = S.cnt;\n\t\t\t\tC = 1 / (T + q), b && (x.ac = C * (T * x.ac + q * S.ac)), x.rc = C * (T * x.rc + q * S.rc), x.gc = C * (T * x.gc + q * S.gc), x.bc = C * (T * x.bc + q * S.bc), x.cnt += S.cnt, x.mtm = ++U, M[S.bk].fw = S.fw, M[S.fw].bk = S.bk, S.mtm = v;\n\t\t\t}\n\t\t\tlet R = [];\n\t\t\tvar P = 0;\n\t\t\tfor (U = 0;; ++P) {\n\t\t\t\tlet t = f(Math.round(M[U].rc), 0, 255), r = f(Math.round(M[U].gc), 0, 255), e = f(Math.round(M[U].bc), 0, 255), n = 255;\n\t\t\t\tb && (n = f(Math.round(M[U].ac), 0, 255), w && (n = n <= ("number" == typeof w ? w : 127) ? 0 : 255), o && n <= y && (t = r = e = a, n = 0));\n\t\t\t\tconst i = b ? [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te,\n\t\t\t\t\tn\n\t\t\t\t] : [\n\t\t\t\t\tt,\n\t\t\t\t\tr,\n\t\t\t\t\te\n\t\t\t\t];\n\t\t\t\tif (h(R, i) || R.push(i), 0 == (U = M[U].fw)) break;\n\t\t\t}\n\t\t\treturn R;\n\t\t}\n\t\tfunction h(t, r) {\n\t\t\tfor (let e = 0; e < t.length; e++) {\n\t\t\t\tconst n = t[e];\n\t\t\t\tlet o = n[0] === r[0] && n[1] === r[1] && n[2] === r[2], a = !(n.length >= 4 && r.length >= 4) || n[3] === r[3];\n\t\t\t\tif (o && a) return !0;\n\t\t\t}\n\t\t\treturn !1;\n\t\t}\n\t\tfunction w(t, r) {\n\t\t\tvar e, n = 0;\n\t\t\tfor (e = 0; e < t.length; e++) {\n\t\t\t\tconst o = t[e] - r[e];\n\t\t\t\tn += o * o;\n\t\t\t}\n\t\t\treturn n;\n\t\t}\n\t\tfunction d(t, r) {\n\t\t\treturn r > 1 ? Math.round(t / r) * r : t;\n\t\t}\n\t\tfunction A(t, { roundRGB: r = 5, roundAlpha: e = 10, oneBitAlpha: n = null } = {}) {\n\t\t\tconst o = new Uint32Array(t.buffer);\n\t\t\tfor (let a = 0; a < o.length; a++) {\n\t\t\t\tconst t = o[a];\n\t\t\t\tlet i = t >> 24 & 255, l = t >> 16 & 255, c = t >> 8 & 255, f = 255 & t;\n\t\t\t\ti = d(i, e), n && (i = i <= ("number" == typeof n ? n : 127) ? 0 : 255), f = d(f, r), c = d(c, r), l = d(l, r), o[a] = i << 24 | l << 16 | c << 8 | f;\n\t\t\t}\n\t\t}\n\t\tfunction b(t, r, e = "rgb565") {\n\t\t\tif (!t || !t.buffer) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (!(t instanceof Uint8Array || t instanceof Uint8ClampedArray)) throw new Error("quantize() expected RGBA Uint8Array data");\n\t\t\tif (r.length > 256) throw new Error("applyPalette() only works with 256 colors or less");\n\t\t\tconst n = new Uint32Array(t.buffer), o = n.length, a = "rgb444" === e ? 4096 : 65536, f = new Uint8Array(o), s = new Array(a);\n\t\t\tif ("rgba4444" === e) for (let i = 0; i < o; i++) {\n\t\t\t\tconst t = n[i], e = t >> 24 & 255, o = t >> 16 & 255, a = t >> 8 & 255, c = 255 & t, u = l(c, a, o, e);\n\t\t\t\tf[i] = u in s ? s[u] : s[u] = M(c, a, o, e, r);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst t = "rgb444" === e ? c : i;\n\t\t\t\tfor (let e = 0; e < o; e++) {\n\t\t\t\t\tconst o = n[e], a = o >> 16 & 255, i = o >> 8 & 255, l = 255 & o, c = t(l, i, a);\n\t\t\t\t\tf[e] = c in s ? s[c] : s[c] = g(l, i, a, r);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn f;\n\t\t}\n\t\tfunction M(t, r, e, n, o) {\n\t\t\tlet a = 0, i = 1e100;\n\t\t\tfor (let l = 0; l < o.length; l++) {\n\t\t\t\tconst c = o[l];\n\t\t\t\tlet f = m(c[3] - n);\n\t\t\t\tf > i || (f += m(c[0] - t), f > i || (f += m(c[1] - r), f > i || (f += m(c[2] - e), f > i || (i = f, a = l))));\n\t\t\t}\n\t\t\treturn a;\n\t\t}\n\t\tfunction g(t, r, e, n) {\n\t\t\tlet o = 0, a = 1e100;\n\t\t\tfor (let i = 0; i < n.length; i++) {\n\t\t\t\tconst l = n[i];\n\t\t\t\tlet c = m(l[0] - t);\n\t\t\t\tc > a || (c += m(l[1] - r), c > a || (c += m(l[2] - e), c > a || (a = c, o = i)));\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction v(t, r, e = 5) {\n\t\t\tif (!t.length || !r.length) return;\n\t\t\tconst n = t.map((t) => t.slice(0, 3)), o = e * e, a = t[0].length;\n\t\t\tfor (let i = 0; i < r.length; i++) {\n\t\t\t\tlet e = r[i];\n\t\t\t\te = e.length < a ? [\n\t\t\t\t\te[0],\n\t\t\t\t\te[1],\n\t\t\t\t\te[2],\n\t\t\t\t\t255\n\t\t\t\t] : e.length > a ? e.slice(0, 3) : e.slice();\n\t\t\t\tconst l = U(n, e.slice(0, 3), w), c = l[0], f = l[1];\n\t\t\t\tf > 0 && f <= o && (t[c] = e);\n\t\t\t}\n\t\t}\n\t\tfunction m(t) {\n\t\t\treturn t * t;\n\t\t}\n\t\tfunction k(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn o;\n\t\t}\n\t\tfunction U(t, r, e = w) {\n\t\t\tlet n = Infinity, o = -1;\n\t\t\tfor (let a = 0; a < t.length; a++) {\n\t\t\t\tconst i = e(r, t[a]);\n\t\t\t\ti < n && (n = i, o = a);\n\t\t\t}\n\t\t\treturn [o, n];\n\t\t}\n\t\tfunction C(t, r, e = w) {\n\t\t\treturn t[k(t, r, e)];\n\t\t}\n\t\tfunction I(t = {}) {\n\t\t\tconst { initialCapacity: r = 4096, auto: o = !0 } = t, i = n(r), l = /* @__PURE__ */ new Uint8Array(256), c = /* @__PURE__ */ new Int32Array(5003), f = /* @__PURE__ */ new Int32Array(5003);\n\t\t\tlet s = !1;\n\t\t\treturn {\n\t\t\t\treset() {\n\t\t\t\t\ti.reset(), s = !1;\n\t\t\t\t},\n\t\t\t\tfinish() {\n\t\t\t\t\ti.writeByte(e.trailer);\n\t\t\t\t},\n\t\t\t\tbytes: () => i.bytes(),\n\t\t\t\tbytesView: () => i.bytesView(),\n\t\t\t\tget buffer() {\n\t\t\t\t\treturn i.buffer;\n\t\t\t\t},\n\t\t\t\tget stream() {\n\t\t\t\t\treturn i;\n\t\t\t\t},\n\t\t\t\twriteHeader: u,\n\t\t\t\twriteFrame(t, r, e, n = {}) {\n\t\t\t\t\tconst { transparent: p = !1, transparentIndex: y = 0, delay: h = 0, palette: w = null, repeat: d = 0, colorDepth: A = 8, dispose: b = -1 } = n;\n\t\t\t\t\tlet M = !1;\n\t\t\t\t\tif (o ? s || (M = !0, u(), s = !0) : M = Boolean(n.first), r = Math.max(0, Math.floor(r)), e = Math.max(0, Math.floor(e)), M) {\n\t\t\t\t\t\tif (!w) throw new Error("First frame must include a { palette } option");\n\t\t\t\t\t\t(function(t, r, e, n, o = 8) {\n\t\t\t\t\t\t\tconst a = o - 1 << 4 | 128 | E(n.length) - 1;\n\t\t\t\t\t\t\tz(t, r), z(t, e), t.writeBytes([\n\t\t\t\t\t\t\t\ta,\n\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t0\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t})(i, r, e, w, A), F(i, w), d >= 0 && function(t, r) {\n\t\t\t\t\t\t\tt.writeByte(33), t.writeByte(255), t.writeByte(11), B(t, "NETSCAPE2.0"), t.writeByte(3), t.writeByte(1), z(t, r), t.writeByte(0);\n\t\t\t\t\t\t}(i, d);\n\t\t\t\t\t}\n\t\t\t\t\tconst g = Math.round(h / 10);\n\t\t\t\t\t(function(t, r, e, n, o) {\n\t\t\t\t\t\tvar a, i;\n\t\t\t\t\t\tt.writeByte(33), t.writeByte(249), t.writeByte(4), o < 0 && (o = 0, n = !1), n ? (a = 1, i = 2) : (a = 0, i = 0), r >= 0 && (i = 7 & r), i <<= 2, t.writeByte(0 | i | a), z(t, e), t.writeByte(o || 0), t.writeByte(0);\n\t\t\t\t\t})(i, b, g, p, y);\n\t\t\t\t\tconst v = Boolean(w) && !M;\n\t\t\t\t\t(function(t, r, e, n) {\n\t\t\t\t\t\tif (t.writeByte(44), z(t, 0), z(t, 0), z(t, r), z(t, e), n) {\n\t\t\t\t\t\t\tconst r = E(n.length) - 1;\n\t\t\t\t\t\t\tt.writeByte(128 | r);\n\t\t\t\t\t\t} else t.writeByte(0);\n\t\t\t\t\t})(i, r, e, v ? w : null), v && F(i, w), function(t, r, e, n, o = 8, i, l, c) {\n\t\t\t\t\t\ta(e, n, r, o, t, i, l, c);\n\t\t\t\t\t}(i, t, r, e, A, l, c, f);\n\t\t\t\t}\n\t\t\t};\n\t\t\tfunction u() {\n\t\t\t\tB(i, "GIF89a");\n\t\t\t}\n\t\t}\n\t\tfunction F(t, r) {\n\t\t\tconst e = 1 << E(r.length);\n\t\t\tfor (let n = 0; n < e; n++) {\n\t\t\t\tlet e = [\n\t\t\t\t\t0,\n\t\t\t\t\t0,\n\t\t\t\t\t0\n\t\t\t\t];\n\t\t\t\tn < r.length && (e = r[n]), t.writeByte(e[0]), t.writeByte(e[1]), t.writeByte(e[2]);\n\t\t\t}\n\t\t}\n\t\tfunction z(t, r) {\n\t\t\tt.writeByte(255 & r), t.writeByte(r >> 8 & 255);\n\t\t}\n\t\tfunction B(t, r) {\n\t\t\tfor (var e = 0; e < r.length; e++) t.writeByte(r.charCodeAt(e));\n\t\t}\n\t\tfunction E(t) {\n\t\t\treturn Math.max(Math.ceil(Math.log2(t)), 1);\n\t\t}\n\t\tvar x = I;\n\t})();\n\tconst e = (0, r.GIFEncoder)();\n\tlet n = 1, o = 1, a = 16, i = 0;\n\tconst l = self;\n\tl.addEventListener("message", (t) => {\n\t\tconst c = t.data;\n\t\ttry {\n\t\t\tif ("init" === c.type) return n = c.width ?? n, o = c.height ?? o, a = c.delay ?? a, i = c.repeat ?? i, void l.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "ready"\n\t\t\t});\n\t\t\tif ("frame" === c.type && c.buffer) {\n\t\t\t\tconst t = new Uint8ClampedArray(c.buffer), f = (0, r.quantize)(t, 256, {}), s = (0, r.applyPalette)(t, f);\n\t\t\t\te.writeFrame(s, n, o, {\n\t\t\t\t\tpalette: f,\n\t\t\t\t\tdelay: a,\n\t\t\t\t\trepeat: 0 === c.frameIndex ? i : -1\n\t\t\t\t}), l.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "frame-complete"\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ("finish" === c.type) {\n\t\t\t\te.finish();\n\t\t\t\tconst t = e.bytes(), r = t.buffer.slice(t.byteOffset, t.byteOffset + t.byteLength);\n\t\t\t\tl.postMessage({\n\t\t\t\t\tid: c.id,\n\t\t\t\t\ttype: "complete",\n\t\t\t\t\tbuffer: r\n\t\t\t\t}, [r]);\n\t\t\t}\n\t\t} catch (f) {\n\t\t\tl.postMessage({\n\t\t\t\tid: c.id,\n\t\t\t\ttype: "error",\n\t\t\t\tmessage: f instanceof Error ? f.message : "GIF worker failed"\n\t\t\t});\n\t\t}\n\t});\n})();\n',I="undefined"!=typeof self&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",P],{type:"text/javascript;charset=utf-8"});function B(t){let e;try{if(e=I&&(self.URL||self.webkitURL).createObjectURL(I),!e)throw"";const i=new Worker(e,{name:t?.name});return i.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),i}catch(i){return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(P),{name:t?.name})}}var F=class{K;tt=new Map;et;it=0;v=!1;constructor(t,e,i,r,n){this.K=new B,this.K.addEventListener("message",this.rt),this.K.addEventListener("error",this.nt),n?.addEventListener("abort",this.dispose,{once:!0}),this.et=this.ot({type:"init",width:t,height:e,delay:Math.round(1e3/i),repeat:r})}async encodeFrame(t,e){await this.et,await this.ot({type:"frame",buffer:t,frameIndex:e},[t])}async finish(){await this.et;const t=await this.ot({type:"finish"});if(!t.buffer)throw new Error("GIF worker returned no encoded output.");return t.buffer}dispose=()=>{if(!this.v){this.v=!0,this.K.terminate();for(const t of this.tt.values())t.reject(new DOMException("GIF export was cancelled.","AbortError"));this.tt.clear()}};ot(t,e=[]){if(this.v)return Promise.reject(new DOMException("GIF export was cancelled.","AbortError"));const i=++this.it;return new Promise((r,n)=>{this.tt.set(i,{resolve:r,reject:n}),this.K.postMessage({...t,id:i},e)})}rt=t=>{const e=t.data,i=this.tt.get(e.id);i&&(this.tt.delete(e.id),"error"!==e.type?i.resolve(e):i.reject(new Error(e.message??"GIF worker failed")))};nt=t=>{const e=new Error(t.message||"GIF worker failed");for(const i of this.tt.values())i.reject(e);this.tt.clear()}},O=C(),R=class{T;k;constructor(t,e){this.T=t,this.k=e}async $saveGIF(t={}){const e=await this.$generateGIFBlob(t);(new a).$downloadFile(e,t.filename,".gif")}async $generateGIFBlob(t={}){const e=this.Z(t),i=this.T.canvas,r=Math.max(1,Math.round(i.width*e.scale)),n=Math.max(1,Math.round(i.height*e.scale)),o=new g(this.T,this.k,{width:r,height:n}),s=o.canvas.getContext("2d",{willReadFrequently:!0});if(!s)throw new Error("GIF export requires a 2D canvas context.");const a="undefined"==typeof Worker?(0,O.GIFEncoder)():null,h="undefined"==typeof Worker?null:new F(r,n,e.frameRate,e.repeat,e.signal);try{let i;if(this.I(e.signal),await o.$render({frameCount:e.frameCount,frameRate:e.frameRate,signal:e.signal,prepareFrame:e.prepareFrame,onFrame:async({frameIndex:i,canvas:r})=>{this.I(e.signal);const n=s.getImageData(0,0,r.width,r.height);if(h)await h.encodeFrame(n.data.buffer,i);else if(a){const t=n.data,o=(0,O.quantize)(t,256,{}),s=(0,O.applyPalette)(t,o);a.writeFrame(s,r.width,r.height,{palette:o,delay:Math.round(1e3/e.frameRate),repeat:0===i?e.repeat:-1})}t.onProgress?.({state:"encoding",frameIndex:i+1,totalFrames:e.frameCount}),(i+1)%2==0&&await this.st(e.signal)}}),this.I(e.signal),h)i=await h.finish();else{if(!a)throw new Error("No GIF encoder is available.");{a.finish();const t=a.bytes();i=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}return t.onProgress?.({state:"completed",totalFrames:e.frameCount}),new Blob([i],{type:"image/gif"})}catch(c){throw t.onProgress?.({state:"error",message:c instanceof Error?c.message:"GIF export failed"}),c}finally{h?.dispose()}}Z(t){return{filename:t.filename,frameCount:Math.max(1,Math.abs(Math.round(t.frameCount??300))),frameRate:Math.max(1,Math.abs(t.frameRate??60)),scale:Math.max(Number.EPSILON,Math.abs(t.scale??1)),repeat:Math.max(-1,Math.round(t.repeat??0)),signal:t.signal,prepareFrame:t.prepareFrame}}I(t){if(t?.aborted)throw new DOMException("GIF export was cancelled.","AbortError")}st(t){return new Promise((e,i)=>{t?.aborted?i(new DOMException("GIF export was cancelled.","AbortError")):setTimeout(e,0)})}},$=class extends Error{code;cause;constructor(t,e,i){super(e),this.name="VideoExportError",this.code=t,this.cause=i}};function D(){return new $("VIDEO_EXPORT_ABORTED","Video export was cancelled.")}function N(t,e){return new $("VIDEO_EXPORT_TIMEOUT",t,e)}function V(t){return t instanceof $?t:w(t)?D():t instanceof p&&"FRAME_SEQUENCE_TIMEOUT"===t.code?N(t.message,t):new $("VIDEO_EXPORT_FAILED",t instanceof Error?t.message:"Video export failed.",t)}function U(t,e="avc"){if("mp4"===t.format&&t.transparent)throw new $("VIDEO_TRANSPARENCY_UNSUPPORTED","MP4/H.264 export does not support portable alpha. Use saveVideo({ format: 'webm', transparent: true }) instead.");const i=Math.max(1,Math.round(t.width)),r=Math.max(1,Math.round(t.height));if("mp4"===t.format&&(i%2!=0||r%2!=0))throw new $("VIDEO_DIMENSIONS_UNSUPPORTED",`MP4/H.264 requires even dimensions; received ${i}x${r}. Increase pixel density or choose WebM.`);return{format:t.format,extension:"mp4"===t.format?".mp4":".webm",mimeType:"mp4"===t.format?"video/mp4":"video/webm",codec:e,quality:t.quality,hardwareAcceleration:t.hardwareAcceleration,keyFrameInterval:t.keyFrameInterval,frameRate:t.frameRate,frameCount:t.frameCount,width:i,height:r,transparent:t.transparent}}function z(t){if(!t)throw new Error("Assertion failed.")}var j,L=t=>{const e=(t%360+360)%360;if(0===e||90===e||180===e||270===e)return e;throw new Error(`Invalid rotation ${t}.`)},q=t=>t&&t[t.length-1],G=t=>t>=0&&t<2**32,H=t=>{let e=0;for(;0===t.readBits(1)&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+t.readBits(e)},W=t=>{const e=H(t);return 1&e?e+1>>1:-(e>>1)},X=t=>t.constructor===Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t),Z=t=>t.constructor===DataView?t:ArrayBuffer.isView(t)?new DataView(t.buffer,t.byteOffset,t.byteLength):new DataView(t),Q=new TextEncoder,Y={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},J={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},K={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},tt=t=>!t||null==t.primaries&&null==t.transfer&&null==t.matrix&&null==t.fullRange,et=t=>t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t),it=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let t;const e=new Promise(e=>{let i=!1;t=()=>{i||(e(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=e,this.pending++,await i,t}},rt=(t,e,i)=>{let r=0,n=t.length-1,o=-1;for(;r<=n;){const s=r+(n-r+1)/2|0;i(t[s])<=e?(o=s,r=s+1):n=s-1}return o},nt=()=>{let t,e;return{promise:new Promise((i,r)=>{t=i,e=r}),resolve:t,reject:e}},ot=t=>{throw new Error(`Unexpected value: ${t}`)},st=(t,e,i)=>{const r=t.getUint8(e),n=t.getUint8(e+1),o=t.getUint8(e+2);return i?r|n<<8|o<<16:r<<16|n<<8|o},at=(t,e,i)=>Math.max(e,Math.min(i,t)),ht=(t,e)=>Math.round(t/e)*e,ct=(t,e)=>Math.round(t*e)/e,lt=(t,e)=>Math.floor(t*e)/e,dt=t=>{let e=0;for(;0!==t;)t&=t-1,e++;return e},ut=/^[a-z]{3}$/,ft=1e6*(1+Number.EPSILON),pt=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},mt=null,wt=()=>null!==mt?mt:mt=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),vt=null,bt=()=>null!==vt?vt:vt="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),yt=null,gt=()=>null!==yt?yt:yt=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),xt=(async()=>{})().constructor,Et=t=>t instanceof xt||t instanceof Promise||"function"==typeof t?.then,Tt=function*(t){for(const e in t){const i=t[e];void 0!==i&&(yield{key:e,value:i})}},kt=t=>{switch(t.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},_t=(t,e)=>{if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!==e[i])return!1;return!0},Mt=t=>"number"==typeof t&&!Number.isNaN(t),At=t=>{z(Number.isInteger(t.num)),z(Number.isInteger(t.den)),z(0!==t.den);let e=Math.abs(t.num),i=Math.abs(t.den);for(;0!==i;){const t=e%i;e=i,i=t}const r=e||1;return{num:t.num/r,den:t.den/r}},St=(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.`)},Ct=t=>Array.isArray(t)?t:[t],Pt=class{constructor(){this.ht=new Map}on(t,e,i){this.ht.has(t)||this.ht.set(t,new Set);const r={fn:e,once:i?.once??!1};return this.ht.get(t).add(r),()=>{this.ht.get(t)?.delete(r)}}ct(...t){const[e,i]=t,r=this.ht.get(e);if(r)for(const o of r){try{o.fn(i)}catch(n){console.error(n)}o.once&&r.delete(o)}}},It=t=>null!==t&&"object"==typeof t&&Object.getPrototypeOf(t)===Object.prototype&&Object.values(t).every(t=>"string"==typeof t);!function(t){t[t.Silent=0]="Silent",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.Info=3]="Info"}(j||(j={}));var Bt=class t{constructor(){}static get level(){return t.lt}static set level(e){if(e!==j.Silent&&e!==j.Errors&&e!==j.Warnings&&e!==j.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");t.lt=e}static get dt(){return t.ut??=new Pt}static on(e,i,r){return t.dt.on(e,i,r)}static ft(...e){t.dt.ct("error",e),t.lt>=j.Errors&&console.error(...e)}static wt(...e){t.dt.ct("warn",e),t.lt>=j.Warnings&&console.warn(...e)}static vt(...e){t.dt.ct("info",e),t.lt>=j.Info&&console.info(...e)}};Bt.lt=j.Info,Bt.ut=null;var Ft,Ot,Rt=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.")}},Dt=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}},Nt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Vt=[-1,1,2,3,4,5,6,8],Ut=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=Vt.indexOf(n);if(-1===o)throw new TypeError(`Unsupported number of channels: ${t.outputNumberOfChannels}`);let s=16;t.objectType>=32&&(s+=6),15===Lt(r)&&(s+=24),e&&(s+=9,15===Lt(t.outputSampleRate)&&(s+=24));const a=Math.ceil(s/8),h=new Uint8Array(a),c=new Dt(h);return zt(c,t.objectType),jt(c,r),c.writeBits(4,o),e&&(jt(c,t.outputSampleRate),zt(c,2)),c.writeBits(3,0),h},zt=(t,e)=>{e<32?t.writeBits(5,e):(t.writeBits(5,31),t.writeBits(6,e-32))},jt=(t,e)=>{const i=Lt(e);t.writeBits(4,i),15===i&&t.writeBits(24,e)},Lt=t=>{const e=Nt.indexOf(t);return-1===e?15:e},qt=[48e3,44100,32e3],Gt=[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"}(Ft||(Ft={})),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"}(Ot||(Ot={}));var Ht,Wt=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})},Xt=function*(t,e){let i=0;const r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(;i+e<=t.length;){let t;1===e?t=r.getUint8(i):2===e?t=r.getUint16(i,!1):3===e?t=st(r,i,!1):(z(4===e),t=r.getUint32(i,!1)),i+=e,yield{offset:i,length:t},i+=t}},Zt=t=>31&t,Qt=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)},Yt=(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}}),Jt=t=>{const e=H(t);t.skipBits(4),t.skipBits(4);for(let i=0;i<=e;i++)H(t),H(t),t.skipBits(1);t.skipBits(5),t.skipBits(5),t.skipBits(5),t.skipBits(5)},Kt=t=>t>>1&63,te=(t,e)=>{const i=t.readBits(2),r=t.readBits(1),n=t.readBits(5);let o=0;for(let l=0;l<32;l++)o=o<<1|t.readBits(1);const s=new Uint8Array(6);for(let l=0;l<6;l++)s[l]=t.readBits(8);const a=t.readBits(8),h=[],c=[];for(let l=0;l<e;l++)h.push(t.readBits(1)),c.push(t.readBits(1));if(e>0)for(let l=e;l<8;l++)t.skipBits(2);for(let l=0;l<e;l++)h[l]&&t.skipBits(88),c[l]&&t.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:s,general_level_idc:a}},ee=t=>{for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBits(1)){const i=Math.min(64,1<<4+(e<<1));e>1&&W(t);for(let e=0;e<i;e++)W(t)}else H(t)},ie=(t,e)=>{const i=[];for(let r=0;r<e;r++)i[r]=re(t,r,e,i)},re=(t,e,i,r)=>{let n=0,o=0,s=0;if(0!==e&&(o=t.readBits(1)),o){s=e===i?e-(H(t)+1):e-1,t.readBits(1),H(t);const o=r[s]??0;for(let e=0;e<=o;e++)t.readBits(1)||t.readBits(1);n=r[s]}else{const e=H(t),i=H(t);for(let r=0;r<e;r++)H(t),t.readBits(1);for(let r=0;r<i;r++)H(t),t.readBits(1);n=e+i}return n},ne=(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=Yt[e];t&&(a=t)}}return t.readBits(1)&&t.readBits(1),t.readBits(1)&&(t.readBits(3),o=t.readBits(1),t.readBits(1)&&(i=t.readBits(8),r=t.readBits(8),n=t.readBits(8))),t.readBits(1)&&(H(t),H(t)),t.readBits(1),t.readBits(1),t.readBits(1),t.readBits(1)&&(H(t),H(t),H(t),H(t)),t.readBits(1)&&(t.readBits(32),t.readBits(32),t.readBits(1)&&H(t),t.readBits(1)&&oe(t,!0,e)),t.readBits(1)&&(t.readBits(1),t.readBits(1),t.readBits(1),s=H(t),H(t),H(t),H(t),H(t)),{pixelAspectRatio:a,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:o,minSpatialSegmentationIdc:s}},oe=(t,e,i)=>{let r=!1,n=!1,o=!1;e&&(r=1===t.readBits(1),n=1===t.readBits(1),(r||n)&&(o=1===t.readBits(1),o&&(t.readBits(8),t.readBits(5),t.readBits(1),t.readBits(5)),t.readBits(4),t.readBits(4),o&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5)));for(let s=0;s<=i;s++){let e=!0;1===t.readBits(1)||(e=1===t.readBits(1));let i=!1;e?H(t):i=1===t.readBits(1);let s=1;i||(s=H(t)+1),r&&se(t,s,o),n&&se(t,s,o)}},se=(t,e,i)=>{for(let r=0;r<e;r++)H(t),H(t),i&&(H(t),H(t)),t.readBits(1)};!function(t){t[t.audAllowed=0]="audAllowed",t[t.beforeFirstVcl=1]="beforeFirstVcl",t[t.afterFirstVcl=2]="afterFirstVcl",t[t.eoBitstreamAllowed=3]="eoBitstreamAllowed",t[t.noMoreDataAllowed=4]="noMoreDataAllowed"}(Ht||(Ht={}));var ae,he=t=>{const e=Z(t),i=e.getUint8(9),r=e.getUint16(10,!0),n=e.getUint32(12,!0),o=e.getInt16(16,!0),s=e.getUint8(18);let a=null;return s&&(a=t.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:o,channelMappingFamily:s,channelMappingTable:a}};!function(t){t[t.STREAMINFO=0]="STREAMINFO",t[t.VORBIS_COMMENT=4]="VORBIS_COMMENT",t[t.PICTURE=6]="PICTURE"}(ae||(ae={})),new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var ce,le=[1,2,3,6],de=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],ue=[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],fe=[16,16,20,20,0,24,24,0],pe=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],me=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],we=[32e3,44100,48e3,0],ve=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],be=[512,1024,2048,4096],ye=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 Dt(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=we[e.readBits(2)],c=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const l=e.readBits(3)+1,d=e.readBits(3)+1,u=[];for(let v=0;v<l;v++)u.push(e.readBits(i+1));for(const v of u)e.skipBits(8*dt(v));if(e.readBits(1)){e.skipBits(2);const t=e.readBits(2)+1<<2,i=e.readBits(2)+1;e.skipBits(i*t)}for(let v=0;v<d;v++)e.skipBits(o);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const f=e.readBits(5)+1,p=ve[e.readBits(4)],m=e.readBits(8)+1;let w=0;if(e.readBits(1)&&(m>2&&e.skipBits(1),m>6&&e.skipBits(1),e.readBits(1))){const t=e.readBits(2)+1<<2;w=e.readBits(t)}return 0===h||e.getBitsLeft()<0?a:{frameSize:s,asset:{sampleRate:p,numberOfChannels:m,sampleCount:Math.round(c*p/h),channelLayout:w,pcmResolution:f}}},ge=t=>{const e=new Uint8Array(20),i=Z(e);i.setUint32(0,t.sampleRate),i.setUint32(4,t.bitRate),i.setUint32(8,t.bitRate),e[12]=t.pcmResolution;const r=t.core&&!t.hasExtensions?1:0,n=new Dt(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},xe=["avc","hevc","vp9","av1","vp8","prores"],Ee=["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"],Te=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],ke=[...Te,...Ee],_e=["webvtt"],Me=[{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}],Ae=[{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}],Se=[{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}],Ce=[{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}],Pe=["ap4x","ap4h","apch","apcn","apcs","apco"],Ie=["dtsc","dtsh","dtsl","dtse"],Be=[{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}],Fe=(t,e,i,r,n)=>{if("avc"===t){const t=100,n=Math.ceil(e/16)*Math.ceil(i/16),o=Me.find(t=>n<=t.maxMacroblocks&&r<=t.maxBitrate)??q(Me),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=Ae.find(t=>s<=t.maxPictureSize&&r<=t.maxBitrate)??q(Ae);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.${(Se.find(e=>t<=e.maxPictureSize&&r<=e.maxBitrate)??q(Se)).level.toString().padStart(2,"0")}.08`}if("av1"===t){const t=0,n=e*i,o=Ce.find(t=>n<=t.maxPictureSize&&r<=t.maxBitrate)??q(Ce);return`av01.${t}.${o.level.toString().padStart(2,"0")}${o.tier}.08`}if("prores"===t){const t=Math.pow(e*i/2073600,.95),o=Be.filter(t=>t.alpha===n);let s=o[0].fourCc,a=1/0;for(const{fourCc:e,bitrate:i}of o){const n=Math.abs(i*t-r);n<a&&(a=n,s=e)}return s}throw ot(t),new TypeError(`Unhandled codec '${String(t)}'.`)},Oe=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]},Re=/^pcm-([usf])(\d+)(be)?$/,$e=t=>{if(z(Ee.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=Re.exec(t);let i;return z(e),i="u"===e[1]?"unsigned":"s"===e[1]?"signed":"float",{dataType:i,sampleSize:Number(e[2])/8,littleEndian:"be"!==e[3],silentValue:"pcm-u8"===t?128:0}},De=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":Pe.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":Ie.includes(t)?"dts":"ulaw"===t?"ulaw":"alaw"===t?"alaw":Re.test(t)?t:"webvtt"===t?"webvtt":null,Ne=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Pe],Ve=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ue=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ze=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,je=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Le=(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(!Ne.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.codedWidth)||t.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(t.decoderConfig.codedHeight)||t.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==t.decoderConfig.displayAspectWidth&&(!Number.isInteger(t.decoderConfig.displayAspectWidth)||t.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectHeight&&(!Number.isInteger(t.decoderConfig.displayAspectHeight)||t.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(void 0!==t.decoderConfig.displayAspectWidth!=(void 0!==t.decoderConfig.displayAspectHeight))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(void 0!==t.decoderConfig.description&&!et(t.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==t.decoderConfig.colorSpace){const{colorSpace:e}=t.decoderConfig;if("object"!=typeof e)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(Y);if(null!=e.primaries&&!i.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(J);if(null!=e.transfer&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const n=Object.keys(K);if(null!=e.matrix&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(t.decoderConfig.codec.startsWith("avc1")||t.decoderConfig.codec.startsWith("avc3")){if(!Ve.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(!Ue.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(!ze.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(!je.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(Pe.some(e=>t.decoderConfig.codec.startsWith(e))&&!Pe.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: ${Pe.join(", ")}.`);if(null!==e&&De(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}'.`)},qe=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],Ge=(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(!qe.some(e=>t.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(t.decoderConfig.sampleRate)||t.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(t.decoderConfig.numberOfChannels)||t.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==t.decoderConfig.description&&!et(t.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(t.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(t.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("mp3")||t.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==t.decoderConfig.codec&&"mp4a.69"!==t.decoderConfig.codec&&"mp4a.6B"!==t.decoderConfig.codec&&"mp4a.6b"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(t.decoderConfig.codec.startsWith("opus")){if("opus"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(t.decoderConfig.description&&t.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(t.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!t.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("flac")){if("flac"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(t.decoderConfig.codec.startsWith("ac-3")||t.decoderConfig.codec.startsWith("ac3")){if("ac-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(t.decoderConfig.codec.startsWith("ec-3")||t.decoderConfig.codec.startsWith("eac3")){if("ec-3"!==t.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(t.decoderConfig.codec.startsWith("dts")){if(!Ie.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: ${Ie.join(", ")}.`)}else if((t.decoderConfig.codec.startsWith("pcm")||t.decoderConfig.codec.startsWith("ulaw")||t.decoderConfig.codec.startsWith("alaw"))&&!Ee.includes(t.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ee.join(", ")}).`);if(null!==e&&De(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}'.`)},He=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.")},We=new Uint8Array(0),Xe=class t{constructor(t,e,i,r,n=-1,o,s){if(this.data=t,this.type=e,this.timestamp=i,this.duration=r,this.sequenceNumber=n,t===We&&void 0===o)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===o&&(o=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==e&&"delta"!==e)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==s&&("object"!=typeof s||!s))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==s?.alpha&&!(s.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==s?.alphaByteLength&&(!Number.isInteger(s.alphaByteLength)||s.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=s??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===We}get microsecondTimestamp(){return Math.trunc(ft*this.timestamp)}get microsecondDuration(){return Math.trunc(ft*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,i){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new t(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,i)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!=typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new t(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}},Ze=class{constructor(t){this.value=t}},Qe=class{constructor(t){this.value=t}},Ye=class{constructor(t){this.value=t}},Je=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"}(ce||(ce={})),ce.EBML,ce.Segment,ce.SeekHead,ce.Info,ce.Cluster,ce.Tracks,ce.Cues,ce.Attachments,ce.Chapters,ce.Tags;var Ke=t=>t<256?1:t<65536?2:t<1<<24?3:t<2**32?4:t<2**40?5:6,ti=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,ei=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,ii=class{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=Ke(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=ti(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=ei(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??Ke(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if("bigint"==typeof t.data){const e=t.size??ti(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 Ze)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof Qe)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof Ye){const e=t.size??ei(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Je){const e=Q.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else ot(t.data)}},ri={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"},ni=t=>{const e=t.filePos,i=new Dt(ji(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}},oi=i((t,e)=>{e.exports={}}),si=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 ai=-1/0,hi=-1/0,ci=null;"undefined"!=typeof FinalizationRegistry&&(ci=new FinalizationRegistry(t=>{const e=performance.now();"video"===t.type?(e-ai>=1e3&&(Bt.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."),ai=e),"undefined"!=typeof VideoFrame&&t.data instanceof VideoFrame&&t.data.close()):(e-hi>=1e3&&(Bt.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."),hi=e),"undefined"!=typeof AudioData&&t.data instanceof AudioData&&t.data.close())}));var li=class{constructor(){this.bt=0,this.yt=null}},di=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],ui=new Set(di),fi=class t{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(ft*this.timestamp)}get microsecondDuration(){return Math.trunc(ft*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,i){if(this.gt=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!i||"object"!=typeof i)throw new TypeError("init must be an object.");if(void 0===i.format||!ui.has(i.format))throw new TypeError("init.format must be one of: "+di.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&&St(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??Ti(i.format,i.codedWidth,i.codedHeight);let r=i.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:i.visibleRect?.left??0,top:i.visibleRect?.top??0,width:i.visibleRect?.width??i.codedWidth,height:i.visibleRect?.height??i.codedHeight},void 0!==i.displayWidth?(this.squarePixelWidth=this.rotation%180==0?i.displayWidth:i.displayHeight,this.squarePixelHeight=this.rotation%180==0?i.displayHeight:i.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this.xt=i.Et?X(e):X(e).slice(),this.Tt=t,this.colorSpace=new bi(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&&St(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 bi(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&&St(i.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new t(new VideoFrame(e,{timestamp:Math.trunc(i.timestamp*ft),duration:Math.trunc((i.duration??0)*ft)||void 0,visibleRect:i.visibleRect&&{x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height}}),i);let r=0,n=0;if("naturalWidth"in e?(r=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,n=e.videoHeight):"width"in e&&(r=Number(e.width),n=Number(e.height)),!r||!n)throw new TypeError("Could not determine dimensions.");const o=i.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(o.width,o.height),a=s.getContext("2d",{alpha:bt(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-o.left,-o.top),this.xt=s,this.Tt=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:o.width,height:o.height},this.squarePixelWidth=o.width,this.squarePixelHeight=o.height,this.rotation=i.rotation??0,this.timestamp=i.timestamp,this.duration=i.duration??0,this.colorSpace=new bi({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof li))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&&!di.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=At({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),ci?.register(this,{type:"video",data:this.xt},this)}clone(){if(this.gt)throw new Error("VideoSample is closed.");return z(null!==this.xt),this.xt instanceof li?new t(this.xt,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):yi(this.xt)?new t(this.xt.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this.xt instanceof Uint8Array?(z(this.Tt),new t(this.xt,{format:this.format,layout:this.Tt,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,Et:!0})):new t(this.xt,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this.gt||(ci?.unregister(this),this.xt instanceof li?(this.xt.bt--,0===this.xt.bt&&this.xt.close()):yi(this.xt)?this.xt.close():this.xt=null,this.gt=!0)}allocationSize(t={}){if(Ei(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 yi(this.xt)?this.xt.allocationSize(t):_i(this,t).allocationSize}async copyTo(e,i={}){if(!et(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ei(i),this.gt)throw new Error("VideoSample is closed.");if(null==(i.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(z(null!==this.xt),yi(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 li)){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{si(r)}}}const r=_i(this,i);z(this.format);const n=X(e);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);const o=ki(this.format);let s;if(this.xt instanceof li){let t=this.xt.getDataPlanes();if(Et(t)&&(t=await t),!Array.isArray(t)||t.some(t=>!(t.data instanceof Uint8Array)||!Number.isInteger(t.stride)||t.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=t}else if(this.xt instanceof Uint8Array)z(this.Tt),z(this.Tt.length===o.length),s=this.Tt.map((t,e)=>{const i=Math.ceil(this.codedHeight/o[e].heightDivisor);return{data:this.xt.subarray(t.offset,t.offset+t.stride*i),stride:t.stride}});else{const t=this.xt.getContext("2d");z(t),s=[{data:X(t.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const a=[],h=o.length;for(let t=0;t<h;t++){const e=r.computedLayouts[t],i=s[t].stride,o=s[t].data;let h=e.sourceTop*i;h+=e.sourceLeftBytes;let c=e.destinationOffset;const l=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let t=0;t<e.sourceHeight;t++){if(h+l>o.byteLength)throw new Error("Source buffer OOB read.");if(c+l>n.byteLength)throw new Error("Destination buffer OOB write.");const t=o.subarray(h,h+l);n.set(t,c),h+=i,c+=e.destinationStride}a.push(d)}if(void 0!==i.format){const t=this.format.startsWith("RGB")!==i.format.startsWith("RGB"),e=this.format.includes("X")&&i.format.includes("A");if(t||e)for(let i=0;i<r.allocationSize;i+=4){if(t){const t=n[i];n[i]=n[i+2],n[i+2]=t}e&&(n[i+3]=255)}}return a}toVideoFrame(){if(this.gt)throw new Error("VideoSample is closed.");if(z(null!==this.xt),this.xt instanceof li){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(Et(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 yi(this.xt)?new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this.xt instanceof Uint8Array?(z(this.Tt),new VideoFrame(this.xt,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this.Tt,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this.xt,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,i,r,n,o,s,a,h){let c=0,l=0,d=this.displayWidth,u=this.displayHeight,f=0,p=0,m=this.displayWidth,w=this.displayHeight;if(void 0!==o?(c=e,l=i,d=r,u=n,f=o,p=s,void 0!==a?(m=a,w=h):(m=d,w=u)):(f=e,p=i,void 0!==r&&(m=r,w=n)),!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dHeight must be a non-negative number.");if(this.gt)throw new Error("VideoSample is closed.");({sx:c,sy:l,sWidth:d,sHeight:u}=this.kt(c,l,d,u,this.rotation));const v=this.toCanvasImageSource();t.save();const b=f+m/2,y=p+w/2;t.translate(b,y),t.rotate(this.rotation*Math.PI/180);const g=this.rotation%180==0?1:m/w;t.scale(1/g,g),t.drawImage(v,c,l,d,u,-m/2,-w/2,m,w),t.restore()}drawWithFit(t,e){if(!("undefined"!=typeof CanvasRenderingContext2D&&t instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==e.rotation&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==e.crop&&xi(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=gi(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?vi(l,d):{canvas:t,context:e,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,l,d)):p||f.clearRect(0,0,l,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let m=c;m>1;m--){const t=r*2**m,e=n*2**m;f.drawImage(u,0,0,t,e,0,0,t/2,e/2)}f.globalCompositeOperation="source-over",c>0&&(e.imageSmoothingQuality="high",e.globalCompositeOperation="copy",e.drawImage(u,0,0,2*r,2*n,0,0,r,n),e.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this.gt)throw new Error("VideoSample is closed.");if(z(null!==this.xt),this.xt instanceof li||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&&xi(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const i=L(this.rotation+(e.rotate??0)),[r,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=e.crop;o&&(o=gi(o,r,n));const s=o?o.width:r,a=o?o.height:n,h=s/a;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/h):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*h):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=a),c=ht(c,e.roundDimensionsTo??1),l=ht(l,e.roundDimensionsTo??1);const d={width:c,height:l,fit:e.fit??"fill",rotation:i,crop:o??{left:0,top:0,width:r,height:n},alpha:e.alpha??"keep"};for(const t of pi){let e=t(this,d);if(Et(e)&&(e=await e),null!==e)return e}const{canvas:u,context:f,isNew:p}=vi(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()}},pi=[],mi=[],wi=0,vi=(t,e)=>{for(const n of mi)if(n.canvas.width===t&&n.canvas.height===e)return n.age=wi++,{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 mi.length>=3&&mi.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})(mi,t=>t.age),1),mi.push({canvas:i,context:r,age:wi++}),{canvas:i,context:r,isNew:!0}},bi=class{constructor(t){if(void 0!==t){if(!t||"object"!=typeof t)throw new TypeError("init.colorSpace, when provided, must be an object.");const e=Object.keys(Y);if(null!=t.primaries&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);const i=Object.keys(J);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(K);if(null!=t.matrix&&!r.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},yi=t=>"undefined"!=typeof VideoFrame&&t instanceof VideoFrame,gi=(t,e,i)=>{const r=Math.min(t.left,e),n=Math.min(t.top,i),o=Math.min(t.width,e-r),s=Math.min(t.height,i-n);return z(o>=0),z(s>=0),{left:r,top:n,width:o,height:s}},xi=(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.")},Ei=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.")}},Ti=(t,e,i)=>{const r=ki(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},ki=t=>{const e=(t,e,i,r,n)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:e,widthDivisor:i,heightDivisor:r},{sampleBytes:e,widthDivisor:i,heightDivisor:r}];return n&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(t){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:ot(t),z(!1)}},_i=(t,e)=>{const i={left:0,top:0,width:t.codedWidth,height:t.codedHeight},r=e.rect,n=Mi(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 Si(n,s,o)},Mi=(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(!Ai(n,o))throw new TypeError("visibleRect alignment is invalid for the format.");return o},Ai=(t,e)=>{if(null===t)return!0;const i=ki(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},Si=(t,e,i)=>{const r=ki(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}},Ci=new Map,Pi=(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&&De(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.")},Ii=t=>{const e=t.bitrateMode,i=t.quality.Mt(t.codec,t.width,t.height,e),r=(e,i,r)=>{return{codec:t.fullCodecString??Fe(t.codec,t.width,t.height,r,"keep"===t.alpha),width:t.width,height:t.height,displayWidth:t.squarePixelWidth,displayHeight:t.squarePixelHeight,bitrate:e,bitrateMode:i,alpha:t.alpha??"discard",framerate:t.framerate,latencyMode:t.latencyMode,hardwareAcceleration:t.hardwareAcceleration,scalabilityMode:t.scalabilityMode,contentHint:t.contentHint,...(n=t.codec,"avc"===n?{avc:{format:"avc"}}:"hevc"===n?{hevc:{format:"hevc"}}:{})};var n},n=[];return null!==i.quantizer&&n.push({config:r(void 0,"quantizer",i.bitrate),quantizer:i.quantizer}),"quantizer"!==i.bitrateMode&&n.push({config:r(i.bitrate,i.bitrateMode,i.bitrate),quantizer:null}),z(n.length>0),n},Bi=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 Fi):"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?Fi[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=Oi[t];let o=null,s=this.It??r??"variable";if(void 0!==this.Pt){if(n)if(this.Pt<n.min||this.Pt>n.max){if(void 0===this.Ct)throw new Error(`Quantizer ${this.Pt} is out of range for codec '${t}'; must be between ${n.min} and ${n.max}.`)}else o=this.Pt,void 0===this.Ct&&(s="quantizer");else if(void 0===this.Ct)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else void 0===this.Ct&&n&&!this.St&&(z(void 0!==this.At),o=at(Math.round((a=n.worst)+(n.best-a)*this.At),n.min,n.max));var a;let h;if(void 0!==this.Ct)h=this.Ct;else{let r=this.At;void 0===r&&(z(null!==o&&n),r=at((o-n.worst)/(n.best-n.worst),0,1)),h=$i(t,e,i,Ri(r))}return{quantizer:o,bitrate:h,bitrateMode:s}}Bt(t,e,i){return void 0!==this.Ct?this.Ct:(z(void 0!==this.At),$i(t,e,i,Ri(this.At)))}Ft(t){if(Ee.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=Ri(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)}},Fi={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Oi={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}},Ri=t=>.3*Math.exp(2.5538*t),$i=(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)},Di=(t,e)=>"avc"===t?{avc:{quantizer:e}}:"hevc"===t?{hevc:{quantizer:e}}:"vp9"===t?{vp9:{quantizer:e}}:"av1"===t?{av1:{quantizer:e}}:void z(!1),Ni=async(t,e={})=>{const{width:i=1280,height:r=720,quality:n,bitrate:o,...s}=e;if(!xe.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 Bi))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 Bi)&&(!Number.isInteger(o)||o<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Pi(t,s);const a=Vi(n,o)??new Bi("medium");let h;try{h=Ii({codec:t,width:i,height:r,quality:a,framerate:void 0,...s,alpha:"discard"})}catch{return!1}const c=JSON.stringify(h),l=Ci.get(c);if(l)return l;const d=(async()=>{for(const{config:e}of h)if(Ui.some(i=>i.supports(t,e)))return!0;if("undefined"==typeof VideoEncoder)return!1;if(!(i%2!=1&&r%2!=1||"avc"!==t&&"hevc"!==t))return!1;for(const{config:e,quantizer:n}of h){try{if(!(await VideoEncoder.isConfigSupported(e)).supported)continue}catch{continue}if(!bt())return!0;if(await new Promise(async o=>{try{const s=new VideoEncoder({output:()=>{},error:()=>o(!1)});s.configure(e);const a=new Uint8Array(i*r*4),h=new VideoFrame(a,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});s.encode(h,null!==n?Di(t,n):void 0),h.close(),await s.flush(),o(!0)}catch{o(!1)}}))return!0}return!1})();return Ci.set(c,d),d},Vi=(t,e)=>void 0!==t?t:void 0!==e?e instanceof Bi?e:new Bi({bitrate:e}):void 0,Ui=[],zi=class t{constructor(t,e,i,r,n){this.bytes=t,this.view=e,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new t(e,Z(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(e,i=this.end-e){if(e<this.start||e+i>this.end)throw new RangeError("Slicing outside of original slice.");return new t(this.bytes,this.view,this.offset,e,e+i)}},ji=(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},Li=class{constructor(t){this.mutex=new it,this.trackTimestampInfo=new WeakMap,this.output=t}onTrackClose(t){}validateTimestamp(t,e,i){let r=this.trackTimestampInfo.get(t);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&e<r.maxTimestampBeforeLastKeyPacket)throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,e)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,r)}}},qi=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Gi=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Hi=t=>{const e=Math.floor(t/36e5),i=Math.floor(t%36e5/6e4),r=Math.floor(t%6e4/1e3),n=t%1e3;return e.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")},Wi=class{constructor(t){this.writer=t,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8==7&&this.writer.write(this.helper);t.length%8!=0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{const e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(const n of t.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=t.size??i-e;this.writer.seek(e),this.writeBoxHeader(t,r),this.writer.seek(i)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){const e=this.offsets.get(t);z(void 0!==e);const i=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(i)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(const i of t.children)i&&(e+=this.measureBox(i));return e}}},Xi=new Uint8Array(8),Zi=new DataView(Xi.buffer),Qi=t=>[(t%256+256)%256],Yi=t=>(Zi.setUint16(0,t,!1),[Xi[0],Xi[1]]),Ji=t=>(Zi.setInt16(0,t,!1),[Xi[0],Xi[1]]),Ki=t=>(Zi.setUint32(0,t,!1),[Xi[1],Xi[2],Xi[3]]),tr=t=>(Zi.setUint32(0,t,!1),[Xi[0],Xi[1],Xi[2],Xi[3]]),er=t=>(Zi.setInt32(0,t,!1),[Xi[0],Xi[1],Xi[2],Xi[3]]),ir=t=>(Zi.setUint32(0,Math.floor(t/2**32),!1),Zi.setUint32(4,t,!1),[Xi[0],Xi[1],Xi[2],Xi[3],Xi[4],Xi[5],Xi[6],Xi[7]]),rr=t=>(Zi.setInt32(0,Math.floor(t/2**32),!1),Zi.setUint32(4,t,!1),[Xi[0],Xi[1],Xi[2],Xi[3],Xi[4],Xi[5],Xi[6],Xi[7]]),nr=t=>(Zi.setInt16(0,256*t,!1),[Xi[0],Xi[1]]),or=t=>(Zi.setInt32(0,65536*t,!1),[Xi[0],Xi[1],Xi[2],Xi[3]]),sr=t=>(Zi.setInt32(0,2**30*t,!1),[Xi[0],Xi[1],Xi[2],Xi[3]]),ar=(t,e)=>{const i=[];let r=t;do{let t=127&r;r>>=7,i.length>0&&(t|=128),i.push(t),void 0!==e&&e--}while(r>0||e);return i.reverse()},hr=(t,e=!1)=>{const i=Array(t.length).fill(null).map((e,i)=>t.charCodeAt(i));return e&&i.push(0),i},cr=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]},lr=cr(0),dr=t=>[or(t[0]),or(t[1]),sr(t[2]),or(t[3]),or(t[4]),sr(t[5]),or(t[6]),or(t[7]),sr(t[8])],ur=(t,e,i)=>({type:t,contents:e&&new Uint8Array(e.flat(10)),children:i}),fr=(t,e,i,r,n)=>ur(t,[Qi(e),Ki(i),r??[]],n),pr=()=>ur("styp",[hr("iso5"),tr(0),hr("iso5"),hr("iso6"),hr("mp41"),hr("cmfc"),hr("dash")]),mr=(t,e)=>{const i=Math.max(0,t.minWrittenTimestamp);let r=Math.max(0,t.maxWrittenEndTimestamp-i);return Number.isFinite(r)||(r=0),fr("sidx",1,0,[tr(1),tr(zn),ir(Ln(i,zn)),ir(0),Yi(0),Yi(1),tr(2147483647&e),tr(Ln(r,zn)),tr(0)])},wr=t=>({type:"mdat",largeSize:t}),vr=t=>ur("moov",void 0,[br(t.creationTime,t.trackDatas),...t.trackDatas.map(e=>gr(e,t.creationTime)),t.isFragmented?on(t.trackDatas):null,bn(t)]),br=(t,e)=>{const i=Math.max(0,...e.map(t=>Math.max(0,Ln(yr(t),zn)+Ln(t.startTimestampOffset??0,zn)))),r=Math.max(0,...e.map(t=>t.track.id))+1,n=!G(t)||!G(i),o=n?ir:tr;return fr("mvhd",+n,0,[o(t),o(t),tr(zn),o(i),or(1),nr(1),Array(10).fill(0),dr(lr),Array(24).fill(0),tr(r)])},yr=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},gr=(t,e)=>{const i=jn(t),r=null!==t.startTimestampOffset&&0!==t.startTimestampOffset;return ur("trak",void 0,[xr(t,e),r?Er(t):null,Tr(t,e),void 0!==i.name?ur("udta",void 0,[ur("name",[...Q.encode(i.name)])]):null])},xr=(t,e)=>{const i=Math.max(0,Ln(yr(t),zn)+Ln(t.startTimestampOffset??0,zn)),r=!G(e)||!G(i),n=r?ir:tr;let o;if("video"===t.type){const e=t.track.metadata.rotation;o=cr(e??0)}else o=lr;let s=2;!1!==t.track.metadata.disposition?.default&&(s|=1);const a="video"===t.type?0:"audio"===t.type?1:"subtitle"===t.type?2:ot(t);return fr("tkhd",+r,s,[n(e),n(e),tr(t.track.id),tr(0),n(i),Array(8).fill(0),Yi(0),Yi(a),nr("audio"===t.type?1:0),Yi(0),dr(o),or("video"===t.type?t.info.width:0),or("video"===t.type?t.info.height:0)])},Er=t=>{const e=t.startTimestampOffset;if(z(null!==e),e>0){const i=Ln(e,zn),r=Ln(yr(t),zn),n=!G(i)||!G(r),o=n?ir:tr,s=n?rr:er;return ur("edts",void 0,[fr("elst",n?1:0,0,[tr(2),o(i),s(-1),or(1),o(r),s(0),or(1)])])}{const r=Ln(-e,t.timescale),n=Math.max(0,Ln(yr(t),zn)+Ln(e,zn)),o=!((i=r)>=-(2**31)&&i<2**31&&G(n)),s=o?ir:tr,a=o?rr:er;return ur("edts",void 0,[fr("elst",o?1:0,0,[tr(1),s(n),a(r),or(1)])])}var i},Tr=(t,e)=>ur("mdia",void 0,[kr(t,e),Ar(!0,_r[t.type],Mr[t.type]),Sr(t)]),kr=(t,e)=>{const i=Ln(yr(t),t.timescale),r=!G(e)||!G(i),n=r?ir:tr;return fr("mdhd",+r,0,[n(e),n(e),tr(t.timescale),n(i),Yi(Bn(t.track.metadata.languageCode??"und")),Yi(0)])},_r={video:"vide",audio:"soun",subtitle:"text"},Mr={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},Ar=(t,e,i,r="\0\0\0\0")=>fr("hdlr",0,0,[t?hr("mhlr"):tr(0),hr(e),hr(r),tr(0),tr(0),hr(i,!0)]),Sr=t=>ur("minf",void 0,[Cr[t.type](),Pr(),Fr(t)]),Cr={video:()=>fr("vmhd",0,1,[Yi(0),Yi(0),Yi(0),Yi(0)]),audio:()=>fr("smhd",0,0,[Yi(0),Yi(0)]),subtitle:()=>fr("nmhd",0,0)},Pr=()=>ur("dinf",void 0,[Ir()]),Ir=()=>fr("dref",0,0,[tr(1)],[Br()]),Br=()=>fr("url ",0,1),Fr=t=>{const e=t.compositionTimeOffsetTable.length>1||t.compositionTimeOffsetTable.some(t=>0!==t.sampleCompositionTimeOffset);return ur("stbl",void 0,[Or(t),Yr(t),e?rn(t):null,e?nn(t):null,Kr(t),tn(t),en(t),Jr(t)])},Or=t=>{let e;if("video"===t.type)e=Rr(Mn(t.track.source.Ot,t.info.decoderConfig.codec),t);else if("audio"===t.type){const i=Sn(t.track.source.Ot,t.info.decoderConfig.codec,t.muxer.isQuickTime);z(i),e=Vr(i,t)}else"subtitle"===t.type&&(e=Qr(Pn[t.track.source.Ot],t));return z(e),fr("stsd",0,0,[tr(1)],[e])},Rr=(t,e)=>ur(t,[Array(6).fill(0),Yi(1),Yi(0),Yi(0),Array(12).fill(0),Yi(e.info.width),Yi(e.info.height),tr(4718592),tr(4718592),tr(0),Yi(1),Qi(10),hr("Mediabunny"),Array(21).fill(0),Yi(e.info.hasAlphaChannel?32:24),Ji(65535)],[An[e.track.source.Ot]?.(e)??null,$r(e),tt(e.info.decoderConfig.colorSpace)?null:Dr(e)]),$r=t=>t.info.pixelAspectRatio.num===t.info.pixelAspectRatio.den?null:ur("pasp",[tr(t.info.pixelAspectRatio.num),tr(t.info.pixelAspectRatio.den)]),Dr=t=>{const e=t.info.decoderConfig.colorSpace;return ur("colr",[hr(t.muxer.isQuickTime?"nclc":"nclx"),Yi(null!=e?.primaries?Y[e.primaries]:2),Yi(null!=e?.transfer?J[e.transfer]:2),Yi(null!=e?.matrix?K[e.matrix]:2),t.muxer.isQuickTime?[]:Qi((e?.fullRange?1:0)<<7)])},Nr=t=>{if(!t.info.decoderConfig)return null;const e=t.info.decoderConfig,i=e.codec.split("."),r=Number(i[1]),n=Number(i[2]),o=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(e.colorSpace?.fullRange??0)),s=i[5]?Number(i[5]):e.colorSpace?.primaries?Y[e.colorSpace.primaries]:1,a=i[6]?Number(i[6]):e.colorSpace?.transfer?J[e.colorSpace.transfer]:1,h=i[7]?Number(i[7]):e.colorSpace?.matrix?K[e.colorSpace.matrix]:1;return fr("vpcC",1,0,[Qi(r),Qi(n),Qi(o),Qi(s),Qi(a),Qi(h),Yi(0)])},Vr=(t,e)=>{let i,r=0,n=16;const o=Ee.includes(e.track.source.Ot);if(o){const t=e.track.source.Ot,{sampleSize:i}=$e(t);n=8*i,n>16&&(r=1)}if(e.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),Yi(1),Yi(r),Yi(0),tr(0),Yi(e.info.numberOfChannels),Yi(n),Yi(0),Yi(0),Yi(e.info.sampleRate<65536?e.info.sampleRate:0),Yi(0)];else{const t=o?0:-2;i=[Array(6).fill(0),Yi(1),Yi(r),Yi(0),tr(0),Yi(e.info.numberOfChannels),Yi(Math.min(n,16)),Ji(t),Yi(0),Yi(e.info.sampleRate<65536?e.info.sampleRate:0),Yi(0),o?[tr(1),tr(n/8),tr(e.info.numberOfChannels*n/8)]:[tr(0),tr(0),tr(0)],tr(2)]}return ur(t,i,[Cn(e.track.source.Ot,e.muxer.isQuickTime)?.(e)??null])},Ur=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=[...Qi(e),...Qi(21),...Ki(0),...tr(0),...tr(0)];if(t.info.decoderConfig.description){const e=X(t.info.decoderConfig.description);i=[...i,...Qi(5),...ar(e.byteLength),...e]}return i=[...Yi(1),...Qi(0),...Qi(4),...ar(i.length),...i,...Qi(6),...Qi(1),...Qi(2)],i=[...Qi(3),...ar(i.length),...i],fr("esds",0,0,i)},zr=t=>ur("wave",void 0,[jr(t),Lr(t),ur("\0\0\0\0")]),jr=t=>ur("frma",[hr(Sn(t.track.source.Ot,t.info.decoderConfig.codec,t.muxer.isQuickTime))]),Lr=t=>{const{littleEndian:e}=$e(t.track.source.Ot);return ur("enda",[Yi(+e)])},qr=t=>{let e=t.info.numberOfChannels,i=3840,r=t.info.sampleRate,n=0,o=0,s=new Uint8Array(0);const a=t.info.decoderConfig?.description;if(a){z(a.byteLength>=18);const t=he(X(a));e=t.outputChannelCount,i=t.preSkip,r=t.inputSampleRate,n=t.outputGain,o=t.channelMappingFamily,t.channelMappingTable&&(s=t.channelMappingTable)}return ur("dOps",[Qi(0),Qi(e),Yi(i),tr(r),Ji(n),Qi(o),...s])},Gr=t=>{const e=t.info.decoderConfig?.description;z(e);const i=X(e);return fr("dfLa",0,0,[...i.subarray(4)])},Hr=t=>{const{littleEndian:e,sampleSize:i}=$e(t.track.source.Ot);return fr("pcmC",0,0,[Qi(+e),Qi(8*i)])},Wr=t=>{z(t.info.primingPacket);const e=(t=>{if(t.length<7)return null;if(11!==t[0]||119!==t[1])return null;const e=new Dt(t);e.skipBits(16),e.skipBits(16);const i=e.readBits(2);if(3===i)return null;const r=e.readBits(6),n=e.readBits(5);if(n>8)return null;const o=e.readBits(3),s=e.readBits(3);return 1&s&&1!==s&&e.skipBits(2),4&s&&e.skipBits(2),2===s&&e.skipBits(2),{fscod:i,bsid:n,bsmod:o,acmod:s,lfeon:e.readBits(1),bitRateCode:Math.floor(r/2)}})(t.info.primingPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const i=new Uint8Array(3),r=new Dt(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),ur("dac3",[...i])},Xr=t=>{z(t.info.primingPacket);const e=(t=>{if(t.length<6)return null;if(11!==t[0]||119!==t[1])return null;const e=new Dt(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=le[o];let d;return d=n<3?qt[n]/1e3:Gt[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 Dt(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 ur("dec3",[...n])},Zr=t=>{z(t.info.primingPacket);const e=(t=>{const e=(t=>{if(t.length<18)return null;if(127!==t[0]||254!==t[1]||128!==t[2]||1!==t[3])return null;const e=new Dt(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>=pe.length)return null;const s=de[e.readBits(4)];if(0===s)return null;const a=ue[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=fe[e.readBits(3)];if(0===c)return null;const l=0!==h;return{frameSize:n,sampleRate:s,numberOfChannels:pe[o]+(l?1:0),sampleCount:32*r,channelLayout:me[o]|(l?8:0),amode:o,lfePresent:l,bitRate:a,pcmResolution:c}})(t),i=Z(t);let r=e?4*Math.ceil(e.frameSize/4):0,n=null;for(;r+4<=t.length&&1683496997===i.getUint32(r);){const e=ye(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 ur("ddts",[...ge(e)])},Qr=(t,e)=>ur(t,[Array(6).fill(0),Yi(1)],[In[e.track.source.Ot](e)]),Yr=t=>fr("stts",0,0,[tr(t.timeToSampleTable.length),t.timeToSampleTable.map(t=>[tr(t.sampleCount),tr(t.sampleDelta)])]),Jr=t=>{if(t.samples.every(t=>"key"===t.type))return null;const e=[...t.samples.entries()].filter(([,t])=>"key"===t.type);return fr("stss",0,0,[tr(e.length),e.map(([t])=>tr(t+1))])},Kr=t=>fr("stsc",0,0,[tr(t.compactlyCodedChunkTable.length),t.compactlyCodedChunkTable.map(t=>[tr(t.firstChunk),tr(t.samplesPerChunk),tr(1)])]),tn=t=>{if("audio"===t.type&&t.info.requiresPcmTransformation){const{sampleSize:e}=$e(t.track.source.Ot);return fr("stsz",0,0,[tr(e*t.info.numberOfChannels),tr(t.samples.reduce((e,i)=>e+Ln(i.duration,t.timescale),0))])}return fr("stsz",0,0,[tr(0),tr(t.samples.length),t.samples.map(t=>tr(t.size))])},en=t=>t.finalizedChunks.length>0&&q(t.finalizedChunks).offset>=2**32?fr("co64",0,0,[tr(t.finalizedChunks.length),t.finalizedChunks.map(t=>ir(t.offset))]):fr("stco",0,0,[tr(t.finalizedChunks.length),t.finalizedChunks.map(t=>tr(t.offset))]),rn=t=>fr("ctts",1,0,[tr(t.compositionTimeOffsetTable.length),t.compositionTimeOffsetTable.map(t=>[tr(t.sampleCount),er(t.sampleCompositionTimeOffset)])]),nn=t=>{let e=1/0,i=-1/0,r=1/0,n=-1/0;z(t.compositionTimeOffsetTable.length>0),z(t.samples.length>0);for(let s=0;s<t.compositionTimeOffsetTable.length;s++){const r=t.compositionTimeOffsetTable[s];e=Math.min(e,r.sampleCompositionTimeOffset),i=Math.max(i,r.sampleCompositionTimeOffset)}for(let s=0;s<t.samples.length;s++){const e=t.samples[s];r=Math.min(r,Ln(e.timestamp,t.timescale)),n=Math.max(n,Ln(e.timestamp+e.duration,t.timescale))}const o=Math.max(-e,0);return n>=2**31?null:fr("cslg",0,0,[er(o),er(e),er(i),er(r),er(n)])},on=t=>ur("mvex",void 0,t.map(sn)),sn=t=>fr("trex",0,0,[tr(t.track.id),tr(1),tr(0),tr(0),tr(0)]),an=(t,e)=>ur("moof",void 0,[hn(t),...e.map(ln)]),hn=t=>fr("mfhd",0,0,[tr(t)]),cn=t=>{let e=0,i=0;const r="delta"===t.type;return i|=+r,e|=r?1:2,e<<24|i<<16},ln=t=>ur("traf",void 0,[dn(t),un(t),fn(t)]),dn=t=>{z(t.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const i=t.currentChunk.samples[1]??t.currentChunk.samples[0],r={duration:i.timescaleUnitsToNextSample,size:i.size,flags:cn(i)};return fr("tfhd",0,131128,[tr(t.track.id),tr(r.duration),tr(r.size),tr(r.flags)])},un=t=>(z(t.currentChunk),fr("tfdt",1,0,[ir(Ln(t.currentChunk.startTimestamp,t.timescale))])),fn=t=>{z(t.currentChunk);const e=t.currentChunk.samples.map(t=>t.timescaleUnitsToNextSample),i=t.currentChunk.samples.map(t=>t.size),r=t.currentChunk.samples.map(cn),n=t.currentChunk.samples.map(e=>Ln(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,fr("trun",1,p,[tr(t.currentChunk.samples.length),tr(t.currentChunk.offset-t.currentChunk.moofOffset||0),c?tr(r[0]):[],t.currentChunk.samples.map((t,o)=>[l?tr(e[o]):[],d?tr(i[o]):[],u?tr(r[o]):[],f?er(n[o]):[]])])},pn=t=>fr("tfra",1,0,[tr(t.track.id),tr(63),tr(t.finalizedChunks.length),t.finalizedChunks.map(e=>[ir(Ln(e.samples[0].timestamp,t.timescale)),ir(e.moofOffset),tr(e.trafIndex+1),tr(1),tr(1)])]),mn=()=>ur("vtte"),wn=(t,e,i,r,n)=>ur("vttc",void 0,[null!==n?ur("vsid",[er(n)]):null,null!==i?ur("iden",[...Q.encode(i)]):null,null!==e?ur("ctim",[...Q.encode(Hi(e))]):null,null!==r?ur("sttg",[...Q.encode(r)]):null,ur("payl",[...Q.encode(t)])]),vn=t=>ur("vtta",[...Q.encode(t)]),bn=t=>{const e=[],i=t.format.Rt.metadataFormat??"auto",r=t.output.$t;if("mdir"===i||"auto"===i&&!t.isQuickTime){const t=Tn(r);t&&e.push(t)}else if("mdta"===i){const t=kn(r);t&&e.push(t)}else("udta"===i||"auto"===i&&t.isQuickTime)&&yn(e,t.output.$t);return 0===e.length?null:ur("udta",void 0,e)},yn=(t,e)=>{for(const{key:i,value:r}of Tt(e))switch(i){case"title":t.push(gn("©nam",r));break;case"description":t.push(gn("©des",r));break;case"artist":t.push(gn("©ART",r));break;case"album":t.push(gn("©alb",r));break;case"albumArtist":t.push(gn("albr",r));break;case"genre":t.push(gn("©gen",r));break;case"date":t.push(gn("©day",r.toISOString().slice(0,10)));break;case"comment":t.push(gn("©cmt",r));break;case"lyrics":t.push(gn("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:ot(i)}if(e.raw)for(const i in e.raw){const r=e.raw[i];null==r||4!==i.length||t.some(t=>t.type===i)||("string"==typeof r?t.push(gn(i,r)):r instanceof Uint8Array&&t.push(ur(i,Array.from(r))))}},gn=(t,e)=>{const i=Q.encode(e);return ur(t,[Yi(i.length),Yi(Bn("und")),Array.from(i)])},xn={"image/jpeg":13,"image/png":14,"image/bmp":27},En=(t,e)=>{const i=[];for(const{key:r,value:n}of Tt(t))switch(r){case"title":i.push({key:e?"title":"©nam",value:_n(n)});break;case"description":i.push({key:e?"description":"©des",value:_n(n)});break;case"artist":i.push({key:e?"artist":"©ART",value:_n(n)});break;case"album":i.push({key:e?"album":"©alb",value:_n(n)});break;case"albumArtist":i.push({key:e?"album_artist":"aART",value:_n(n)});break;case"comment":i.push({key:e?"comment":"©cmt",value:_n(n)});break;case"genre":i.push({key:e?"genre":"©gen",value:_n(n)});break;case"lyrics":i.push({key:e?"lyrics":"©lyr",value:_n(n)});break;case"date":i.push({key:e?"date":"©day",value:_n(n.toISOString().slice(0,10))});break;case"images":for(const t of n)"coverFront"===t.kind&&i.push({key:"covr",value:ur("data",[tr(xn[t.mimeType]??0),tr(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:_n(e)})}else i.push({key:"trkn",value:ur("data",[tr(0),tr(0),Yi(0),Yi(n),Yi(t.tracksTotal??0),Yi(0)])});break;case"discNumber":e||i.push({key:"disc",value:ur("data",[tr(0),tr(0),Yi(0),Yi(n),Yi(t.discsTotal??0),Yi(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:ot(r)}if(t.raw)for(const r in t.raw){const n=t.raw[r];null==n||!e&&4!==r.length||i.some(t=>t.key===r)||("string"==typeof n?i.push({key:r,value:_n(n)}):n instanceof Uint8Array?i.push({key:r,value:ur("data",[tr(0),tr(0),Array.from(n)])}):n instanceof Rt&&i.push({key:r,value:ur("data",[tr(xn[n.mimeType]??0),tr(0),Array.from(n.data)])}))}return i},Tn=t=>{const e=En(t,!1);return 0===e.length?null:fr("meta",0,0,void 0,[Ar(!1,"mdir","","appl"),ur("ilst",void 0,e.map(t=>ur(t.key,void 0,[t.value])))])},kn=t=>{const e=En(t,!0);return 0===e.length?null:ur("meta",void 0,[Ar(!1,"mdta",""),fr("keys",0,0,[tr(e.length)],e.map(t=>ur("mdta",[...Q.encode(t.key)]))),ur("ilst",void 0,e.map((t,e)=>{const i=String.fromCharCode(...tr(e+1));return ur(i,void 0,[t.value])}))])},_n=t=>ur("data",[tr(1),tr(0),...Q.encode(t)]),Mn=(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}},An={avc:t=>t.info.decoderConfig&&ur("avcC",[...X(t.info.decoderConfig.description)]),hevc:t=>t.info.decoderConfig&&ur("hvcC",[...X(t.info.decoderConfig.description)]),vp8:Nr,vp9:Nr,av1:t=>ur("av1C",Oe(t.info.decoderConfig.codec)),prores:null},Sn=(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"}},Cn=(t,e)=>{switch(t){case"aac":case"mp3":case"vorbis":return Ur;case"opus":return qr;case"flac":return Gr;case"ac3":return Wr;case"eac3":return Xr;case"dts":return Zr}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 zr}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 Hr}return null},Pn={webvtt:"wvtt"},In={webvtt:t=>ur("vttC",[...Q.encode(t.info.config.description)])},Bn=t=>{z(3===t.length);let e=0;for(let i=0;i<3;i++)e<<=5,e+=t.charCodeAt(i)-96;return e},Fn=class{constructor(t,e){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,t.Dt)throw new Error("Can't have multiple Writers for the same Target.");this.target=t,t.Nt(e),t.Dt=!0}start(){z(!this.started),this.target.Vt(),this.started=!0}write(t){z(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target.Ut(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return z(this.started&&!this.finalized),this.target.zt()}async finalize(){z(this.started&&!this.finalized),await this.target.jt(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=0}const i=e+t.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const t=new Uint8Array(r);t.set(this.trackedWrites,0),this.trackedWrites=t}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}},On=(oi(),class extends Pt{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 Vn(this,t)}}),Rn=65536,$n=2**32,Dn=class extends On{constructor(t={}){if(super(),this.buffer=null,this.Gt=0,!t||"object"!=typeof t)throw new TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==t.onFinalize&&"function"!=typeof t.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");if(this.Rt=t,this.Ht="resize"in new ArrayBuffer(0),this.Ht)try{this.Wt=new ArrayBuffer(Rn,{maxByteLength:$n})}catch{this.Wt=new ArrayBuffer(Rn),this.Ht=!1}else this.Wt=new ArrayBuffer(Rn);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>$n)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)}},Nn=class extends On{constructor(t,e={}){if(super(),this.Jt=[],this.Kt=0,this.te=0,this.ee=null,this.ie=null,this.re=[],!(t instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=e&&"object"!=typeof e)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==e.chunked&&"boolean"!=typeof e.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==e.chunkSize&&(!Number.isInteger(e.chunkSize)||e.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this.ne=t,this.Rt=e,this.oe=e.chunked??!1,this.se=e.chunkSize??16777216}Vt(){this.ee=this.ne.getWriter()}Ut(t,e){if(e>this.Kt){const t=e-this.Kt;this.Ut(new Uint8Array(t),this.Kt)}this.Jt.push({data:t.slice(),start:e}),this.Kt=Math.max(this.Kt,e+t.byteLength),this.qt(e,e+t.byteLength)}async zt(){if(null!==this.ie)throw this.ie;if(z(this.ee),0===this.Jt.length)return;const t=[],e=[...this.Jt].sort((t,e)=>t.start-e.start);t.push({start:e[0].start,size:e[0].data.byteLength});for(let i=1;i<e.length;i++){const r=t[t.length-1],n=e[i];n.start<=r.start+r.size?r.size=Math.max(r.size,n.start+n.data.byteLength-r.start):t.push({start:n.start,size:n.data.byteLength})}for(const i of t){i.data=new Uint8Array(i.size);for(const t of this.Jt)i.start<=t.start&&t.start<i.start+i.size&&i.data.set(t.data,t.start-i.start);if(null!==this.ee.desiredSize&&this.ee.desiredSize<=0&&await this.ee.ready,this.oe)this.ae(i.data,i.start),this.he();else{if(!0===this.Lt&&i.start!==this.te)throw new Error("Internal error: Monotonicity violation.");this.ee.write({type:"write",data:i.data,position:i.start}).catch(t=>{this.ie??=t}),this.te=i.start+i.data.byteLength}}this.Jt.length=0}ae(t,e){let i=this.re.findIndex(t=>t.start<=e&&e<t.start+this.se);-1===i&&(i=this.ce(e));const r=this.re[i],n=e-r.start,o=t.subarray(0,Math.min(this.se-n,t.byteLength));r.data.set(o,n);const s={start:n,end:n+o.byteLength};if(this.le(r,s),0===r.written[0].start&&r.written[0].end===this.se&&(r.shouldFlush=!0),this.re.length>2){for(let t=0;t<this.re.length-1;t++)this.re[t].shouldFlush=!0;this.he()}o.byteLength<t.byteLength&&this.ae(t.subarray(o.byteLength),e+o.byteLength)}le(t,e){let i=0,r=t.written.length-1,n=-1;for(;i<=r;){const o=Math.floor(i+(r-i+1)/2);t.written[o].start<=e.start?(i=o+1,n=o):r=o-1}for(t.written.splice(n+1,0,e),(-1===n||t.written[n].end<e.start)&&n++;n<t.written.length-1&&t.written[n].end>=t.written[n+1].start;)t.written[n].end=Math.max(t.written[n].end,t.written[n+1].end),t.written.splice(n+1,1)}ce(t){const e={start:Math.floor(t/this.se)*this.se,data:new Uint8Array(this.se),written:[],shouldFlush:!1};return this.re.push(e),this.re.sort((t,e)=>t.start-e.start),this.re.indexOf(e)}he(t=!1){z(this.ee);for(let e=0;e<this.re.length;e++){const i=this.re[e];if(i.shouldFlush||t){for(const t of i.written){const e=i.start+t.start;if(!0===this.Lt&&e!==this.te)throw new Error("Internal error: Monotonicity violation.");let r;r=0===t.start&&t.end===i.data.byteLength||!wt()?i.data.subarray(t.start,t.end):i.data.slice(t.start,t.end),this.ee.write({type:"write",data:r,position:e}).catch(t=>{this.ie??=t}),this.te=i.start+t.end}this.re.splice(e--,1)}}}async jt(){if(this.oe&&this.he(!0),null!==this.ie)throw this.ie;z(this.ee),await this.ee.ready,await this.ee.close(),this.ct("finalized")}async Qt(){return this.ee?.close()}},Vn=class extends On{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)}},Un=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.")}},zn=57600,jn=t=>{const e={},i=t.track;return void 0!==i.metadata.name&&(e.name=i.metadata.name),e},Ln=(t,e,i=!0)=>{const r=t*e;return i?Math.round(r):r},qn=class extends Li{constructor(t,e){super(t),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Dn,this.auxWriter=new Fn(this.auxTarget,!1),this.auxBoxWriter=new Wi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=nt(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=e,this.formatOptions={...e.Rt},this.isQuickTime=e instanceof lo,this.isCmaf=e instanceof co,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(e instanceof co?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 Dn),this.boxWriter=new Wi(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Dn&&"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 Fn(await this.output.me(),!0);t.start(),this.initWriter=t,this.initBoxWriter=new Wi(t)}const e=this.output.tracks.some(t=>t.isVideoTrack()&&"avc"===t.source.Ot);{const t=this.initBoxWriter??this.boxWriter;if(z(t),this.formatOptions.onFtyp&&t.writer.startTrackingWrites(),t.writeBox((t=>{const e=512;return ur("ftyp",t.isQuickTime?[hr("qt "),tr(e),hr("qt ")]:t.fragmented?t.cmaf?[hr("iso5"),tr(e),hr("iso5"),hr("iso6"),hr("mp41"),hr("cmfc"),hr("dash")]:[hr("iso5"),tr(e),hr("iso5"),hr("iso6"),hr("mp41")]:[hr("isom"),tr(e),hr("isom"),t.holdsAvc?hr("avc1"):[],hr("mp41")])})({isQuickTime:this.isQuickTime,holdsAvc:e,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onFtyp(e,i)}this.ftypSize=t.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const i of this.output.tracks)if(void 0===i.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(z(this.writer),z(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=wr(!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;Le(i,t.source.Ot),z(i),z(i.decoderConfig);const n={...i.decoderConfig};z(void 0!==n.codedWidth),z(void 0!==n.codedHeight);let o=!1;if("avc"!==t.source.Ot||n.description){if("hevc"===t.source.Ot&&!n.description){if(!e)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");const t=(t=>{try{const e=[],i=[],r=[],n=[];for(const h of Wt(t)){const o=t.subarray(h.offset,h.offset+h.length),s=Kt(o[0]);s===Ot.VPS_NUT?e.push(o):s===Ot.SPS_NUT?i.push(o):s===Ot.PPS_NUT?r.push(o):s!==Ot.PREFIX_SEI_NUT&&s!==Ot.SUFFIX_SEI_NUT||n.push(o)}if(0===i.length||0===r.length)return null;const o=(t=>{try{const e=new Dt(Qt(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}=te(e,i);H(e);const l=H(e);let d=0;3===l&&(d=e.readBits(1));const u=H(e),f=H(e);let p=u,m=f;if(e.readBits(1)){const t=H(e),i=H(e),r=H(e),n=H(e);let o=1,s=1;const a=0===d?l:0;1===a?(o=2,s=2):2===a&&(o=2,s=1),p-=(t+i)*o,m-=(r+n)*s}const w=H(e),v=H(e);H(e);const b=e.readBits(1)?0:i;let y=0;for(let t=b;t<=i;t++)H(e),y=H(e),H(e);H(e),H(e),H(e),H(e),H(e),H(e),e.readBits(1)&&e.readBits(1)&&ee(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),H(e),H(e),e.skipBits(1));const g=H(e);if(ie(e,g),e.readBits(1)){const t=H(e);for(let i=0;i<t;i++)H(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let x=2,E=2,T=2,k=0,_=0,M={num:1,den:1};if(e.readBits(1)){const t=ne(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 Bt.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 Dt(Qt(t));e.skipBits(16),H(e),H(e),e.skipBits(1),e.skipBits(1),e.skipBits(3),e.skipBits(1),e.skipBits(1),H(e),H(e),W(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&H(e),W(e),W(e),e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const i=e.readBits(1),n=e.readBits(1);s=i||n?i&&!n?2:!i&&n?3:0:0}const a=[...e.length?[{arrayCompleteness:1,nalUnitType:Ot.VPS_NUT,nalUnits:e}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ot.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ot.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Kt(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 Bt.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 Wt(t)){const n=t.subarray(s.offset,s.offset+s.length),o=Zt(n[0]);o===Ft.SPS?e.push(n):o===Ft.PPS?i.push(n):o===Ft.SPS_EXT&&r.push(n)}if(0===e.length)return null;if(0===i.length)return null;const n=(t=>{try{const e=Qt(t),i=new Dt(e);if(i.skipBits(1),i.skipBits(2),7!==i.readBits(5))return null;const r=i.readAlignedByte(),n=i.readAlignedByte(),o=i.readAlignedByte();H(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=H(i),3===s&&(c=i.readBits(1)),a=H(i),h=H(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+W(i)+256)%256),r=0===n?r:n}H(i);const l=H(i);if(0===l)H(i);else if(1===l){i.skipBits(1),W(i),W(i);const t=H(i);for(let e=0;e<t;e++)W(i)}H(i),i.skipBits(1);const d=H(i),u=H(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=H(i),e=H(i),r=H(i),n=H(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=Yt[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)&&(H(i),H(i)),i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.skipBits(1));const t=i.readBits(1);t&&Jt(i);const e=i.readBits(1);e&&Jt(i),(t||e)&&i.skipBits(1),i.skipBits(1),_=i.pos,M=i.readBits(1),M&&(i.skipBits(1),H(i),H(i),H(i),H(i),T=H(i),k=H(i))}if(null===T)if(z(null===k),(44===r||86===r||100===r||110===r||122===r||244===r)&&16&n)T=0,k=0;else{const t=d+1,e=(2-v)*(u+1),i=Me.find(t=>t.level>=o)??q(Me),r=Math.min(Math.floor(i.maxDpbMbs/(t*e)),16);T=r,k=r}return z(null!==k),{emulationUnpreventedBytes:e,profileIdc:r,constraintFlags:n,levelIdc:o,frameMbsOnlyFlag:v,chromaFormatIdc:s,bitDepthLumaMinus8:a,bitDepthChromaMinus8:h,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:w,pixelAspectRatio:E,colourPrimaries:b,matrixCoefficients:g,transferCharacteristics:y,fullRangeFlag:x,numReorderFrames:T,maxDecFrameBuffering:k,vuiParametersFlagBitOffset:A,bitstreamRestrictionFlagBitOffset:_,bitstreamRestrictionFlag:M}}catch(e){return Bt.ft("Error parsing AVC SPS:",e),null}})(e[0]);z(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:i,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return Bt.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){z(null!==t.bitDepthLumaMinus8),z(null!==t.bitDepthChromaMinus8),z(null!==t.sequenceParameterSetExt),e.push(252|3&t.chromaFormat),e.push(248|7&t.bitDepthLumaMinus8),e.push(248|7&t.bitDepthChromaMinus8),e.push(t.sequenceParameterSetExt.length);for(const i of t.sequenceParameterSetExt){const t=i.byteLength;e.push(t>>8),e.push(255&t);for(let r=0;r<t;r++)e.push(i[r])}}return new Uint8Array(e)})(t),o=!0}const s=(t=>{const e=t<0?-1:1;let i=0,r=1,n=1,o=0,s=t=Math.abs(t);for(;;){const t=Math.floor(s),a=t*n+i,h=t*o+r;if(h>1e6)return{num:e*n,den:o};if(i=n,r=o,n=a,o=h,s=1/(s-t),!isFinite(s))break}return{num:e*n,den:o}})(1/(t.metadata.frameRate??57600)).den,a=n.displayAspectWidth,h=n.displayAspectHeight,c=void 0===a||void 0===h?{num:1,den:1}:At({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;Ge(i,t.source.Ot),z(i),z(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ot&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=ni(zi.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=Nt[t.samplingFrequencyIndex],r=Vt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Ut({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&&Ee.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;He(e),z(e),z(e.config);const r={muxer:this,track:t,type:"subtitle",info:{config:e.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);let n=e.data;if(r.info.requiresAnnexBTransformation){const t=[...Wt(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=ni(zi.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=$e(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=Ln(i,t.timescale);if(i=r/t.timescale,r>0){const{sampleSize:n,silentValue:o}=$e(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=new Set([]);for(const h of t.cueQueue)z(h.timestamp<=e),z(t.lastCueEndTimestamp<=h.timestamp+h.duration),i.add(Math.max(h.timestamp,t.lastCueEndTimestamp)),i.add(h.timestamp+h.duration);const r=[...i].sort((t,e)=>t-e),n=r[0],o=r[1]??n;if(e<o)break;if(t.lastCueEndTimestamp<n){this.auxWriter.seek(0);const e=mn();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;qi.lastIndex=0;const r=qi.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=vn(i.notes);this.auxBoxWriter.writeBox(t)}const h=wn(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:Ln(r,t.timescale)}}processTimestamps(t,e){if(0===t.timestampProcessingQueue.length)return;if("audio"===t.type&&t.info.requiresPcmTransformation){z(!this.isFragmented),t.startTimestampOffset??=t.timestampProcessingQueue[0].timestamp;let e=0;for(let i=0;i<t.timestampProcessingQueue.length;i++){const r=t.timestampProcessingQueue[i];e+=Ln(r.duration,t.timescale)}return 0===t.timeToSampleTable.length?t.timeToSampleTable.push({sampleCount:e,sampleDelta:1}):q(t.timeToSampleTable).sampleCount+=e,void(t.timestampProcessingQueue.length=0)}const i=t.timestampProcessingQueue.map(t=>t.timestamp).sort((t,e)=>t-e);this.isFragmented?t.startTimestampOffset??=Math.min(i[0],0):t.startTimestampOffset??=i[0];for(let r=0;r<t.timestampProcessingQueue.length;r++){const e=t.timestampProcessingQueue[r];e.decodeTimestamp=i[r];const n=Ln(e.timestamp-e.decodeTimestamp,t.timescale),o=Ln(e.duration,t.timescale);if(null!==t.lastTimescaleUnits){z(t.lastSample);const i=Ln(e.decodeTimestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);if(z(r>=0),t.lastTimescaleUnits+=r,t.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let e=q(t.timeToSampleTable);if(z(e),1===e.sampleCount){e.sampleDelta=r;const i=t.timeToSampleTable[t.timeToSampleTable.length-2];i&&i.sampleDelta===r&&(i.sampleCount++,t.timeToSampleTable.pop(),e=i)}else e.sampleDelta!==r&&(e.sampleCount--,t.timeToSampleTable.push(e={sampleCount:1,sampleDelta:r}));e.sampleDelta===o?e.sampleCount++:t.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const i=q(t.compositionTimeOffsetTable);z(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else t.lastTimescaleUnits=Ln(e.decodeTimestamp,t.timescale,!1),this.isFragmented||(t.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),t.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));t.lastSample=e}if(t.timestampProcessingQueue.length=0,z(t.lastSample),z(null!==t.lastTimescaleUnits),void 0!==e&&0===t.lastSample.timescaleUnitsToNextSample){z("key"===e.type);const i=Ln(e.timestamp,t.timescale,!1),r=Math.round(i-t.lastTimescaleUnits);t.lastSample.timescaleUnitsToNextSample=r}}async registerSample(t,e){"key"===e.type&&this.processTimestamps(t,e),t.timestampProcessingQueue.push(e),this.isFragmented?(t.sampleQueue.push(e),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(t,e):await this.addSampleToTrack(t,e)}async addSampleToTrack(t,e){if(!this.isFragmented&&(t.samples.push(e),"reserve"===this.fastStart)){const e=t.track.metadata.maximumPacketCount;if(z(void 0!==e),t.samples.length>e)throw new Error(`Track #${t.track.id} has already reached the maximum packet count (${e}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(t.currentChunk){t.currentChunk.startTimestamp=Math.min(t.currentChunk.startTimestamp,e.timestamp);const r=e.timestamp-t.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.closed});r>=this.minimumFragmentDuration&&n&&e.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(t.currentChunk&&await this.finalizeCurrentChunk(t),t.currentChunk={startTimestamp:e.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),z(t.currentChunk),t.currentChunk.samples.push(e),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,e.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,e.timestamp+e.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,e.timestamp))}async finalizeCurrentChunk(t){if(z(!this.isFragmented),z(this.writer),!t.currentChunk)return;t.finalizedChunks.push(t.currentChunk),this.finalizedChunks.push(t.currentChunk);let e=t.currentChunk.samples.length;if("audio"===t.type&&t.info.requiresPcmTransformation&&(e=t.currentChunk.samples.reduce((e,i)=>e+Ln(i.duration,t.timescale),0)),0!==t.compactlyCodedChunkTable.length&&q(t.compactlyCodedChunkTable).samplesPerChunk===e||t.compactlyCodedChunkTable.push({firstChunk:t.finalizedChunks.length,samplesPerChunk:e}),"in-memory"!==this.fastStart){t.currentChunk.offset=this.writer.getPos();for(const e of t.currentChunk.samples)z(e.data),this.writer.write(e.data),e.data=null;await this.writer.flush()}else t.currentChunk.offset=0}async interleaveSamples(t=!1){if(z(this.isFragmented),t||this.allTracksAreKnown())t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.sampleQueue.length&&!n.closed)break t;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(e=n,i=n.sampleQueue[0].timestamp)}if(!e)break;const r=e.sampleQueue.shift();await this.addSampleToTrack(e,r)}}async finalizeFragment(t=!this.isCmaf){if(z(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const t=this.initBoxWriter??this.boxWriter;z(t),this.formatOptions.onMoov&&t.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const e=vr(this);if(t.writeBox(e),this.formatOptions.onMoov){const{data:e,start:i}=t.writer.stopTrackingWrites();this.formatOptions.onMoov(e,i)}if(this.isCmaf){z(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output.fe(!0),this.boxWriter=new Wi(this.writer);const t=this.boxWriter.measureBox(pr()),e=this.boxWriter.measureBox(mr(this,0));this.segmentHeaderSize=t+e,this.writer.seek(this.segmentHeaderSize)}}z(this.writer),z(this.boxWriter);const e=this.trackDatas.filter(t=>t.currentChunk);if(0===e.length)return void(t&&await this.writer.flush());const i=this.nextFragmentNumber++,r=an(i,e),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let s=o+8,a=1/0;for(let u=0;u<e.length;u++){const t=e[u];z(t.currentChunk),z(null!==t.startTimestampOffset),t.currentChunk.offset=s,t.currentChunk.moofOffset=n,t.currentChunk.trafIndex=u,t.currentChunk.startTimestamp-=t.startTimestampOffset;for(const e of t.currentChunk.samples)s+=e.size,e.timestamp-=t.startTimestampOffset,e.decodeTimestamp-=t.startTimestampOffset;a=Math.min(a,t.currentChunk.startTimestamp)}const h=s-o,c=h>=2**32;if(c)for(const u of e)u.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const l=an(i,e);if(this.boxWriter.writeBox(l),this.formatOptions.onMoof){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(t,e,a)}z(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const d=wr(c);d.size=h,this.boxWriter.writeBox(d),this.writer.seek(o+(c?16:8));for(const u of e)for(const t of u.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}for(const u of e)u.finalizedChunks.push(u.currentChunk),this.finalizedChunks.push(u.currentChunk),u.currentChunk=null;t&&await this.writer.flush()}async registerSampleFastStartReserve(t,e){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(t,e)):t.sampleQueue.push(e)}async createFastStartReserveMdat(){z(this.writer),z(this.boxWriter),this.ensureOneEnabledTrack();const t=vr(this),e=this.boxWriter.measureBox(t)+this.computeSampleTableSizeUpperBound()+4096;z(null!==this.ftypSize),this.writer.seek(this.ftypSize+e),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=wr(!0),this.boxWriter.writeBox(this.mdat);for(const i of this.trackDatas){for(const t of i.sampleQueue)await this.addSampleToTrack(i,t);i.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){z("reserve"===this.fastStart);let t=0;for(const e of this.trackDatas){const i=e.track.metadata.maximumPacketCount;z(void 0!==i),t+=8*Math.ceil(2/3*i),t+=4*i,t+=8*Math.ceil(2/3*i),t+=12*Math.ceil(2/3*i),t+=4*i,t+=8*i}return t}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0,"subtitle"===i.type&&"webvtt"===t.source.Ot&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),e()}ensureOneEnabledTrack(){for(const t of["video","audio","subtitle"]){const e=this.trackDatas.filter(e=>e.type===t);if(0!==e.length&&!e.some(t=>!1!==t.track.metadata.disposition?.default)){const t=e[0];t.track.metadata.disposition={...t.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){z(this.isFragmented);const t=await this.mutex.acquire();try{for(const t of this.trackDatas)"subtitle"===t.type&&"webvtt"===t.track.source.Ot&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{t()}}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),this.mdat||"reserve"!==this.fastStart||await this.createFastStartReserveMdat();for(const i of this.trackDatas)i.closed=!0,"subtitle"===i.type&&"webvtt"===i.track.source.Ot&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const i of this.trackDatas)if(await this.finalizeCurrentChunk(i),null!==i.startTimestampOffset)for(let t=0;t<i.samples.length;t++){const e=i.samples[t];e.timestamp-=i.startTimestampOffset,e.decodeTimestamp-=i.startTimestampOffset}if(z(this.writer),z(this.boxWriter),"in-memory"===this.fastStart){let t;this.mdat=wr(!1);for(let i=0;i<2;i++){const e=vr(this),i=this.boxWriter.measureBox(e);t=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+t;for(const n of this.finalizedChunks){n.offset=r;for(const{data:e}of n.samples)z(e),r+=e.byteLength,t+=e.byteLength}if(r<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();const e=vr(this);if(this.boxWriter.writeBox(e),this.formatOptions.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(t,e)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const t of i.samples)z(t.data),this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}}else if(this.isFragmented)if(this.isCmaf){const t=null!==this.segmentHeaderSize?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(pr()),this.boxWriter.writeBox(mr(this,t))}else{const t=this.writer.getPos(),i=(e=this.trackDatas,ur("mfra",void 0,[...e.map(pn),fr("mfro",0,0,[tr(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{z(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);z(void 0!==t);const e=this.writer.getPos()-t;if(this.mdat.size=e,this.mdat.largeSize=e>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(t,e)}const i=vr(this);if("reserve"===this.fastStart){z(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const t=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:t})}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.formatOptions.onMoov){const{data:t,start:e}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(t,e)}}var e;t()}},Gn="Mediabunny",Hn={video:1,audio:2,subtitle:17},Wn=class extends Li{constructor(t,e){super(t),this.trackDatas=[],this.allTracksKnown=nt(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.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 ii(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:ce.EBML,data:[{id:ce.EBMLVersion,data:1},{id:ce.EBMLReadVersion,data:1},{id:ce.EBMLMaxIDLength,data:4},{id:ce.EBMLMaxSizeLength,data:8},{id:ce.DocType,data:this.format instanceof fo?"webm":"matroska"},{id:ce.DocTypeVersion,data:2},{id:ce.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:ce.SeekHead,data:[{id:ce.Seek,data:[{id:ce.SeekID,data:e},{id:ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:ce.Seek,data:[{id:ce.SeekID,data:i},{id:ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:ce.Seek,data:[{id:ce.SeekID,data:r},{id:ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:ce.Seek,data:[{id:ce.SeekID,data:n},{id:ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:ce.Seek,data:[{id:ce.SeekID,data:o},{id:ce.SeekPosition,size:5,data:t?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=s}createSegmentInfo(){const t={id:ce.Duration,data:new Qe(0)};this.segmentDuration=t;const e={id:ce.Info,data:[{id:ce.TimestampScale,data:1e6},{id:ce.MuxingApp,data:Gn},{id:ce.WritingApp,data:Gn},this.format.Rt.appendOnly?null:t]};this.segmentInfo=e}createTracks(){const t={id:ce.Tracks,data:[]};this.tracksElement=t;for(const e of this.trackDatas){let i=ri[e.track.source.Ot];z(i),"audio"===e.type&&"dts"===e.track.source.Ot&&("dtse"===e.info.decoderConfig.codec?i="A_DTS/EXPRESS":"dtsl"===e.info.decoderConfig.codec&&(i="A_DTS/LOSSLESS"));let r=0;if("audio"===e.type&&"opus"===e.track.source.Ot){r=8e7;const t=e.info.decoderConfig.description;if(t){const e=he(X(t));r=Math.round(e.preSkip/48e3*1e9)}}t.data.push({id:ce.TrackEntry,data:[{id:ce.TrackNumber,data:e.track.id},{id:ce.TrackUID,data:e.track.id},{id:ce.TrackType,data:Hn[e.type]},!1===e.track.metadata.disposition?.default?{id:ce.FlagDefault,data:0}:null,e.track.metadata.disposition?.forced?{id:ce.FlagForced,data:1}:null,e.track.metadata.disposition?.hearingImpaired?{id:ce.FlagHearingImpaired,data:1}:null,e.track.metadata.disposition?.visuallyImpaired?{id:ce.FlagVisualImpaired,data:1}:null,e.track.metadata.disposition?.original?{id:ce.FlagOriginal,data:1}:null,e.track.metadata.disposition?.commentary?{id:ce.FlagCommentary,data:1}:null,{id:ce.FlagLacing,data:0},{id:ce.Language,data:e.track.metadata.languageCode??"und"},{id:ce.CodecID,data:i},e.codecPrivate?{id:ce.CodecPrivate,data:X(e.codecPrivate)}:null,{id:ce.CodecDelay,data:0},{id:ce.SeekPreRoll,data:r},void 0!==e.track.metadata.name?{id:ce.Name,data:new Je(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:ce.DefaultDuration,data:1e9/e}:null],n=i?L(-i):0,o=!!t.info.aspectRatio&&t.info.aspectRatio.num*t.info.height!==t.info.aspectRatio.den*t.info.width,s=t.info.decoderConfig.colorSpace,a={id:ce.Video,data:[{id:ce.PixelWidth,data:t.info.width},{id:ce.PixelHeight,data:t.info.height},o?{id:ce.DisplayWidth,data:t.info.aspectRatio.num}:null,o?{id:ce.DisplayHeight,data:t.info.aspectRatio.den}:null,o?{id:ce.DisplayUnit,data:3}:null,t.info.alphaMode?{id:ce.AlphaMode,data:1}:null,tt(s)?null:{id:ce.Colour,data:[{id:ce.MatrixCoefficients,data:null!=s?.matrix?K[s.matrix]:2},{id:ce.TransferCharacteristics,data:null!=s?.transfer?J[s.transfer]:2},{id:ce.Primaries,data:null!=s?.primaries?Y[s.primaries]:2},{id:ce.Range,data:null!=s?.fullRange?s.fullRange?2:1:0}]},n?{id:ce.Projection,data:[{id:ce.ProjectionType,data:0},{id:ce.ProjectionPoseRoll,data:new Ze((n+180)%360-180)}]}:null]};return r.push(a),r}audioSpecificTrackInfo(t){const e=Ee.includes(t.track.source.Ot)?$e(t.track.source.Ot):null;return[{id:ce.Audio,data:[{id:ce.SamplingFrequency,data:new Ze(t.info.sampleRate)},{id:ce.Channels,data:t.info.numberOfChannels},e?{id:ce.BitDepth,data:8*e.sampleSize}:null]}]}subtitleSpecificTrackInfo(t){return[]}maybeCreateTags(){const t=[],e=(e,i)=>{t.push({id:ce.SimpleTag,data:[{id:ce.TagName,data:new Je(e)},"string"==typeof i?{id:ce.TagString,data:new Je(i)}:{id:ce.TagBinary,data:i}]})},i=this.output.$t,r=new Set;for(const{key:n,value:o}of Tt(i))switch(n){case"title":e("TITLE",o),r.add("TITLE");break;case"description":e("DESCRIPTION",o),r.add("DESCRIPTION");break;case"artist":e("ARTIST",o),r.add("ARTIST");break;case"album":e("ALBUM",o),r.add("ALBUM");break;case"albumArtist":e("ALBUM_ARTIST",o),r.add("ALBUM_ARTIST");break;case"genre":e("GENRE",o),r.add("GENRE");break;case"comment":e("COMMENT",o),r.add("COMMENT");break;case"lyrics":e("LYRICS",o),r.add("LYRICS");break;case"date":e("DATE",o.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":e("PART_NUMBER",void 0!==i.tracksTotal?`${o}/${i.tracksTotal}`:o.toString()),r.add("PART_NUMBER");break;case"discNumber":e("DISC",void 0!==i.discsTotal?`${o}/${i.discsTotal}`:o.toString()),r.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:ot(n)}if(i.raw)for(const n in i.raw){const t=i.raw[n];null==t||r.has(n)||("string"==typeof t||t instanceof Uint8Array)&&e(n,t)}0!==t.length&&(this.tagsElement={id:ce.Tags,data:[{id:ce.Tag,data:[{id:ce.Targets,data:[{id:ce.TargetTypeValue,data:50},{id:ce.TargetType,data:"MOVIE"}]},...t]}]})}maybeCreateAttachments(){const t=this.output.$t,e=[],i=new Set,r=t.images??[];for(const n of r){let t,r=n.name;for(void 0===r&&(r=("coverFront"===n.kind?"cover":"coverBack"===n.kind?"back":"image")+(kt(n.mimeType)??""));;){t=0n;for(let e=0;e<8;e++)t<<=8n,t|=BigInt(Math.floor(256*Math.random()));if(0n!==t&&!i.has(t))break}i.add(t),e.push({id:ce.AttachedFile,data:[void 0!==n.description?{id:ce.FileDescription,data:new Je(n.description)}:null,{id:ce.FileName,data:new Je(r)},{id:ce.FileMediaType,data:n.mimeType},{id:ce.FileData,data:n.data},{id:ce.FileUID,data:t}]})}for(const[n,o]of Object.entries(t.raw??{}))o instanceof $t&&/^\d+$/.test(n)&&(r.find(t=>t.mimeType===o.mimeType&&_t(t.data,o.data))||e.push({id:ce.AttachedFile,data:[void 0!==o.description?{id:ce.FileDescription,data:new Je(o.description)}:null,{id:ce.FileName,data:new Je(o.name??"")},{id:ce.FileMediaType,data:o.mimeType??""},{id:ce.FileData,data:o.data},{id:ce.FileUID,data:BigInt(n)}]}));0!==e.length&&(this.attachmentsElement={id:ce.Attachments,data:e})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const t={id:ce.Segment,size:this.format.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:ce.Cues,data:[]}}get segmentDataOffset(){return z(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const t of this.output.tracks)if(!t.source.gt&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const t=this.trackDatas.map(t=>"video"===t.type||"audio"===t.type?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source.Ot]);return(t=>{let e=(t.hasVideo?"video/":t.hasAudio?"audio/":"application/")+(t.isWebM?"webm":"x-matroska");return t.codecStrings.length>0&&(e+=`; codecs="${[...new Set(t.codecStrings.filter(Boolean))].join(", ")}"`),e})({isWebM:this.format instanceof fo,hasVideo:this.trackDatas.some(t=>"video"===t.type),hasAudio:this.trackDatas.some(t=>"audio"===t.type),codecStrings:t})}getVideoTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Le(i,t.source.Ot),z(i),z(i.decoderConfig),z(void 0!==i.decoderConfig.codedWidth),z(void 0!==i.decoderConfig.codedHeight);const n=i.decoderConfig.displayAspectWidth,o=i.decoderConfig.displayAspectHeight,s=void 0===n||void 0===o?null:At({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(Oe(a.info.decoderConfig.codec)):"prores"===t.source.Ot&&(a.codecPrivate=Q.encode(i.decoderConfig.codec)),this.trackDatas.push(a),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getAudioTrackData(t,e,i){const r=this.trackDatas.find(e=>e.track===t);if(r)return r;Ge(i,t.source.Ot),z(i),z(i.decoderConfig);const n={...i.decoderConfig};let o=!1;if("aac"===t.source.Ot&&!n.description){if(!e)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const t=ni(zi.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=Nt[t.samplingFrequencyIndex],r=Vt[t.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");n.description=Ut({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;He(e),z(e),z(e.config);const r={track:t,type:"subtitle",info:{config:e.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Q.encode(e.config.description),closed:!1};return this.trackDatas.push(r),this.trackDatas.sort((t,e)=>t.track.id-e.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(t,e,i);r.info.alphaMode??=!!e.sideData.alpha;let n=e.data;if("prores"===t.source.Ot){if(n.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");n=n.subarray(8)}const o="key"===e.type;this.validateTimestamp(r.track,e.timestamp,o);let s=e.timestamp,a=e.duration;void 0!==t.metadata.frameRate&&(s=ct(s,t.metadata.frameRate),a=ct(a,t.metadata.frameRate));const h=r.info.alphaMode?e.sideData.alpha??null:null,c=this.createInternalChunk(n,s,a,e.type,h);"vp9"===t.source.Ot&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(t,e,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(t,e,i);let n=e.data;if(r.info.requiresAdtsStripping){const t=ni(zi.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);qi.lastIndex=0,n=n.replace(qi,t=>`<${Hi((t=>{const e=Gi.exec(t);if(!e)throw new Error("Expected match.");return 36e5*Number(e[1]||"0")+6e4*Number(e[2])+1e3*Number(e[3])+Number(e[4])})(t.slice(1,-1))-o)}>`);const s=Q.encode(n),a=`${e.settings??""}\n${e.identifier??""}\n${e.notes??""}`,h=this.createInternalChunk(s,e.timestamp,e.duration,"key",a.trim()?Q.encode(a):null);r.chunkQueue.push(h),await this.interleaveChunks()}finally{r()}}async interleaveChunks(t=!1){if(t||this.allTracksAreKnown()){t:for(;;){let e=null,i=1/0;for(const n of this.trackDatas){if(!t&&0===n.chunkQueue.length&&!n.closed)break t;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(e=n,i=n.chunkQueue[0].timestamp)}if(!e)break;const r=e.chunkQueue.shift();this.writeBlock(e,r)}t||await this.writer.flush()}}fixVP9ColorSpace(t,e){if("key"!==e.type)return;if(!t.info.decoderConfig.colorSpace||!t.info.decoderConfig.colorSpace.matrix)return;const i=new Dt(e.data);i.skipBits(2);const r=i.readBits(1),n=(i.readBits(1)<<1)+r;if(3===n&&i.skipBits(1),i.readBits(1))return;if(0!==i.readBits(1))return;if(i.skipBits(2),4817730!==i.readBits(24))return;n>=2&&i.skipBits(1);const o={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[t.info.decoderConfig.colorSpace.matrix];((t,e,i,r)=>{for(let n=e;n<i;n++){const e=Math.floor(n/8);let o=t[e];const s=7-(7&n);o&=~(1<<s),o|=(r&1<<i-n-1)>>i-n-1<<s,t[e]=o}})(e.data,i.pos,i.pos+3,o)}createInternalChunk(t,e,i,r,n=null){return{data:t,type:r,timestamp:e,duration:i,additions:n}}writeBlock(t,e){this.segment||this.createSegment();const i=Math.round(1e3*e.timestamp),r=this.trackDatas.every(i=>{if(t===i)return"key"===e.type;const r=i.chunkQueue[0];return r?"key"===r.type:i.closed});let n=!1;if(this.currentCluster){z(null!==this.currentClusterStartMsTimestamp),z(null!==this.currentClusterMaxMsTimestamp);const t=i-this.currentClusterStartMsTimestamp;n=r&&i>this.currentClusterMaxMsTimestamp&&t>=1e3*(this.format.Rt.minimumClusterDuration??1)||t>32767}else n=!0;n&&this.createNewCluster(i);const o=i-this.currentClusterStartMsTimestamp;if(o<-32768){if(!this.warnedAboutTooNegativeTimestamp){const t=this.format instanceof fo?"WebM":"Matroska";Bt.wt(`Packets had to be discarded because their timestamp is too negative to represent in ${t}.`),this.warnedAboutTooNegativeTimestamp=!0}return}const s=new Uint8Array(4),a=new DataView(s.buffer);a.setUint8(0,128|t.track.id),a.setInt16(1,o,!1);const h=Math.round(1e3*e.duration);if(e.additions||"subtitle"===t.type){const r={id:ce.BlockGroup,data:[{id:ce.Block,data:[s,e.data]},"delta"===e.type?{id:ce.ReferenceBlock,data:new Ye(t.lastWrittenMsTimestamp-i)}:null,e.additions?{id:ce.BlockAdditions,data:[{id:ce.BlockMore,data:[{id:ce.BlockAddID,data:1},{id:ce.BlockAdditional,data:e.additions}]}]}:null,h>0?{id:ce.BlockDuration,data:h}:null]};this.ebmlWriter.writeEBML(r)}else{a.setUint8(3,Number("key"===e.type)<<7);const t={id:ce.SimpleBlock,data:[s,e.data]};this.ebmlWriter.writeEBML(t)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+h),t.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(t)||this.trackDatasInCurrentCluster.set(t,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(t){t=Math.max(0,t),this.currentCluster&&this.finalizeCurrentCluster(),this.format.Rt.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:ce.Cluster,size:this.format.Rt.appendOnly?-1:5,data:[{id:ce.Timestamp,data:t}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=t,this.currentClusterMaxMsTimestamp=t,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(z(this.currentCluster),!this.format.Rt.appendOnly){const t=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),e=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(t,5),this.writer.seek(e)}if(this.format.Rt.onCluster){z(null!==this.currentClusterStartMsTimestamp);const{data:t,start:e}=this.writer.stopTrackingWrites();this.format.Rt.onCluster(t,e,this.currentClusterStartMsTimestamp/1e3)}const t=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,e=new Map;for(const[r,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)e.has(n)||e.set(n,[]),e.get(n).push(r);const i=[...e.entries()].sort((t,e)=>t[0]-e[0]);for(const[r,n]of i)z(this.cues),this.cues.data.push({id:ce.CuePoint,data:[{id:ce.CueTime,data:Math.max(0,r)},...n.map(e=>({id:ce.CueTrackPositions,data:[{id:ce.CueTrack,data:e.track.id},{id:ce.CueClusterPosition,data:t}]}))]})}async onTrackClose(t){const e=await this.mutex.acquire(),i=this.trackDatas.find(e=>e.track===t);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const t=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),z(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format.Rt.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,6);const e=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Qe(e),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),z(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}t()}},Xn=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},Zn=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}),Qn=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})()}},Yn=class extends Qn{constructor(t){if(super(),this.we=null,!xe.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${xe.join(", ")}.`);this.Ot=t}},Jn=(t,e)=>{if(t.metadata.hasOnlyKeyPackets&&"key"!==e.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Kn=class{setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}constructor(t,e){this.source=t,this.encodingConfig=e,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new pt,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(t,e,i){const r=t;try{this.checkForEncoderError(),this.source.be();const n=this.encodingConfig,o=n.sizeChangeBehavior??"deny";let s=!1;if(null!==this.codedWidth&&null!==this.codedHeight){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(s=!0,"deny"===o))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(void 0!==n.transform?.width||void 0!==n.transform?.height||void 0!==n.transform?.rotate||void 0!==n.transform?.crop||!0===n.transform?.force||s&&"passThrough"!==o){let i=n.transform?.width,r=n.transform?.height,a=n.transform?.fit??"fill";s&&"passThrough"!==o&&(z(this.outputWidth),z(this.outputHeight),z("deny"!==o),i=this.outputWidth,r=this.outputHeight,a=o);const h=await t.transform({width:i,height:r,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,fit:a,alpha:n.alpha});null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=h.displayWidth,this.outputHeight=h.displayHeight),e&&t.close(),t=h,e=!0}else null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);const a=n.transform?.frameRate;if(void 0!==a){const n=t.timestamp+t.duration,o=lt(t.timestamp,a);if(null!==this.frameRateLastSample){if(o<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),void(this.frameRateLastEndTimestamp=n);await this.padFrameRate(o,i)}t===r&&(t=t.clone(),e=!0),t.setTimestamp(o),t.setDuration(1/a),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=o,this.frameRateLastEndTimestamp=n}await this.processAndEncode(t,i)}finally{e&&t.close()}}async processAndEncode(t,e){const i=this.encodingConfig;let r;if(i.transform?.process){let e=i.transform.process(t);if(Et(e)&&(e=await e),null===e)return;Array.isArray(e)||(e=[e]);const o=[];try{for(const i of e)i instanceof fi?o.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?o.push(new fi(i)):o.push(new fi(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 fi&&i!==t||"undefined"!=typeof VideoFrame&&i instanceof VideoFrame)&&i.close();throw n}r=o}else r=[t];try{for(const t of r){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),z(this.encoderInitialized),this.closed)break;const i=this.encodingConfig.keyFrameInterval??2,r=Math.floor(t.timestamp/i),n={...this.defaultEncodeOptions,...t.encodeOptions,...e},o={...n,keyFrame:void 0!==n.keyFrame?n.keyFrame:0===i||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;const e=t.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(e,o)).catch(t=>this.setError(t)).finally(()=>{this.customEncoderQueueSize--,e.close()});this.customEncoderQueueSize>=4&&await i}else{z(this.encoder);const e=t.toVideoFrame(),i=rt(this.preciseTimings,e.timestamp,t=>t.microsecondTimestamp),r=-1!==i?this.preciseTimings[i]:null;if(r&&r.microsecondTimestamp===e.timestamp?(r.timestamp!==t.timestamp&&(r.timestampIsValid=!1),r.duration!==t.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(i+1,0,{microsecondTimestamp:e.timestamp,timestamp:t.timestamp,duration:t.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(e.format&&!e.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(e,o)}finally{e.close()}}else{this.splitter||(this.splitter=new eo);const{colorFrame:t,alphaFrame:i}=await this.splitter.split(e);this.alphaFrameQueue.push(i);try{this.encoder.encode(t,o)}finally{t.close()}}else try{this.encoder.encode(e,o)}finally{e.close()}this.encoder.encodeQueueSize>=4&&await new Promise(t=>this.encoder.addEventListener("dequeue",t,{once:!0}))}await this.lastMuxerPromise}}finally{for(const e of r)e!==t&&e.close()}}async padFrameRate(t,e){const i=this.encodingConfig.transform.frameRate;z(this.frameRateLastSample);const r=Math.round((t-this.frameRateLastTimestamp)*i);for(let o=1;o<r;o++){const t={stack:[],error:void 0,hasError:!1};try{const r=Xn(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{Zn(t)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{const e=Vi(this.encodingConfig.quality,this.encodingConfig.bitrate);z(void 0!==e);const i=Ii({...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=Ui.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=Di(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 Xe))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.");Jn(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=Xe.fromEncodedChunk(t,r);const o=rt(this.preciseTimings,t.timestamp,t=>t.microsecondTimestamp),s=-1!==o?this.preciseTimings[o]:null;let a=null;0===this.emittedEncoderPackets&&"delta"===n.type&&i?.decoderConfig&&(a=((t,e,i)=>{switch(t){case"avc":for(const t of((t,e)=>{if(e.description){const i=1+(3&X(e.description)[4]);return Xt(t,i)}return Wt(t)})(i,e)){const e=i[t.offset],r=Zt(e);if(r>=Ft.NON_IDR_SLICE&&r<=Ft.SLICE_DPC)return"delta";if(r===Ft.IDR)return"key";if(r===Ft.SEI&&!gt()){const e=i.subarray(t.offset,t.offset+t.length),r=Qt(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 Dt(r);t.pos=8*n;const e=H(t),i=t.readBits(1);if(0===e&&1===i)return"key"}n+=e}while(n<r.length-1)}}return"delta";case"hevc":for(const t of((t,e)=>{if(e.description){const i=1+(3&X(e.description)[21]);return Xt(t,i)}return Wt(t)})(i,e)){const e=Kt(i[t.offset]);if(e<Ot.BLA_W_LP)return"delta";if(e<=Ot.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const t=new Dt(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 Dt(t),i=()=>{let t=0;for(let i=0;i<8;i++){const r=e.readAlignedByte();if(t+=(127&r)*2**(7*i),!(128&r))break;if(7===i&&128&r)return null}return t>2**32-1?null:t};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),n=e.readBits(1),o=e.readBits(1);let s;if(e.skipBits(1),n&&e.skipBits(8),o){const t=i();if(null===t)return;s=t}else s=Math.floor(e.getBitsLeft()/8);z(e.pos%8==0),yield{type:r,data:t.subarray(e.pos/8,e.pos/8+s)},e.skipBits(8*s)}}(i))if(1===e){const e=new Dt(r);e.skipBits(4),t=!!e.readBits(1)}else if(3===e||6===e||7===e){if(t)return"key";const e=new Dt(r);return e.readBits(1)?null:0===e.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:ot(t),z(!1)}})(this.encodingConfig.codec,i.decoderConfig,n.data)),(s&&s.microsecondTimestamp===t.timestamp||null!==a)&&(n=n.clone({timestamp:s?.timestampIsValid?s.timestamp:void 0,duration:s?.durationIsValid?s.duration:void 0,type:a??void 0})),Jn(this.source.we,n),this.encodingConfig.onEncodedPacket?.(n,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source.we,n,i).catch(t=>{this.setError(t)}),this.emittedEncoderPackets++},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(o,s)=>{if(!this.alphaEncoder)return void n(o,null,s);const a=this.alphaFrameQueue.shift();z(void 0!==a),a?(this.alphaEncoder.encode(a,{...this.defaultEncodeOptions,keyFrame:"key"===o.type}),r++,a.close(),t.push({chunk:o,meta:s})):0===r?n(o,null,s):(e.push(i+r),t.push({chunk:o,meta:s}))},error:t=>{t.stack=o,this.setError(t)}}),this.encoder.configure(s),"keep"===this.encodingConfig.alpha){const o=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(o,s)=>{r--;const a=t.shift();for(z(void 0!==a),n(a.chunk,o,a.meta),i++;e.length>0&&e[0]===i;){e.shift();const i=t.shift();z(void 0!==i),n(i.chunk,null,i.meta)}},error:t=>{t.stack=o,this.setError(t)}}),this.alphaEncoder.configure(s)}}z(this.source.we),this.muxer=this.source.we.output.ge,this.encoderInitialized=!0})()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,e=lt(this.frameRateLastEndTimestamp,t);await this.padFrameRate(e)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await(this.alphaEncoder?.flush()),await new Promise(t=>setTimeout(t,25))))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):this.encoder&&("closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},to=null,eo=class{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(t){if(!this.worker){if(!to){const t=new Blob([`(${io.toString()})()`],{type:"application/javascript"});to=URL.createObjectURL(t)}this.worker=new Worker(to),this.worker.addEventListener("message",t=>{const e=t.data,i=this.pendingRequests.get(e.id);i&&(this.pendingRequests.delete(e.id),"error"in e?i.reject(new Error(e.error)):i.resolve({colorFrame:e.colorFrame,alphaFrame:e.alphaFrame}))}),this.worker.addEventListener("error",t=>{const e=new Error(t.message||"Color/alpha splitter worker error.");for(const i of this.pendingRequests.values())i.reject(e);this.pendingRequests.clear()})}const e=this.nextRequestId++,i=nt();return this.pendingRequests.set(e,i),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const t=new Error("Color/alpha splitter closed.");for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},io=()=>{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)}}},ro=class extends Yn{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(!xe.includes(t.codec))throw new TypeError(`Invalid video codec '${t.codec}'. Must be one of: ${xe.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 Bi))throw new TypeError("config.quality, when provided, must be a Quality.");if(void 0!==e&&!(e instanceof Bi)&&(!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&&xi(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.");Pi(t.codec,t)})(e),super(e.codec),this.Ee=new Kn(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 fi(this.Te,{timestamp:t,duration:e});return this.Ee.add(r,!0,i)}ye(t){return this.Ee.flushAndClose(t)}},no=class extends Qn{constructor(t){if(super(),this.we=null,!ke.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${ke.join(", ")}.`);this.Ot=t}},oo=class extends Qn{constructor(t){if(super(),this.we=null,!_e.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${_e.join(", ")}.`);this.Ot=t}},so=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>xe.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>ke.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>_e.includes(t))}ke(t){return""}_e(){return!1}},ao=class extends so{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&&(!Mt(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 qn(t,this)}_e(){return"fragmented"===this.Rt.fastStart}},ho=class extends ao{constructor(t){super(t)}get Ae(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...xe,...Te,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",..._e]}ke(t){return(new lo).getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},co=class extends ao{constructor(t){super(t)}get Ae(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...xe,...Te,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",..._e]}},lo=class extends ao{constructor(t){super(t)}get Ae(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...xe,...ke]}ke(t){return(new ho).getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},uo=class extends so{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&&(!Mt(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 Wn(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[...xe,...Te,...Ee.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),..._e]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},fo=class extends uo{constructor(t){super(t)}getSupportedCodecs(){return[...xe.filter(t=>["vp8","vp9","av1"].includes(t)),...ke.filter(t=>["opus","vorbis"].includes(t)),..._e]}get Ae(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}ke(t){return(new uo).getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},po=["video","audio","subtitle"],mo=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=Ct(this.metadata.group),r=Ct(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}},wo=class extends mo{constructor(t,e,i,r){super(t,e,"video",i,r)}},vo=class extends mo{constructor(t,e,i,r){super(t,e,"audio",i,r)}},bo=class extends mo{constructor(t,e,i,r){super(t,e,"subtitle",i,r)}},yo=class t{constructor(){this.Se=new Set}pairWith(e){if(!(e instanceof t))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this.Se.add(e),e.Se.add(this)}},go=t=>{if(!t||"object"!=typeof t)throw new TypeError("metadata must be an object.");if(void 0!==t.languageCode&&!(t=>ut.test(t))(t.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==t.name&&"string"!=typeof t.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==t.disposition&&(t=>{if(!t||"object"!=typeof t)throw new TypeError("disposition must be an object.");if(void 0!==t.default&&"boolean"!=typeof t.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==t.primary&&"boolean"!=typeof t.primary)throw new TypeError("disposition.primary must be a boolean.");if(void 0!==t.forced&&"boolean"!=typeof t.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==t.original&&"boolean"!=typeof t.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==t.commentary&&"boolean"!=typeof t.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==t.hearingImpaired&&"boolean"!=typeof t.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==t.visuallyImpaired&&"boolean"!=typeof t.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(t.disposition),void 0!==t.maximumPacketCount&&(!Number.isInteger(t.maximumPacketCount)||t.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==t.group&&!(t.group instanceof yo)&&(!Array.isArray(t.group)||t.group.some(t=>!(t instanceof yo))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},xo=class extends Pt{get target(){const t="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this.Ce)throw new TypeError(t);const e=this.Pe();if(Et(e))throw new TypeError(t);return e}constructor(t){if(super(),this.state="pending",this.defaultTrackGroup=new yo,this.tracks=[],this.Ie=null,this.Be=new Set,this.Fe=null,this.Oe=null,this.Re=null,this.$e=null,this.De=new it,this.$t={},this.Ne=null,this.Ce=null,this.Ve=null,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!(t.format instanceof so))throw new TypeError("options.format must be an OutputFormat.");if(!(t.target instanceof On||t.target instanceof Un))throw new TypeError("options.target must be a Target or a PathedTarget.");if(t.target instanceof On&&this.Ue(t.target),void 0!==t.initTarget&&!(t.initTarget instanceof On)&&"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 On&&this.Ue(this.je),this.ge=t.format.Me(this)}Le(t){z(this.ze instanceof Un);const e=this.ze.getTarget(t),i=t=>{if(!(t instanceof On))throw new TypeError("getTarget must return a Target.");return t};return Et(e)?e.then(i):i(e)}async qe(t){z(this.ze instanceof Un);const e=await this.Le(t);return this.ct("target",{target:e,request:t,isRoot:t.isRoot}),"canceled"===this.state?await e.Qt():this.Ue(e),e}Ue(t){this.Be.add(t),t.on("finalized",()=>this.Be.delete(t),{once:!0})}async me(){if(z(null!==this.je),this.je instanceof On)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 On)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 Et(e)?this.Ce=e.then(i):i(e)}fe(t){return this.Fe??=(async()=>{const e=await this.Pe(),i=new Fn(e,"boolean"==typeof t?t:t(e));return i.start(),i})()}addVideoTrack(t,e={}){if(!(t instanceof Yn))throw new TypeError("source must be a VideoSource.");if(go(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&&Le({decoderConfig:e.decoderConfig},t.Ot),void 0!==e.primingPacket){if(!(e.primingPacket instanceof Xe))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))}addAudioTrack(t,e={}){if(!(t instanceof no))throw new TypeError("source must be an AudioSource.");if(go(e),void 0!==e.decoderConfig&&Ge({decoderConfig:e.decoderConfig},t.Ot),void 0!==e.primingPacket){if(!(e.primingPacket instanceof Xe))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 vo(this.tracks.length+1,this,t,i))}addSubtitleTrack(t,e={}){if(!(t instanceof oo))throw new TypeError("source must be a SubtitleSource.");go(e);const i={...e};return i.group??=this.defaultTrackGroup,this.Ge(new bo(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 Rt||e instanceof $t||It(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 po)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 po){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?(Bt.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?(Bt.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&&Bt.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?(Bt.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 Eo(t,e,i,r){return new Promise((n,o)=>{if(i?.aborted)return void o(D());let s=!1;const a=setTimeout(()=>h(()=>o(N(e))),r),h=t=>{s||(s=!0,clearTimeout(a),i?.removeEventListener("abort",c),t())},c=()=>h(()=>o(D()));i?.addEventListener("abort",c,{once:!0}),t.then(t=>h(()=>n(t)),t=>h(()=>o(t)))})}var To=["vp9","vp8"],ko=["avc"],_o=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 ho:new fo,s="stream"===r.kind?new Nn(r.writable,{chunked:!0}):new Dn,a=new xo({format:o,target:s}),h=new ro(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 Eo(a.start(),"Video output did not start within 30000ms.",t.signal,3e4),await e.$render({frameCount:n.frameCount,frameRate:n.frameRate,signal:t.signal,prepareFrame:t.prepareFrame,onFrame:async({frameIndex:e})=>{this.I(t.signal);const r=y(e,n.frameRate);await this.Ye(h.add(r.startSeconds,r.durationSeconds),t.signal),this.Ze(i,"recording","capturing",e+1,n.frameCount,n)}}),this.I(t.signal),d(),this.Ze(i,"encoding","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),await Eo(a.finalize(),"Video output did not finalize within 30000ms.",t.signal,3e4),this.Ze(i,"completed","stream"===r.kind?"writing":"finalizing",n.frameCount,n.frameCount,n),"stream"===r.kind)return;const o=s;if(!o.buffer)throw new $("VIDEO_EXPORT_FAILED","Video encoder finalized without producing data.");return new Blob([o.buffer],{type:n.mimeType})}catch(u){d(),await(async()=>{if(!l){l=!0;try{await a.cancel()}catch{}}})();const t=this.Je(u);throw i?.({state:"error",message:t.message}),t}}async We(t){const e=U(t),i="mp4"===t.format?new ho:new fo,r="mp4"===t.format?ko:To,n=i.getSupportedVideoCodecs().filter(t=>r.includes(t));for(const o of n)if(await Ni(o,{width:e.width,height:e.height,quality:this.Qe(e),alpha:e.transparent?"keep":"discard",latencyMode:"quality",hardwareAcceleration:e.hardwareAcceleration,contentHint:"text"}))return U(t,o);throw new $("VIDEO_CODEC_UNSUPPORTED",`This browser cannot encode ${r.join(" or ")} video at ${e.width}x${e.height}. Try another format, lower the export dimensions, or change the encoder preference.`)}Qe(t){return new Bi(t.quality)}He(){const t=globalThis;if("function"!=typeof t.VideoEncoder||"function"!=typeof t.VideoFrame)throw new $("VIDEO_EXPORT_UNSUPPORTED","Video export requires native WebCodecs VideoEncoder and VideoFrame support. This browser cannot produce deterministic video exports without a native encoder.")}Ye(t,e){return e?new Promise((i,r)=>{if(e.aborted)return void r(D());const n=()=>r(D());e.addEventListener("abort",n,{once:!0}),t.then(t=>{e.removeEventListener("abort",n),i(t)},t=>{e.removeEventListener("abort",n),r(t)})}):t}I(t){if(t?.aborted)throw D()}Ze(t,e,i,r,n,o){t?.({state:e,phase:i,frameIndex:r,frame:r,totalFrames:n,progress:n>0?r/n:0,codec:o.codec,codedWidth:o.width,codedHeight:o.height,frameRate:o.frameRate})}Je(t){return V(t)}Xe(t,...e){t.debugLogging&&console.debug("[textmode-export]",...e)}},Mo=class{Ke;T;k;constructor(t,e){this.Ke=new _o,this.T=t,this.k=e}async $saveVideo(t={}){const e=t.format??"mp4",i=this.Z(e,t),r=U(i);if("file-system"===t.destination){const n=await this.ti((new s).$resolve(t.filename,`.${e}`),r.mimeType);try{await this.ei(i,n,t.onProgress)}catch(o){try{await(n.abort?.(o))}catch{}throw o}return}const n=await this.ei(i,{kind:"blob"},t.onProgress);if(!n)throw new $("VIDEO_EXPORT_FAILED","Video export did not produce a downloadable file.");(new a).$downloadFile(n,t.filename,`.${e}`)}async $generateVideoBlob(t={}){const e=t.format??"mp4",i=this.Z(e,t);U(i);const r=await this.ei(i,{kind:"blob"},t.onProgress);if(!r)throw new $("VIDEO_EXPORT_FAILED","Video export did not produce an in-memory file.");return r}async ei(t,e,i){const r=new g(this.T,this.k,{width:t.width,height:t.height});try{return await this.Ke.$record(t,r,i,e)}catch(n){if(i?.({state:"error",message:n instanceof Error?n.message:`${t.format.toUpperCase()} export failed`}),n instanceof p||w(n))throw V(n);throw n}}Z(t,e){const i=this.ii(e.frameRate,60),r=this.ri(e.frameCount,300),n=this.ii(e.pixelDensity,1),o=this.ni(),s=Math.max(1,Math.round(this.T.canvas.width/o*n)),a=Math.max(1,Math.round(this.T.canvas.height/o*n));return{filename:e.filename,format:t,frameRate:i,frameCount:r,quality:this.At(e.quality),hardwareAcceleration:this.oi(e.hardwareAcceleration),keyFrameInterval:this.si(e.keyFrameInterval),pixelDensity:n,width:s,height:a,transparent:Boolean(e.transparent),debugLogging:Boolean(e.debugLogging),signal:e.signal,prepareFrame:e.prepareFrame}}ri(t,e){return Number.isFinite(t)?Math.max(1,Math.round(Math.abs(t))):e}ii(t,e){return Number.isFinite(t)?Math.max(Number.EPSILON,Math.abs(t)):e}At(t){if(void 0===t)return"medium";if("very-low"===t||"low"===t||"medium"===t||"high"===t||"very-high"===t)return t;if("object"!=typeof t||null===t||!Number.isFinite(t.bitrate)||t.bitrate<=0)throw new TypeError("Video quality must be a Mediabunny quality level or a positive bitrate.");if(void 0!==t.bitrateMode&&!this.ai(t.bitrateMode))throw new TypeError("Video quality bitrateMode must be 'variable' or 'constant'.");return t.bitrateMode?{bitrate:t.bitrate,bitrateMode:t.bitrateMode}:{bitrate:t.bitrate}}ai(t){return"constant"===t||"variable"===t}oi(t){return"prefer-hardware"===t||"prefer-software"===t||"no-preference"===t?t:"no-preference"}si(t){return Number.isFinite(t)?Math.max(0,Math.abs(t)):2}ni(){const t=this.T.pixelDensity?.();return"number"==typeof t&&Number.isFinite(t)&&t>0?t:1}async ti(t,e){const i=globalThis;if(!i.showSaveFilePicker)throw new $("VIDEO_EXPORT_UNSUPPORTED","This browser cannot stream video exports to disk because the File System Access API is unavailable.");const r=await(await i.showSaveFilePicker({suggestedName:t,types:[{description:"Video file",accept:{[e]:[t.slice(t.lastIndexOf("."))]}}]})).createWritable();let n=!1;return{kind:"stream",writable:new WritableStream({write:t=>r.write(t),async close(){n=!0,await r.close()},async abort(t){n=!0,await r.abort(t)}}),async abort(t){n||(n=!0,await r.abort(t))}}}},Ao=class extends r{$extractCellData(t){const e=this.$extractFramebufferData(t.drawFramebuffer),i=[],r=t.grid,n=t.font;let o=0;for(let s=0;s<r.rows;s++)for(let t=0;t<r.cols;t++){const r=4*o,a=this.$getEncodedCharacterValue(e.characterPixels,r),h=this.$extractCellTransform(e.characterPixels,r),c=l(n,a)?.character??" ";i.push({x:t,y:s,character:c,foreground:x(e.primaryColorPixels,r),background:x(e.secondaryColorPixels,r),transform:{invert:h.isInverted,flipX:h.flipHorizontal,flipY:h.flipVertical,rotation:h.rotation}}),o++}return i}},So="1.9.0-beta.2",Co="textmode.document",Po="2.0.0",Io="object-rows-v1",Bo={[e.LayerBlendMode.NORMAL]:"normal",[e.LayerBlendMode.ADDITIVE]:"additive",[e.LayerBlendMode.MULTIPLY]:"multiply",[e.LayerBlendMode.SCREEN]:"screen",[e.LayerBlendMode.SUBTRACT]:"subtract",[e.LayerBlendMode.DARKEN]:"darken",[e.LayerBlendMode.LIGHTEN]:"lighten",[e.LayerBlendMode.OVERLAY]:"overlay",[e.LayerBlendMode.SOFT_LIGHT]:"softLight",[e.LayerBlendMode.HARD_LIGHT]:"hardLight",[e.LayerBlendMode.COLOR_DODGE]:"colorDodge",[e.LayerBlendMode.COLOR_BURN]:"colorBurn",[e.LayerBlendMode.DIFFERENCE]:"difference",[e.LayerBlendMode.EXCLUSION]:"exclusion"},Fo=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:So}}: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:Io,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 Ao).$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:Bo[t.blendMode],offsetX:t.offsetX,offsetY:t.offsetY,rotationZ:t.rotationZ,grid:this.di(t),cells:this.ui(t,e)}}$generateJSONData(t,i={},r=new Date){const n=this.Z(i),o=this.hi(n,r);if("all"===n.target){const i=function(t){return[t.layers.base,...t.layers.all].map(i=>{const r=f(t,i),n=i.offset();return{...r,visible:i.isVisible(),opacity:i.opacity()??1,blendMode:i.blendMode()??e.LayerBlendMode.NORMAL,offsetX:n?.x??0,offsetY:n?.y??0,rotationZ:i.rotateZ()??0}})}(t),r=i[0].grid;return{format:Co,formatVersion:Po,target:"all",...o?{metadata:o}:{},canvas:{width:r.width,height:r.height},layers:i.map(t=>this.fi(t,n))}}const s=f(t,n.layer);return{format:Co,formatVersion:Po,target:"selected",...o?{metadata:o}:{},canvas:{width:s.grid.width,height:s.grid.height},grid:this.di(s),layer:{id:s.id,cells:this.ui(s,n)}}}$generateJSONString(t,e={},i=new Date){const r=this.Z(e),n=this.$generateJSONData(t,r,i),o="number"==typeof r.pretty?r.pretty:r.pretty?2:0;return JSON.stringify(n,null,o)}$saveJSON(t,e={}){const i=this.Z(e);(new a).$downloadFile(new Blob([this.$generateJSONString(t,i)],{type:"application/json;charset=utf-8"}),i.filename,".json")}},Oo=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 Ro(t){return new Oo("ZIP_EXPORT_ABORTED","ZIP frame-sequence export was cancelled.",t)}function $o(t){if(t instanceof Oo)return t;if(w(t))return Ro(t);if(t instanceof p){if("FRAME_SEQUENCE_TIMEOUT"===t.code)return new Oo("ZIP_EXPORT_TIMEOUT",t.message,t);if("FRAME_SEQUENCE_BUSY"===t.code)return new Oo("ZIP_EXPORT_BUSY",t.message,t);if("FRAME_SEQUENCE_DISPOSED"===t.code)return new Oo("ZIP_EXPORT_DISPOSED",t.message,t)}return new Oo("ZIP_EXPORT_FAILED",t instanceof Error?t.message:"ZIP frame-sequence export failed.",t)}var Do=new TextEncoder;function No(t){if(!t||"object"!=typeof t||Array.isArray(t))return{};const e={...t};return delete e.filename,delete e.format,e}function Vo(t){const e=new A;return{extension:`.${t}`,compression:"store",getDimensions({canvas:t,frameOptions:e}){const i=No(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,{...No(r),format:t}),o=M[t];if(n.type.toLowerCase()!==o)throw new Oo("ZIP_EXPORT_ENCODING_UNSUPPORTED",`The browser returned '${n.type||"an unknown format"}' instead of '${o}'.`);return new Uint8Array(await n.arrayBuffer())}}}function Uo(t,e){return{extension:`.${t}`,compression:"deflate",getDimensions({frameOptions:i}){const r=No(i),n="json"===t&&"all"===r.target?f(e):f(e,r.layer);return{width:n.grid.width,height:n.grid.height}},async serialize({frameOptions:i,createdAt:r}){const n=No(i);let o;return o="svg"===t?(new _).$generateSVG(e,n):"json"===t?(new Fo).$generateJSONString(e,n,r):(new S).$generateTXT(e,n),Do.encode(o)}}}var zo=Uint8Array,jo=Uint16Array,Lo=Int32Array,qo=new zo([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]),Go=new zo([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]),Ho=new zo([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Wo=function(t,e){for(var i=new jo(31),r=0;r<31;++r)i[r]=e+=1<<t[r-1];var n=new Lo(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}},Xo=Wo(qo,2),Zo=Xo.b,Qo=Xo.r;Zo[28]=258,Qo[258]=28;for(var Yo=Wo(Go,0),Jo=(Yo.b,Yo.r),Ko=new jo(32768),ts=0;ts<32768;++ts){var es=(43690&ts)>>1|(21845&ts)<<1;es=(61680&(es=(52428&es)>>2|(13107&es)<<2))>>4|(3855&es)<<4,Ko[ts]=((65280&es)>>8|(255&es)<<8)>>1}var is=function(t,e,i){for(var r=t.length,n=0,o=new jo(e);n<r;++n)t[n]&&++o[t[n]-1];var s,a=new jo(e);for(n=1;n<e;++n)a[n]=a[n-1]+o[n-1]<<1;if(i){s=new jo(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[Ko[d]>>h]=c}else for(s=new jo(r),n=0;n<r;++n)t[n]&&(s[n]=Ko[a[t[n]-1]++]>>15-t[n]);return s},rs=new zo(288);for(ts=0;ts<144;++ts)rs[ts]=8;for(ts=144;ts<256;++ts)rs[ts]=9;for(ts=256;ts<280;++ts)rs[ts]=7;for(ts=280;ts<288;++ts)rs[ts]=8;var ns=new zo(32);for(ts=0;ts<32;++ts)ns[ts]=5;var os=is(rs,9,0),ss=is(ns,5,0),as=function(t){return(t+7)/8|0},hs=function(t,e,i){return(null==e||e<0)&&(e=0),(null==i||i>t.length)&&(i=t.length),new zo(t.subarray(e,i))},cs=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ls=function(t,e,i){var r=new Error(e||cs[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,ls),!i)throw r;return r},ds=function(t,e,i){i<<=7&e;var r=e/8|0;t[r]|=i,t[r+1]|=i>>8},us=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},fs=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:gs,l:0};if(1==n){var s=new zo(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 jo(u+1),p=ps(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 zo(f),l:p}},ps=function(t,e,i){return-1==t.s?Math.max(ps(t.l,e,i+1),ps(t.r,e,i+1)):e[t.s]=i},ms=function(t){for(var e=t.length;e&&!t[--e];);for(var i=new jo(++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}},ws=function(t,e){for(var i=0,r=0;r<e.length;++r)i+=t[r]*e[r];return i},vs=function(t,e,i){var r=i.length,n=as(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)},bs=function(t,e,i,r,n,o,s,a,h,c,l){ds(e,l++,i),++n[256];for(var d=fs(n,15),u=d.t,f=d.l,p=fs(o,15),m=p.t,w=p.l,v=ms(u),b=v.c,y=v.n,g=ms(m),x=g.c,E=g.n,T=new jo(19),k=0;k<b.length;++k)++T[31&b[k]];for(k=0;k<x.length;++k)++T[31&x[k]];for(var _=fs(T,7),M=_.t,A=_.l,S=19;S>4&&!M[Ho[S-1]];--S);var C,P,I,B,F=c+5<<3,O=ws(n,rs)+ws(o,ns)+s,R=ws(n,u)+ws(o,m)+s+14+3*S+ws(T,M)+2*T[16]+3*T[17]+7*T[18];if(h>=0&&F<=O&&F<=R)return vs(e,l,t.subarray(h,h+c));if(ds(e,l,1+(R<O)),l+=2,R<O){C=is(u,f,0),P=u,I=is(m,w,0),B=m;var $=is(M,A,0);for(ds(e,l,y-257),ds(e,l+5,E-1),ds(e,l+10,S-4),l+=14,k=0;k<S;++k)ds(e,l+3*k,M[Ho[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];ds(e,l,$[U]),l+=M[U],U>15&&(ds(e,l,V[k]>>5&127),l+=V[k]>>12)}}}else C=os,P=rs,I=ss,B=ns;for(k=0;k<a;++k){var z=r[k];if(z>255){us(e,l,C[257+(U=z>>18&31)]),l+=P[U+257],U>7&&(ds(e,l,z>>23&31),l+=qo[U]);var j=31&z;us(e,l,I[j]),l+=B[j],j>3&&(us(e,l,z>>5&8191),l+=Go[j])}else us(e,l,C[z]),l+=P[z]}return us(e,l,C[256]),l+P[256]},ys=new Lo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),gs=new zo(0),xs=function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var i=e,r=9;--r;)i=(1&i&&-306674912)^i>>>1;t[e]=i}return t}(),Es=function(t,e,i){for(;i;++e)t[e]=i,i>>>=8},Ts=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 zo(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 zo(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 zo(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=ys[e-1],u=d>>13,f=8191&d,p=(1<<i)-1,m=o.p||new jo(32768),w=o.h||new jo(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 Lo(25e3),x=new jo(288),E=new jo(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=bs(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|Qo[O]<<18|Jo[R];var H=31&Qo[O],W=31&Jo[R];k+=qo[H]+Go[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=bs(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=vs(h,l+1,t.subarray(_,X))}o.i=s}return hs(a,0,r+as(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||ls(5),this.s.l&&ls(4);var i=t.length+this.s.z;if(i>this.b.length){if(i>2*this.b.length-32768){var r=new zo(-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=gs)},t.prototype.flush=function(t){if(this.ondata||ls(5),this.s.l&&ls(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2,t){var e=new zo(6);e[0]=this.s.r>>3;var i=vs(e,this.s.r,gs);this.s.r=0,this.ondata(e.subarray(0,i>>3),!1)}},t}(),ks="undefined"!=typeof TextEncoder&&new TextEncoder,_s="undefined"!=typeof TextDecoder&&new TextDecoder;try{_s.decode(gs,{stream:!0})}catch(ja){}function Ms(t,e){if(e){for(var i=new zo(t.length),r=0;r<t.length;++r)i[r]=t.charCodeAt(r);return i}if(ks)return ks.encode(t);var n=t.length,o=new zo(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 zo(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 hs(o,0,s)}var As=function(t){var e=0;if(t)for(var i in t){var r=t[i].length;r>65535&&ls(9),e+=r+4}return e},Ss=function(t,e,i,r,n,o,s,a){var h=r.length,c=i.extra,l=a&&a.length,d=As(c);Es(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)&&ls(10),Es(t,e,f<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,-1!=o&&(Es(t,e,i.crc),Es(t,e+4,o<0?-o-2:o),Es(t,e+8,i.size)),Es(t,e+12,h),Es(t,e+14,d),e+=16,null!=s&&(Es(t,e,l),Es(t,e+6,i.attrs),Es(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;Es(t,e,+p),Es(t,e+2,w),t.set(m,e+4),e+=4+w}return l&&(t.set(a,e),e+=l),e},Cs=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=xs[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||ls(5),this.c.p(t),this.size+=t.length,e&&(this.crc=this.c.d()),this.process(t,e||!1)},t}(),Ps=function(){function t(t,e){var i,r=this;e||(e={}),Cs.call(this,t),this.d=new Ts(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(ja){this.ondata(ja,null,e)}},t.prototype.push=function(t,e){Cs.prototype.push.call(this,t,e)},t}(),Is=function(){function t(t){this.ondata=t,this.u=[],this.d=1}return t.prototype.add=function(t){var e=this;if(this.ondata||ls(5),2&this.d)this.ondata(ls(4+8*(1&this.d),0,1),null,!1);else{var i=Ms(t.filename),r=i.length,n=t.comment,o=n&&Ms(n),s=r!=t.filename.length||o&&n.length!=o.length,a=r+As(t.extra)+30;r>65535&&this.ondata(ls(11,0,1),null,!1);var h=new zo(a);Ss(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 zo(16);Es(o,0,134695760),Es(o,4,t.crc),Es(o,8,p),Es(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(ls(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+As(f.extra)+(f.o?f.o.length:0);for(var o,s,a,h,c,l=new zo(i+22),d=0,u=this.u;d<u.length;d++){var f=u[d];Ss(l,t,f,f.f,f.u,-f.c-2,e,f.o),t+=46+f.f.length+As(f.extra)+(f.o?f.o.length:0),e+=f.b}o=l,s=t,a=this.u.length,h=i,c=e,Es(o,s,101010256),Es(o,s+8,a),Es(o,s+10,a),Es(o,s+12,h),Es(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}(),Bs=class{pi;re=[];mi=new Set;wi;bi;yi="open";gi=0;xi;Ei;Ti;constructor(t,e=4294967295){this.wi=t,this.bi=e,this.pi=new Is((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 Oo("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 Oo("ZIP_EXPORT_FAILED",`Duplicate ZIP entry: ${t}`);if(this.mi.size>=65535)throw new Oo("ZIP_EXPORT_TOO_LARGE","Classic ZIP archives cannot contain more than 65,535 entries.");if(e.byteLength>this.bi)throw new Oo("ZIP_EXPORT_TOO_LARGE",`A classic ZIP entry cannot exceed ${this.bi.toLocaleString("en-US")} bytes.`);const r="store"===i?new Cs(t):new Ps(t,{level:6});if(r.mtime=this.wi,this.mi.add(t),this.pi.add(r),(r instanceof Cs||r instanceof Ps)&&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=Ro()){"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 Oo("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 Oo("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)}},Fs=new Set(["png","jpg","webp","svg","json","txt"]),Os=class{T;k;Ai;constructor(t,e,i={}){this.T=t,this.k=e,this.Ai=i}async $saveZIP(t){await this.Si(t,({blob:t,filename:e})=>{(new a).$downloadFile(t,e,".zip")})}async $generateZIPBlob(t){return(await this.Si(t)).blob}async Si(t,e){try{return await this.Ci(t,e)}catch(i){const e=$o(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 $o(r)}throw e}}async Ci(t,e){const i=this.Ii(t),r=this.Ai.now?.()??new Date,n=(new s).$resolve(i.filename,".zip",r),o=n.slice(0,-4);let a,h=!1,c=0;try{this.I(i.signal);const t=(l=this.T,{png:Vo("png"),jpg:Vo("jpg"),webp:Vo("webp"),svg:Uo("svg",l),json:Uo("json",l),txt:Uo("txt",l)}),s=this.Ai.resolveSerializer?.(i.format)??t[i.format];a=this.Ai.createWriter?.(r)??new Bs(r);const d=a,u=this.Ai.createDriver?.()??new g(this.T,this.k),f=s.getDimensions({canvas:u.canvas,frameOptions:i.frameOptions});this.Ze(i,{state:"capturing",frameIndex:0,totalFrames:i.frameCount,progress:0}),this.I(i.signal);const p=function(t){return{schema:"textmode.frame-sequence",schemaVersion:"1.0.0",generator:{name:"textmode.export.js",version:So},createdAt:t.createdAt.toISOString(),format:t.format,frameCount:t.frameCount,frameRate:t.frameRate,width:t.width,height:t.height,indexBase:1,filePattern:`frames/frame-%06d${t.extension}`}}({createdAt:r,format:i.format,frameCount:i.frameCount,frameRate:i.frameRate,width:f.width,height:f.height,extension:s.extension});await d.$addEntry(`${o}/manifest.json`,function(t){return(new TextEncoder).encode(`${JSON.stringify(t,null,2)}\n`)}(p),"deflate"),this.I(i.signal),await u.$render({frameCount:i.frameCount,frameRate:i.frameRate,prepareFrame:i.prepareFrame,signal:i.signal,onFrame:async({frameIndex:t,canvas:e})=>{this.I(i.signal);const n=await s.serialize({canvas:e,frameOptions:i.frameOptions,createdAt:r});this.I(i.signal),await d.$addEntry(function(t,e,i){return`${t}/frames/frame-${String(e+1).padStart(6,"0")}${i}`}(o,t,s.extension),n,s.compression),this.I(i.signal);const a=t+1;c=a,this.Ze(i,{state:"capturing",frameIndex:a,totalFrames:i.frameCount,progress:a/i.frameCount}),await this.st(i.signal)}}),this.I(i.signal),this.Ze(i,{state:"finalizing",frameIndex:i.frameCount,totalFrames:i.frameCount,progress:1}),this.I(i.signal);const m=await d.$finalize();return this.I(i.signal),await(e?.({blob:m,filename:n})),this.I(i.signal),this.Ze(i,{state:"completed",frameIndex:i.frameCount,totalFrames:i.frameCount,progress:1}),h=!0,{blob:m,filename:n}}catch(d){const t=$o(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 Oo("ZIP_EXPORT_INVALID_OPTIONS","ZIP export options are required.");const e=t.format;if("string"!=typeof e||!Fs.has(e))throw new Oo("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 Oo("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 Oo("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 Ro()}st(t){return new Promise((e,i)=>{if(t?.aborted)return void i(Ro());let r=!1;const n=()=>{r||(r=!0,i(Ro()))};t?.addEventListener("abort",n,{once:!0}),setTimeout(()=>{r||(r=!0,t?.removeEventListener("abort",n),e())},0)})}},Rs="textmode-export-overlay__stack",$s="textmode-export-overlay__stack--dense",Ds="textmode-export-overlay__stack--compact",Ns="textmode-export-overlay__section",Vs="textmode-export-overlay--dragging",Us="textmode-export-overlay__label",zs="textmode-export-overlay__field",js="textmode-export-overlay__field--compact",Ls="textmode-export-overlay__field--dense",qs="textmode-export-overlay__field--full",Gs="textmode-export-overlay__field--channel",Hs="textmode-export-overlay__input",Ws="textmode-export-overlay__muted",Xs="textmode-export-overlay__button--primary",Zs="textmode-export-overlay__button--secondary",Qs="textmode-export-overlay__button--full",Ys="textmode-export-overlay__link-icon",Js=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}},Ks=class t extends Js{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(Rs,$s,"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",Ys,[{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(Ys,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}},ta=class extends Js{props;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.classList.add(zs),this.applyVariant(t,this.props.variant);const e=document.createElement("label");if(e.classList.add(Us),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(Ws),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(zs),this.applyVariant(e,t.variant);const i=document.createElement("label");if(i.classList.add(Us),i.textContent=t.label,t.labelFor&&(i.htmlFor=t.labelFor),e.appendChild(i),t.description){const i=document.createElement("span");i.classList.add(Ws),i.textContent=t.description,e.appendChild(i)}}applyVariant(t,e){switch(t.classList.remove(js,Ls,qs,Gs),e){case"compact":t.classList.add(js);break;case"dense":t.classList.add(Ls);break;case"full":t.classList.add(qs);break;case"channel":t.classList.add(Gs)}}},ea=class extends Js{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(Hs),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)}}},ia=class extends Js{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(Zs):this.button.classList.add(Xs),this.props.fullWidth&&this.button.classList.add(Qs),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(Zs),this.button.classList.remove(Xs)):(this.button.classList.add(Xs),this.button.classList.remove(Zs)),this.button.classList.toggle(Qs,Boolean(t.fullWidth))}},ra=class{ht={};Vi(t){const e=this.ht[t];if(e)return e;const i=new Set;return this.ht[t]=i,i}$on(t,e){const i=this.Vi(t);return i.add(e),()=>{i.delete(e),0===i.size&&delete this.ht[t]}}$emit(t,e){const i=this.ht[t];if(i)for(const n of[...i])try{n(e)}catch(r){console.error("[textmode-export] Event handler failed",r)}}$clear(){for(const t of Object.keys(this.ht))delete this.ht[t]}},na=class{yi;ht=new Set;constructor(t){this.yi=t}get snapshot(){return Object.freeze({...this.yi})}$set(t){const e=Object.keys(t);if(0===e.length)return;let i=!1;for(const o of e)if(this.yi[o]!==t[o]){i=!0;break}if(!i)return;this.yi=Object.assign({},this.yi,t);const r=this.snapshot;for(const o of[...this.ht])try{o(r)}catch(n){console.error("[textmode-export] State listener failed",n)}}$subscribe(t){return this.ht.add(t),t(this.snapshot),()=>{this.ht.delete(t)}}$reset(t){this.yi=t;const e=this.snapshot;for(const i of[...this.ht])i(e)}},oa=new Set(["txt","json","svg","image"]),sa=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 oa.has(t)}},aa={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)}},ha=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 aa[t](this.api,e,r),this.events.$emit("export:success",{format:t})}catch(r){throw this.events.$emit("export:error",{format:t,error:r}),r}}},ca=t=>"number"==typeof t&&Number.isFinite(t)&&Math.abs(t)<=1e5,la=class{key;constructor(t="textmode.export.overlay.position.v1"){this.key=t}load(){try{const t=window.localStorage.getItem(this.key);if(!t)return;const e=JSON.parse(t);if(1!==e.version||!ca(e.offsetX)||!ca(e.offsetY))return;return{version:1,offsetX:e.offsetX,offsetY:e.offsetY}}catch{return}}save(t,e){if(ca(t)&&ca(e))try{const i={version:1,offsetX:t,offsetY:e};window.localStorage.setItem(this.key,JSON.stringify(i))}catch{}}clear(){try{window.localStorage.removeItem(this.key)}catch{}}},da=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 la){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(Vs))}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(Vs),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(Vs),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()}},ua=class extends Js{capabilities;Ui;zi=new Set;constructor(t,e){super(),this.Ui=t,this.capabilities={clipboard:t.supportsClipboard,layerTarget:!!t.layerTargetProvider,recording:!1,...e}}ji(t){return this.zi.add(t),t}Bi(){for(const t of this.zi)t.unmount()}Fi(){for(const t of this.zi)t.destroy();this.zi.clear()}},fa=class extends Js{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)}},pa=class extends Js{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(Hs),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)}},ma=class extends Js{provider;field;select;constructor(t){super(),this.provider=t.provider,this.field=new ta({label:"layer",labelFor:t.id,variant:"full"}),this.select=new ea({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()}},wa=class extends ua{layerTarget;trailingSpaces=this.ji(new fa({label:"preserve trailing spaces",defaultChecked:!1}));emptyCharacter=this.ji(new pa({id:"textmode-export-empty-character",defaultValue:" ",maxLength:1}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.ji(new ma({id:"textmode-export-txt-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Rs),this.layerTarget?.mount(t),this.trailingSpaces.mount(t);const e=new ta({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??" "}},va=class extends ua{layerTarget;layerTargetContainer;target=this.ji(new ea({id:"textmode-export-json-target",options:[{value:"selected",label:"selected layer"},{value:"all",label:"all layers"}],defaultValue:"selected"}));prettyPrint=this.ji(new fa({id:"textmode-export-json-pretty",label:"pretty print",defaultChecked:!0}));includeMetadata=this.ji(new fa({id:"textmode-export-json-metadata",label:"include metadata",defaultChecked:!0}));colorMode=this.ji(new ea({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 ma({id:"textmode-export-json-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Rs);const e=new ta({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 ta({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)}},ba="textmode-export-number-input",ya=`${ba}__field`,ga=`${ba}__controls`,xa=`${ba}__control`,Ea=`${ba}__display`,Ta=`${Ea}--visible`,ka=t=>{const e=document.createElement("button");return e.type="button",e.className=xa,e.textContent=t>0?"▲":"▼",e},_a=class extends Js{props;input;display;incrementButton;decrementButton;suppressClickAfterPointer=new WeakMap;holdTimeoutId;holdIntervalId;activePointerId;disabledObserver;constructor(t){super(),this.props=t}render(){const t=document.createElement("div");t.className=ba,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=ya,this.display=document.createElement("div"),this.display.className=Ea;const e=document.createElement("div");return e.className=ga,this.incrementButton=ka(1),this.decrementButton=ka(-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(Ta),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(Ta),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(Ta),this.input.style.color="transparent",this.input.style.caretColor="#f8fafc"):(this.display.textContent="",this.display.classList.remove(Ta),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)}},Ma=class extends Js{variant;additionalClasses;constructor(t="stack",e=[]){super(),this.variant=t,this.additionalClasses=e}render(){const t=document.createElement("div"),e=["stack"===this.variant?Rs:void 0,"stackDense"===this.variant?$s:void 0,"stackCompact"===this.variant?Ds:void 0,"row"===this.variant?"textmode-export-overlay__row":void 0,"section"===this.variant?Ns:void 0,...this.additionalClasses].filter(Boolean);return t.classList.add(...e),t}},Aa=class extends ua{formatSelect=this.ji(new ea({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 _a({defaultValue:"1",attributes:{min:"0.1",step:"0.1"}}));constructor(t){super(t)}render(){const t=document.createElement("div");t.classList.add(Rs);const e=new Ma("row");e.mount(t);const i=new ta({label:"image format",labelFor:"textmode-export-image-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new ta({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)}},Sa=class extends ua{layerTarget;includeBackground=this.ji(new fa({id:"textmode-export-svg-include-backgrounds",label:"include cell backgrounds",defaultChecked:!0}));drawMode=this.ji(new ea({id:"textmode-export-svg-draw-mode",options:[{value:"fill",label:"fill"},{value:"stroke",label:"stroke"}],defaultValue:"fill"}));strokeWidth=this.ji(new _a({defaultValue:"1",attributes:{min:"0",step:"0.1"}}));constructor(t){super(t),t.layerTargetProvider&&(this.layerTarget=this.ji(new ma({id:"textmode-export-svg-layer",provider:t.layerTargetProvider})))}render(){const t=document.createElement("div");t.classList.add(Rs),this.layerTarget?.mount(t),this.includeBackground.mount(t);const e=new Ma("row");e.mount(t);const i=new ta({label:"draw mode",labelFor:"textmode-export-svg-draw-mode",variant:"compact"});i.mount(e.root),this.drawMode.mount(i.root);const r=new ta({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()}},Ca={neutral:"textmode-export-overlay__status-value--neutral",active:"textmode-export-overlay__status-value--active",alert:"textmode-export-overlay__status-value--alert"},Pa=class extends Js{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(Ca)),this.messageElement.classList.add(Ca[t])}},Ia=class extends ua{frameCountInput=this.ji(new _a({defaultValue:"300",attributes:{min:"1",max:"600",step:"1"}}));frameRateInput=this.ji(new _a({defaultValue:"60",attributes:{min:"1",max:"60",step:"1"}}));scaleInput=this.ji(new _a({defaultValue:"1",attributes:{min:"0.1",max:"8",step:"0.1"}}));repeatInput=this.ji(new _a({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 Pa({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(Rs);const e=new Ma("row");e.mount(t);const i=new ta({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 ta({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 Ma("row");n.mount(t);const o=new ta({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 ta({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}},Ba=class extends ua{formatSelect=this.ji(new ea({id:"textmode-export-video-format",options:[{value:"mp4",label:"MP4/H.264 (.mp4)"},{value:"webm",label:"WebM (.webm)"}],defaultValue:"mp4"}));qualitySelect=this.ji(new ea({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 _a({defaultValue:"60",attributes:{min:String(1),max:String(60),step:"1"},formatDisplay:t=>Number.isFinite(t)?`${t} fps`:null}));frameCountInput=this.ji(new _a({defaultValue:"480",attributes:{min:String(1),max:String(3600),step:"1"}}));hardwareAccelerationSelect=this.ji(new ea({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 _a({defaultValue:"2",attributes:{min:"0",step:"0.25"},formatDisplay:t=>Number.isFinite(t)?`${t}s`:null}));transparencyInput=this.ji(new fa({id:"textmode-export-video-transparent",label:"preserve transparency",defaultChecked:!1}));status=this.ji(new Pa({title:"status",message:"ready to record",variant:"neutral",context:"video"}));estimate=this.ji(new Pa({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(Rs);const e=new Ma("row");e.mount(t);const i=new ta({label:"video format",labelFor:"textmode-export-video-format",variant:"compact"});i.mount(e.root),this.formatSelect.mount(i.root);const r=new ta({label:"quality",labelFor:"textmode-export-video-quality",variant:"compact"});r.mount(e.root),this.qualitySelect.mount(r.root);const n=new Ma("row");n.mount(t);const o=new ta({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 ta({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 Ma("row");a.mount(t);const h=new ta({label:"hardware",labelFor:"textmode-export-video-hardware-acceleration",variant:"compact"});h.mount(a.root),this.hardwareAccelerationSelect.mount(h.root);const c=new ta({label:"keyframe interval",labelFor:"textmode-export-video-keyframe-interval",variant:"compact"});return c.mount(a.root),this.keyFrameIntervalInput.mount(c.root),this.keyFrameIntervalInput.inputElement.id="textmode-export-video-keyframe-interval",this.transparencyInput.mount(t),this.formatSelect.selectElement.addEventListener("change",this.handleFormatChange),this.syncTransparencyAvailability(),this.qualitySelect.selectElement.addEventListener("change",this.handleQualityChange),this.frameCountInput.inputElement.addEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.addEventListener("input",this.handleEstimateChange),this.formatSelect.selectElement.addEventListener("change",this.handleEstimateChange),this.estimate.mount(t),this.status.mount(t),this.syncOutputEstimate(),this.Ui.videoDimensionsTarget&&"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>this.syncOutputEstimate()),this.resizeObserver.observe(this.Ui.videoDimensionsTarget)),t}getOptions(){const t=this.Ui.defaultOptions,e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value),r=Number.parseFloat(this.keyFrameIntervalInput.value),n=this.formatSelect.value,o={format:n,quality:this.qualitySelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.isFinite(r)?r:t.keyFrameInterval??2,frameCount:Number.isFinite(e)?e:t.frameCount??480,frameRate:Number.isFinite(i)?i:t.frameRate??60};return"webm"===n&&(o.transparent=this.transparencyInput.checked),o}setDefaults(t){Object.assign(this.Ui.defaultOptions,t),this.reset()}reset(){this.recordingState="idle",this.applyDefaults(),this.syncReadyStatus()}validate(){const t=Number.parseInt(this.frameCountInput.value,10),e=Number.parseFloat(this.frameRateInput.value),i=Number.parseFloat(this.keyFrameIntervalInput.value);return Number.isFinite(t)&&t>=1&&Number.isFinite(e)&&e>=1&&Number.isFinite(i)&&i>=0}isRecording(){return"recording"===this.recordingState||"encoding"===this.recordingState}setRecordingState(t,e){this.recordingState=t;const i="recording"===t||"encoding"===t;this.formatSelect.selectElement.disabled=i,this.qualitySelect.selectElement.disabled=i,this.frameCountInput.inputElement.disabled=i,this.frameRateInput.inputElement.disabled=i,this.hardwareAccelerationSelect.selectElement.disabled=i,this.keyFrameIntervalInput.inputElement.disabled=i,this.transparencyInput.inputElement.disabled=i||"webm"!==this.formatSelect.value,this.syncStatus(t,e)}handleProgress(t){this.syncStatus(t.state,t)}syncStatus(t,e){switch(t){case"recording":{const t=e?.frameIndex??0,i=e?.totalFrames??this.resolvePlannedFrameCount();if(i){const e=Math.min(Math.max(0,Math.round(t)),i);this.status.setMessage(`recording ${e}/${i} frames`,"active")}else this.status.setMessage(`recording ${Math.max(0,Math.round(t))} frames`,"active");break}case"encoding":this.status.setMessage("writing"===e?.phase?"writing video to disk":"finalizing video","active");break;case"completed":this.status.setMessage("saved to disk","active");break;case"error":this.status.setMessage(e?.message?`error: ${e.message}`:"recording failed","alert");break;default:this.syncReadyStatus()}}resolvePlannedFrameCount(){const t=Number.parseInt(this.frameCountInput.value,10);return Number.isFinite(t)&&t>0?Math.round(t):void 0}applyDefaults(){const t=this.Ui.defaultOptions;this.formatSelect.value=t.format??"mp4",this.qualitySelect.value=this.resolveQuality(t.quality),this.frameCountInput.value=String(t.frameCount??480),this.frameRateInput.value=String(t.frameRate??60),this.hardwareAccelerationSelect.value=t.hardwareAcceleration??"no-preference",this.keyFrameIntervalInput.value=String(t.keyFrameInterval??2),this.transparencyInput.checked=Boolean(t.transparent),this.frameCountInput.refresh(),this.frameRateInput.refresh(),this.keyFrameIntervalInput.refresh(),this.syncTransparencyAvailability()}resolveQuality(t){return"very-low"===t||"low"===t||"medium"===t||"high"===t||"very-high"===t?t:"medium"}handleQualityChange=()=>{this.isRecording()||this.syncReadyStatus(),this.syncOutputEstimate()};handleEstimateChange=()=>this.syncOutputEstimate();syncReadyStatus(){this.status.setMessage("constant quality; file size depends on content","neutral")}handleFormatChange=()=>{this.syncTransparencyAvailability(),this.syncOutputEstimate()};syncOutputEstimate(){if(!this.estimate.isMounted())return;const t=this.Ui.videoDimensionsProvider?.(),e=Number.parseInt(this.frameCountInput.value,10),i=Number.parseFloat(this.frameRateInput.value);if(!t||!Number.isFinite(e)||!Number.isFinite(i)||i<=0)return void this.estimate.setMessage("logical dimensions · duration · size","neutral");const r={format:this.formatSelect.value,frameCount:Math.max(1,Math.round(e)),frameRate:i,quality:this.qualitySelect.value,hardwareAcceleration:this.hardwareAccelerationSelect.value,keyFrameInterval:Number.parseFloat(this.keyFrameIntervalInput.value)||2,pixelDensity:1,width:t.width,height:t.height,transparent:"webm"===this.formatSelect.value&&this.transparencyInput.checked,debugLogging:!1};try{const t=U(r);this.estimate.setMessage(`${t.width}×${t.height} · ${(t.frameCount/t.frameRate).toFixed(1)}s · content-dependent size`,"neutral")}catch{this.estimate.setMessage(`${t.width}×${t.height} · MP4 requires even dimensions`,"alert")}}Bi(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.qualitySelect.selectElement.removeEventListener("change",this.handleQualityChange),this.formatSelect.selectElement.removeEventListener("change",this.handleFormatChange),this.formatSelect.selectElement.removeEventListener("change",this.handleEstimateChange),this.frameCountInput.inputElement.removeEventListener("input",this.handleEstimateChange),this.frameRateInput.inputElement.removeEventListener("input",this.handleEstimateChange),super.Bi()}syncTransparencyAvailability(){if(!this.transparencyInput.isMounted())return;const t="webm"===this.formatSelect.value;this.transparencyInput.root.style.display=t?"":"none",this.transparencyInput.inputElement.disabled=!t||this.isRecording(),t||(this.transparencyInput.checked=!1)}};function Fa(t){return t.capabilities.recording}var Oa=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 Ra(){return{format:Oa.format,txt:{...Oa.txt},json:{...Oa.json},image:{...Oa.image},svg:{...Oa.svg},gif:{...Oa.gif},video:{...Oa.video}}}function $a(t,e){for(const i of Object.keys(t))delete t[i];Object.assign(t,e)}var Da=class{Li;constructor(){this.Li=Ra()}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=Ra();if(!t)return this.Li.format=e.format,$a(this.Li.txt,e.txt),$a(this.Li.json,e.json),$a(this.Li.image,e.image),$a(this.Li.svg,e.svg),$a(this.Li.gif,e.gif),void $a(this.Li.video,e.video);switch(t){case"format":this.Li.format=e.format;break;case"txt":$a(this.Li.txt,e.txt);break;case"json":$a(this.Li.json,e.json);break;case"image":$a(this.Li.image,e.image);break;case"svg":$a(this.Li.svg,e.svg);break;case"gif":$a(this.Li.gif,e.gif);break;case"video":$a(this.Li.video,e.video)}}},Na=class{T;qi;yi;Gi;Hi;Wi;Xi;Zi=new Map;Qi=[];Yi;Ji;Ki;tr;er;ir;rr=new Ks;nr=new ta({label:"export format",labelFor:"textmode-export-format",variant:"full"});sr=new ea({id:"textmode-export-format",options:[]});ar=new ia({label:"download file",fullWidth:!0,variant:"primary"});hr=new ia({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 na((t=>({format:t,isBusy:!1}))(n)),this.Gi=new ra,this.Hi=new ha(e,this.Gi),this.Wi=new sa(e),this.Xi=r,this.cr=n,this.yr(),this.gr()}$mount(){this.Er(),this.Tr(),this.ir=new da(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",Rs),this.Ji.appendChild(this.Ki),document.body.appendChild(this.Yi)}Tr(){this.rr.mount(this.Ki);const t=document.createElement("div");t.classList.add(Ns),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(Rs,Ds),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(Rs,$s),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&&Fa(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&&Fa(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(Fa(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(Fa(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 Va=["saveCanvas","toImageBlob","copyCanvas","saveSVG","saveStrings","toSVG","toString","toJSON","toJSONString","saveJSON","saveGIF","toGIFBlob","saveVideo","toVideoBlob","saveZip","toZipBlob"],Ua=class{api;k;Ir=new Set;Br=new v;Fr;Or;v=!1;constructor(t,e){this.k=e;const i={saveCanvas:async(e={})=>(this.Rr(),(new A).$saveImage(t.canvas,e)),copyCanvas:async(e={})=>(this.Rr(),(new A).$copyImageToClipboard(t.canvas,e)),toImageBlob:async(e={})=>(this.Rr(),(new A).$toImageBlob(t.canvas,e)),saveSVG:(e={})=>{this.Rr(),(new _).$saveSVG(t,e)},saveStrings:(e={})=>{this.Rr(),(new S).$saveTXT(t,e)},toSVG:(e={})=>(this.Rr(),(new _).$generateSVG(t,e)),toString:(e={})=>(this.Rr(),(new S).$generateTXT(t,e)),toJSON:(e={})=>(this.Rr(),(new Fo).$generateJSONData(t,e)),toJSONString:(e={})=>(this.Rr(),(new Fo).$generateJSONString(t,e)),saveJSON:(e={})=>{this.Rr(),(new Fo).$saveJSON(t,e)},saveGIF:(e={})=>this.$r("gif",e.signal,i=>new R(t,t=>this.k(t)).$saveGIF({...e,signal:i})),toGIFBlob:(e={})=>this.$r("gif",e.signal,i=>new R(t,t=>this.k(t)).$generateGIFBlob({...e,signal:i})),saveVideo:(e={})=>this.$r("video",e.signal,i=>new Mo(t,t=>this.k(t)).$saveVideo({...e,signal:i})),toVideoBlob:(e={})=>this.$r("video",e.signal,i=>new Mo(t,t=>this.k(t)).$generateVideoBlob({...e,signal:i})),saveZip:async e=>this.$r("zip",e?.signal,i=>new Os(t,t=>this.k(t)).$saveZIP({...e,signal:i}),t=>this.Dr(e,t)),toZipBlob:async e=>this.$r("zip",e?.signal,i=>new Os(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 Da,n=new Na(t,e,r,function(t,e=(()=>{const t=Ra();return e=>t[e]})(),i,r){return[{format:"txt",label:"plain text (.txt)",supportsClipboard:!0,createBlade:()=>new wa({format:"txt",label:"plain text (.txt)",supportsClipboard:!0,defaultOptions:e("txt"),layerTargetProvider:t})},{format:"json",label:"document data (.json)",supportsClipboard:!0,createBlade:()=>new va({format:"json",label:"document data (.json)",supportsClipboard:!0,defaultOptions:e("json"),layerTargetProvider:t})},{format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,createBlade:()=>new Aa({format:"image",label:"image (.png / .jpg / .webp)",supportsClipboard:!0,defaultOptions:e("image")})},{format:"svg",label:"vector (.svg)",supportsClipboard:!0,createBlade:()=>new Sa({format:"svg",label:"vector (.svg)",supportsClipboard:!0,defaultOptions:e("svg"),layerTargetProvider:t})},{format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,createBlade:()=>new Ia({format:"gif",label:"animated GIF (.gif)",supportsClipboard:!1,defaultOptions:e("gif")})},{format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,createBlade:()=>new Ba({format:"video",label:"video (.webm / .mp4)",supportsClipboard:!1,defaultOptions:e("video"),videoDimensionsProvider:i,videoDimensionsTarget:r})}]}(i,t=>r.get(t),()=>{const e=t.pixelDensity?.()??1;return{width:Math.max(1,Math.round(t.canvas.width/e)),height:Math.max(1,Math.round(t.canvas.height/e))}},t.canvas));try{n.$mount()}catch(o){throw n.$dispose(),o}return n}(t,i,function(t){return{getOptions:()=>u(t),getLayerById:e=>u(t).find(t=>t.id===e)?.layer,getDefaultId:()=>"base"}}(t));let n;try{n=this.k(()=>{!this.v&&r.isVisible()&&r.refreshLayerTargets()})}catch(o){throw r.$dispose(),o}this.Fr=r,this.Or=n,i.exportOverlay=this.Nr()}dispose(){if(!this.v){this.v=!0;for(const t of this.Ir)t.abort();this.Ir.clear(),this.Br.dispose(),this.Or(),this.Fr.$dispose()}}Nr(){return{show:()=>{this.Rr(),this.Fr.show()},hide:()=>{this.Rr(),this.Fr.hide()},toggle:()=>{this.Rr(),this.Fr.toggle()},isVisible:()=>(this.Rr(),this.Fr.isVisible()),resetPosition:()=>{this.Rr(),this.Fr.resetPosition()},getPosition:()=>(this.Rr(),this.Fr.getPosition()),setPosition:t=>{this.Rr(),this.Fr.setPosition(t)},setDefaults:t=>{this.Rr(),this.Fr.setDefaults(t)},getDefaults:()=>(this.Rr(),this.Fr.getDefaults()),resetDefaults:t=>{this.Rr(),this.Fr.resetDefaults(t)}}}Vr(t,e){this.Rr();const i=new AbortController,r=new AbortController,n=()=>r.abort(),o=()=>r.abort();return t?.addEventListener("abort",n,{once:!0}),i.signal.addEventListener("abort",o,{once:!0}),t?.aborted&&r.abort(),this.Ir.add(i),Promise.resolve().then(()=>e(r.signal)).finally(()=>{t?.removeEventListener("abort",n),i.signal.removeEventListener("abort",o),this.Ir.delete(i)})}$r(t,e,i,r){return this.Vr(e,async e=>{let n;try{n=this.Br.acquire()}catch(o){if("video"===t)throw V(o);if("zip"===t){const t=$o(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.")}},za={name:"textmode.export.js",install(t,e){const i=new Ua(t,t=>e.on("postDraw",t));try{for(const t of Va)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=za),t.ExportPlugin=za,t.TEXTMODE_DOCUMENT_FORMAT=Co,t.TEXTMODE_DOCUMENT_FORMAT_VERSION=Po,t.TEXTMODE_OBJECT_ROWS_ENCODING=Io,t.ZIPExportError=Oo});