@vidtreo/recorder-wc 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# @vidtreo/recorder-wc
|
|
2
|
+
|
|
3
|
+
Web component package for the Vidtreo video recording SDK. This package contains only the web component files and depends on `@vidtreo/recorder` for the core SDK functionality.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @vidtreo/recorder-wc
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
**Note:** This package automatically includes `@vidtreo/recorder` as a peer dependency. You don't need to install it separately.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
### Via npm (Node.js/Bundler)
|
|
16
|
+
|
|
17
|
+
```html
|
|
18
|
+
<link rel="stylesheet" href="node_modules/@vidtreo/recorder-wc/dist/vidtreo-recorder.css">
|
|
19
|
+
<script type="module" src="node_modules/@vidtreo/recorder-wc/dist/vidtreo-recorder.js"></script>
|
|
20
|
+
|
|
21
|
+
<vidtreo-recorder
|
|
22
|
+
api-key="your-api-key"
|
|
23
|
+
backend-url="https://your-worker.workers.dev"
|
|
24
|
+
></vidtreo-recorder>
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Via CDN (jsDelivr)
|
|
28
|
+
|
|
29
|
+
#### Specific Version (Recommended for Production)
|
|
30
|
+
|
|
31
|
+
```html
|
|
32
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@vidtreo/recorder-wc@1.3.2/dist/vidtreo-recorder.css">
|
|
33
|
+
<script type="module" src="https://cdn.jsdelivr.net/npm/@vidtreo/recorder-wc@1.3.2/dist/vidtreo-recorder.js"></script>
|
|
34
|
+
|
|
35
|
+
<vidtreo-recorder
|
|
36
|
+
api-key="your-api-key"
|
|
37
|
+
backend-url="https://your-worker.workers.dev"
|
|
38
|
+
></vidtreo-recorder>
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
#### Latest Version (Use with Caution)
|
|
42
|
+
|
|
43
|
+
```html
|
|
44
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@vidtreo/recorder-wc@latest/dist/vidtreo-recorder.css">
|
|
45
|
+
<script type="module" src="https://cdn.jsdelivr.net/npm/@vidtreo/recorder-wc@latest/dist/vidtreo-recorder.js"></script>
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Attributes
|
|
49
|
+
|
|
50
|
+
See the [@vidtreo/recorder README](../recorder/README.md#web-component-usage) for complete attribute documentation.
|
|
51
|
+
|
|
52
|
+
## Package Structure
|
|
53
|
+
|
|
54
|
+
This package contains only the compiled web component files:
|
|
55
|
+
- `dist/vidtreo-recorder.js` - The web component JavaScript bundle
|
|
56
|
+
- `dist/vidtreo-recorder.css` - The web component styles
|
|
57
|
+
|
|
58
|
+
The core SDK functionality is provided by the `@vidtreo/recorder` package, which is automatically installed as a peer dependency.
|
|
59
|
+
|
|
60
|
+
## Why Separate Packages?
|
|
61
|
+
|
|
62
|
+
- **Smaller SDK Package**: Users who only need the programmatic SDK don't download web component files
|
|
63
|
+
- **CDN Optimization**: Web component users can use jsDelivr CDN for faster loading
|
|
64
|
+
- **Clear Separation**: Web component and SDK have independent versioning and distribution
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT
|
|
69
|
+
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
class AudioCaptureProcessor extends AudioWorkletProcessor {
|
|
2
|
+
process(inputs) {
|
|
3
|
+
const input = inputs[0];
|
|
4
|
+
if (!input?.length) {
|
|
5
|
+
return true;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const bufferLength = input[0].length;
|
|
9
|
+
const numberOfChannels = input.length;
|
|
10
|
+
const combinedBuffer = new Float32Array(bufferLength * numberOfChannels);
|
|
11
|
+
|
|
12
|
+
for (let channel = 0; channel < numberOfChannels; channel++) {
|
|
13
|
+
combinedBuffer.set(input[channel], channel * bufferLength);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const arrayBuffer = combinedBuffer.buffer.slice(
|
|
17
|
+
0,
|
|
18
|
+
combinedBuffer.length * Float32Array.BYTES_PER_ELEMENT
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
this.port.postMessage(
|
|
22
|
+
{
|
|
23
|
+
type: "audioData",
|
|
24
|
+
data: arrayBuffer,
|
|
25
|
+
sampleRate,
|
|
26
|
+
numberOfChannels,
|
|
27
|
+
duration: bufferLength / sampleRate,
|
|
28
|
+
bufferLength: combinedBuffer.length,
|
|
29
|
+
},
|
|
30
|
+
[arrayBuffer]
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
registerProcessor("audio-capture-processor", AudioCaptureProcessor);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
:host{display:block;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;--background: 0 0% 100%;--foreground: 0 0% 3.9%;--card: 0 0% 100%;--card-foreground: 0 0% 3.9%;--primary: 0 0% 9%;--primary-foreground: 0 0% 98%;--secondary: 0 0% 96.1%;--secondary-foreground: 0 0% 9%;--muted: 0 0% 96.1%;--muted-foreground: 0 0% 45.1%;--accent: 0 0% 96.1%;--accent-foreground: 0 0% 9%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 0 0% 98%;--border: 0 0% 89.8%;--input: 0 0% 89.8%;--ring: 0 0% 3.9%;--radius: .5rem;--preview-bg: 0 0% 98%}.container{background:hsl(var(--background));border-radius:16px;padding:40px;max-width:600px;width:100%;box-shadow:0 20px 60px #0000004d}h1{color:#333;margin-bottom:10px;font-size:28px}.subtitle{color:#666;margin-bottom:30px;font-size:14px}.preview-container{position:relative;width:100%;aspect-ratio:9 / 16;border-radius:.5rem;overflow:hidden;border:1px solid hsl(var(--border));background:hsl(var(--preview-bg));display:flex;align-items:center;justify-content:center}@media(min-width:768px){.preview-container{aspect-ratio:16 / 9}}.camera-area{border:2px solid #667eea;border-radius:12px;padding:20px;background:#f8f9ff;margin-bottom:20px;display:none;position:relative}.source-transition-overlay{position:absolute;inset:20px;background:#000000b3;display:none;align-items:center;justify-content:center;flex-direction:column;border-radius:8px;z-index:10;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px);transition:opacity .3s ease}.source-transition-overlay.active{display:flex;animation:fadeIn .2s ease}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}.transition-spinner{width:40px;height:40px;border:4px solid rgba(255,255,255,.3);border-top-color:#667eea;border-radius:50%;animation:spin .8s linear infinite;margin-bottom:12px}@keyframes spin{to{transform:rotate(360deg)}}.transition-message{color:#fff;font-size:14px;font-weight:500;text-align:center}.camera-area.active{display:block}.preview-container{position:relative;width:100%;height:100%}.preview-skeleton{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;background:hsl(var(--background) / .95);border-radius:.5rem;z-index:10;gap:1rem}.skeleton-spinner{width:40px;height:40px;border:4px solid hsl(var(--muted) / .3);border-top-color:hsl(var(--primary));border-radius:50%;animation:spin .8s linear infinite}.skeleton-text{color:hsl(var(--muted-foreground));font-size:.875rem;font-weight:500}.video-preview{width:100%;height:100%;border-radius:.5rem;background:#000;display:block;-o-object-fit:contain;object-fit:contain;transition:opacity .3s ease,transform .3s ease;position:absolute;inset:0}.video-preview.screen-share{-o-object-fit:cover;object-fit:cover}.video-preview.transitioning{opacity:.5;transform:scale(.98)}.countdown-overlay{position:absolute;inset:0;background:hsl(var(--background) / .95);display:none;align-items:center;justify-content:center;border-radius:.5rem;z-index:20}.countdown-overlay.active{display:flex}.countdown-number{font-size:9rem;font-weight:700;color:hsl(var(--foreground));animation:zoomIn .3s ease}@keyframes zoomIn{0%{transform:scale(.5);opacity:0}to{transform:scale(1);opacity:1}}.countdown-text{font-size:.875rem;color:hsl(var(--muted-foreground));margin-top:1rem;font-weight:500}.settings-panel{margin-top:1rem;background:hsl(var(--background));border:1px solid hsl(var(--border));border-radius:.5rem;padding:1.25rem;display:none;animation:slideIn .3s ease}.settings-panel.active{display:block}@keyframes slideIn{0%{transform:translateY(1rem);opacity:0}to{transform:translateY(0);opacity:1}}.settings-title{font-size:.875rem;font-weight:600;margin-bottom:1.25rem}.device-select-group{margin-bottom:1.25rem}.device-select-label{display:flex;align-items:center;gap:.5rem;font-size:.75rem;color:hsl(var(--muted-foreground));font-weight:500;margin-bottom:.5rem}.device-select{width:100%;height:2.25rem;border-radius:.375rem;border:1px solid hsl(var(--input));background:hsl(var(--background));padding:0 .75rem;font-size:.875rem}.audio-level-bars{position:absolute;bottom:.75rem;right:.75rem;display:flex;align-items:center;gap:.125rem;height:1rem;z-index:10}@media(min-width:768px){.audio-level-bars{height:1.25rem}}.audio-level-bar{width:.125rem;border-radius:9999px;background:hsl(var(--border));transition:all .1s ease;align-self:flex-end}.recording-controls{display:flex;gap:12px;align-items:center;justify-content:center}.recording-indicator{display:flex;align-items:center;gap:8px;color:#c33;font-weight:600;display:none}.recording-indicator.active{display:flex}.recording-dot{width:12px;height:12px;background:#c33;border-radius:50%;animation:pulse 1.5s ease-in-out infinite}@keyframes pulse{0%,to{opacity:1}50%{opacity:.3}}.recording-timer{font-family:monospace;font-size:18px;color:#333}.start-camera-area{border:2px dashed #667eea;border-radius:12px;padding:40px;text-align:center;background:#f8f9ff;transition:all .3s ease;cursor:pointer;margin-bottom:20px}.start-camera-area:hover:not(.loading){border-color:#764ba2;background:#f0f2ff}.start-camera-area.loading{cursor:wait;opacity:.7}.start-camera-area.loading .camera-text{color:#999}.camera-icon{font-size:48px;margin-bottom:16px}.camera-text{color:#667eea;font-weight:600;margin-bottom:8px}.camera-hint{color:#999;font-size:12px}.recording-info{margin-top:20px;padding:16px;background:#f5f5f5;border-radius:8px;display:none}.recording-info.active{display:block}.recording-size{color:#666;font-size:14px}button{width:100%;padding:16px;background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;border:none;border-radius:8px;font-size:16px;font-weight:600;cursor:pointer;transition:transform .2s ease,box-shadow .2s ease;margin-top:20px}button:hover:not(:disabled){transform:translateY(-2px);box-shadow:0 8px 20px #667eea66}button:disabled{opacity:.6;cursor:not-allowed}.recording-controls{position:absolute;bottom:0;left:0;right:0;padding:.75rem 1rem}.recording-controls-row{display:flex;align-items:center;justify-content:center;gap:.5rem}.recording-timer-row{display:flex;align-items:center;justify-content:space-between;gap:.5rem}.recording-timer-badge{position:absolute;top:.75rem;right:.75rem;display:flex;align-items:center;gap:.375rem;background:hsl(var(--background) / .9);border:1px solid hsl(var(--border));padding:.25rem .5rem;border-radius:9999px;box-shadow:0 1px 3px #0000001a,0 1px 2px -1px #0000001a;z-index:10}.recording-dot-small{width:.375rem;height:.375rem;background:hsl(var(--destructive));border-radius:50%;animation:pulse 1.5s ease-in-out infinite}.recording-timer-text{font-size:.75rem;font-family:monospace;font-weight:500;color:hsl(var(--foreground))}.control-buttons-row{display:flex;align-items:center;justify-content:center;gap:.375rem}.control-button{width:2rem;height:2rem;border-radius:9999px;border:1px solid hsl(var(--border));background:hsl(var(--background) / .9);display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s ease;color:hsl(var(--foreground))}.control-button svg{width:24px!important;height:24px!important;color:inherit;fill:currentColor;flex-shrink:0}@media(min-width:768px){.control-button svg{width:26px!important;height:26px!important}}@media(min-width:768px){.control-button{width:2.25rem;height:2.25rem}}.control-button:hover:not(:disabled){background:hsl(var(--accent))}.control-button:disabled{opacity:.5;cursor:not-allowed}.control-button.muted{background:hsl(var(--muted));color:hsl(var(--foreground))}.record-button{height:2rem;padding:0 .75rem;border-radius:9999px;font-weight:500;font-size:.75rem;background:hsl(var(--destructive));color:hsl(var(--destructive-foreground));border:none;display:flex;align-items:center;gap:.375rem;transition:all .2s ease}@media(min-width:768px){.record-button{height:2.25rem;font-size:.875rem}}.record-button:hover:not(:disabled){background:hsl(var(--destructive) / .9)}.rec-indicator-top{position:absolute;top:.75rem;left:.75rem;display:flex;align-items:center;gap:.375rem;background:hsl(var(--background) / .9);border:1px solid hsl(var(--border));padding:.25rem .5rem;border-radius:9999px;box-shadow:0 1px 3px #0000001a,0 1px 2px -1px #0000001a}.rec-indicator-top span{font-size:.75rem;font-weight:500}.progress{margin-top:20px;display:none}.progress.active{display:block}.progress-bar{width:100%;height:8px;background:#e0e0e0;border-radius:4px;overflow:hidden;margin-bottom:8px}.progress-fill{height:100%;background:linear-gradient(90deg,#667eea,#764ba2);width:0%;transition:width .3s ease}.progress-text{text-align:center;color:#666;font-size:14px}.result{margin-top:20px;padding:20px;background:#f0f9ff;border:2px solid #667eea;border-radius:8px;display:none}.result.active{display:block}.result-title{font-weight:600;color:#333;margin-bottom:12px}.result-info{color:#666;font-size:14px;margin-bottom:12px}.result-actions{display:flex;gap:12px}.result-actions button{flex:1;margin-top:0;padding:12px;font-size:14px}.error{margin-top:20px;padding:16px;background:#fee;border:2px solid #fcc;border-radius:8px;color:#c33;display:none}.error.active{display:block}.upload-progress{margin-top:20px;display:none}.upload-progress.active{display:block}.upload-status{margin-top:20px;padding:16px;border-radius:8px;display:none}.upload-status.active{display:block}.upload-status.success{background:#f0f9ff;border:2px solid #48bb78;color:#22543d}.upload-status.error{background:#fee;border:2px solid #fcc;color:#c33}.upload-status-text{font-size:14px;font-weight:500}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=function(e){"use strict";var t="undefined"!=typeof document?document.currentScript:null;function r(e){if(!e)throw Error("Assertion failed.")}const i=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw Error(`Invalid rotation ${e}.`)},a=e=>e&&e[e.length-1],s=e=>e>=0&&2**32>e;class n{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(7&this.pos),i=(t&1<<r)>>r;return this.pos++,i}readBits(e){if(1===e)return this.readBit();let t=0;for(let r=0;e>r;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const r=this.pos+e;for(let i=this.pos;r>i;i++){const e=Math.floor(i/8);let a=this.bytes[e];const s=7-(7&i);a&=~(1<<s),a|=(t&1<<r-i-1)>>r-i-1<<s,this.bytes[e]=a}this.pos=r}readAlignedByte(){if(this.pos%8!=0)throw Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new n(this.bytes);return e.pos=this.pos,e}}const o=e=>{let t=0;for(;0===e.readBits(1)&&32>t;)t++;if(t>=32)throw Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},c=e=>{const t=o(e);return 1&t?t+1>>1:-(t>>1)},d=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),l=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),h=new TextDecoder,u=new TextEncoder,m=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),p={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},f=m(p),g={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},w=m(g),b={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},v=m(b),y=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class k{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(t=>{e=t}),r=this.currentPromise;return this.currentPromise=t,await r,e}}const S=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),T=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,C=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;a>=i;){const n=i+a>>1,o=r(e[n]);o===t?(s=n,a=n-1):t>o?i=n+1:a=n-1}return s},E=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;a>=i;){const n=i+(a-i+1)/2|0;r(e[n])>t?a=n-1:(s=n,i=n+1)}return s},x=(e,t,r)=>{const i=E(e,r(t),r);e.splice(i+1,0,t)},_=()=>{let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}},P=e=>{throw Error("Unexpected value: "+e)},M=(e,t,r)=>{const i=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return r?i|a<<8|s<<16:i<<16|a<<8|s},I=(e,t,r,i)=>{r>>>=0,r&=16777215,i?(e.setUint8(t,255&r),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,r>>>16&255)):(e.setUint8(t,r>>>16&255),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,255&r))},A=(e,t)=>({async next(){const r=await e.next();return r.done?{value:void 0,done:!0}:{value:t(r.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),R=(e,t,r)=>Math.max(t,Math.min(r,e)),B="und",z=/^[a-z]{3}$/,F=e=>z.test(e),D=1e6*(1+Number.EPSILON);class O{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let U=null;const L=()=>null!==U?U:U=!("undefined"==typeof navigator||!navigator.vendor?.match(/apple/i));let V=null;const N=()=>null!==V?V:V="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox");let W=null;const H=(e,t,r,i)=>i>=e&&t>=r,q=function*(e){for(const t in e){const r=e[t];void 0!==r&&(yield{key:t,value:r})}},j=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},$=e=>"number"==typeof e&&!Number.isNaN(e);class Q{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof t)throw new TypeError("mimeType must be a string.")}}class K{constructor(e,t,r,i){if(this.data=e,this.mimeType=t,this.name=r,this.description=i,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("name, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("description, when provided, must be a string.")}}const G=e=>{if(!e||"object"!=typeof e)throw new TypeError("tags must be an object.");if(void 0!==e.title&&"string"!=typeof e.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==e.description&&"string"!=typeof e.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==e.artist&&"string"!=typeof e.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==e.album&&"string"!=typeof e.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==e.albumArtist&&"string"!=typeof e.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(!(void 0===e.trackNumber||Number.isInteger(e.trackNumber)&&e.trackNumber>0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(!(void 0===e.tracksTotal||Number.isInteger(e.tracksTotal)&&e.tracksTotal>0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(!(void 0===e.discNumber||Number.isInteger(e.discNumber)&&e.discNumber>0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(!(void 0===e.discsTotal||Number.isInteger(e.discsTotal)&&e.discsTotal>0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==e.genre&&"string"!=typeof e.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==e.date&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==e.lyrics&&"string"!=typeof e.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==e.images){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const t of e.images){if(!t||"object"!=typeof t)throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof t.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==e.comment&&"string"!=typeof e.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==e.raw){if(!e.raw||"object"!=typeof e.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const t of Object.values(e.raw))if(!(null===t||"string"==typeof t||t instanceof Uint8Array||t instanceof Q||t instanceof K))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},X={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Z=["avc","hevc","vp9","av1","vp8"],Y=["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"],J=["aac","opus","mp3","vorbis","flac"],ee=[...J,...Y],te=["webvtt"],re=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],ie=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],ae=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],se=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],ne=(e,t,r,i)=>{if("avc"===e){const e=100,s=Math.ceil(t/16)*Math.ceil(r/16),n=re.find(e=>s<=e.maxMacroblocks&&i<=e.maxBitrate)??a(re),o=n?n.level:0;return`avc1.${e.toString(16).padStart(2,"0")}00${o.toString(16).padStart(2,"0")}`}if("hevc"===e){const e="",s=1,n="6",o=t*r,c=ie.find(e=>o<=e.maxPictureSize&&i<=e.maxBitrate)??a(ie),d="B0";return`hev1.${e}${s}.${n}.${c.tier}${c.level}.${d}`}if("vp8"===e)return"vp8";if("vp9"===e){const e=t*r,s="08";return`vp09.00.${(ae.find(t=>e<=t.maxPictureSize&&i<=t.maxBitrate)??a(ae)).level.toString().padStart(2,"0")}.${s}`}if("av1"===e){const e=0,s=t*r,n=se.find(e=>s<=e.maxPictureSize&&i<=e.maxBitrate)??a(se),o="08";return`av01.${e}.${n.level.toString().padStart(2,"0")}${n.tier}.${o}`}throw new TypeError(`Unhandled codec '${e}'.`)},oe=e=>{const{codec:t,codecDescription:i,colorSpace:s,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:c,av1CodecInfo:d}=e;if("avc"===t){if(r(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${S(t)}`}if(!i||4>i.byteLength)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${S(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,r=T(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!i||23>i.byteLength)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=l(i),c=o.getUint8(1);e=c>>6&3,t=31&c,r=T(o.getUint32(2)),a=c>>5&1,s=o.getUint8(12),n=[];for(let e=0;6>e;e++)n.push(o.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=r.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(c+=".",c+=n.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!c){const t=e.width*e.height;let r=a(ae).level;for(const e of ae)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.toString().padStart(2,"0")}.08`}let t=`vp09.${c.profile.toString().padStart(2,"0")}.${c.level.toString().padStart(2,"0")}.${c.bitDepth.toString().padStart(2,"0")}.${c.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${c.colourPrimaries.toString().padStart(2,"0")}.${c.transferCharacteristics.toString().padStart(2,"0")}.${c.matrixCoefficients.toString().padStart(2,"0")}.${c.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(".01.01.01.01.00")&&(t=t.slice(0,-15)),t}if("av1"===t){if(!d){const t=e.width*e.height;let r=a(ae).level;for(const e of ae)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}const t=d.profile,r=d.level.toString().padStart(2,"0"),i=d.tier?"H":"M",n=d.bitDepth.toString().padStart(2,"0"),o=d.monochrome?"1":"0",c=100*d.chromaSubsamplingX+10*d.chromaSubsamplingY+1*(d.chromaSubsamplingX&&d.chromaSubsamplingY?d.chromaSamplePosition:0),l=s?.primaries?p[s.primaries]:1,h=s?.transfer?g[s.transfer]:1,u=s?.matrix?b[s.matrix]:1,m=s?.fullRange?1:0;let f=`av01.${t}.${r}${i}.${n}`;return f+=`.${o}.${c.toString().padStart(3,"0")}`,f+="."+l.toString().padStart(2,"0"),f+="."+h.toString().padStart(2,"0"),f+="."+u.toString().padStart(2,"0"),f+="."+m,f.endsWith(".0.110.01.01.01.0")&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${t}'.`)},ce=(e,t,r)=>{if("aac"===e)return 2>t||r>24e3?r>24e3?"mp4a.40.2":"mp4a.40.5":"mp4a.40.29";if("mp3"===e)return"mp3";if("opus"===e)return"opus";if("vorbis"===e)return"vorbis";if("flac"===e)return"flac";if(Y.includes(e))return e;throw new TypeError(`Unhandled codec '${e}'.`)},de=e=>{const{codec:t,codecDescription:r,aacCodecInfo:i}=e;if("aac"===t){if(!i)throw new TypeError("AAC codec info must be provided.");return i.isMpeg2?"mp4a.67":"mp4a.40."+ue(r).objectType}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&Y.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},le=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],he=[-1,1,2,3,4,5,6,8],ue=e=>{if(!e||2>e.byteLength)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new n(e);let r=t.readBits(5);31===r&&(r=32+t.readBits(6));const i=t.readBits(4);let a=null;15===i?a=t.readBits(24):i<le.length&&(a=le[i]);const s=t.readBits(4);let o=null;return 1>s||s>7||(o=he[s]),{objectType:r,frequencyIndex:i,sampleRate:a,channelConfiguration:s,numberOfChannels:o}},me=/^pcm-([usf])(\d+)+(be)?$/,pe=e=>{if(r(Y.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=me.exec(e);let i;return r(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float",{dataType:i,sampleSize:+t[2]/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},fe=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":e.startsWith("mp4a.40")||"mp4a.67"===e?"aac":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e?"mp3":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ulaw"===e?"ulaw":"alaw"===e?"alaw":me.test(e)?e:"webvtt"===e?"webvtt":null,ge=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],we=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,be=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ve=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,ye=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ke=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"];class Se{constructor(e){this.mutex=new k,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let i=this.trackTimestampInfo.get(e);if(!i){if(!r)throw Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,i)}if(0>t)throw Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),t<i.maxTimestampBeforeLastKeyPacket)throw 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 ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);return i.maxTimestamp=Math.max(i.maxTimestamp,t),t}}var Te,Ce,Ee,xe;(Ce=Te||(Te={}))[Ce.IDR=5]="IDR",Ce[Ce.SPS=7]="SPS",Ce[Ce.PPS=8]="PPS",Ce[Ce.SPS_EXT=13]="SPS_EXT",(xe=Ee||(Ee={}))[xe.RASL_N=8]="RASL_N",xe[xe.RASL_R=9]="RASL_R",xe[xe.BLA_W_LP=16]="BLA_W_LP",xe[xe.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",xe[xe.VPS_NUT=32]="VPS_NUT",xe[xe.SPS_NUT=33]="SPS_NUT",xe[xe.PPS_NUT=34]="PPS_NUT",xe[xe.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",xe[xe.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const _e=e=>{const t=[];let r=0;for(;r<e.length;){let i=-1,a=0;for(let t=r;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){i=t,a=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){i=t,a=4;break}}if(-1===i)break;if(r>0&&i>r){const a=e.subarray(r,i);a.length>0&&t.push(a)}r=i+a}if(r<e.length){const i=e.subarray(r);i.length>0&&t.push(i)}return t},Pe=(e,t)=>{const i=[];let a=0;const s=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;a+t<=e.length;){let n;1===t?n=s.getUint8(a):2===t?n=s.getUint16(a,!1):3===t?n=M(s,a,!1):4===t?n=s.getUint32(a,!1):(P(t),r(!1)),a+=t;const o=e.subarray(a,a+n);i.push(o),a+=n}return i},Me=e=>{const t=[],r=e.length;for(let i=0;r>i;i++)r>i+2&&0===e[i]&&0===e[i+1]&&3===e[i+2]?(t.push(0,0),i+=2):t.push(e[i]);return new Uint8Array(t)},Ie=e=>31&e[0],Ae=e=>{try{const t=new n(Me(e));if(t.skipBits(1),t.skipBits(2),7!==t.readBits(5))return null;const r=t.readAlignedByte(),i=t.readAlignedByte(),a=t.readAlignedByte();o(t);let s=null,d=null,l=null;if((100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r)&&(s=o(t),3===s&&t.skipBits(1),d=o(t),l=o(t),t.skipBits(1),t.readBits(1)))for(let e=0;(3!==s?8:12)>e;e++)if(t.readBits(1)){const r=6>e?16:64;let i=8,a=8;for(let e=0;r>e;e++)0!==a&&(a=(i+c(t)+256)%256),i=0===a?i:a}o(t);const h=o(t);if(0===h)o(t);else if(1===h){t.skipBits(1),c(t),c(t);const e=o(t);for(let r=0;e>r;r++)c(t)}return o(t),t.skipBits(1),o(t),o(t),{profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:s,bitDepthLumaMinus8:d,bitDepthChromaMinus8:l}}catch(t){return null}},Re=(e,t)=>{if(t.description){const r=3&d(t.description)[21];return Pe(e,r+1)}return _e(e)},Be=e=>e[0]>>1&63,ze=(e,t,r,i)=>{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){n=t===r?t-(o(e)+1):t-1,e.readBits(1),o(e);const s=i[n]??0;for(let t=0;s>=t;t++)e.readBits(1)||e.readBits(1);a=i[n]}else{const t=o(e),r=o(e);for(let i=0;t>i;i++)o(e),e.readBits(1);for(let i=0;r>i;i++)o(e),e.readBits(1);a=t+r}return a},Fe=(e,t,r)=>{for(let i=0;t>i;i++)o(e),o(e),r&&(o(e),o(e)),e.readBits(1)},De=function*(e){const t=new n(e),i=()=>{let e=0;for(let r=0;8>r;r++){const i=t.readAlignedByte();if(e|=(127&i)<<7*r,!(128&i))break;if(7===r&&128&i)return null}return 2**32-1>e?e:null};for(;t.getBitsLeft()>=8;){t.skipBits(1);const a=t.readBits(4),s=t.readBits(1),n=t.readBits(1);let o;if(t.skipBits(1),s&&t.skipBits(8),n){const e=i();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);r(t.pos%8==0),yield{type:a,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},Oe=(e,t,i)=>{switch(e){case"avc":{const e=((e,t)=>{if(t.description){const r=3&d(t.description)[4];return Pe(e,r+1)}return _e(e)})(i,t);return e.some(e=>Ie(e)===Te.IDR)?"key":"delta"}case"hevc":return Re(i,t).some(e=>{const t=Be(e);return Ee.BLA_W_LP<=t&&t<=Ee.RSV_IRAP_VCL23})?"key":"delta";case"vp8":return 1&i[0]?"delta":"key";case"vp9":{const e=new n(i);if(2!==e.readBits(2))return null;const t=e.readBits(1);return 3===(e.readBits(1)<<1)+t&&e.skipBits(1),e.readBits(1)?null:0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:r}of De(i))if(1===t){const t=new n(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new n(r);return t.readBits(1)?null:0===t.readBits(2)?"key":"delta"}return null}default:P(e),r(!1)}};var Ue,Le;(Le=Ue||(Ue={}))[Le.STREAMINFO=0]="STREAMINFO",Le[Le.VORBIS_COMMENT=4]="VORBIS_COMMENT",Le[Le.PICTURE=6]="PICTURE";class Ve{constructor(e){this.input=e}}const Ne=[],We=[],He=[],qe=[],je=new Uint8Array(0);class $e{constructor(e,t,r,i,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=r,this.duration=i,this.sequenceNumber=a,e===je&&void 0===s)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||0>i)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||0>s)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!=typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||0>n.alphaByteLength))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===je}get microsecondTimestamp(){return Math.trunc(D*this.timestamp)}get microsecondDuration(){return Math.trunc(D*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=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 Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,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 Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){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 $e(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}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?.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.");return new $e(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}j();class Qe{get displayWidth(){return this.rotation%180==0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180==0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(D*this.timestamp)}get microsecondDuration(){return Math.trunc(D*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(!("format"in t)||"string"!=typeof t.format)throw new TypeError("init.format must be a string.");if(!Number.isInteger(t.codedWidth)||0>=t.codedWidth)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||0>=t.codedHeight)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||0>t.duration))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=d(e).slice(),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace(t.colorSpace)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||0>t.duration))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=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))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!t||"object"!=typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||0>t.duration))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new Qe(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*D),duration:Math.trunc((t.duration??0)*D)||void 0}),t);let i=0,a=0;if("naturalWidth"in e?(i=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,a=e.videoHeight):"width"in e&&(i=+e.width,a=+e.height),!i||!a)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(i,a),n=s.getContext("2d",{alpha:N(),willReadFrequently:!0});r(n),n.drawImage(e,0,0),this._data=s,this.format="RGBX",this.codedWidth=i,this.codedHeight=a,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}}clone(){if(this._closed)throw Error("VideoSample is closed.");return r(null!==this._data),Ke(this._data)?new Qe(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new Qe(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new Qe(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(Ke(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw Error("VideoSample is closed.");return r(null!==this._data),Ke(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!y(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw Error("VideoSample is closed.");if(r(null!==this._data),Ke(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)d(e).set(this._data);else{const t=this._data.getContext("2d");r(t);const i=t.getImageData(0,0,this.codedWidth,this.codedHeight);d(e).set(i.data)}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");return r(null!==this._data),Ke(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,r,i,a,s,n,o,c){let d=0,l=0,h=this.displayWidth,u=this.displayHeight,m=0,p=0,f=this.displayWidth,g=this.displayHeight;if(void 0!==s?(d=t,l=r,h=i,u=a,m=s,p=n,void 0!==o?(f=o,g=c):(f=h,g=u)):(m=t,p=r,void 0!==i&&(f=i,g=a)),!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||0>h)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||0>u)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(f)||0>f)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||0>g)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:d,sy:l,sWidth:h,sHeight:u}=this._rotateSourceRegion(d,l,h,u,this.rotation));const w=this.toCanvasImageSource();e.save();const b=m+f/2,v=p+g/2;e.translate(b,v),e.rotate(this.rotation*Math.PI/180);const y=this.rotation%180==0?1:f/g;e.scale(1/y,y),e.drawImage(w,d,l,h,u,-f/2,-g/2,f,g),e.restore()}drawWithFit(e,t){if(!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Xe(t.crop,"options.");const r=e.canvas.width,i=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let o,c,d,l;t.crop&&Ge(t.crop,s,n);const{sx:h,sy:u,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,d=r,l=i;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],h="contain"===t.fit?Math.min(r/e,i/a):Math.max(r/e,i/a);d=e*h,l=a*h,o=(r-d)/2,c=(i-l)/2}e.save();const f=a%180==0?1:d/l;e.translate(r/2,i/2),e.rotate(a*Math.PI/180),e.scale(1/f,f),e.translate(-r/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,u,m,p,o,c,d,l),e.restore()}_rotateSourceRegion(e,t,r,i,a){return 90===a?[e,t,r,i]=[t,this.codedHeight-e-r,i,r]:180===a?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-i]:270===a&&([e,t,r,i]=[this.codedWidth-t-i,e,i,r]),{sx:e,sy:t,sWidth:r,sHeight:i}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(r(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||0>e)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}const Ke=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,Ge=(e,t,i)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,i),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,i-e.top),r(e.width>=0),r(e.height>=0)},Xe=(e,t)=>{if(!e||"object"!=typeof e)throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||0>e.left)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||0>e.top)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||0>e.width)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||0>e.height)throw new TypeError(t+"crop.height must be a non-negative integer.")},Ze=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Ye{get microsecondTimestamp(){return Math.trunc(D*this.timestamp)}get microsecondDuration(){return Math.trunc(D*this.duration)}constructor(e){if(this._closed=!1,it(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!=typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ze.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||0>=e.sampleRate)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Je(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let r;if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate,e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const i=this.numberOfFrames*this.numberOfChannels*Je(this.format);if(r.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}}allocationSize(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||0>e.planeIndex)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!Ze.has(e.format))throw new TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||0>e.frameOffset))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||0>e.frameCount))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");const t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const i=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(i>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const a=Je(t),s=et(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?i:i*this.numberOfChannels)*a}copyTo(e,t){if(!y(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||0>t.planeIndex)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!Ze.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||0>t.frameOffset))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||0>t.frameCount))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");const{planeIndex:r,format:i,frameCount:a,frameOffset:s}=t,n=i??this.format;if(!n)throw Error("Destination format not determined");const o=this.numberOfFrames,c=this.numberOfChannels,d=s??0;if(d>=o)throw new RangeError("frameOffset out of range");const h=void 0!==a?a:o-d;if(h>o-d)throw new RangeError("frameCount out of range");const u=Je(n),m=et(n);if(m&&r>=c)throw new RangeError("planeIndex out of range");if(!m&&0!==r)throw new RangeError("planeIndex out of range");const p=(m?h:h*c)*u;if(e.byteLength<p)throw new RangeError("Destination buffer is too small");const f=l(e),g=rt(n);if(it(this._data))if(m)if("f32-planar"===n)this._data.copyTo(e,{planeIndex:r,frameOffset:d,frameCount:h,format:"f32-planar"});else{const e=new ArrayBuffer(4*h),t=new Float32Array(e);this._data.copyTo(t,{planeIndex:r,frameOffset:d,frameCount:h,format:"f32-planar"});const i=new DataView(e);for(let r=0;h>r;r++)g(f,r*u,i.getFloat32(4*r,!0))}else{const e=c,t=new Float32Array(h);for(let r=0;e>r;r++){this._data.copyTo(t,{planeIndex:r,frameOffset:d,frameCount:h,format:"f32-planar"});for(let i=0;h>i;i++)g(f,(i*e+r)*u,t[i])}}else{const e=this._data,t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=this.format,a=tt(i),s=Je(i),n=et(i);for(let l=0;h>l;l++)if(m){let e;e=n?(r*o+(l+d))*s:((l+d)*c+r)*s,g(f,l*u,a(t,e))}else for(let e=0;c>e;e++){let r;r=n?(e*o+(l+d))*s:((l+d)*c+e)*s,g(f,(l*c+e)*u,a(t,r))}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(it(this._data)){const e=new Ye(this._data.clone());return e.setTimestamp(this.timestamp),e}return new Ye({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(it(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(it(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(et(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,s=Math.floor(24e4/r);let n=0,o=a;for(;o>0;){const a=Math.min(s,o),c=new Float32Array(r*a);for(let t=0;r>t;t++)e.copyFromChannel(c.subarray(t*a,(t+1)*a),t,n);yield new Ye({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:c}),n+=a,o-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,s=Math.floor(24e4/r);let n=0,o=a;const c=[];for(;o>0;){const a=Math.min(s,o),d=new Float32Array(r*a);for(let t=0;r>t;t++)e.copyFromChannel(d.subarray(t*a,(t+1)*a),t,n);const l=new Ye({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:d});c.push(l),n+=a,o-=a}return c}}const Je=e=>{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},et=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},tt=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},rt=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,R(127.5*(r+1),0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,R(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,R(Math.round(2147483647*r),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},it=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,at=e=>{if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},st=e=>{if(!$(e))throw new TypeError("timestamp must be a number.")},nt=(e,t,r)=>r.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const r=await e.determinePacketType(t);return r&&(t.type=r),t}):t;class ot{constructor(e){if(!(e instanceof bt))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(at(e),this._track.input._disposed)throw new Jt;return nt(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(st(e),at(t),this._track.input._disposed)throw new Jt;return nt(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof $e))throw new TypeError("packet must be an EncodedPacket.");if(at(t),this._track.input._disposed)throw new Jt;return nt(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(st(e),at(t),this._track.input._disposed)throw new Jt;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);return r&&"delta"!==r.type&&"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/this._track.timeResolution,t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof $e))throw new TypeError("packet must be an EncodedPacket.");if(at(t),this._track.input._disposed)throw new Jt;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);return r&&"delta"!==r.type&&"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(void 0!==e&&!(e instanceof $e))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof $e))throw new TypeError("endPacket must be an EncodedPacket.");if(at(r),this._track.input._disposed)throw new Jt;const i=[];let{promise:a,resolve:s}=_(),{promise:n,resolve:o}=_(),c=!1,d=!1,l=null;const h=[],u=()=>Math.max(2,h.length);(async()=>{let l=e??await this.getFirstPacket(r);for(;l&&!d&&!this._track.input._disposed&&(!t||l.sequenceNumber<t?.sequenceNumber);)i.length>u()?(({promise:n,resolve:o}=_()),await n):(i.push(l),s(),({promise:a,resolve:s}=_()),l=await this.getNextPacket(l,r));c=!0,s()})().catch(e=>{l||(l=e,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Jt;if(d)return{value:void 0,done:!0};if(l)throw l;if(i.length>0){const e=i.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(d=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class ct{constructor(e,t){this.onSample=e,this.onError=t}}class dt{mediaSamplesInRange(e=0,t=1/0){st(e),st(t);const r=[];let i=!1,a=null,{promise:s,resolve:n}=_(),{promise:o,resolve:c}=_(),d=!1,l=!1,h=!1,u=null;(async()=>{const m=Error(),p=await this._createDecoder(o=>{c(),o.timestamp<t||(l=!0),l?o.close():(a&&(o.timestamp>e?(r.push(a),i=!0):a.close()),o.timestamp<e||(r.push(o),i=!0),a=i?null:o,r.length>0&&(n(),({promise:s,resolve:n}=_())))},e=>{u||(e.stack=m.stack,u=e,n())}),f=this._createPacketSink(),g=await f.getKeyPacket(e,{verifyKeyPackets:!0})??await f.getFirstPacket();if(!g)return;let w,b=g;if(1/0>t){const e=await f.getPacket(t),r=e?"key"===e.type&&e.timestamp===t?e:await f.getNextKeyPacket(e,{verifyKeyPackets:!0}):null;r&&(w=r)}const v=f.packets(g,w);for(await v.next();b&&!l&&!this._track.input._disposed;){const e=lt(r.length);if(r.length+p.getDecodeQueueSize()>e){({promise:o,resolve:c}=_()),await o;continue}p.decode(b);const t=await v.next();if(t.done)break;b=t.value}await v.return(),h||this._track.input._disposed||await p.flush(),p.close(),!i&&a&&r.push(a),d=!0,n()})().catch(e=>{u||(u=e,n())});const m=this._track,p=()=>{a?.close();for(const e of r)e.close()};return{async next(){for(;;){if(m.input._disposed)throw p(),new Jt;if(h)return{value:void 0,done:!0};if(u)throw p(),u;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(d)return{value:void 0,done:!0};await s}},return:async()=>(h=!0,l=!0,c(),n(),p(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const t=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),i=[],a=[];let{promise:s,resolve:n}=_(),{promise:o,resolve:c}=_(),d=!1,l=!1,h=null;const u=e=>{a.push(e),n(),({promise:s,resolve:n}=_())};(async()=>{const e=Error(),s=await this._createDecoder(e=>{if(c(),l)return void e.close();let t=0;for(;i.length>0&&e.timestamp-i[0]>-1e-10;)t++,i.shift();if(t>0)for(let r=0;t>r;r++)u(t-1>r?e.clone():e);else e.close()},t=>{h||(t.stack=e.stack,h=t,n())}),m=this._createPacketSink();let p=null,f=null,g=-1;const w=async()=>{r(f);let e=f;for(s.decode(e);e.sequenceNumber<g;){const t=lt(a.length);for(;a.length+s.getDecodeQueueSize()>t&&!l;)({promise:o,resolve:c}=_()),await o;if(l)break;const i=await m.getNextPacket(e);r(i),s.decode(i),e=i}g=-1},b=async()=>{await s.flush();for(let e=0;e<i.length;e++)u(null);i.length=0};for await(const r of t){if(st(r),l||this._track.input._disposed)break;const e=await m.getPacket(r),t=e&&await m.getKeyPacket(r,{verifyKeyPackets:!0});t?(p&&(t.sequenceNumber!==f.sequenceNumber||e.timestamp<p.timestamp)&&(await w(),await b()),i.push(e.timestamp),g=Math.max(e.sequenceNumber,g),p=e,f=t):(-1!==g&&(await w(),await b()),u(null),p=null)}l||this._track.input._disposed||(-1!==g&&await w(),await b()),s.close(),d=!0,n()})().catch(e=>{h||(h=e,n())});const m=this._track,p=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(m.input._disposed)throw p(),new Jt;if(l)return{value:void 0,done:!0};if(h)throw p(),h;if(a.length>0){const e=a.shift();return r(void 0!==e),c(),{value:e,done:!1}}if(d)return{value:void 0,done:!0};await s}},return:async()=>(l=!0,c(),n(),p(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const lt=e=>0===e?40:8;class ht extends ct{constructor(e,t,i,a,s,n){super(e,t),this.codec=i,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new O,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const o=Ne.find(e=>e.supports(i,a));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof Qe))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();r(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===i&&this.decoderConfig.description&&(null!==W?W:W=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")))){const e=(e=>{try{const t=l(e);let r=0;const i=t.getUint8(r++),a=t.getUint8(r++),s=t.getUint8(r++),n=t.getUint8(r++),o=3&t.getUint8(r++),c=31&t.getUint8(r++),d=[];for(let l=0;c>l;l++){const i=t.getUint16(r,!1);r+=2,d.push(e.subarray(r,r+i)),r+=i}const h=t.getUint8(r++),u=[];for(let l=0;h>l;l++){const i=t.getUint16(r,!1);r+=2,u.push(e.subarray(r,r+i)),r+=i}const m={configurationVersion:i,avcProfileIndication:a,profileCompatibility:s,avcLevelIndication:n,lengthSizeMinusOne:o,sequenceParameterSets:d,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&r+4<=e.length){const i=3&t.getUint8(r++),a=7&t.getUint8(r++),s=7&t.getUint8(r++),n=t.getUint8(r++);m.chromaFormat=i,m.bitDepthLumaMinus8=a,m.bitDepthChromaMinus8=s;const o=[];for(let c=0;n>c;c++){const i=t.getUint16(r,!1);r+=2,o.push(e.subarray(r,r+i)),r+=i}m.sequenceParameterSetExt=o}return m}catch(t){return null}})(d(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Ae(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(r){this.onError(r)}},error:t}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(r(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}this.currentPacketIndex++,this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(r(this.decoder),L()||x(this.inputTimestamps,e.timestamp,e=>e),this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e))}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new ut}catch(i){return this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();r(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();r(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)};this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:this.onError}),this.alphaDecoder.configure(this.decoderConfig)}const t=Oe(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return Re(e,this.decoderConfig).some(e=>{const t=Be(e);return t===Ee.RASL_N||t===Ee.RASL_R})}sampleHandler(e){if(L()){if(this.sampleQueue.length>0&&e.timestamp>=a(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}x(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();r(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){const t=new Qe(e);return void this.sampleHandler(t)}r(this.merger),this.merger.update(e,t),e.close(),t.close();const i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),a=new Qe(i);this.sampleHandler(a)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(r(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),L()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(r(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}class ut{constructor(){"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const i=this.gl.getAttribLocation(this.program,"a_position"),a=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class mt extends dt{constructor(e){if(!(e instanceof vt))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=this._track.codec,a=this._track.rotation,s=await this._track.getDecoderConfig(),n=this._track.timeResolution;return r(i&&s),new ht(e,t,i,s,a,n)}_createPacketSink(){return new ot(this._track)}async getSample(e){st(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class pt{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof vt))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.alpha&&"boolean"!=typeof t.alpha)throw new TypeError("options.alpha, when provided, must be a boolean.");if(!(void 0===t.width||Number.isInteger(t.width)&&t.width>0))throw new TypeError("options.width, when defined, must be a positive integer.");if(!(void 0===t.height||Number.isInteger(t.height)&&t.height>0))throw new TypeError("options.height, when defined, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&Xe(t.crop,"options."),void 0!==t.poolSize&&("number"!=typeof t.poolSize||!Number.isInteger(t.poolSize)||0>t.poolSize))throw new TypeError("poolSize must be a non-negative integer.");const r=t.rotation??e.rotation,[i,a]=r%180==0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&Ge(s,i,a);let[n,o]=s?[s.width,s.height]:[i,a];const c=n/o;void 0!==t.width&&void 0===t.height?(n=t.width,o=Math.round(n/c)):void 0===t.width&&void 0!==t.height?(o=t.height,n=Math.round(o*c)):void 0!==t.width&&void 0!==t.height&&(n=t.width,o=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=n,this._height=o,this._rotation=r,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new mt(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],i=!1;t||("undefined"!=typeof document?(t=document.createElement("canvas"),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),i=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=t.getContext("2d",{alpha:this._alpha||N()});r(a),a.resetTransform(),i||(!this._alpha&&N()?(a.fillStyle="black",a.fillRect(0,0,this._width,this._height)):a.clearRect(0,0,this._width,this._height)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});const s={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e){st(e);const t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return A(this._videoSampleSink.samples(e,t),e=>this._videoSampleToWrappedCanvas(e))}canvasesAtTimestamps(e){return A(this._videoSampleSink.samplesAtTimestamps(e),e=>e&&this._videoSampleToWrappedCanvas(e))}}class ft extends ct{constructor(e,t,r,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new O,this.customDecoderQueueSize=0,this.currentTimestamp=null;const a=t=>{null!==this.currentTimestamp&&Math.abs(t.timestamp-this.currentTimestamp)<t.duration||(this.currentTimestamp=t.timestamp);const r=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const a=i.sampleRate;t.setTimestamp(Math.round(r*a)/a),e(t)},s=We.find(e=>e.supports(r,i));s?(this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof Ye))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init())):(this.decoder=new AudioDecoder({output:e=>{try{a(new Ye(e))}catch(t){this.onError(t)}},error:t}),this.decoder.configure(i))}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(r(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(r(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(r(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(r(this.decoder),this.decoder.close())}}class gt extends ct{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,r(Y.includes(i.codec)),this.codec=i.codec;const{dataType:a,sampleSize:s,littleEndian:n}=pe(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=~e;128&i&&(i&=-129,t=-1),r=5+((240&i)>>4);const a=(1<<r|(15&i)<<r-4|1<<r-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===a?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=85^e;128&i&&(i&=-129,t=-1),r=4+((240&i)>>4);let a=0;return a=4!==r?1<<r|(15&i)<<r-4|1<<r-5:i<<1|1,0===t?a:-a})(e.getUint8(t)):r(!1);break;case 2:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):r(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>M(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,r)=>M(e,t,r)<<8>>8)(e,t,n):r(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):r(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):r(!1);break;default:P(s),r(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,r)=>e.setUint8(t,r+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r<<8,!0);break;case 4:this.outputSampleSize=4,"float"===a?(this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0);break;default:P(s),r(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=l(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(i),s=new DataView(a);for(let d=0;d<r*this.decoderConfig.numberOfChannels;d++){const e=d*this.inputSampleSize,r=d*this.outputSampleSize,i=this.readInputValue(t,e);this.writeOutputValue(s,r,i)}const n=r/this.decoderConfig.sampleRate;null!==this.currentTimestamp&&Math.abs(e.timestamp-this.currentTimestamp)<n||(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const c=new Ye({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:o});this.onSample(c)}async flush(){}close(){}}class wt extends dt{constructor(e){if(!(e instanceof yt))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=this._track.codec,a=await this._track.getDecoderConfig();return r(i&&a),Y.includes(a.codec)?new gt(e,t,a):new ft(e,t,i,a)}_createPacketSink(){return new ot(this._track)}async getSample(e){st(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class bt{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof vt}isAudioTrack(){return this instanceof yt}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){const t=new ot(this);let r=1/0,i=-1/0,a=0,s=0;for await(const n of t.packets(void 0,void 0,{metadataOnly:!0})){if(a>=e&&n.timestamp>=i)break;r=Math.min(r,n.timestamp),i=Math.max(i,n.timestamp+n.duration),a++,s+=n.byteLength}return{packetCount:a,averagePacketRate:a?+(a/(i-r)).toPrecision(16):0,averageBitrate:a?+(8*s/(i-r)).toPrecision(16):0}}}class vt extends bt{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180==0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180==0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();return r(null!==t),!!Ne.some(r=>r.supports(t,e))||"undefined"!=typeof VideoDecoder&&!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return!1}}async determinePacketType(e){if(!(e instanceof $e))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;const t=await this.getDecoderConfig();return r(t),Oe(this.codec,t,e.data)}}class yt extends bt{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=this._backing.getCodec();return r(null!==t),!!We.some(r=>r.supports(t,e))||!!e.codec.startsWith("pcm-")||"undefined"!=typeof AudioDecoder&&!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return!1}}async determinePacketType(e){if(!(e instanceof $e))throw new TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"}}const kt=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");return e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`),t},St=16,Tt=e=>{let t=cr(e);const r=mr(e,4);let i=8;1===t&&(t=lr(e),i=16);const a=t-i;return 0>a?null:{name:r,totalSize:t,headerSize:i,contentSize:a}},Ct=e=>dr(e)/65536,Et=e=>dr(e)/1073741824,xt=e=>{let t=0;for(let r=0;4>r;r++){t<<=7;const r=ar(e);if(t|=127&r,!(128&r))break}return t},_t=e=>{let t=sr(e);return e.skip(2),t=Math.min(t,e.remainingLength),h.decode(ir(e,t))},Pt=e=>{const t=Tt(e);if(!t||"data"!==t.name)return null;if(8>e.remainingLength)return null;const r=cr(e);e.skip(4);const i=ir(e,t.contentSize-8);switch(r){case 1:return h.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new Q(i,"image/jpeg");case 14:return new Q(i,"image/png");case 27:return new Q(i,"image/bmp");default:return i}};class Mt extends Ve{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));return kt({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,St);if(t instanceof Promise&&(t=await t),!t)break;const r=e,i=Tt(t);if(!i)break;if("ftyp"===i.name){const e=mr(t,4);this.isQuickTime="qt "===e}else if("moov"===i.name){let e=this.reader.requestSlice(t.filePos,i.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>+t.disposition.default-+e.disposition.default);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}break}e=r+i.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),r(e);const t=cr(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-St){let e=this.reader.requestSliceRange(i,8,St);if(e instanceof Promise&&(e=await e),e){const t=Tt(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=await r),r&&this.readContiguousBoxes(r)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,r(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,"audio"===e.info?.type&&e.info.codec&&Y.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){r("audio"===e.info?.type);const i=pe(e.info.codec),s=[],n=[];for(let r=0;r<t.sampleToChunk.length;r++){const o=t.sampleToChunk[r],c=t.sampleToChunk[r+1],d=(c?c.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let r=0;d>r;r++){const c=o.startSampleIndex+r*o.samplesPerChunk,d=c+o.samplesPerChunk,l=E(t.sampleTimingEntries,c,e=>e.startIndex),h=t.sampleTimingEntries[l],u=E(t.sampleTimingEntries,d,e=>e.startIndex),m=t.sampleTimingEntries[u],p=h.startDecodeTimestamp+(c-h.startIndex)*h.delta,f=m.startDecodeTimestamp+(d-m.startIndex)*m.delta-p,g=a(s);g&&g.delta===f?g.count++:s.push({startIndex:o.startChunkIndex+r,startDecodeTimestamp:p,count:1,delta:f});const w=o.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;n.push(w)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=s,t.sampleSizes=n}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let r=0;r<e.count;r++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+r*e.delta,sampleIndex:e.startIndex+r});for(const e of t.sampleCompositionTimeOffsets)for(let r=0;r<e.count;r++){const i=e.startIndex+r,a=t.presentationTimestamps[i];a&&(a.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,St);t instanceof Promise&&(t=await t),r(t);const i=Tt(t);r("moof"===i?.name);let a=this.reader.requestSlice(e,i.totalSize);a instanceof Promise&&(a=await a),r(a),this.traverseBox(a);const s=this.lastReadFragment;r(s&&s.moofOffset===e);for(const[,r]of s.trackData){const e=r.track,{fragmentPositionCache:t}=e;if(!r.startTimestampIsFinal){const i=e.fragmentLookupTable.find(e=>e.moofOffset===s.moofOffset);if(i)Ot(r,i.timestamp);else{const e=E(t,s.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Ot(r,i.endTimestamp)}}r.startTimestampIsFinal=!0}const i=E(t,r.startTimestamp,e=>e.startTimestamp);-1!==i&&t[i].moofOffset===s.moofOffset||t.splice(i+1,0,{moofOffset:s.moofOffset,startTimestamp:r.startTimestamp,endTimestamp:r.endTimestamp})}return s}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,r=Tt(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){const t=e.filePos,s=Tt(e);if(!s)return!1;const o=e.filePos,c=t+s.totalSize;switch(s.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice(o,s.contentSize));break;case"mvhd":{const t=ar(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=cr(e),this.movieDurationInTimescale=lr(e)):(e.skip(8),this.movieTimescale=cr(e),this.movieDurationInTimescale=cr(e))}break;case"trak":{const t={id:-1,demuxer:this,inputTrack:null,disposition:{...X},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:B,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(o,s.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info)if("video"===t.info.type&&-1!==t.info.width){const e=t;t.inputTrack=new vt(this.input,new At(e)),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.inputTrack=new yt(this.input,new Rt(e)),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const a=ar(e),s=!!(1&nr(e));if(t.disposition.default=s,0===a)e.skip(8),t.id=cr(e),e.skip(4),t.durationInMovieTimescale=cr(e);else{if(1!==a)throw Error(`Incorrect track header version ${a}.`);e.skip(16),t.id=cr(e),e.skip(4),t.durationInMovieTimescale=lr(e)}e.skip(16);const n=[Ct(e),Ct(e),Et(e),Ct(e),Ct(e),Et(e),Ct(e),Ct(e),Et(e)],o=i((d=Ut(n),90*Math.round(d/90)));r(0===o||90===o||180===o||270===o),t.rotation=o}break;case"elst":{const t=this.currentTrack;if(!t)break;const r=ar(e);e.skip(3);let i=!1,a=0;const s=cr(e);for(let n=0;s>n;n++){const s=1===r?lr(e):cr(e),n=1===r?hr(e):dr(e),o=Ct(e);if(0!==s){if(i)break;if(-1!==n){if(1!==o)break;t.editListPreviousSegmentDurations=a,t.editListOffset=n,i=!0}else a+=s}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const r=ar(e);e.skip(3),0===r?(e.skip(8),t.timescale=cr(e),t.durationInMediaTimescale=cr(e)):1===r&&(e.skip(16),t.timescale=cr(e),t.durationInMediaTimescale=lr(e));let i=sr(e);if(i>0){t.languageCode="";for(let e=0;3>e;e++)t.languageCode=String.fromCharCode(96+(31&i))+t.languageCode,i>>=5;F(t.languageCode)||(t.languageCode=B)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const r=mr(e,4);"vide"===r?t.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===r&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const r=this.currentTrack;if(!r)break;r.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(o,s.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const r=ar(e);e.skip(3);const i=cr(e);for(let a=0;i>a;a++){const i=e.filePos,a=Tt(e);if(!a)break;t.internalCodecId=a.name;const s=a.name.toLowerCase();if("video"===t.info.type)"avc1"===s||"avc3"===s?(t.info.codec="avc",t.info.avcType="avc1"===s?1:3):"hvc1"===s||"hev1"===s?t.info.codec="hevc":"vp08"===s?t.info.codec="vp8":"vp09"===s?t.info.codec="vp9":"av01"===s&&(t.info.codec="av1"),e.skip(24),t.info.width=sr(e),t.info.height=sr(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos));else{"mp4a"===s||("opus"===s?t.info.codec="opus":"flac"===s?t.info.codec="flac":"twos"===s||"sowt"===s||"raw "===s||"in24"===s||"in32"===s||"fl32"===s||"fl64"===s||"lpcm"===s||"ipcm"===s||"fpcm"===s||("ulaw"===s?t.info.codec="ulaw":"alaw"===s&&(t.info.codec="alaw"))),e.skip(8);const n=sr(e);e.skip(6);let o=sr(e),c=sr(e);e.skip(4);let d=cr(e)/65536;if(0===r&&n>0)if(1===n)e.skip(4),c=8*cr(e),e.skip(8);else if(2===n){e.skip(4),d=ur(e),o=cr(e),e.skip(4),c=cr(e);const r=cr(e);if(e.skip(8),"lpcm"===s){const e=c+7>>3,i=!!(2&r),a=4&r?-1:0;c>0&&64>=c&&(1&r?32===c&&(t.info.codec=i?"pcm-f32be":"pcm-f32"):a&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=i?"pcm-s16be":"pcm-s16":3===e?t.info.codec=i?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=i?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),t.info.codec}}"opus"===t.info.codec&&(d=48e3),t.info.numberOfChannels=o,t.info.sampleRate=d,"twos"===s?t.info.codec=8===c?"pcm-s8":16===c?"pcm-s16be":null:"sowt"===s?t.info.codec=8===c?"pcm-s8":16===c?"pcm-s16":null:"raw "===s?t.info.codec="pcm-u8":"in24"===s?t.info.codec="pcm-s24be":"in32"===s?t.info.codec="pcm-s32be":"fl32"===s?t.info.codec="pcm-f32be":"fl64"===s?t.info.codec="pcm-f64be":"ipcm"===s?t.info.codec="pcm-s16be":"fpcm"===s&&(t.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos))}}}break;case"avcC":{const t=this.currentTrack;if(!t)break;r(t.info),t.info.codecDescription=ir(e,s.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;r(t.info),t.info.codecDescription=ir(e,s.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;r("video"===t.info?.type),e.skip(4);const i=ar(e),a=ar(e),s=ar(e),n=s>>4,o=s>>1&7,c=1&s,d=ar(e),l=ar(e),h=ar(e);t.info.vp9CodecInfo={profile:i,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:d,transferCharacteristics:l,matrixCoefficients:h}}break;case"av1C":{const t=this.currentTrack;if(!t)break;r("video"===t.info?.type),e.skip(1);const i=ar(e),a=i>>5,s=31&i,n=ar(e),o=n>>7,c=n>>6&1,d=n>>4&1,l=n>>3&1,h=n>>2&1,u=3&n,m=2===a&&c?n>>5&1?12:10:c?10:8;t.info.av1CodecInfo={profile:a,level:s,tier:o,bitDepth:m,monochrome:d,chromaSubsamplingX:l,chromaSubsamplingY:h,chromaSamplePosition:u}}break;case"colr":{const t=this.currentTrack;if(!t)break;if(r("video"===t.info?.type),"nclx"!==mr(e,4))break;const i=sr(e),a=sr(e),s=sr(e),n=!!(128&ar(e));t.info.colorSpace={primaries:f[i],transfer:w[a],matrix:v[s],fullRange:n}}break;case"esds":{const t=this.currentTrack;if(!t)break;r("audio"===t.info?.type),e.skip(4),r(3===ar(e)),xt(e),e.skip(2);const i=ar(e),a=!!(64&i),s=!!(32&i);if(!!(128&i)&&e.skip(2),a){const t=ar(e);e.skip(t)}s&&e.skip(2),r(4===ar(e));const n=xt(e),o=e.filePos,c=ar(e);if(64===c||103===c?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===c}):105===c||107===c?t.info.codec="mp3":221===c&&(t.info.codec="vorbis"),e.skip(12),n>e.filePos-o){r(5===ar(e));const i=xt(e);if(t.info.codecDescription=ir(e,i),"aac"===t.info.codec){const e=ue(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;r("audio"===t.info?.type),255&sr(e)&&("pcm-s16be"===t.info.codec?t.info.codec="pcm-s16":"pcm-s24be"===t.info.codec?t.info.codec="pcm-s24":"pcm-s32be"===t.info.codec?t.info.codec="pcm-s32":"pcm-f32be"===t.info.codec?t.info.codec="pcm-f32":"pcm-f64be"===t.info.codec&&(t.info.codec="pcm-f64"))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;r("audio"===t.info?.type),e.skip(4);const i=!!(1&ar(e)),a=ar(e);"pcm-s16be"===t.info.codec?t.info.codec=i?16===a?"pcm-s16":24===a?"pcm-s24":32===a?"pcm-s32":null:16===a?"pcm-s16be":24===a?"pcm-s24be":32===a?"pcm-s32be":null:"pcm-f32be"===t.info.codec&&(t.info.codec=i?32===a?"pcm-f32":64===a?"pcm-f64":null:32===a?"pcm-f32be":64===a?"pcm-f64be":null);break}case"dOps":{const t=this.currentTrack;if(!t)break;r("audio"===t.info?.type),e.skip(1);const i=ar(e),a=sr(e),s=cr(e),n=or(e),o=ar(e);let c;c=0!==o?ir(e,2+i):new Uint8Array(0);const d=new Uint8Array(19+c.byteLength),l=new DataView(d.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,i),l.setUint16(10,a,!0),l.setUint32(12,s,!0),l.setInt16(16,n,!0),l.setUint8(18,o),d.set(c,19),t.info.codecDescription=d,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;r("audio"===t.info?.type),e.skip(4);const i=127,a=128,s=e.filePos;for(;e.filePos<c;){const r=ar(e),s=nr(e);if((r&i)===Ue.STREAMINFO){e.skip(10);const r=cr(e),i=r>>>12,a=1+(r>>9&7);t.info.sampleRate=i,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(r&a)break}const n=e.filePos;e.filePos=s;const o=ir(e,n-s),d=new Uint8Array(4+o.byteLength);new DataView(d.buffer).setUint32(0,1716281667,!1),d.set(o,4),t.info.codecDescription=d}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=cr(e);let i=0,a=0;for(let s=0;r>s;s++){const r=cr(e),s=cr(e);t.sampleTable.sampleTimingEntries.push({startIndex:i,startDecodeTimestamp:a,count:r,delta:s}),i+=r,a+=r*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=cr(e);let i=0;for(let a=0;r>a;a++){const r=cr(e),a=dr(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:i,count:r,offset:a}),i+=r}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=cr(e),i=cr(e);if(0===r)for(let a=0;i>a;a++){const r=cr(e);t.sampleTable.sampleSizes.push(r)}else t.sampleTable.sampleSizes.push(r)}break;case"stz2":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),e.skip(3);const r=ar(e),i=cr(e),a=ir(e,Math.ceil(i*r/8)),s=new n(a);for(let e=0;i>e;e++){const e=s.readBits(r);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];const r=cr(e);for(let i=0;r>i;i++){const r=cr(e)-1;t.sampleTable.keySampleIndices.push(r)}0!==t.sampleTable.keySampleIndices[0]&&t.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=cr(e);for(let a=0;r>a;a++){const r=cr(e)-1,i=cr(e),a=cr(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:i,sampleDescriptionIndex:a})}let i=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)t.sampleTable.sampleToChunk[e].startSampleIndex=i,e<t.sampleTable.sampleToChunk.length-1&&(i+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk)}break;case"stco":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=cr(e);for(let i=0;r>i;i++){const r=cr(e);t.sampleTable.chunkOffsets.push(r)}}break;case"co64":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=cr(e);for(let i=0;r>i;i++){const r=lr(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,s.contentSize));break;case"mehd":{const t=ar(e);e.skip(3);const r=1===t?lr(e):cr(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);const t=cr(e),r=cr(e),i=cr(e),a=cr(e),s=cr(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:i,defaultSampleSize:a,defaultSampleFlags:s})}break;case"tfra":{const t=ar(e);e.skip(3);const r=cr(e),i=this.tracks.find(e=>e.id===r);if(!i)break;const a=cr(e),s=(12&a)>>2,n=3&a,o=[ar,sr,nr,cr],c=o[(48&a)>>4],d=o[s],l=o[n],h=cr(e);for(let u=0;h>u;u++){const r=1===t?lr(e):cr(e),a=1===t?lr(e):cr(e);c(e),d(e),l(e),i.fragmentLookupTable.push({timestamp:r,moofOffset:a})}i.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<i.fragmentLookupTable.length-1;e++){const t=i.fragmentLookupTable[e],r=i.fragmentLookupTable[e+1];t.timestamp===r.timestamp&&(i.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:s.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(o,s.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(r(this.currentFragment),this.readContiguousBoxes(e.slice(o,s.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){const{currentFragmentState:t}=this.currentTrack;r(t),null!==t.startTimestamp&&(Ot(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{r(this.currentFragment),e.skip(1);const t=nr(e),i=!!(1&t),a=!!(2&t),s=!!(8&t),n=!!(16&t),o=!!(32&t),c=!!(65536&t),d=!!(131072&t),l=cr(e),h=this.tracks.find(e=>e.id===l);if(!h)break;const u=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:u?.defaultSampleDescriptionIndex??null,defaultSampleDuration:u?.defaultSampleDuration??null,defaultSampleSize:u?.defaultSampleSize??null,defaultSampleFlags:u?.defaultSampleFlags??null,startTimestamp:null},i?h.currentFragmentState.baseDataOffset=lr(e):d&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(h.currentFragmentState.sampleDescriptionIndex=cr(e)),s&&(h.currentFragmentState.defaultSampleDuration=cr(e)),n&&(h.currentFragmentState.defaultSampleSize=cr(e)),o&&(h.currentFragmentState.defaultSampleFlags=cr(e)),c&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;r(t.currentFragmentState);const i=ar(e);e.skip(3);const a=0===i?cr(e):lr(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{const t=this.currentTrack;if(!t)break;if(r(this.currentFragment),r(t.currentFragmentState),this.currentFragment.trackData.has(t.id))break;const i=ar(e),s=nr(e),n=!!(1&s),o=!!(4&s),c=!!(256&s),d=!!(512&s),l=!!(1024&s),h=!!(2048&s),u=cr(e);let m=t.currentFragmentState.baseDataOffset;n&&(m+=dr(e));let p=null;o&&(p=cr(e));let f=m;if(0===u){this.currentFragment.implicitBaseDataOffset=f;break}let g=0;const w={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,w);for(let a=0;u>a;a++){let s,n,o;c?s=cr(e):(r(null!==t.currentFragmentState.defaultSampleDuration),s=t.currentFragmentState.defaultSampleDuration),d?n=cr(e):(r(null!==t.currentFragmentState.defaultSampleSize),n=t.currentFragmentState.defaultSampleSize),l?o=cr(e):(r(null!==t.currentFragmentState.defaultSampleFlags),o=t.currentFragmentState.defaultSampleFlags),0===a&&null!==p&&(o=p);let u=0;h&&(u=0===i?cr(e):dr(e));const m=!(65536&o);w.samples.push({presentationTimestamp:g+u,duration:s,byteOffset:f,byteSize:n,isKeyFrame:m}),f+=n,g+=s}w.presentationTimestamps=w.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<w.presentationTimestamps.length;e++){const t=w.presentationTimestamps[e],r=w.samples[t.sampleIndex];if(null===w.firstKeyFrameTimestamp&&r.isKeyFrame&&(w.firstKeyFrameTimestamp=r.presentationTimestamp),e<w.presentationTimestamps.length-1){const i=w.presentationTimestamps[e+1];r.duration=i.presentationTimestamp-t.presentationTimestamp}}const b=w.samples[w.presentationTimestamps[0].sampleIndex],v=w.samples[a(w.presentationTimestamps).sampleIndex];w.startTimestamp=b.presentationTimestamp,w.endTimestamp=v.presentationTimestamp+v.duration,this.currentFragment.implicitBaseDataOffset=f}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(o,s.contentSize));for(const{boxInfo:e,slice:r}of t){if("meta"!==e.name&&!this.currentTrack){const t=r.filePos;this.metadataTags.raw??={},"©"===e.name[0]?this.metadataTags.raw[e.name]??=_t(r):this.metadataTags.raw[e.name]??=ir(r,e.contentSize),r.filePos=t}switch(e.name){case"meta":r.skip(-e.headerSize),this.traverseBox(r);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=h.decode(ir(r,e.contentSize)):this.metadataTags.title??=_t(r);break;case"©des":this.currentTrack||(this.metadataTags.description??=_t(r));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=_t(r));break;case"©alb":this.currentTrack||(this.metadataTags.album??=_t(r));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=_t(r));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=_t(r));break;case"©day":if(!this.currentTrack){const e=new Date(_t(r));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=_t(r));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=_t(r))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==cr(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(o,s.contentSize)):this.readContiguousBoxes(e.slice(o+4,s.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=cr(e);for(let r=0;t>r;r++){const t=cr(e);e.skip(4);const i=h.decode(ir(e,t-8));this.currentMetadataKeys.set(r+1,i)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(o,s.contentSize));for(const{boxInfo:e,slice:r}of t){let t=e.name;const i=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(i)&&(t=this.currentMetadataKeys.get(i));const a=Pt(r);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=a,t){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof a&&(this.metadataTags.title??=a);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof a&&(this.metadataTags.description??=a);break;case"©ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof a&&(this.metadataTags.artist??=a);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof a&&(this.metadataTags.album??=a);break;case"aART":case"album_artist":"string"==typeof a&&(this.metadataTags.albumArtist??=a);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof a&&(this.metadataTags.comment??=a);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof a&&(this.metadataTags.genre??=a);break;case"©lyr":case"lyrics":"string"==typeof a&&(this.metadataTags.lyrics??=a);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof a){const e=new Date(a);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"covr":case"com.apple.quicktime.artwork":a instanceof Q?(this.metadataTags.images??=[],this.metadataTags.images.push({data:a.data,kind:"coverFront",mimeType:a.mimeType})):a instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:a,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof a){const e=a.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=l(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),r>0&&(this.metadataTags.tracksTotal??=r)}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=l(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),r>0&&(this.metadataTags.discsTotal??=r)}}}}}var d;return e.filePos=c,!0}}class It{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return(e=>{const t=Math.round(e);return 10*Number.EPSILON>Math.abs(e/t-1)?t:e})(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Bt(i,r),s=await this.fetchPacketForSampleIndex(a,t);return Lt(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=E(t.presentationTimestamps,r,e=>e.presentationTimestamp);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):s}async getNextPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r)return this.fetchPacketForSampleIndex(r+1,t);const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<t.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Bt(i,r),s=-1===a?-1:Ft(i,a),n=await this.fetchPacketForSampleIndex(s,t);return Lt(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=((e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1})(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):n}async getNextKeyPacket(e,t){const i=this.packetToSampleIndex.get(e);if(void 0!==i){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Dt(e,i);return this.fetchPacketForSampleIndex(r,t)}const a=this.packetToFragmentLocation.get(e);if(void 0===a)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,e=>{if(e===a.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return r(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=zt(i,e);if(!a)return null;let s;if(t.metadataOnly)s=je;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);e instanceof Promise&&(e=await e),r(e),s=ir(e,a.sampleSize)}const n=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new $e(s,a.isKeyFrame?"key":"delta",n,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,i){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).samples[t];let s;if(r(a),i.metadataOnly)s=je;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);e instanceof Promise&&(e=await e),r(e),s=ir(e,a.byteSize)}const n=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new $e(s,a.isKeyFrame?"key":"delta",n,o,e.moofOffset+t,a.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:t}),c}async performFragmentedLookup(e,t,i,a,s){const n=this.internalTrack.demuxer;let o=null,c=null,d=-1;if(e){const{sampleIndex:r,correctSampleFound:i}=t(e);if(i)return this.fetchPacketInFragment(e,r,s);-1!==r&&(c=e,d=r)}const l=E(this.internalTrack.fragmentLookupTable,i,e=>e.timestamp),h=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,u=E(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),m=-1!==u?this.internalTrack.fragmentPositionCache[u]:null,p=Math.max(h?.moofOffset??0,m?.moofOffset??0)||null;let f;for(e?null!==p&&e.moofOffset<p?f=p:(f=e.moofOffset+e.moofSize,o=e):f=p??0;;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=n.reader.requestSliceRange(f,8,St);if(e instanceof Promise&&(e=await e),!e)break;const r=f,i=Tt(e);if(!i)break;if("moof"===i.name){o=await n.readFragment(r);const{sampleIndex:e,correctSampleFound:i}=t(o);if(i)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,d=e)}f=r+i.totalSize}if(h&&(!c||c.moofOffset<h.moofOffset)){const e=this.internalTrack.fragmentLookupTable[l-1];r(!e||e.timestamp<h.timestamp);const i=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,i,a,s)}return c?this.fetchPacketInFragment(c,d,s):null}}class At extends It{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&(e=>{for(const{type:t,data:r}of De(e)){if(1!==t)continue;const e=new n(r),i=e.readBits(3);e.readBits(1);let a=0,s=0,o=0;if(e.readBits(1))a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const r=e.readBits(5);for(let i=0;r>=i;i++){e.skipBits(12);const r=e.readBits(5);if(0===i&&(a=r),r>7){const t=e.readBits(1);0===i&&(s=t)}if(t&&e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}const c=e.readBits(1);let d=8;2===i&&c?d=e.readBits(1)?12:10:i>2||(d=c?10:8);let l=0;1!==i&&(l=e.readBits(1));let h=1,u=1,m=0;return l||(0===i?(h=1,u=1):1===i?(h=0,u=0):12===d&&(h=e.readBits(1),h&&(u=e.readBits(1))),h&&u&&(m=e.readBits(2))),{profile:i,level:a,tier:s,bitDepth:d,monochrome:l,chromaSubsamplingX:h,chromaSubsamplingY:u,chromaSamplePosition:m}}return null})(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&(e=>{const t=new n(e);if(2!==t.readBits(2))return null;const r=t.readBits(1),i=(t.readBits(1)<<1)+r;if(3===i&&t.skipBits(1),1===t.readBits(1))return null;if(0!==t.readBits(1))return null;if(t.skipBits(2),4817730!==t.readBits(24))return null;let s=8;2>i||(s=t.readBits(1)?12:10);const o=t.readBits(3);let c=0,d=0;if(7!==o)if(d=t.readBits(1),1===i||3===i){const e=t.readBits(1),r=t.readBits(1);c=e||r?e&&!r?2:1:3,t.skipBits(1)}else c=1;else c=3,d=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let h=a(ae).level;for(const a of ae)if(l<=a.maxPictureSize){h=a.level;break}return{profile:i,level:h,bitDepth:s,chromaSubsampling:c,videoFullRangeFlag:d,colourPrimaries:2===o?1:1===o?6:2,transferCharacteristics:2===o?1:1===o?6:2,matrixCoefficients:7===o?0:2===o?1:1===o?6:2}})(e.data)}return{codec:oe(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class Rt extends It{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:de(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const Bt=(e,t)=>{if(e.presentationTimestamps){const r=E(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===r?-1:e.presentationTimestamps[r].sampleIndex}{const r=E(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===r)return-1;const i=e.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((t-i.startDecodeTimestamp)/i.delta),i.count-1)}},zt=(e,t)=>{const i=E(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[i];if(!a||a.startIndex+a.count<=t)return null;let s=a.startDecodeTimestamp+(t-a.startIndex)*a.delta;const n=E(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndex<o.count&&(s+=o.offset);const c=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],d=E(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[d];r(l);const h=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),u=e.chunkOffsets[h],m=l.startSampleIndex+(h-l.startChunkIndex)*l.samplesPerChunk;let p=0,f=u;if(1===e.sampleSizes.length)f+=c*(t-m),p+=c*l.samplesPerChunk;else for(let r=m;r<m+l.samplesPerChunk;r++){const i=e.sampleSizes[r];t>r&&(f+=i),p+=i}let g=a.delta;if(e.presentationTimestamps){const i=e.presentationTimestampIndexMap[t];r(void 0!==i),i<e.presentationTimestamps.length-1&&(g=e.presentationTimestamps[i+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:f,sampleSize:c,chunkOffset:u,chunkSize:p,isKeyFrame:!e.keySampleIndices||-1!==C(e.keySampleIndices,t,e=>e)}},Ft=(e,t)=>{if(!e.keySampleIndices)return t;const r=E(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r]??-1},Dt=(e,t)=>{if(!e.keySampleIndices)return t+1;const r=E(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r+1]??-1},Ot=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const r of e.samples)r.presentationTimestamp+=t;for(const r of e.presentationTimestamps)r.presentationTimestamp+=t},Ut=e=>{const[t,,,r]=e,i=Math.hypot(t,r),a=180/Math.PI*-Math.atan2(r/i,t/i);return Number.isFinite(a)?a:0},Lt=e=>0===e.sampleSizes.length;class Vt{}class Nt extends Vt{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),t?(t.skip(4),"ftyp"!==mr(t,4)?null:mr(t,4)):null}_createDemuxer(e){return new Mt(e)}}class Wt extends Nt{async _canReadInput(e){const t=await this._getMajorBrand(e);return!!t&&"qt "!==t}get name(){return"MP4"}get mimeType(){return"video/mp4"}}const Ht=new Wt,qt=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})),jt=void 0!==qt?qt:void 0;class $t{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new Jt;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new Jt;const e=await this.getSizeOrNull();if(null===e)throw Error("Cannot determine the size of an unsized source.");return e}}class Qt extends $t{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!$(t.maxCacheSize)||0>t.maxCacheSize))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Zt({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Xt.fileSystem})}_retrieveSize(){const e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);void 0===t&&(t="stream"in this._blob&&!L()?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,t));for(;e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:r,value:i}=await t.read();if(r)throw this._orchestrator.forgetWorker(e),Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{const t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}e.running=!1}_dispose(){this._orchestrator.dispose()}}class Kt extends $t{constructor(e,t={}){if("string"!=typeof e)throw new TypeError("filePath must be a string.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!$(t.maxCacheSize)||0>t.maxCacheSize))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._fileHandle=null,this._streamSource=new Gt({getSize:async()=>(this._fileHandle=await jt.fs.open(e,"r"),(await this._fileHandle.stat()).size),read:async(e,t)=>{r(this._fileHandle);const i=new Uint8Array(t-e);return await this._fileHandle.read(i,0,t-e,e),i},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,t){return this._streamSource._read(e,t)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}}class Gt extends $t{constructor(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if("function"!=typeof e.getSize)throw new TypeError("options.getSize must be a function.");if("function"!=typeof e.read)throw new TypeError("options.read must be a function.");if(void 0!==e.dispose&&"function"!=typeof e.dispose)throw new TypeError("options.dispose, when provided, must be a function.");if(void 0!==e.maxCacheSize&&(!$(e.maxCacheSize)||0>e.maxCacheSize))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new Zt({maxCacheSize:e.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:Xt[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){const e=this._options.getSize();if(e instanceof Promise)return e.then(e=>{if(!Number.isInteger(e)||0>e)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e});if(!Number.isInteger(e)||0>e)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,r=e.targetPos;let i=this._options.read(e.currentPos,r);if(i instanceof Promise&&(i=await i),e.aborted)break;if(i instanceof Uint8Array){if(i=d(i),i.length!==r-e.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${r-e.currentPos} bytes, but got ${i.length}.`);this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{if(!(i instanceof ReadableStream))throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.");{const a=i.getReader();for(;e.currentPos<r&&!e.aborted;){const{done:i,value:s}=await a.read();if(i){if(e.currentPos<r)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${r-t} bytes, but got ${e.currentPos-t}`);break}if(!(s instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const n=d(s);this.onread?.(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}}e.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}const Xt={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{const r=65536;return{start:e=Math.floor((e-r)/r)*r,end:t=Math.ceil((t+r)/r)*r}},network:(e,t,r)=>{const i=65536;e=Math.max(0,Math.floor((e-i)/i)*i);for(const a of r){const r=8388608,i=Math.max((a.startPos+a.targetPos)/2,a.targetPos-r);if(H(e,t,i,a.targetPos)){const e=a.targetPos-a.startPos,i=Math.ceil((e+1)/r)*r,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,i);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+524288)}}};class Zt{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){r(null!==this.fileSize);const i=this.options.prefetchProfile(e,t,this.workers),a=Math.max(i.start,0),s=Math.min(i.end,this.fileSize);r(e>=a&&s>=t);let n=null;const o=E(this.cache,e,e=>e.start),c=-1!==o?this.cache[o]:null;!c||c.start>e||t>c.end||(c.age=this.nextAge++,n={bytes:c.bytes,view:c.view,offset:c.start});const d=E(this.cache,a,e=>e.start),h=n?null:new Uint8Array(t-e);let u=0,m=a;const p=[];if(-1!==d){for(let i=d;i<this.cache.length;i++){const n=this.cache[i];if(n.start>=s)break;if(n.end<=a)continue;const o=Math.max(a,n.start),c=Math.min(s,n.end);if(r(c>=o),o>m&&p.push({start:m,end:o}),m=c,h){const r=Math.max(e,n.start),i=Math.min(t,n.end);if(i>r){const t=r-e;h.set(n.bytes.subarray(r-n.start,i-n.start),t),t===u&&(u=i-e)}}n.age=this.nextAge++}s>m&&p.push({start:m,end:s})}else p.push({start:a,end:s});if(h&&u>=h.length&&(n={bytes:h,view:l(h),offset:e}),0===p.length)return r(n),n;const{promise:f,resolve:g,reject:w}=_(),b=[];for(const r of p){const i=Math.max(e,r.start),a=Math.min(t,r.end);i===r.start&&a===r.end?b.push(r):a>i&&b.push({start:i,end:a})}for(const r of p){const t=h&&{start:e,bytes:h,holes:b,resolve:g,reject:w};let i=!1;for(const e of this.workers){const a=2**17;if(H(r.start-a,r.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,r.end),i=!0,t&&!e.pendingSlices.includes(t)&&e.pendingSlices.push(t),e.running||this.runWorker(e);break}}if(!i){const e=this.createWorker(r.start,r.end);t&&(e.pendingSlices=[t]),this.runWorker(e)}}return n||(r(h),n=f.then(t=>({bytes:t,view:l(t),offset:e}))),n}createWorker(e,t){const r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let r=1;r<this.workers.length;r++){const i=this.workers[r];i.age<t.age&&(e=r,t=i)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return r}runWorker(e){r(!e.running),r(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,0>=e.pendingSlices.length)throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0})}supplyWorkerData(e,t){r(!e.aborted);const i=e.currentPos,a=i+t.length;this.insertIntoCache({start:i,end:a,bytes:t,view:l(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let r=0;r<e.pendingSlices.length;r++){const s=e.pendingSlices[r],n=Math.max(i,s.start),o=Math.min(a,s.start+s.bytes.length);o>n&&s.bytes.set(t.subarray(n-i,o-i),n-s.start);for(let e=0;e<s.holes.length;e++){const t=s.holes[e];i<=t.start&&a>t.start&&(t.start=a),t.end>t.start||(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(r,1),r--)}for(let r=0;r<this.workers.length;r++){const t=this.workers[r];e===t||t.running||H(i,a,t.currentPos,t.targetPos)&&(this.workers.splice(r,1),r--)}}forgetWorker(e){const t=this.workers.indexOf(e);r(-1!==t),this.workers.splice(t,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=E(this.cache,e.start,e=>e.start)+1;if(t>0){const r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){const i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=l(i),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){const t=this.cache[r];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(r,1),this.currentCacheSize-=t.bytes.length,r--;continue}const i=new Uint8Array(t.end-e.start);i.set(e.bytes,0),i.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=i,e.view=l(i),e.end=t.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let r=1;r<this.cache.length;r++){const i=this.cache[r];i.age<t.age&&(e=r,t=i)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}j();class Yt{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Vt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof $t))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new er(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),r(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}}class Jt extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class er{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new Jt;if(null!==this.fileSize&&e+t>this.fileSize)return null;const r=e+t,i=this.source._read(e,r);return i instanceof Promise?i.then(t=>t?new tr(t.bytes,t.view,t.offset,e,r):null):i?new tr(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Jt;if(null!==this.fileSize)return this.requestSlice(e,R(this.fileSize-e,t,i));{const a=this.requestSlice(e,i),s=a=>{if(a)return a;const s=a=>(r(null!==a),this.requestSlice(e,R(a-e,t,i))),n=this.source._retrieveSize();return n instanceof Promise?n.then(s):s(n)};return a instanceof Promise?a.then(s):s(a)}}}class tr{constructor(e,t,r,i,a){this.bytes=e,this.view=t,this.offset=r,this.start=i,this.end=a,this.bufferPos=i-r}static tempFromBytes(e){return new tr(e,l(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new tr(this.bytes,this.view,this.offset,e,e+t)}}const rr=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw new RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},ir=(e,t)=>{rr(e,t);const r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},ar=e=>(rr(e,1),e.view.getUint8(e.bufferPos++)),sr=e=>{rr(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},nr=e=>{rr(e,3);const t=M(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},or=e=>{rr(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},cr=e=>{rr(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},dr=e=>{rr(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},lr=e=>4294967296*cr(e)+cr(e),hr=e=>4294967296*dr(e)+cr(e),ur=e=>{rr(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},mr=(e,t)=>{rr(e,t);let r="";for(let i=0;t>i;i++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r},pr=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,fr=e=>{const t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),i=Math.floor(e%6e4/1e3),a=e%1e3;return t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};class gr{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const a of e.children)a&&this.writeBox(a);const r=this.writer.getPos(),i=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);r(void 0!==t);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const r of e.children)r&&(t+=this.measureBox(r));return t}}}const wr=new Uint8Array(8),br=new DataView(wr.buffer),vr=e=>[(e%256+256)%256],yr=e=>(br.setUint16(0,e,!1),[wr[0],wr[1]]),kr=e=>(br.setInt16(0,e,!1),[wr[0],wr[1]]),Sr=e=>(br.setUint32(0,e,!1),[wr[1],wr[2],wr[3]]),Tr=e=>(br.setUint32(0,e,!1),[wr[0],wr[1],wr[2],wr[3]]),Cr=e=>(br.setInt32(0,e,!1),[wr[0],wr[1],wr[2],wr[3]]),Er=e=>(br.setUint32(0,Math.floor(e/2**32),!1),br.setUint32(4,e,!1),[wr[0],wr[1],wr[2],wr[3],wr[4],wr[5],wr[6],wr[7]]),xr=e=>(br.setInt16(0,256*e,!1),[wr[0],wr[1]]),_r=e=>(br.setInt32(0,65536*e,!1),[wr[0],wr[1],wr[2],wr[3]]),Pr=e=>(br.setInt32(0,2**30*e,!1),[wr[0],wr[1],wr[2],wr[3]]),Mr=(e,t)=>{const r=[];let i=e;do{let e=127&i;i>>=7,r.length>0&&(e|=128),r.push(e)}while(i>0||t);return r.reverse()},Ir=(e,t=!1)=>{const r=Array(e.length).fill(null).map((t,r)=>e.charCodeAt(r));return t&&r.push(0),r},Ar=e=>{let t=null;for(const r of e)t&&r.timestamp<=t.timestamp||(t=r);return t},Rr=e=>{const t=e*(Math.PI/180),r=Math.round(Math.cos(t)),i=Math.round(Math.sin(t));return[r,i,0,-i,r,0,0,0,1]},Br=Rr(0),zr=e=>[_r(e[0]),_r(e[1]),Pr(e[2]),_r(e[3]),_r(e[4]),Pr(e[5]),_r(e[6]),_r(e[7]),Pr(e[8])],Fr=(e,t,r)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:r}),Dr=(e,t,r,i,a)=>Fr(e,[vr(t),Sr(r),i??[]],a),Or=e=>({type:"mdat",largeSize:e}),Ur=e=>Fr("moov",void 0,[Lr(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>Vr(t,e.creationTime)),e.isFragmented?vi(e.trackDatas):null,Ri(e)]),Lr=(e,t)=>{const r=sa(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{const t=Ar(e.samples);return t.timestamp+t.duration})),ia),i=Math.max(0,...t.map(e=>e.track.id))+1,a=!s(e)||!s(r),n=a?Er:Tr;return Dr("mvhd",+a,0,[n(e),n(e),Tr(ia),n(r),_r(1),xr(1),[,,,,,,,,,,].fill(0),zr(Br),Array(24).fill(0),Tr(i)])},Vr=(e,t)=>{const r=aa(e);return Fr("trak",void 0,[Nr(e,t),Wr(e,t),void 0!==r.name?Fr("udta",void 0,[Fr("name",[...u.encode(r.name)])]):null])},Nr=(e,t)=>{const r=Ar(e.samples),i=sa(r?r.timestamp+r.duration:0,ia),a=!s(t)||!s(i),n=a?Er:Tr;let o;if("video"===e.type){const t=e.track.metadata.rotation;o=Rr(t??0)}else o=Br;let c=2;return!1!==e.track.metadata.disposition?.default&&(c|=1),Dr("tkhd",+a,c,[n(t),n(t),Tr(e.track.id),Tr(0),n(i),[,,,,,,,,].fill(0),yr(0),yr(e.track.id),xr("audio"===e.type?1:0),yr(0),zr(o),_r("video"===e.type?e.info.width:0),_r("video"===e.type?e.info.height:0)])},Wr=(e,t)=>Fr("mdia",void 0,[Hr(e,t),$r(!0,qr[e.type],jr[e.type]),Qr(e)]),Hr=(e,t)=>{const r=Ar(e.samples),i=sa(r?r.timestamp+r.duration:0,e.timescale),a=!s(t)||!s(i),n=a?Er:Tr;return Dr("mdhd",+a,0,[n(t),n(t),Tr(e.timescale),n(i),yr($i(e.track.metadata.languageCode??B)),yr(0)])},qr={video:"vide",audio:"soun",subtitle:"text"},jr={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},$r=(e,t,r,i="\0\0\0\0")=>Dr("hdlr",0,0,[e?Ir("mhlr"):Tr(0),Ir(t),Ir(i),Tr(0),Tr(0),Ir(r,!0)]),Qr=e=>Fr("minf",void 0,[Kr[e.type](),Gr(),Yr(e)]),Kr={video:()=>Dr("vmhd",0,1,[yr(0),yr(0),yr(0),yr(0)]),audio:()=>Dr("smhd",0,0,[yr(0),yr(0)]),subtitle:()=>Dr("nmhd",0,0)},Gr=()=>Fr("dinf",void 0,[Xr()]),Xr=()=>Dr("dref",0,0,[Tr(1)],[Zr()]),Zr=()=>Dr("url ",0,1),Yr=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return Fr("stbl",void 0,[Jr(e),ui(e),t?wi(e):null,t?bi(e):null,pi(e),fi(e),gi(e),mi(e)])},Jr=e=>{let t;if("video"===e.type)t=ei(Vi(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){const i=Wi(e.track.source._codec,e.muxer.isQuickTime);r(i),t=ii(i,e)}else"subtitle"===e.type&&(t=hi(qi[e.track.source._codec],e));return r(t),Dr("stsd",0,0,[Tr(1)],[t])},ei=(e,t)=>{return Fr(e,[[,,,,,,].fill(0),yr(1),yr(0),yr(0),Array(12).fill(0),yr(t.info.width),yr(t.info.height),Tr(4718592),Tr(4718592),Tr(0),yr(1),Array(32).fill(0),yr(24),kr(65535)],[Ni[t.track.source._codec](t),(r=t.info.decoderConfig.colorSpace,r&&r.primaries&&r.transfer&&r.matrix&&void 0!==r.fullRange?ti(t):null)]);var r},ti=e=>Fr("colr",[Ir("nclx"),yr(p[e.info.decoderConfig.colorSpace.primaries]),yr(g[e.info.decoderConfig.colorSpace.transfer]),yr(b[e.info.decoderConfig.colorSpace.matrix]),vr((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),ri=e=>{if(!e.info.decoderConfig)return null;const t=e.info.decoderConfig,r=t.codec.split("."),i=+r[1],a=+r[2],s=(+r[3]<<4)+((r[4]?+r[4]:1)<<1)+(r[8]?+r[8]:+(t.colorSpace?.fullRange??0)),n=r[5]?+r[5]:t.colorSpace?.primaries?p[t.colorSpace.primaries]:2,o=r[6]?+r[6]:t.colorSpace?.transfer?g[t.colorSpace.transfer]:2,c=r[7]?+r[7]:t.colorSpace?.matrix?b[t.colorSpace.matrix]:2;return Dr("vpcC",1,0,[vr(i),vr(a),vr(s),vr(n),vr(o),vr(c),yr(0)])},ii=(e,t)=>{let r,i=0,a=16;if(Y.includes(t.track.source._codec)){const e=t.track.source._codec,{sampleSize:r}=pe(e);a=8*r,a>16&&(i=1)}return r=0===i?[[,,,,,,].fill(0),yr(1),yr(i),yr(0),Tr(0),yr(t.info.numberOfChannels),yr(a),yr(0),yr(0),yr(65536>t.info.sampleRate?t.info.sampleRate:0),yr(0)]:[[,,,,,,].fill(0),yr(1),yr(i),yr(0),Tr(0),yr(t.info.numberOfChannels),yr(Math.min(a,16)),yr(0),yr(0),yr(65536>t.info.sampleRate?t.info.sampleRate:0),yr(0),Tr(1),Tr(a/8),Tr(t.info.numberOfChannels*a/8),Tr(2)],Fr(e,r,[Hi(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},ai=e=>{let t;switch(e.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw Error("Unhandled audio codec: "+e.track.source._codec)}let r=[...vr(t),...vr(21),...Sr(0),...Tr(0),...Tr(0)];if(e.info.decoderConfig.description){const t=d(e.info.decoderConfig.description);r=[...r,...vr(5),...Mr(t.byteLength),...t]}return r=[...yr(1),...vr(0),...vr(4),...Mr(r.length),...r,...vr(6),...vr(1),...vr(2)],r=[...vr(3),...Mr(r.length),...r],Dr("esds",0,0,r)},si=e=>Fr("wave",void 0,[ni(e),oi(e),Fr("\0\0\0\0")]),ni=e=>Fr("frma",[Ir(Wi(e.track.source._codec,e.muxer.isQuickTime))]),oi=e=>{const{littleEndian:t}=pe(e.track.source._codec);return Fr("enda",[yr(+t)])},ci=e=>{let t=e.info.numberOfChannels,i=3840,a=e.info.sampleRate,s=0,n=0,o=new Uint8Array(0);const c=e.info.decoderConfig?.description;if(c){r(c.byteLength>=18);const e=(e=>{const t=l(e),r=t.getUint8(9),i=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}})(d(c));t=e.outputChannelCount,i=e.preSkip,a=e.inputSampleRate,s=e.outputGain,n=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return Fr("dOps",[vr(0),vr(t),yr(i),Tr(a),kr(s),vr(n),...o])},di=e=>{const t=e.info.decoderConfig?.description;r(t);const i=d(t);return Dr("dfLa",0,0,[...i.subarray(4)])},li=e=>{const{littleEndian:t,sampleSize:r}=pe(e.track.source._codec);return Dr("pcmC",0,0,[vr(+t),vr(8*r)])},hi=(e,t)=>Fr(e,[[,,,,,,].fill(0),yr(1)],[ji[t.track.source._codec](t)]),ui=e=>Dr("stts",0,0,[Tr(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Tr(e.sampleCount),Tr(e.sampleDelta)])]),mi=e=>{if(e.samples.every(e=>"key"===e.type))return null;const t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return Dr("stss",0,0,[Tr(t.length),t.map(([e])=>Tr(e+1))])},pi=e=>Dr("stsc",0,0,[Tr(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Tr(e.firstChunk),Tr(e.samplesPerChunk),Tr(1)])]),fi=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){const{sampleSize:t}=pe(e.track.source._codec);return Dr("stsz",0,0,[Tr(t*e.info.numberOfChannels),Tr(e.samples.reduce((t,r)=>t+sa(r.duration,e.timescale),0))])}return Dr("stsz",0,0,[Tr(0),Tr(e.samples.length),e.samples.map(e=>Tr(e.size))])},gi=e=>e.finalizedChunks.length>0&&a(e.finalizedChunks).offset>=2**32?Dr("co64",0,0,[Tr(e.finalizedChunks.length),e.finalizedChunks.map(e=>Er(e.offset))]):Dr("stco",0,0,[Tr(e.finalizedChunks.length),e.finalizedChunks.map(e=>Tr(e.offset))]),wi=e=>Dr("ctts",1,0,[Tr(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Tr(e.sampleCount),Cr(e.sampleCompositionTimeOffset)])]),bi=e=>{let t=1/0,i=-1/0,a=1/0,s=-1/0;r(e.compositionTimeOffsetTable.length>0),r(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){const a=e.compositionTimeOffsetTable[r];t=Math.min(t,a.sampleCompositionTimeOffset),i=Math.max(i,a.sampleCompositionTimeOffset)}for(let r=0;r<e.samples.length;r++){const t=e.samples[r];a=Math.min(a,sa(t.timestamp,e.timescale)),s=Math.max(s,sa(t.timestamp+t.duration,e.timescale))}return 2**31>s?Dr("cslg",0,0,[Cr(Math.max(-t,0)),Cr(t),Cr(i),Cr(a),Cr(s)]):null},vi=e=>Fr("mvex",void 0,e.map(yi)),yi=e=>Dr("trex",0,0,[Tr(e.track.id),Tr(1),Tr(0),Tr(0),Tr(0)]),ki=(e,t)=>Fr("moof",void 0,[Si(e),...t.map(Ci)]),Si=e=>Dr("mfhd",0,0,[Tr(e)]),Ti=e=>{let t=0,r=0;const i="delta"===e.type;return r|=+i,t|=i?1:2,t<<24|r<<16},Ci=e=>Fr("traf",void 0,[Ei(e),xi(e),_i(e)]),Ei=e=>{r(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const i=e.currentChunk.samples[1]??e.currentChunk.samples[0],a={duration:i.timescaleUnitsToNextSample,size:i.size,flags:Ti(i)};return Dr("tfhd",0,131128,[Tr(e.track.id),Tr(a.duration),Tr(a.size),Tr(a.flags)])},xi=e=>(r(e.currentChunk),Dr("tfdt",1,0,[Er(sa(e.currentChunk.startTimestamp,e.timescale))])),_i=e=>{r(e.currentChunk);const t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),i=e.currentChunk.samples.map(e=>e.size),a=e.currentChunk.samples.map(Ti),s=e.currentChunk.samples.map(t=>sa(t.timestamp-t.decodeTimestamp,e.timescale)),n=new Set(t),o=new Set(i),c=new Set(a),d=new Set(s),l=2===c.size&&a[0]!==a[1],h=n.size>1,u=o.size>1,m=!l&&c.size>1,p=d.size>1||[...d].some(e=>0!==e);let f=0;return f|=1,f|=4*+l,f|=256*+h,f|=512*+u,f|=1024*+m,f|=2048*+p,Dr("trun",1,f,[Tr(e.currentChunk.samples.length),Tr(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?Tr(a[0]):[],e.currentChunk.samples.map((e,r)=>[h?Tr(t[r]):[],u?Tr(i[r]):[],m?Tr(a[r]):[],p?Cr(s[r]):[]])])},Pi=(e,t)=>Dr("tfra",1,0,[Tr(e.track.id),Tr(63),Tr(e.finalizedChunks.length),e.finalizedChunks.map(r=>[Er(sa(r.samples[0].timestamp,e.timescale)),Er(r.moofOffset),Tr(t+1),Tr(1),Tr(1)])]),Mi=()=>Fr("vtte"),Ii=(e,t,r,i,a)=>Fr("vttc",void 0,[null!==a?Fr("vsid",[Cr(a)]):null,null!==r?Fr("iden",[...u.encode(r)]):null,null!==t?Fr("ctim",[...u.encode(fr(t))]):null,null!==i?Fr("sttg",[...u.encode(i)]):null,Fr("payl",[...u.encode(e)])]),Ai=e=>Fr("vtta",[...u.encode(e)]),Ri=e=>{const t=[],r=e.format._options.metadataFormat??"auto",i=e.output._metadataTags;if("mdir"===r||"auto"===r&&!e.isQuickTime){const e=Oi(i);e&&t.push(e)}else if("mdta"===r){const e=Ui(i);e&&t.push(e)}else("udta"===r||"auto"===r&&e.isQuickTime)&&Bi(t,e.output._metadataTags);return 0===t.length?null:Fr("udta",void 0,t)},Bi=(e,t)=>{for(const{key:r,value:i}of q(t))switch(r){case"title":e.push(zi("©nam",i));break;case"description":e.push(zi("©des",i));break;case"artist":e.push(zi("©ART",i));break;case"album":e.push(zi("©alb",i));break;case"albumArtist":e.push(zi("albr",i));break;case"genre":e.push(zi("©gen",i));break;case"date":e.push(zi("©day",i.toISOString().slice(0,10)));break;case"comment":e.push(zi("©cmt",i));break;case"lyrics":e.push(zi("©lyr",i));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:P(r)}if(t.raw)for(const r in t.raw){const i=t.raw[r];null==i||4!==r.length||e.some(e=>e.type===r)||("string"==typeof i?e.push(zi(r,i)):i instanceof Uint8Array&&e.push(Fr(r,Array.from(i))))}},zi=(e,t)=>{const r=u.encode(t);return Fr(e,[yr(r.length),yr($i("und")),Array.from(r)])},Fi={"image/jpeg":13,"image/png":14,"image/bmp":27},Di=(e,t)=>{const r=[];for(const{key:i,value:a}of q(e))switch(i){case"title":r.push({key:t?"title":"©nam",value:Li(a)});break;case"description":r.push({key:t?"description":"©des",value:Li(a)});break;case"artist":r.push({key:t?"artist":"©ART",value:Li(a)});break;case"album":r.push({key:t?"album":"©alb",value:Li(a)});break;case"albumArtist":r.push({key:t?"album_artist":"aART",value:Li(a)});break;case"comment":r.push({key:t?"comment":"©cmt",value:Li(a)});break;case"genre":r.push({key:t?"genre":"©gen",value:Li(a)});break;case"lyrics":r.push({key:t?"lyrics":"©lyr",value:Li(a)});break;case"date":r.push({key:t?"date":"©day",value:Li(a.toISOString().slice(0,10))});break;case"images":for(const e of a)"coverFront"===e.kind&&r.push({key:"covr",value:Fr("data",[Tr(Fi[e.mimeType]??0),Tr(0),Array.from(e.data)])});break;case"trackNumber":if(t){const t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();r.push({key:"track",value:Li(t)})}else r.push({key:"trkn",value:Fr("data",[Tr(0),Tr(0),yr(0),yr(a),yr(e.tracksTotal??0),yr(0)])});break;case"discNumber":t||r.push({key:"disc",value:Fr("data",[Tr(0),Tr(0),yr(0),yr(a),yr(e.discsTotal??0),yr(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:P(i)}if(e.raw)for(const i in e.raw){const a=e.raw[i];null==a||!t&&4!==i.length||r.some(e=>e.key===i)||("string"==typeof a?r.push({key:i,value:Li(a)}):a instanceof Uint8Array?r.push({key:i,value:Fr("data",[Tr(0),Tr(0),Array.from(a)])}):a instanceof Q&&r.push({key:i,value:Fr("data",[Tr(Fi[a.mimeType]??0),Tr(0),Array.from(a.data)])}))}return r},Oi=e=>{const t=Di(e,!1);return 0===t.length?null:Dr("meta",0,0,void 0,[$r(!1,"mdir","","appl"),Fr("ilst",void 0,t.map(e=>Fr(e.key,void 0,[e.value])))])},Ui=e=>{const t=Di(e,!0);return 0===t.length?null:Fr("meta",void 0,[$r(!1,"mdta",""),Dr("keys",0,0,[Tr(t.length)],t.map(e=>Fr("mdta",[...u.encode(e.key)]))),Fr("ilst",void 0,t.map((e,t)=>{const r=String.fromCharCode(...Tr(t+1));return Fr(r,void 0,[e.value])}))])},Li=e=>Fr("data",[Tr(1),Tr(0),...u.encode(e)]),Vi=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},Ni={avc:e=>e.info.decoderConfig&&Fr("avcC",[...d(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&Fr("hvcC",[...d(e.info.decoderConfig.description)]),vp8:ri,vp9:ri,av1:e=>Fr("av1C",(e=>{const t=e.split("."),r=+t[1],i=t[2];return[129,(r<<5)+ +i.slice(0,-1),(("H"===i.slice(-1)?1:0)<<7)+((8===+t[3]?0:1)<<6)+0+((t[4]?+t[4]:0)<<4)+((t[5]?+t[5][0]:1)<<3)+((t[5]?+t[5][1]:1)<<2)+(t[5]?+t[5][2]:0),0]})(e.info.decoderConfig.codec))},Wi=(e,t)=>{switch(e){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"}if(t)switch(e){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(e){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"}},Hi=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return ai;case"opus":return ci;case"flac":return di}if(t)switch(e){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 si}else switch(e){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 li}return null},qi={webvtt:"wvtt"},ji={webvtt:e=>Fr("vttC",[...u.encode(e.info.config.description)])},$i=e=>{r(3===e.length);let t=0;for(let r=0;3>r;r++)t<<=5,t+=e.charCodeAt(r)-96;return t};class Qi{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const r=t+e.byteLength-this.trackedStart;let i=this.trackedWrites.byteLength;for(;r>i;)i*=2;if(i!==this.trackedWrites.byteLength){const e=new Uint8Array(i);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error("Internal error: Can't get tracked writes since nothing was tracked.");const e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}}const Ki=65536,Gi=2**32;class Xi extends Qi{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(Ki,{maxByteLength:Gi})}catch{this.buffer=new ArrayBuffer(Ki),this.supportsResize=!1}else this.buffer=new ArrayBuffer(Ki);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;e>t;)t*=2;if(t!==this.buffer.byteLength){if(t>Gi)throw Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this.supportsResize)this.buffer.resize(t);else{const e=new ArrayBuffer(t),r=new Uint8Array(e);r.set(this.bytes,0),this.buffer=e,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}class Zi extends Qi{constructor(e){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.chunks=[],this.target=e,this.chunked=e._options.chunked??!1,this.chunkSize=e._options.chunkSize??16777216}start(){this.writer=this.target._writable.getWriter()}write(e){if(this.pos>this.lastWriteEnd){const e=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(e))}this.maybeTrackWrites(e),this.sections.push({data:e.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){const e=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(e))}if(r(this.writer),0===this.sections.length)return;const e=[],t=[...this.sections].sort((e,t)=>e.start-t.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let r=1;r<t.length;r++){const i=e[e.length-1],a=t[r];a.start>i.start+i.size?e.push({start:a.start,size:a.data.byteLength}):i.size=Math.max(i.size,a.start+a.data.byteLength-i.start)}for(const r of e){r.data=new Uint8Array(r.size);for(const e of this.sections)r.start<=e.start&&e.start<r.start+r.size&&r.data.set(e.data,e.start-r.start);if(null===this.writer.desiredSize||this.writer.desiredSize>0||await this.writer.ready,this.chunked)this.writeDataIntoChunks(r.data,r.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&r.start!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:r.data,position:r.start}),this.lastFlushEnd=r.start+r.data.byteLength}}this.sections.length=0}writeDataIntoChunks(e,t){let r=this.chunks.findIndex(e=>e.start<=t&&t<e.start+this.chunkSize);-1===r&&(r=this.createChunk(t));const i=this.chunks[r],a=t-i.start,s=e.subarray(0,Math.min(this.chunkSize-a,e.byteLength));i.data.set(s,a);const n={start:a,end:a+s.byteLength};if(this.insertSectionIntoChunk(i,n),0===i.written[0].start&&i.written[0].end===this.chunkSize&&(i.shouldFlush=!0),this.chunks.length>2){for(let e=0;e<this.chunks.length-1;e++)this.chunks[e].shouldFlush=!0;this.tryToFlushChunks()}s.byteLength<e.byteLength&&this.writeDataIntoChunks(e.subarray(s.byteLength),t+s.byteLength)}insertSectionIntoChunk(e,t){let r=0,i=e.written.length-1,a=-1;for(;i>=r;){const s=Math.floor(r+(i-r+1)/2);e.written[s].start>t.start?i=s-1:(r=s+1,a=s)}for(e.written.splice(a+1,0,t),(-1===a||e.written[a].end<t.start)&&a++;a<e.written.length-1&&e.written[a].end>=e.written[a+1].start;)e.written[a].end=Math.max(e.written[a].end,e.written[a+1].end),e.written.splice(a+1,1)}createChunk(e){const t={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(t),this.chunks.sort((e,t)=>e.start-t.start),this.chunks.indexOf(t)}tryToFlushChunks(e=!1){r(this.writer);for(let t=0;t<this.chunks.length;t++){const r=this.chunks[t];if(r.shouldFlush||e){for(const e of r.written){const t=r.start+e.start;if(this.ensureMonotonicity&&t!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:r.data.subarray(e.start,e.end),position:t}),this.lastFlushEnd=r.start+e.end}this.chunks.splice(t--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),r(this.writer),this.writer.close()}async close(){return this.writer?.close()}}class Yi extends Qi{constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}}class Ji{constructor(){this._output=null,this.onwrite=null}}class ea extends Ji{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Xi(this)}}class ta extends Ji{constructor(e,t={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=t&&"object"!=typeof t)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==t.chunked&&"boolean"!=typeof t.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==t.chunkSize&&(!Number.isInteger(t.chunkSize)||1024>t.chunkSize))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t}_createWriter(){return new Zi(this)}}class ra extends Ji{_createWriter(){return new Yi(this)}}const ia=1e3,aa=e=>{const t={},r=e.track;return void 0!==r.metadata.name&&(t.name=r.metadata.name),t},sa=(e,t,r=!0)=>{const i=e*t;return r?Math.round(i):i};class na extends Se{constructor(e,t){super(e),this.auxTarget=new ea,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new gr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=_(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new gr(this.writer),this.isQuickTime=t instanceof la;const r=this.writer instanceof Xi&&"in-memory";this.fastStart=t._options.fastStart??r,this.isFragmented="fragmented"===this.fastStart,("in-memory"===this.fastStart||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(e=>"video"===e.type&&"avc"===e.source._codec);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox((r={isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented}).isQuickTime?Fr("ftyp",[Ir("qt "),Tr(512),Ir("qt ")]):Fr("ftyp",r.fragmented?[Ir("iso5"),Tr(512),Ir("iso5"),Ir("iso6"),Ir("mp41")]:[Ir("isom"),Tr(512),Ir("isom"),r.holdsAvc?Ir("avc1"):[],Ir("mp41")])),this.format._options.onFtyp){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}var r;if(this.ftypSize=this.writer.getPos(),"in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const i of this.output._tracks)if(void 0===i.metadata.maximumPacketCount)throw Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Or(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>"video"===e.type||"audio"===e.type?e.info.decoderConfig.codec:{webvtt:"wvtt"}[e.track.source._codec]);return kt({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,i){const a=this.trackDatas.find(t=>t.track===e);if(a)return a;(e=>{if(!e)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!ge.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.codedWidth)||0>=e.decoderConfig.codedWidth)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||0>=e.decoderConfig.codedHeight)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.description&&!y(e.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){const{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const r=Object.keys(p);if(null!=t.primaries&&!r.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const i=Object.keys(g);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const a=Object.keys(b);if(null!=t.matrix&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!we.test(e.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(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!be.test(e.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(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!ve.test(e.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(e.decoderConfig.codec.startsWith("av01")&&!ye.test(e.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/.')})(i),r(i),r(i.decoderConfig);const s={...i.decoderConfig};r(void 0!==s.codedWidth),r(void 0!==s.codedHeight);let d=!1;if("avc"!==e.source._codec||s.description){if("hevc"===e.source._codec&&!s.description){const e=(e=>{try{const t=_e(e),r=t.filter(e=>Be(e)===Ee.VPS_NUT),i=t.filter(e=>Be(e)===Ee.SPS_NUT),a=t.filter(e=>Be(e)===Ee.PPS_NUT),s=t.filter(e=>Be(e)===Ee.PREFIX_SEI_NUT||Be(e)===Ee.SUFFIX_SEI_NUT);if(0===i.length||0===a.length)return null;const d=i[0],l=new n(Me(d));l.skipBits(16),l.readBits(4);const h=l.readBits(3),u=l.readBits(1),{general_profile_space:m,general_tier_flag:p,general_profile_idc:f,general_profile_compatibility_flags:g,general_constraint_indicator_flags:w,general_level_idc:b}=((e,t)=>{const r=e.readBits(2),i=e.readBits(1),a=e.readBits(5);let s=0;for(let l=0;32>l;l++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let l=0;6>l;l++)n[l]=e.readBits(8);const o=e.readBits(8),c=[],d=[];for(let l=0;t>l;l++)c.push(e.readBits(1)),d.push(e.readBits(1));if(t>0)for(let l=t;8>l;l++)e.skipBits(2);for(let l=0;t>l;l++)c[l]&&e.skipBits(88),d[l]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}})(l,h);o(l);const v=o(l);3===v&&l.skipBits(1),o(l),o(l),l.readBits(1)&&(o(l),o(l),o(l),o(l));const y=o(l),k=o(l);o(l);for(let e=l.readBits(1)?0:h;h>=e;e++)o(l),o(l),o(l);if(o(l),o(l),o(l),o(l),o(l),o(l),l.readBits(1)&&l.readBits(1)&&(e=>{for(let t=0;4>t;t++)for(let r=0;(3===t?2:6)>r;r++)if(e.readBits(1)){const r=Math.min(64,1<<4+(t<<1));t>1&&c(e);for(let t=0;r>t;t++)c(e)}else o(e)})(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&(l.skipBits(4),l.skipBits(4),o(l),o(l),l.skipBits(1)),((e,t)=>{const r=[];for(let i=0;t>i;i++)r[i]=ze(e,i,t,r)})(l,o(l)),l.readBits(1)){const e=o(l);for(let t=0;e>t;t++)o(l),l.skipBits(1)}l.skipBits(1),l.skipBits(1);let S=0;l.readBits(1)&&(S=((e,t)=>{if(e.readBits(1)&&255===e.readBits(8)&&(e.readBits(16),e.readBits(16)),e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),e.readBits(1),e.readBits(1)&&(e.readBits(8),e.readBits(8),e.readBits(8))),e.readBits(1)&&(o(e),o(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(o(e),o(e),o(e),o(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&o(e),e.readBits(1)&&((e,t,r)=>{let i=!1,a=!1,s=!1;i=1===e.readBits(1),a=1===e.readBits(1),(i||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;r>=n;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let r=!1;t?o(e):r=1===e.readBits(1);let n=1;r||(n=o(e)+1),i&&Fe(e,n,s),a&&Fe(e,n,s)}})(e,0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=o(e);return o(e),o(e),o(e),o(e),t}return 0})(l,h));let T=0;if(a.length>0){const e=a[0],t=new n(Me(e));t.skipBits(16),o(t),o(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),o(t),o(t),c(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&o(t),c(t),c(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const r=t.readBits(1),i=t.readBits(1);T=r||i?r&&!i?2:!r&&i?3:0:0}return{configurationVersion:1,generalProfileSpace:m,generalTierFlag:p,generalProfileIdc:f,generalProfileCompatibilityFlags:g,generalConstraintIndicatorFlags:w,generalLevelIdc:b,minSpatialSegmentationIdc:S,parallelismType:T,chromaFormatIdc:v,bitDepthLumaMinus8:y,bitDepthChromaMinus8:k,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:h+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:[...r.length?[{arrayCompleteness:1,nalUnitType:Ee.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ee.SPS_NUT,nalUnits:i}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ee.PPS_NUT,nalUnits:a}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Be(s[0]),nalUnits:s}]:[]]}}catch(t){return null}})(t.data);if(!e)throw Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=(e=>{const t=[];t.push(e.configurationVersion),t.push((3&e.generalProfileSpace)<<6|(1&e.generalTierFlag)<<5|31&e.generalProfileIdc),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(255&e.generalProfileCompatibilityFlags),t.push(...e.generalConstraintIndicatorFlags),t.push(255&e.generalLevelIdc),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(255&e.minSpatialSegmentationIdc),t.push(252|3&e.parallelismType),t.push(252|3&e.chromaFormatIdc),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.avgFrameRate>>8&255),t.push(255&e.avgFrameRate),t.push((3&e.constantFrameRate)<<6|(7&e.numTemporalLayers)<<3|(1&e.temporalIdNested)<<2|3&e.lengthSizeMinusOne),t.push(255&e.arrays.length);for(const r of e.arrays){t.push((1&r.arrayCompleteness)<<7|63&r.nalUnitType),t.push(r.nalUnits.length>>8&255),t.push(255&r.nalUnits.length);for(const e of r.nalUnits){t.push(e.length>>8&255),t.push(255&e.length);for(let r=0;r<e.length;r++)t.push(e[r])}}return new Uint8Array(t)})(e),d=!0}}else{const e=(e=>{try{const t=_e(e),i=t.filter(e=>Ie(e)===Te.SPS),a=t.filter(e=>Ie(e)===Te.PPS),s=t.filter(e=>Ie(e)===Te.SPS_EXT);if(0===i.length)return null;if(0===a.length)return null;const n=i[0],o=Ae(n);r(null!==o);const c=100===o.profileIdc||110===o.profileIdc||122===o.profileIdc||144===o.profileIdc;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:i,pictureParameterSets:a,chromaFormat:c?o.chromaFormatIdc:null,bitDepthLumaMinus8:c?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:c?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:c?s:null}}catch(t){return null}})(t.data);if(!e)throw Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=(e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const r of e.sequenceParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;e>i;i++)t.push(r[i])}t.push(e.pictureParameterSets.length);for(const r of e.pictureParameterSets){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;e>i;i++)t.push(r[i])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication){r(null!==e.chromaFormat),r(null!==e.bitDepthLumaMinus8),r(null!==e.bitDepthChromaMinus8),r(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length);for(const r of e.sequenceParameterSetExt){const e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;e>i;i++)t.push(r[i])}}return new Uint8Array(t)})(e),d=!0}const l=(e=>{const t=0>e?-1:1;let r=0,i=1,a=1,s=0,n=e=Math.abs(e);for(;;){const e=Math.floor(n),o=e*a+r,c=e*s+i;if(c>1e6)return{numerator:t*a,denominator:s};if(r=a,i=s,a=o,s=c,n=1/(n-e),!isFinite(n))break}return{numerator:t*a,denominator:s}})(1/(e.metadata.frameRate??57600)).denominator,h={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:d},timescale:l,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(h),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),h}getAudioTrackData(e,t){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;(e=>{if(!e)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!ke.some(t=>e.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(e.decoderConfig.sampleRate)||0>=e.decoderConfig.sampleRate)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||0>=e.decoderConfig.numberOfChannels)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!y(e.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.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/.");if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&18>e.decoderConfig.description.byteLength)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(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.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(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');const t=42;if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<t)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((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!Y.includes(e.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Y.join(", ")}).`)})(t),r(t),r(t.decoderConfig);const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&Y.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,t){const i=this.trackDatas.find(t=>t.track===e);if(i)return i;(e=>{if(!e)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw new TypeError("Subtitle metadata must be an object.");if(!e.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw new TypeError("Subtitle metadata config description must be a string.")})(t),r(t),r(t.config);const a={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getVideoTrackData(e,t,r);let a=t.data;if(i.info.requiresAnnexBTransformation){const e=(e=>{const t=_e(e);if(0===t.length)return null;let r=0;for(const n of t)r+=4+n.byteLength;const i=new Uint8Array(r),a=new DataView(i.buffer);let s=0;for(const n of t){const e=n.byteLength;a.setUint32(s,e,!1),s+=4,i.set(n,s),s+=n.byteLength}return i})(a);if(!e)throw 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.");a=e}const s=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),n=this.createSampleForTrack(i,a,s,t.duration,t.type);await this.registerSample(i,n)}finally{i()}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getAudioTrackData(e,r),a=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),s=this.createSampleForTrack(i,t.data,a,t.duration,t.type);i.info.requiresPcmTransformation&&await this.maybePadWithSilence(i,a),await this.registerSample(i,s)}finally{i()}}async maybePadWithSilence(e,t){const r=a(e.samples),i=r?r.timestamp+r.duration:0,s=t-i,n=sa(s,e.timescale);if(n>0){const{sampleSize:t,silentValue:r}=pe(e.info.decoderConfig.codec),a=n*e.info.numberOfChannels,o=new Uint8Array(t*a).fill(r),c=this.createSampleForTrack(e,new Uint8Array(o.buffer),i,s,"key");await this.registerSample(e,c)}}async addSubtitleCue(e,t,r){const i=await this.mutex.acquire();try{const i=this.getSubtitleTrackData(e,r);this.validateAndNormalizeTimestamp(i.track,t.timestamp,!0),"webvtt"===e.source._codec&&(i.cueQueue.push(t),await this.processWebVTTCues(i,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const d of e.cueQueue)r(d.timestamp<=t),r(e.lastCueEndTimestamp<=d.timestamp+d.duration),i.add(Math.max(d.timestamp,e.lastCueEndTimestamp)),i.add(d.timestamp+d.duration);const a=[...i].sort((e,t)=>e-t),s=a[0],n=a[1]??s;if(n>t)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const t=Mi();this.auxBoxWriter.writeBox(t);const r=this.auxWriter.getSlice(0,this.auxWriter.getPos()),i=this.createSampleForTrack(e,r,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,i),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){const r=e.cueQueue[t];if(r.timestamp>=n)break;pr.lastIndex=0;const i=pr.test(r.text),a=r.timestamp+r.duration;let o=e.cueToSourceId.get(r);if(void 0===o&&a>n&&(o=e.nextSourceId++,e.cueToSourceId.set(r,o)),r.notes){const e=Ai(r.notes);this.auxBoxWriter.writeBox(e)}const c=Ii(r.text,i?s:null,r.identifier??null,r.settings??null,o??null);this.auxBoxWriter.writeBox(c),a===n&&e.cueQueue.splice(t--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,n-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=n}}createSampleForTrack(e,t,r,i,a){return{timestamp:r,decodeTimestamp:r,duration:i,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:sa(i,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){let t=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const i=e.timestampProcessingQueue[r];t+=sa(i.duration,e.timescale)}return 0===e.timeToSampleTable.length?e.timeToSampleTable.push({sampleCount:t,sampleDelta:1}):a(e.timeToSampleTable).sampleCount+=t,void(e.timestampProcessingQueue.length=0)}const i=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let s=0;s<e.timestampProcessingQueue.length;s++){const t=e.timestampProcessingQueue[s];t.decodeTimestamp=i[s],this.isFragmented||null!==e.lastTimescaleUnits||(t.decodeTimestamp=0);const n=sa(t.timestamp-t.decodeTimestamp,e.timescale),o=sa(t.duration,e.timescale);if(null!==e.lastTimescaleUnits){r(e.lastSample);const i=sa(t.decodeTimestamp,e.timescale,!1),s=Math.round(i-e.lastTimescaleUnits);if(r(s>=0),e.lastTimescaleUnits+=s,e.lastSample.timescaleUnitsToNextSample=s,!this.isFragmented){let t=a(e.timeToSampleTable);if(r(t),1===t.sampleCount){t.sampleDelta=s;const r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===s&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==s&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:s}));t.sampleDelta===o?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const i=a(e.compositionTimeOffsetTable);r(i),i.sampleCompositionTimeOffset===n?i.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else e.lastTimescaleUnits=sa(t.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));e.lastSample=t}if(e.timestampProcessingQueue.length=0,r(e.lastSample),r(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){r("key"===t.type);const i=sa(t.timestamp,e.timescale,!1),a=Math.round(i-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=a}}async registerSample(e,t){"key"===t.type&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),"reserve"===this.fastStart)){const t=e.track.metadata.maximumPacketCount;if(r(void 0!==t),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const a=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;const i=r.sampleQueue[0];return i?"key"===i.type:r.track.source._closed});r>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),r(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(r(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,r)=>t+sa(r.duration,e.timescale),0)),0!==e.compactlyCodedChunkTable.length&&a(e.compactlyCodedChunkTable).samplesPerChunk===t||e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),"in-memory"!==this.fastStart){e.currentChunk.offset=this.writer.getPos();for(const t of e.currentChunk.samples)r(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}else e.currentChunk.offset=0}async interleaveSamples(e=!1){if(r(this.isFragmented),e||this.allTracksAreKnown())e:for(;;){let t=null,r=1/0;for(const a of this.trackDatas){if(!e&&0===a.sampleQueue.length&&!a.track.source._closed)break e;a.sampleQueue.length>0&&a.sampleQueue[0].timestamp<r&&(t=a,r=a.sampleQueue[0].timestamp)}if(!t)break;const i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!0){r(this.isFragmented);const t=this.nextFragmentNumber++;if(1===t){this.format._options.onMoov&&this.writer.startTrackingWrites();const e=Ur(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}const i=this.trackDatas.filter(e=>e.currentChunk),a=ki(t,i),s=this.writer.getPos(),n=s+this.boxWriter.measureBox(a);let o=n+8,c=1/0;for(const r of i){r.currentChunk.offset=o,r.currentChunk.moofOffset=s;for(const e of r.currentChunk.samples)o+=e.size;c=Math.min(c,r.currentChunk.startTimestamp)}const d=o-n,l=d>=2**32;if(l)for(const r of i)r.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const h=ki(t,i);if(this.boxWriter.writeBox(h),this.format._options.onMoof){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,c)}r(this.writer.getPos()===n),this.format._options.onMdat&&this.writer.startTrackingWrites();const u=Or(l);u.size=d,this.boxWriter.writeBox(u),this.writer.seek(n+(l?St:8));for(const r of i)for(const e of r.currentChunk.samples)this.writer.write(e.data),e.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(const r of i)r.finalizedChunks.push(r.currentChunk),this.finalizedChunks.push(r.currentChunk),r.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){const e=Ur(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;r(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Or(!0),this.boxWriter.writeBox(this.mdat);for(const r of this.trackDatas){for(const e of r.sampleQueue)await this.addSampleToTrack(r,e);r.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){r("reserve"===this.fastStart);let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;r(void 0!==i),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire();if("subtitle"===e.type&&"webvtt"===e.source._codec){const t=this.trackDatas.find(t=>t.track===e);t&&await this.processWebVTTCues(t,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const r of this.trackDatas)"subtitle"===r.type&&"webvtt"===r.track.source._codec&&await this.processWebVTTCues(r,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const e of this.trackDatas)this.processTimestamps(e);await this.finalizeFragment(!1)}else for(const r of this.trackDatas)this.processTimestamps(r),await this.finalizeCurrentChunk(r);if("in-memory"===this.fastStart){let e;this.mdat=Or(!1);for(let i=0;2>i;i++){const t=Ur(this),i=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+i+e;for(const s of this.finalizedChunks){s.offset=a;for(const{data:t}of s.samples)r(t),a+=t.byteLength,e+=t.byteLength}if(2**32>a)break;2**32>e||(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const t=Ur(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(const i of this.finalizedChunks)for(const e of i.samples)r(e.data),this.writer.write(e.data),e.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){const e=this.writer.getPos(),r=(t=this.trackDatas,Fr("mfra",void 0,[...t.map(Pi),Dr("mfro",0,0,[Tr(0)])]));this.boxWriter.writeBox(r);const i=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{r(this.mdat);const e=this.boxWriter.offsets.get(this.mdat);r(void 0!==e);const t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}const i=Ur(this);if("reserve"===this.fastStart){r(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);const e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:e})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}var t;e()}}class oa{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Z.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>ee.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>te.includes(e))}_codecUnsupportedHint(e){return""}}class ca extends oa{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==e.minimumFragmentDuration&&(!Number.isFinite(e.minimumFragmentDuration)||0>e.minimumFragmentDuration))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==e.onFtyp&&"function"!=typeof e.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==e.onMoov&&"function"!=typeof e.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==e.onMdat&&"function"!=typeof e.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==e.onMoof&&"function"!=typeof e.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==e.metadataFormat&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new na(e,this)}}class da extends ca{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Z,...J,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...te]}_codecUnsupportedHint(e){return(new la).getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class la extends ca{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Z,...ee]}_codecUnsupportedHint(e){return(new da).getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}const ha=e=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding config must be an object.");if(!Z.includes(e.codec))throw new TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${Z.join(", ")}.`);if(!(e.bitrate instanceof ga||Number.isInteger(e.bitrate)&&e.bitrate>0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(void 0!==e.keyFrameInterval&&(!Number.isFinite(e.keyFrameInterval)||0>e.keyFrameInterval))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==e.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(e.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==e.onEncodedPacket&&"function"!=typeof e.onEncodedPacket)throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(void 0!==e.onEncoderConfig&&"function"!=typeof e.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");ua(e.codec,e)},ua=(e,t)=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding options must be an object.");if(void 0!==t.alpha&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==t.latencyMode&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==t.fullCodecString&&"string"!=typeof t.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==t.fullCodecString&&fe(t.fullCodecString)!==e)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(void 0!==t.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==t.scalabilityMode&&"string"!=typeof t.scalabilityMode)throw new TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==t.contentHint&&"string"!=typeof t.contentHint)throw new TypeError("contentHint, when provided, must be a string.")},ma=e=>{const t=e.bitrate instanceof ga?e.bitrate._toVideoBitrate(e.codec,e.width,e.height):e.bitrate;return{codec:e.fullCodecString??ne(e.codec,e.width,e.height,t),width:e.width,height:e.height,bitrate:t,bitrateMode:e.bitrateMode,alpha:e.alpha??"discard",framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...(r=e.codec,"avc"===r?{avc:{format:"avc"}}:"hevc"===r?{hevc:{format:"hevc"}}:{})};var r},pa=(e,t)=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding options must be an object.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==t.fullCodecString&&"string"!=typeof t.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==t.fullCodecString&&fe(t.fullCodecString)!==e)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},fa=e=>{const t=e.bitrate instanceof ga?e.bitrate._toAudioBitrate(e.codec):e.bitrate;return{codec:e.fullCodecString??ce(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:t,bitrateMode:e.bitrateMode,...(r=e.codec,"aac"===r?{aac:{format:"aac"}}:"opus"===r?{opus:{format:"opus"}}:{})};var r};class ga{constructor(e){this._factor=e}_toVideoBitrate(e,t,r){const i=3e6*Math.pow(t*r/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[e]*this._factor;return 1e3*Math.ceil(i/1e3)}_toAudioBitrate(e){if(Y.includes(e)||"flac"===e)return;const t={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!t)throw Error("Unhandled codec: "+e);let r=t*this._factor;return"aac"===e?r=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(e-r)>Math.abs(t-r)?t:e):"opus"===e||"vorbis"===e?r=Math.max(6e3,r):"mp3"===e&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(e-r)>Math.abs(t-r)?t:e)),1e3*Math.round(r/1e3)}}const wa=new ga(2),ba=async(e,t={})=>{const{width:r=1280,height:i=720,bitrate:a=1e6,...s}=t;if(!Z.includes(e))return!1;if(!Number.isInteger(r)||0>=r)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||0>=i)throw new TypeError("height must be a positive integer.");if(!(a instanceof ga||Number.isInteger(a)&&a>0))throw new TypeError("bitrate must be a positive integer or a quality.");ua(e,s);let n=null;return!(0>=He.length||(n??=ma({codec:e,width:r,height:i,bitrate:a,framerate:void 0,...s}),!He.some(t=>t.supports(e,n))))||"undefined"!=typeof VideoEncoder&&(r%2!=1&&i%2!=1||"avc"!==e&&"hevc"!==e)&&(n??=ma({codec:e,width:r,height:i,bitrate:a,framerate:void 0,...s,alpha:"discard"}),!!(await VideoEncoder.isConfigSupported(n)).supported&&(!N()||new Promise(async e=>{try{const t=new VideoEncoder({output:()=>{},error:()=>e(!1)});t.configure(n);const a=new Uint8Array(r*i*4),s=new VideoFrame(a,{format:"RGBA",codedWidth:r,codedHeight:i,timestamp:0});t.encode(s),s.close(),await t.flush(),e(!0)}catch{e(!1)}})))},va=async(e=ee,t)=>{const r=await Promise.all(e.map(e=>(async(e,t={})=>{const{numberOfChannels:r=2,sampleRate:i=48e3,bitrate:a=128e3,...s}=t;if(!ee.includes(e))return!1;if(!Number.isInteger(r)||0>=r)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||0>=i)throw new TypeError("sampleRate must be a positive integer.");if(!(a instanceof ga||Number.isInteger(a)&&a>0))throw new TypeError("bitrate must be a positive integer.");pa(e,s);let n=null;return!(0>=qe.length||(n??=fa({codec:e,numberOfChannels:r,sampleRate:i,bitrate:a,...s}),!qe.some(t=>t.supports(e,n))))||!!Y.includes(e)||"undefined"!=typeof AudioEncoder&&(n??=fa({codec:e,numberOfChannels:r,sampleRate:i,bitrate:a,...s}),!0===(await AudioEncoder.isConfigSupported(n)).supported)})(e,t)));return e.filter((e,t)=>r[t])};class ya{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw Error("Source is not connected to an output track.");if("canceled"===this._connectedTrack.output.state)throw Error("Output has been canceled.");if("finalizing"===this._connectedTrack.output.state||"finalized"===this._connectedTrack.output.state)throw Error("Output has been finalized.");if("pending"===this._connectedTrack.output.state)throw Error("Output has not started.");if(this._closed)throw Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw Error("Cannot call close without connecting the source to an output track.");if("pending"===e.output.state)throw Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,"finalizing"!==e.output.state&&"finalized"!==e.output.state&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}}class ka extends ya{constructor(e){if(super(),this._connectedTrack=null,!Z.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Z.join(", ")}.`);this._codec=e}}class Sa extends ka{constructor(e){super(e)}add(e,t){if(!(e instanceof $e))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Ta{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new O,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,t,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),null!==this.codedWidth&&null!==this.codedHeight){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const i=this.encodingConfig.sizeChangeBehavior??"deny";if("passThrough"===i);else{if("deny"===i)throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let a=!1;this.resizeCanvas||("undefined"!=typeof document?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),a=!0);const s=this.resizeCanvas.getContext("2d",{alpha:N()});r(s),a||(N()?(s.fillStyle="black",s.fillRect(0,0,this.codedWidth,this.codedHeight)):s.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(s,{fit:i}),t&&e.close(),e=new Qe(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),t=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),r(this.encoderInitialized);const s=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/s),o={...i,keyFrame:i?.keyFrame||0===s||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;const t=e.clone(),r=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,o)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});4>this.customEncoderQueueSize||await r}else{r(this.encoder);const i=e.toVideoFrame();if(this.alphaEncoder)if(i.format&&!i.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(i,o),i.close();else{const e=i.displayWidth,t=i.displayHeight;if(!this.splitter)try{this.splitter=new Ca(e,t)}catch(a){this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(i,o),i.close()}if(this.splitter){const e=this.splitter.extractColor(i),t=this.splitter.extractAlpha(i);this.alphaFrameQueue.push(t),this.encoder.encode(e,o),e.close(),i.close()}}else this.encoder.encode(i,o),i.close();t&&e.close(),4>this.encoder.encodeQueueSize||await new Promise(e=>this.encoder.addEventListener("dequeue",e,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}ensureEncoder(e){const t=Error();this.ensureEncoderPromise=(async()=>{const i=ma({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const a=He.find(e=>e.supports(this.encodingConfig.codec,i));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof $e))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if("undefined"==typeof VideoEncoder)throw Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard","keep"===this.encodingConfig.alpha&&(i.latencyMode="quality"),!(i.width%2!=1&&i.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw Error(`The dimensions ${i.width}x${i.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const e=[],a=[];let s=0,n=0;const o=(e,t,r)=>{const i={};if(t){const e=new Uint8Array(t.byteLength);t.copyTo(e),i.alpha=e}const a=$e.fromEncodedChunk(e,i);this.encodingConfig.onEncodedPacket?.(a,r),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(e=>{this.error??=e,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(t,i)=>{if(!this.alphaEncoder)return void o(t,null,i);const c=this.alphaFrameQueue.shift();r(void 0!==c),c?(this.alphaEncoder.encode(c,{keyFrame:"key"===t.type}),n++,c.close(),e.push({chunk:t,meta:i})):0===n?o(t,null,i):(a.push(s+n),e.push({chunk:t,meta:i}))},error:e=>{e.stack=t.stack,this.error??=e}}),this.encoder.configure(i),"keep"===this.encodingConfig.alpha&&(this.alphaEncoder=new VideoEncoder({output:(t,i)=>{n--;const c=e.shift();for(r(void 0!==c),o(c.chunk,t,c.meta),s++;a.length>0&&a[0]===s;){a.shift();const t=e.shift();r(void 0!==t),o(t.chunk,null,t.meta)}},error:e=>{e.stack=t.stack,this.error??=e}}),this.alphaEncoder.configure(i))}r(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await(this.alphaEncoder?.flush())),"closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=Error().stack),this.error}}class Ca{constructor(e,t){this.lastFrame=null,"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);const r=this.canvas.getContext("webgl2",{alpha:!0});if(!r)throw Error("Couldn't acquire WebGL 2 context.");this.gl=r,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t")}createColorProgram(){const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_sourceTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec4 source = texture(u_sourceTexture, v_texCoord);\n\t\t\t\tfragColor = vec4(source.rgb, 1.0);\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createAlphaProgram(){const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_sourceTexture;\n\t\t\tuniform vec2 u_resolution; // The width and height of the canvas\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\n\t\t\t// This function determines the value for a single byte in the YUV stream\n\t\t\tfloat getByteValue(float byteOffset) {\n\t\t\t\tfloat width = u_resolution.x;\n\t\t\t\tfloat height = u_resolution.y;\n\n\t\t\t\tfloat yPlaneSize = width * height;\n\n\t\t\t\tif (byteOffset < yPlaneSize) {\n\t\t\t\t\t// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from\n\t\t\t\t\tfloat y = floor(byteOffset / width);\n\t\t\t\t\tfloat x = mod(byteOffset, width);\n\t\t\t\t\t\n\t\t\t\t\t// Add 0.5 to sample the center of the texel\n\t\t\t\t\tvec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;\n\t\t\t\t\t\n\t\t\t\t\t// The luma value is the alpha from the source texture\n\t\t\t\t\treturn texture(u_sourceTexture, sampleCoord).a;\n\t\t\t\t} else {\n\t\t\t\t\t// Write a fixed value for chroma and beyond\n\t\t\t\t\treturn 128.0 / 255.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\t// Each fragment writes 4 bytes (R, G, B, A)\n\t\t\t\tfloat pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);\n\t\t\t\tfloat baseByteOffset = pixelIndex * 4.0;\n\n\t\t\t\tvec4 result;\n\t\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\t\tfloat currentByteOffset = baseByteOffset + float(i);\n\t\t\t\t\tresult[i] = getByteValue(currentByteOffset);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfragColor = result;\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS),r}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const i=this.gl.getAttribLocation(this.colorProgram,"a_position"),a=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&(e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:t,height:i}=this.canvas,a=t*i+Math.ceil(t/2)*Math.ceil(i/2)*2,s=Math.ceil(a/(4*t));let n=new Uint8Array(4*t*s);this.gl.readPixels(0,0,t,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),n=n.subarray(0,a),r(128===n[t*i]),r(128===n[n.length-1]);const o={format:"I420",codedWidth:t,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[n.buffer]};return new VideoFrame(n,o)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class Ea extends ka{constructor(e){ha(e),super(e.codec),this._encoder=new Ta(this,e)}add(e,t){if(!(e instanceof Qe))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class xa extends ka{constructor(e,t){if(!("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ha(t),super(t.codec),this._encoder=new Ta(this,t),this._canvas=e}add(e,t=0,r){if(!Number.isFinite(e)||0>e)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||0>t)throw new TypeError("duration must be a non-negative number.");const i=new Qe(this._canvas,{timestamp:e,duration:t});return this._encoder.add(i,!0,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class _a extends ya{constructor(e){if(super(),this._connectedTrack=null,!ee.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${ee.join(", ")}.`);this._codec=e}}class Pa extends _a{constructor(e){super(e)}add(e,t){if(!(e instanceof $e))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class Ma{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new O,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null,this.errorNeedsNewStack=!0}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),null!==this.lastNumberOfChannels&&null!==this.lastSampleRate){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),r(this.encoderInitialized);{const t=Math.round(e.timestamp*e.sampleRate),r=Math.round((e.timestamp+e.duration)*e.sampleRate);if(null!==this.lastEndSampleIndex&&t>this.lastEndSampleIndex){const r=t-this.lastEndSampleIndex,i=new Ye({data:new Float32Array(r*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:r,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(i,!0)}this.lastEndSampleIndex=r}if(this.customEncoder){this.customEncoderQueueSize++;const t=e.clone(),r=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});4>this.customEncoderQueueSize||await r,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{r(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),4>this.encoder.encodeQueueSize||await new Promise(e=>this.encoder.addEventListener("dequeue",e,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){r(this.outputSampleSize),r(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:a,sampleRate:s,timestamp:n}=e,o=2048,c=[];for(let r=0;a>r;r+=o){const t=Math.min(o,e.numberOfFrames-r),a=t*i*this.outputSampleSize,s=new ArrayBuffer(a),n=new DataView(s);c.push({frameCount:t,view:n})}const d=e.allocationSize({planeIndex:0,format:"f32-planar"}),l=new Float32Array(d/Float32Array.BYTES_PER_ELEMENT);for(let r=0;i>r;r++){e.copyTo(l,{planeIndex:r,format:"f32-planar"});for(let e=0;e<c.length;e++){const{frameCount:t,view:a}=c[e];for(let s=0;t>s;s++)this.writeOutputValue(a,(s*i+r)*this.outputSampleSize,l[e*o+s])}}t&&e.close();const h={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let r=0;r<c.length;r++){const{frameCount:e,view:t}=c[r],i=t.buffer,a=r*o,d=new $e(new Uint8Array(i),"key",n+a/s,e/s);this.encodingConfig.onEncodedPacket?.(d,h),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,h)}}ensureEncoder(e){const t=Error();this.ensureEncoderPromise=(async()=>{const{numberOfChannels:i,sampleRate:s}=e,o=fa({numberOfChannels:i,sampleRate:s,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(o);const c=qe.find(e=>e.supports(this.encodingConfig.codec,o));if(c)this.customEncoder=new c,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof $e))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(Y.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if("undefined"==typeof AudioEncoder)throw Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(o)).supported)throw Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(e,t)=>{if("aac"===this.encodingConfig.codec&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||2>t.decoderConfig.description.byteLength||0===ue(d(t.decoderConfig.description)).objectType,e){const e=+a(o.codec.split("."));t.decoderConfig.description=(e=>{let t=le.indexOf(e.sampleRate),r=null;-1===t&&(t=15,r=e.sampleRate);const i=he.indexOf(e.numberOfChannels);if(-1===i)throw new TypeError("Unsupported number of channels: "+e.numberOfChannels);let a=13;32>e.objectType||(a+=6),15===t&&(a+=24);const s=new Uint8Array(Math.ceil(a/8)),o=new n(s);return 32>e.objectType?o.writeBits(5,e.objectType):(o.writeBits(5,31),o.writeBits(6,e.objectType-32)),o.writeBits(4,t),15===t&&o.writeBits(24,r),o.writeBits(4,i),s})({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}const r=$e.fromEncodedChunk(e);this.encodingConfig.onEncodedPacket?.(r,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,r,t).catch(e=>{this.error??=e,this.errorNeedsNewStack=!1})},error:e=>{e.stack=t.stack,this.error??=e}}),this.encoder.configure(o)}r(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:a}=pe(e);switch(this.outputSampleSize=i,i){case 1:"unsigned"===t?this.writeOutputValue=(e,t,r)=>e.setUint8(t,R(127.5*(r+1),0,255)):"signed"===t?this.writeOutputValue=(e,t,r)=>{e.setInt8(t,R(Math.round(128*r),-128,127))}:"ulaw"===t?this.writeOutputValue=(e,t,r)=>{const i=R(Math.floor(32767*r),-32768,32767);e.setUint8(t,(e=>{let t=e,r=4096,i=0,a=12,s=0;for(0>t&&(t=-t,i=128),t+=33,t>8191&&(t=8191);(t&r)!==r&&a>=5;)r>>=1,a--;return s=t>>a-4&15,255&~(i|a-5<<4|s)})(i))}:"alaw"===t?this.writeOutputValue=(e,t,r)=>{const i=R(Math.floor(32767*r),-32768,32767);e.setUint8(t,(e=>{let t=2048,r=0,i=11,a=0,s=e;for(0>s&&(s=-s,r=128),s>4095&&(s=4095);(s&t)!==t&&i>=5;)t>>=1,i--;return a=s>>(4===i?1:i-4)&15,85^(r|i-4<<4|a)})(i))}:r(!1);break;case 2:"unsigned"===t?this.writeOutputValue=(e,t,r)=>e.setUint16(t,R(32767.5*(r+1),0,65535),a):"signed"===t?this.writeOutputValue=(e,t,r)=>e.setInt16(t,R(Math.round(32767*r),-32768,32767),a):r(!1);break;case 3:"unsigned"===t?this.writeOutputValue=(e,t,r)=>I(e,t,R(8388607.5*(r+1),0,16777215),a):"signed"===t?this.writeOutputValue=(e,t,r)=>((e,t,r,i)=>{0>(r=R(r,-8388608,8388607))&&(r=r+16777216&16777215),I(e,t,r,i)})(e,t,R(Math.round(8388607*r),-8388608,8388607),a):r(!1);break;case 4:"unsigned"===t?this.writeOutputValue=(e,t,r)=>e.setUint32(t,R(2147483647.5*(r+1),0,4294967295),a):"signed"===t?this.writeOutputValue=(e,t,r)=>e.setInt32(t,R(Math.round(2147483647*r),-2147483648,2147483647),a):"float"===t?this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,a):r(!1);break;case 8:"float"===t?this.writeOutputValue=(e,t,r)=>e.setFloat64(t,r,a):r(!1);break;default:P(i),r(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),"closed"!==this.encoder.state&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=Error().stack),this.error}}class Ia extends _a{constructor(e){(e=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding config must be an object.");if(!ee.includes(e.codec))throw new TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${ee.join(", ")}.`);if(void 0===e.bitrate&&(!Y.includes(e.codec)||"flac"===e.codec))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(!(void 0===e.bitrate||e.bitrate instanceof ga||Number.isInteger(e.bitrate)&&e.bitrate>0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==e.onEncodedPacket&&"function"!=typeof e.onEncodedPacket)throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(void 0!==e.onEncoderConfig&&"function"!=typeof e.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");pa(e.codec,e)})(e),super(e.codec),this._encoder=new Ma(this,e)}add(e){if(!(e instanceof Ye))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Aa extends ya{constructor(e){if(super(),this._connectedTrack=null,!te.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${te.join(", ")}.`);this._codec=e}}const Ra=["video","audio","subtitle"],Ba=e=>{if(!e||"object"!=typeof e)throw new TypeError("metadata must be an object.");if(void 0!==e.languageCode&&!F(e.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==e.name&&"string"!=typeof e.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==e.disposition&&(e=>{if(!e||"object"!=typeof e)throw new TypeError("disposition must be an object.");if(void 0!==e.default&&"boolean"!=typeof e.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==e.forced&&"boolean"!=typeof e.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==e.original&&"boolean"!=typeof e.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==e.commentary&&"boolean"!=typeof e.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==e.hearingImpaired&&"boolean"!=typeof e.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==e.visuallyImpaired&&"boolean"!=typeof e.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(e.disposition),void 0!==e.maximumPacketCount&&(!Number.isInteger(e.maximumPacketCount)||0>e.maximumPacketCount))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class za{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new k,this._metadataTags={},!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.format instanceof oa))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Ji))throw new TypeError("options.target must be a Target.");if(e.target._output)throw Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof ka))throw new TypeError("source must be a VideoSource.");if(Ba(t),void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(this.format._name+" does not support video rotation metadata.");if(!(void 0===t.frameRate||Number.isFinite(t.frameRate)&&t.frameRate>0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof _a))throw new TypeError("source must be an AudioSource.");Ba(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Aa))throw new TypeError("source must be a SubtitleSource.");Ba(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if(G(e),"pending"!==this.state)throw Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,r){if("pending"!==this.state)throw Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw Error("Source is already used for a track.");const i=this.format.getSupportedTrackCounts(),a=this._tracks.reduce((t,r)=>t+(r.type===e?1:0),0),s=i[e].max;if(a===s)throw Error(0===s?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${s} ${e} track${1===s?"":"s"}.`);const n=i.total.max;if(this._tracks.length===n)throw Error(`${this.format._name} does not support more than ${n} tracks${1===n?"":"s"} in total.`);const o={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if("video"===o.type){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw Error(this.format._name+" does not support video tracks."+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("audio"===o.type){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw Error(this.format._name+" does not support audio tracks."+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("subtitle"===o.type){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw Error(this.format._name+" does not support subtitle tracks."+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}this._tracks.push(o),t._connectedTrack=o}async start(){const e=this.format.getSupportedTrackCounts();for(const r of Ra){const t=this._tracks.reduce((e,t)=>e+(t.type===r?1:0),0),i=e[r].min;if(i>t)throw Error(i===e[r].max?`${this.format._name} requires exactly ${i} ${r} track${1===i?"":"s"}.`:`${this.format._name} requires at least ${i} ${r} track${1===i?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${1===t?"":"s"}.`:`${this.format._name} requires at least ${t} track${1===t?"":"s"}.`);if("canceled"===this.state)throw Error("Output has been canceled.");return this._startPromise?this._startPromise:this._startPromise=(async()=>{this.state="started",this._writer.start();const e=await this._mutex.acquire();await this._muxer.start();const t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?this._cancelPromise:"finalizing"!==this.state&&"finalized"!==this.state?this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})():void 0}async finalize(){if("pending"===this.state)throw Error("Cannot finalize before starting.");if("canceled"===this.state)throw Error("Cannot finalize after canceling.");return this._finalizePromise?this._finalizePromise:this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}const Fa=e=>{if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("options.video, when provided, must be an object.");if(void 0!==e?.discard&&"boolean"!=typeof e.discard)throw new TypeError("options.video.discard, when provided, must be a boolean.");if(void 0!==e?.forceTranscode&&"boolean"!=typeof e.forceTranscode)throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(void 0!==e?.codec&&!Z.includes(e.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${Z.join(", ")}.`);if(!(void 0===e?.bitrate||e.bitrate instanceof ga||Number.isInteger(e.bitrate)&&e.bitrate>0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(!(void 0===e?.width||Number.isInteger(e.width)&&e.width>0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(!(void 0===e?.height||Number.isInteger(e.height)&&e.height>0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(void 0!==e?.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.video.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.video.width and options.video.height are provided, options.video.fit must also be provided.");if(void 0!==e?.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e?.crop&&Xe(e.crop,"options.video."),!(void 0===e?.frameRate||Number.isFinite(e.frameRate)&&e.frameRate>0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(void 0!==e?.alpha&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(void 0!==e?.keyFrameInterval&&(!Number.isFinite(e.keyFrameInterval)||0>e.keyFrameInterval))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==e?.process&&"function"!=typeof e.process)throw new TypeError("options.video.process, when provided, must be a function.");if(!(void 0===e?.processedWidth||Number.isInteger(e.processedWidth)&&e.processedWidth>0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(!(void 0===e?.processedHeight||Number.isInteger(e.processedHeight)&&e.processedHeight>0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.")},Da=e=>{if(void 0!==e&&(!e||"object"!=typeof e))throw new TypeError("options.audio, when provided, must be an object.");if(void 0!==e?.discard&&"boolean"!=typeof e.discard)throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(void 0!==e?.forceTranscode&&"boolean"!=typeof e.forceTranscode)throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(void 0!==e?.codec&&!ee.includes(e.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${ee.join(", ")}.`);if(!(void 0===e?.bitrate||e.bitrate instanceof ga||Number.isInteger(e.bitrate)&&e.bitrate>0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(!(void 0===e?.numberOfChannels||Number.isInteger(e.numberOfChannels)&&e.numberOfChannels>0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(!(void 0===e?.sampleRate||Number.isInteger(e.sampleRate)&&e.sampleRate>0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(void 0!==e?.process&&"function"!=typeof e.process)throw new TypeError("options.audio.process, when provided, must be a function.");if(!(void 0===e?.processedNumberOfChannels||Number.isInteger(e.processedNumberOfChannels)&&e.processedNumberOfChannels>0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(!(void 0===e?.processedSampleRate||Number.isInteger(e.processedSampleRate)&&e.processedSampleRate>0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.")},Oa=48e3;class Ua{static async init(e){const t=new Ua(e);return await t._init(),t}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._trackPromises=[],this._executed=!1,this._synchronizer=new La,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.input instanceof Yt))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof za))throw new TypeError("options.output must be an Output.");if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||"pending"!==e.output.state)throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if("function"!=typeof e.video&&Fa(e.video),"function"!=typeof e.audio&&Da(e.audio),void 0!==e.trim&&(!e.trim||"object"!=typeof e.trim))throw new TypeError("options.trim, when provided, must be an object.");if(void 0!==e.trim?.start&&(!Number.isFinite(e.trim.start)||0>e.trim.start))throw new TypeError("options.trim.start, when provided, must be a non-negative number.");if(void 0!==e.trim?.end&&(!Number.isFinite(e.trim.end)||0>e.trim.end))throw new TypeError("options.trim.end, when provided, must be a non-negative number.");if(void 0!==e.trim?.start&&void 0!==e.trim.end&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(void 0!==e.tags&&("object"!=typeof e.tags||!e.tags)&&"function"!=typeof e.tags)throw new TypeError("options.tags, when provided, must be an object or a function.");if("object"==typeof e.tags&&G(e.tags),void 0!==e.showWarnings&&"boolean"!=typeof e.showWarnings)throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this.input=e.input,this.output=e.output,this._startTimestamp=e.trim?.start??0,this._endTimestamp=e.trim?.end??1/0;const{promise:t,resolve:r}=_();this._started=t,this._start=r}async _init(){const e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts();let i=1,a=1;for(const d of e){let e;d.isVideoTrack()?this._options.video&&("function"==typeof this._options.video?(e=await this._options.video(d,i),Fa(e),i++):e=this._options.video):d.isAudioTrack()?this._options.audio&&("function"==typeof this._options.audio?(e=await this._options.audio(d,a),Da(e),a++):e=this._options.audio):r(!1),e?.discard?this.discardedTracks.push({track:d,reason:"discarded_by_user"}):this._totalTrackCount!==t.total.max?this._addedCounts[d.type]!==t[d.type].max?d.isVideoTrack()?await this._processVideoTrack(d,e??{}):d.isAudioTrack()&&await this._processAudioTrack(d,e??{}):this.discardedTracks.push({track:d,reason:"max_track_count_of_type_reached"}):this.discardedTracks.push({track:d,reason:"max_track_count_reached"})}const s=await this.input.getMetadataTags();let n;if(this._options.tags){const e="function"==typeof this._options.tags?await this._options.tags(s):this._options.tags;G(e),n=e}else n=s;const o=(await this.input.getFormat()).mimeType===this.output.format.mimeType,c=s.raw===n.raw;if(s.raw&&c&&!o&&delete n.raw,this.output.setMetadataTags(n),this.isValid=!(this._totalTrackCount<t.total.min||this._addedCounts.video<t.video.min||this._addedCounts.audio<t.audio.min||this._addedCounts.subtitle<t.subtitle.min),this._options.showWarnings??1){const e=[],t=this.discardedTracks.filter(e=>"discarded_by_user"!==e.reason);t.length>0&&e.push("Some tracks had to be discarded from the conversion:",t),this.isValid||e.push("\n\n"+this._getInvalidityExplanation().join("")),e.length}}_getInvalidityExplanation(){const e=[];if(0===this.discardedTracks.length)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(e=>"discarded_by_user"===e.reason||"no_encodable_target_codec"===e.reason);if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const t=this.discardedTracks.flatMap(e=>"discarded_by_user"===e.reason?[]:"video"===e.track.type?this.output.format.getSupportedVideoCodecs():"audio"===e.track.type?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs());1===t.length?e.push(`\nTracks were discarded because your environment is not able to encode '${t[0]}'.`):e.push(`\nTracks were discarded because your environment is not able to encode any of the following codecs: ${t.map(e=>`'${e}'`).join(", ")}.`),t.includes("mp3")&&e.push("\nThe @mediabunny/mp3-encoder extension package provides support for encoding MP3.")}else e.push("\nCheck the discardedTracks field for more info.")}return e}async execute(){if(!this.isValid)throw Error("Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.\n"+this._getInvalidityExplanation().join(""));if(this._executed)throw Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}this._canceled&&await new Promise(()=>{}),await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){"finalizing"!==this.output.state&&"finalized"!==this.output.state&&(this._canceled||(this._canceled=!0,await this.output.cancel()))}async _processVideoTrack(e,t){const a=e.codec;if(!a)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec"});let s;const n=i(e.rotation+(t.rotate??0)),o=this.output.format.supportsVideoRotationMetadata,[c,d]=n%180==0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],l=t.crop;l&&Ge(l,c,d);const[h,u]=l?[l.width,l.height]:[c,d];let m=h,p=u;const f=m/p,g=e=>2*Math.ceil(e/2);void 0!==t.width&&void 0===t.height?(m=g(t.width),p=g(Math.round(m/f))):void 0===t.width&&void 0!==t.height?(p=g(t.height),m=g(Math.round(p*f))):void 0!==t.width&&void 0!==t.height&&(m=g(t.width),p=g(t.height));const w=await e.getFirstTimestamp(),b=!!t.forceTranscode||this._startTimestamp>0||0>w||!!t.frameRate||void 0!==t.keyFrameInterval||void 0!==t.process;let v=m!==h||p!==u||0!==n&&(!o||void 0!==t.process)||!!l;const y=t.alpha??"discard";let k=this.output.format.getSupportedVideoCodecs();if(b||t.bitrate||v||!k.includes(a)||t.codec&&t.codec!==a){if(!(await e.canDecode()))return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});t.codec&&(k=k.filter(e=>e===t.codec));const i=t.bitrate??wa,a=await(async(e,t)=>{for(const r of e)if(await ba(r,t))return r;return null})(k,{width:t.process&&t.processedWidth?t.processedWidth:m,height:t.process&&t.processedHeight?t.processedHeight:p,bitrate:i});if(!a)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});const o={codec:a,bitrate:i,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:y},c=new Ea(o);if(s=c,!v){const t=new za({format:new da,target:new ra}),r=new Ea(o);t.addVideoTrack(r),await t.start();const i=new mt(e),a=await i.getSample(w);if(a)try{await r.add(a),a.close(),await t.finalize()}catch(S){v=!0,t.cancel()}else await t.cancel()}v?this._trackPromises.push((async()=>{await this._started;const i=new pt(e,{width:m,height:p,fit:t.fit??"fill",rotation:n,crop:t.crop,poolSize:1,alpha:"keep"===y}).canvases(this._startTimestamp,this._endTimestamp),a=t.frameRate;let s=null,o=null,d=null;const l=async i=>{r(s),r(void 0!==a);const n=Math.round((i-o)*a);for(let r=1;n>r;r++){const i=new Qe(s,{timestamp:o+r/a,duration:1/a});await this._registerVideoSample(e,t,c,i),i.close()}};for await(const{canvas:r,timestamp:n,duration:h}of i){if(this._canceled)return;let i=Math.max(n-this._startTimestamp,0);if(d=i+h,void 0!==a){const e=Math.floor(i*a)/a;if(null!==s){if(o>=e){s=r,o=e;continue}await l(e)}i=e}const u=new Qe(r,{timestamp:i,duration:void 0!==a?1/a:h});await this._registerVideoSample(e,t,c,u),u.close(),void 0!==a&&(s=r,o=i)}s&&(r(null!==d),r(void 0!==a),await l(Math.floor(d*a)/a)),c.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;const i=new mt(e),a=t.frameRate;let s=null,n=null,o=null;const d=async i=>{r(s),r(void 0!==a);const o=Math.round((i-n)*a);for(let r=1;o>r;r++)s.setTimestamp(n+r/a),s.setDuration(1/a),await this._registerVideoSample(e,t,c,s);s.close()};for await(const r of i.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled)return void s?.close();let i=Math.max(r.timestamp-this._startTimestamp,0);if(o=i+r.duration,void 0!==a){const e=Math.floor(i*a)/a;if(null!==s){if(n>=e){s.close(),s=r,n=e;continue}await d(e)}i=e,r.setDuration(1/a)}r.setTimestamp(i),await this._registerVideoSample(e,t,c,r),void 0!==a?(s=r,n=i):r.close()}s&&(r(null!==o),r(void 0!==a),await d(Math.floor(o*a)/a)),c.close(),this._synchronizer.closeTrack(e.id)})())}else{const t=new Sa(a);s=t,this._trackPromises.push((async()=>{await this._started;const r=new ot(e),i={decoderConfig:await e.getDecoderConfig()??void 0},a=Number.isFinite(this._endTimestamp)?await r.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(const s of r.packets(void 0,a,{verifyKeyPackets:!0})){if(this._canceled)return;"discard"===y&&(delete s.sideData.alpha,delete s.sideData.alphaByteLength),this._reportProgress(e.id,s.timestamp),await t.add(s,i),this._synchronizer.shouldWait(e.id,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(s,{frameRate:t.frameRate,languageCode:F(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:v?0:n}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,r,i){if(this._canceled)return;let a;if(this._reportProgress(e.id,i.timestamp),t.process){let e=t.process(i);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=null===e?[]:[e]),a=e.map(e=>e instanceof Qe?e:"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?new Qe(e):new Qe(e,{timestamp:i.timestamp,duration:i.duration}))}else a=[i];for(const s of a){if(this._canceled)break;await r.add(s),this._synchronizer.shouldWait(e.id,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}for(const s of a)s!==i&&s.close()}async _processAudioTrack(e,t){const r=e.codec;if(!r)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec"});let i;const a=e.numberOfChannels,s=e.sampleRate,n=await e.getFirstTimestamp();let o=t.numberOfChannels??a,c=t.sampleRate??s,d=o!==a||c!==s||this._startTimestamp>0||0>n,l=this.output.format.getSupportedAudioCodecs();if(t.forceTranscode||t.bitrate||d||!l.includes(r)||t.codec&&t.codec!==r||t.process){if(!(await e.canDecode()))return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});let r=null;t.codec&&(l=l.filter(e=>e===t.codec));const a=t.bitrate??wa,s=await va(l,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:o,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:a});if(s.some(e=>J.includes(e))||!l.some(e=>J.includes(e))||2===o&&c===Oa)r=s[0]??null;else{const e=(await va(l,{numberOfChannels:2,sampleRate:Oa,bitrate:a})).find(e=>J.includes(e));e&&(d=!0,r=e,o=2,c=Oa)}if(null===r)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});if(d)i=this._resampleAudio(e,t,r,o,c,a);else{const s=new Ia({codec:r,bitrate:a});i=s,this._trackPromises.push((async()=>{await this._started;const r=new wt(e);for await(const i of r.samples(void 0,this._endTimestamp)){if(this._canceled)return;await this._registerAudioSample(e,t,s,i),i.close()}s.close(),this._synchronizer.closeTrack(e.id)})())}}else{const t=new Pa(r);i=t,this._trackPromises.push((async()=>{await this._started;const r=new ot(e),i={decoderConfig:await e.getDecoderConfig()??void 0},a=Number.isFinite(this._endTimestamp)?await r.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(const s of r.packets(void 0,a)){if(this._canceled)return;this._reportProgress(e.id,s.timestamp),await t.add(s,i),this._synchronizer.shouldWait(e.id,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addAudioTrack(i,{languageCode:F(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,r,i){if(this._canceled)return;let a;if(this._reportProgress(e.id,i.timestamp),t.process){let e=t.process(i);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=null===e?[]:[e]),!e.every(e=>e instanceof Ye))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");a=e}else a=[i];for(const s of a){if(this._canceled)break;await r.add(s),this._synchronizer.shouldWait(e.id,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}for(const s of a)s!==i&&s.close()}_resampleAudio(e,t,r,i,a,s){const n=new Ia({codec:r,bitrate:s});return this._trackPromises.push((async()=>{await this._started;const r=new Va({targetNumberOfChannels:i,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:r=>this._registerAudioSample(e,t,n,r)}),s=new wt(e).samples(this._startTimestamp,this._endTimestamp);for await(const e of s){if(this._canceled)return;await r.add(e)}await r.finalize(),n.close(),this._synchronizer.closeTrack(e.id)})()),n}_reportProgress(e,t){if(!this._computeProgress)return;r(null!==this._totalDuration),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const i=Math.min(...this._maxTimestamps.values()),a=R(i/this._totalDuration,0,1);a!==this._lastProgress&&(this._lastProgress=a,this.onProgress?.(a))}}class La{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){const r=this.resolvers[t];5>r.timestamp-e&&(r.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){return this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0)),t-this.computeMinAndMaybeResolve()>=5}wait(e){const{promise:t,resolve:r}=_();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}}class Va{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(5*this.targetSampleRate),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){r(null!==this.sourceNumberOfChannels);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=1===e&&2===t?(t,r)=>t[r*e]:1===e&&4===t?(t,r,i)=>t[r*e]*+(2>i):1===e&&6===t?(t,r,i)=>t[r*e]*+(2===i):2===e&&1===t?(t,r)=>{const i=r*e;return.5*(t[i]+t[i+1])}:2===e&&4===t||2===e&&6===t?(t,r,i)=>t[r*e+i]*+(2>i):4===e&&1===t?(t,r)=>{const i=r*e;return.25*(t[i]+t[i+1]+t[i+2]+t[i+3])}:4===e&&2===t?(t,r,i)=>{const a=r*e;return.5*(t[a+i]+t[a+i+2])}:4===e&&6===t?(t,r,i)=>{const a=r*e;return 2>i?t[a+i]:2===i||3===i?0:t[a+i-2]}:6===e&&1===t?(t,r)=>{const i=r*e;return Math.SQRT1_2*(t[i]+t[i+1])+t[i+2]+.5*(t[i+4]+t[i+5])}:6===e&&2===t?(t,r,i)=>{const a=r*e;return t[a+i]+Math.SQRT1_2*(t[a+2]+t[a+i+4])}:6===e&&4===t?(t,r,i)=>{const a=r*e;return 2>i?t[a+i]+Math.SQRT1_2*t[a+2]:t[a+i+2]}:(t,r,i)=>e>i?t[r*e+i]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;e>t;)t*=2;if(t!==this.tempSourceBuffer.length){const e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){null===this.sourceSampleRate&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const i=e.allocationSize({planeIndex:0,format:"f32"}),a=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(a,{planeIndex:0,format:"f32"});const s=e.timestamp-this.startTime,n=e.numberOfFrames/this.sourceSampleRate,o=Math.min(s+n,this.endTime-this.startTime),c=Math.floor(s*this.targetSampleRate),d=Math.ceil(o*this.targetSampleRate);for(let l=c;d>l;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const t=l-this.bufferStartFrame;r(t<this.bufferSizeInFrames);const i=(l/this.targetSampleRate-s)*this.sourceSampleRate,n=Math.floor(i),o=Math.ceil(i),c=i-n;for(let r=0;r<this.targetNumberOfChannels;r++){let i=0,s=0;n>=0&&n<e.numberOfFrames&&(i=this.channelMixer(a,n,r)),o>=0&&o<e.numberOfFrames&&(s=this.channelMixer(a,o,r));const d=i+c*(s-i),l=t*this.targetNumberOfChannels+r;this.outputBuffer[l]+=d}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,t)}}async finalizeCurrentBuffer(){if(0>this.maxWrittenFrame)return;const e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const r=this.bufferStartFrame/this.targetSampleRate,i=new Ye({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}}function Na(e){return e instanceof Error?e.message:e+""}class Wa{audioContext=null;analyser=null;audioLevelIntervalId=null;audioLevel=0;getMutedState=null;currentStream=null;startTracking(e,t,r){if(!e)throw Error("Stream is required");if(!r)throw Error("getMutedState callback is required");if(this.stopTracking(),this.currentStream=e,this.getMutedState=r,0===e.getAudioTracks().length)throw Error("Stream has no audio tracks");const i=this.getAudioContextClass();if(!i)throw Error("AudioContext is not supported in this browser");try{this.audioContext=new i}catch(n){throw Error("Failed to create AudioContext: "+Na(n))}const a=this.audioContext.createMediaStreamSource(e);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,this.analyser.smoothingTimeConstant=.8,a.connect(this.analyser);const s=new Uint8Array(this.analyser.fftSize);this.audioLevelIntervalId=window.setInterval(()=>{if(!this.analyser)return;this.analyser.getByteTimeDomainData(s);const e=this.calculateAudioLevel(s);this.audioLevel=e;const r=this.checkMutedState(),i=r?0:e;t.onLevelUpdate(i,r)},100)}stopTracking(){null!==this.audioLevelIntervalId&&(clearInterval(this.audioLevelIntervalId),this.audioLevelIntervalId=null),this.analyser&&(this.analyser.disconnect(),this.analyser=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.audioLevel=0,this.getMutedState=null,this.currentStream=null}getAudioLevel(){return this.audioLevel}getAudioContextClass(){return window.AudioContext?window.AudioContext:window.webkitAudioContext||null}calculateAudioLevel(e){let t=0;for(const a of e){const e=(a-128)/128;t+=e*e}const r=Math.sqrt(t/e.length),i=r>0?20*Math.log10(r):-60;return Math.min(100,110*Math.max(0,Math.min(1,(i+50)/50))**.6)}checkMutedState(){if(!this.getMutedState)throw Error("getMutedState callback is not set");const e=this.getMutedState();if(!this.currentStream)throw Error("Current stream is not set");const t=this.currentStream.getAudioTracks(),r=t.length>0&&t.some(e=>!e.enabled);return e||r}}var Ha=Object.freeze({format:"mp4",fps:30,width:1280,height:720,bitrate:5e5,audioCodec:"aac",audioBitrate:128e3,preset:"medium",packetCount:1200}),qa={sd:5e5,hd:1e6,fhd:2e6,"4k":8e6},ja={sd:800,hd:1200,fhd:2e3,"4k":4e3};class $a{cachedConfig=null;cacheTimestamp=0;cacheTimeout;fetchPromise=null;options;constructor(e){if(this.options=e,void 0!==e.cacheTimeout){if("number"!=typeof e.cacheTimeout||0>=e.cacheTimeout)throw Error("cacheTimeout must be a positive number");this.cacheTimeout=e.cacheTimeout}else this.cacheTimeout=3e5}async fetchConfig(){const e=Date.now();if(this.cachedConfig&&e-this.cacheTimestamp<this.cacheTimeout)return this.cachedConfig;if(this.fetchPromise)return this.fetchPromise;this.fetchPromise=this.fetchConfigFromBackend();try{const t=await this.fetchPromise;return this.cachedConfig=t,this.cacheTimestamp=e,t}catch{return Ha}finally{this.fetchPromise=null}}clearCache(){this.cachedConfig=null,this.cacheTimestamp=0}getCurrentConfig(){if(!this.cachedConfig)throw Error("No cached config available. Call fetchConfig() first.");return this.cachedConfig}async fetchConfigFromBackend(){const e=this.options.backendUrl+"/api/v1/videos/config",t=await fetch(e,{method:"GET",headers:{Authorization:"Bearer "+this.options.apiKey,"Content-Type":"application/json"}});if(!t.ok)throw Error(`Failed to fetch config: ${t.status} ${t.statusText}`);const r=await t.json();if(!r.presetEncoding||"number"!=typeof r.max_width||"number"!=typeof r.max_height)throw Error("Invalid config response from backend");return function(e,t,r){if(!(e in qa))throw Error("Invalid preset: "+e);if("number"!=typeof t||0>=t)throw Error("maxWidth must be a positive number");if("number"!=typeof r||0>=r)throw Error("maxHeight must be a positive number");return{format:"mp4",fps:30,width:t,height:r,bitrate:qa[e],audioCodec:"aac",preset:"medium",packetCount:ja[e],audioBitrate:128e3}}(r.presetEncoding,r.max_width,r.max_height)}}class Qa{configService=null;currentConfig=Ha;configFetchPromise=null;initialize(e,t){if(!e)throw Error("apiKey is required");if(!t)throw Error("backendUrl is required");this.configService=new $a({apiKey:e,backendUrl:t}),this.fetchConfig()}async fetchConfig(){this.configService&&(this.configFetchPromise?this.currentConfig=await this.configFetchPromise:(this.configFetchPromise=this.configService.fetchConfig(),this.currentConfig=await this.configFetchPromise,this.configFetchPromise=null))}async getConfig(){return this.configService&&!this.configFetchPromise&&await this.fetchConfig(),this.currentConfig}clearCache(){if(!this.configService)throw Error("ConfigService is not initialized");this.configService.clearCache()}}let Ka=class{streamManager;callbacks;availableDevices={audioinput:[],videoinput:[]};selectedCameraDeviceId=null;selectedMicDeviceId=null;constructor(e,t){this.streamManager=e,this.callbacks=t}async getAvailableDevices(){return this.availableDevices=await this.streamManager.getAvailableDevices(),this.callbacks?.onDevicesChanged&&this.callbacks.onDevicesChanged(this.availableDevices),this.availableDevices}setCameraDevice(e){this.selectedCameraDeviceId=e,this.streamManager.setVideoDevice(e),this.callbacks?.onDeviceSelected&&this.callbacks.onDeviceSelected("camera",e)}setMicDevice(e){this.selectedMicDeviceId=e,this.streamManager.setAudioDevice(e),this.callbacks?.onDeviceSelected&&this.callbacks.onDeviceSelected("mic",e)}getSelectedCameraDeviceId(){return this.selectedCameraDeviceId}getSelectedMicDeviceId(){return this.selectedMicDeviceId}getAvailableDevicesList(){return this.availableDevices}};function Ga(e){return{video:{width:e.width,height:e.height,fit:"contain",frameRate:e.fps,bitrate:e.bitrate,forceTranscode:!0},audio:{codec:e.audioCodec,forceTranscode:!0}}}class Xa{originalAudioTrack=null;audioContext=null;audioWorkletNode=null;mediaStreamSource=null;gainNode=null;audioSource=null;lastAudioTimestamp=0;isMuted=!1;isPaused=!1;onMuteStateChange;async setupAudioTrack(e,r){if(!e)return null;const i=e.getAudioTracks();if(0===i.length)return null;const a=i[0];if(!a)return null;this.originalAudioTrack=a,this.lastAudioTimestamp=0;const s=window.AudioContext||window.webkitAudioContext;if(!s)return null;if(void 0===r.audioBitrate||null===r.audioBitrate)return null;if(!r.audioCodec)return null;if(this.audioContext=new s,!this.audioContext.audioWorklet)return await this.audioContext.close(),this.audioContext=null,null;const n=r.audioBitrate,o=r.audioCodec;this.audioSource=new Ia({codec:o,bitrate:n}),this.mediaStreamSource=this.audioContext.createMediaStreamSource(e);const c=function(){const e=t&&"SCRIPT"===t.tagName.toUpperCase()&&t.src||new URL("vidtreo-recorder.js",document.baseURI).href;if(!e||"undefined"==typeof URL)return"audio-capture-processor.worklet.js";const r=globalThis.URL;return r&&"URL"!==r.name?"audio-capture-processor.worklet.js":new URL("./audio-capture-processor.worklet.js",e).href}();return await this.audioContext.audioWorklet.addModule(c),this.audioWorkletNode=new AudioWorkletNode(this.audioContext,"audio-capture-processor"),this.audioWorkletNode.port.onmessage=e=>{if(this.isPaused||this.isMuted||!this.audioSource)return;const{data:t,sampleRate:r,numberOfChannels:i,duration:a,bufferLength:s}=e.data,n=new Float32Array(t,0,s),o=new Ye({data:n,format:"f32-planar",numberOfChannels:i,sampleRate:r,timestamp:this.lastAudioTimestamp});this.audioSource.add(o),this.lastAudioTimestamp+=a},this.gainNode=this.audioContext.createGain(),this.gainNode.gain.value=0,this.mediaStreamSource.connect(this.audioWorkletNode),this.audioWorkletNode.connect(this.gainNode),this.gainNode.connect(this.audioContext.destination),this.audioSource}toggleMute(){if(!this.audioSource)throw Error("Audio source not initialized");this.isMuted=!this.isMuted,this.onMuteStateChange&&this.onMuteStateChange(this.isMuted)}isMutedState(){return this.isMuted}pause(){this.audioSource&&!this.isPaused&&(this.isPaused=!0)}resume(){return this.isPaused&&this.audioSource?(this.isPaused=!1,null):null}isPausedState(){return this.isPaused}getClonedAudioTrack(){return this.originalAudioTrack}getAudioSource(){return this.audioSource}getAudioStreamForAnalysis(){return this.originalAudioTrack?"live"!==this.originalAudioTrack.readyState?null:new MediaStream([this.originalAudioTrack]):null}getLastAudioTimestamp(){return this.lastAudioTimestamp}setOnMuteStateChange(e){this.onMuteStateChange=e}cleanup(){this.audioWorkletNode&&(this.audioWorkletNode.disconnect(),this.audioWorkletNode.port.close(),this.audioWorkletNode=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.mediaStreamSource&&(this.mediaStreamSource.disconnect(),this.mediaStreamSource=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.originalAudioTrack&&(this.originalAudioTrack.stop(),this.originalAudioTrack=null),this.audioSource=null,this.lastAudioTimestamp=0}}class Za{canvasContext;constructor(e){this.canvasContext=e}clear(){this.canvasContext.clearRect(0,0,this.canvasContext.canvas.width,this.canvasContext.canvas.height)}drawFrame(e){if(0===e.videoWidth||0===e.videoHeight)return;const t=e.videoWidth/e.videoHeight;let r,i,a,s;t>this.canvasContext.canvas.width/this.canvasContext.canvas.height?(r=this.canvasContext.canvas.width,i=this.canvasContext.canvas.width/t,a=0,s=(this.canvasContext.canvas.height-i)/2):(i=this.canvasContext.canvas.height,r=this.canvasContext.canvas.height*t,a=(this.canvasContext.canvas.width-r)/2,s=0),this.canvasContext.fillStyle="#000000",this.canvasContext.fillRect(0,0,this.canvasContext.canvas.width,this.canvasContext.canvas.height),this.canvasContext.drawImage(e,a,s,r,i)}getContext(){return this.canvasContext}}class Ya{timeoutId=null;isActive=!1;isPaused=!1;frameCount=0;lastFrameTimestamp=0;currentFrameRate=30;canvasSource=null;canvasRenderer=null;videoElement=null;pendingFrameAdd=null;start(e,t,r,i){this.canvasSource=e,this.canvasRenderer=t,this.videoElement=r,this.isActive=!0,this.isPaused=!1,this.frameCount=0,this.lastFrameTimestamp=0,this.currentFrameRate=i,this.captureFrame()}pause(){this.isActive&&!this.isPaused&&(this.isPaused=!0,null!==this.timeoutId&&(window.clearTimeout(this.timeoutId),this.timeoutId=null))}resume(){if(this.isActive&&this.isPaused){if(!this.videoElement||!this.canvasSource)throw Error("Frame capturer not properly initialized");this.isPaused=!1,this.captureFrame()}}isPausedState(){return this.isPaused}getLastFrameTimestamp(){return this.lastFrameTimestamp}async waitForPendingFrames(){this.pendingFrameAdd&&await this.pendingFrameAdd}stop(){this.isActive=!1,null!==this.timeoutId&&(window.clearTimeout(this.timeoutId),this.timeoutId=null)}captureFrame(){if(!this.canCaptureFrame())return;if(!this.isVideoReady())return void this.scheduleNextFrame();if(this.isPaused)return;this.frameCount+=1;const e=1/this.currentFrameRate,t=this.lastFrameTimestamp+e;this.isPaused?this.frameCount-=1:(this.renderFrame(),this.addFrameToSource(t,e),this.isPaused?this.frameCount-=1:(this.lastFrameTimestamp=t,this.scheduleNextFrame()))}canCaptureFrame(){return!!(this.isActive&&!this.isPaused&&this.videoElement&&this.canvasSource&&this.canvasRenderer)}isVideoReady(){return!!this.videoElement&&this.videoElement.readyState>=2&&0!==this.videoElement.videoWidth&&0!==this.videoElement.videoHeight}renderFrame(){this.canvasRenderer&&this.videoElement&&(this.canvasRenderer.clear(),this.canvasRenderer.drawFrame(this.videoElement))}addFrameToSource(e,t){if(!this.canvasSource||this.isPaused)return;const r=1===this.frameCount;this.pendingFrameAdd=this.canvasSource.add(e,t,r?{keyFrame:!0}:void 0).then(()=>{this.pendingFrameAdd=null}).catch(()=>{this.pendingFrameAdd=null})}scheduleNextFrame(){if(this.isPaused)return;const e=1e3/this.currentFrameRate;this.timeoutId=window.setTimeout(()=>{this.captureFrame()},e)}}class Ja{output=null;chunks=[];totalSize=0;create(){const e=new WritableStream({write:e=>{this.chunks.push({data:e.data,position:e.position}),this.totalSize=Math.max(this.totalSize,e.position+e.data.length)}});return this.output=new za({format:new da({fastStart:"fragmented"}),target:new ta(e,{chunked:!0,chunkSize:16777216})}),this.output}getOutput(){if(!this.output)throw Error("Output not initialized");return this.output}getChunks(){return this.chunks}async finalize(){if(!this.output)throw Error("Output not initialized");await this.output.finalize();const e=[...this.chunks].sort((e,t)=>e.position-t.position),t=new ArrayBuffer(this.totalSize),r=new Uint8Array(t);for(const i of e)r.set(i.data,i.position);return{blob:new Blob([t],{type:"video/mp4"}),totalSize:this.totalSize}}async cancel(){this.output&&await this.output.cancel()}getTotalSize(){return this.totalSize}}class es{videoElement=null;isActive=!1;isIntentionallyPaused=!1;create(e){const t=document.createElement("video");return t.srcObject=e,t.autoplay=!0,t.playsInline=!0,t.muted=!0,t.addEventListener("pause",()=>{this.isActive&&this.videoElement&&!this.isIntentionallyPaused&&this.videoElement.play()}),this.videoElement=t,t}async waitForReady(){if(!this.videoElement)throw Error("Video element not created");await this.waitForVideoReady(!0)}async switchSource(e){if(!this.videoElement)throw Error("Video element not initialized");this.videoElement.srcObject=e,await this.waitForVideoReady(!1),await this.videoElement.play()}getElement(){return this.videoElement}setActive(e){this.isActive=e}pause(){this.videoElement&&this.isActive&&(this.isIntentionallyPaused=!0,this.videoElement.pause())}resume(){this.videoElement&&this.isActive&&(this.isIntentionallyPaused=!1,this.videoElement.play())}cleanup(){this.videoElement&&(this.videoElement.srcObject=null,this.videoElement=null)}waitForVideoReady(e){if(!this.videoElement)throw Error("Video element not available");const t=this.videoElement;return new Promise((r,i)=>{const a=()=>{t.removeEventListener("loadedmetadata",s),t.removeEventListener("error",n)},s=()=>{a(),e?t.play().then(r).catch(i):r()},n=()=>{a(),i(Error("Failed to load video metadata"))};2>t.readyState?(t.addEventListener("loadedmetadata",s),t.addEventListener("error",n),e||t.play().catch(i),setTimeout(()=>{a(),i(Error("Timeout waiting for video to load"))},5e3)):e?t.play().then(r).catch(i):r()})}}class ts{outputManager;canvasSource=null;offscreenCanvas=null;videoElementManager;canvasRenderer=null;frameCapturer;audioTrackManager;currentVideoStream=null;onSourceChange;constructor(){this.outputManager=new Ja,this.videoElementManager=new es,this.frameCapturer=new Ya,this.audioTrackManager=new Xa}async startProcessing(e,t){this.offscreenCanvas=new OffscreenCanvas(t.width,t.height);const r=this.offscreenCanvas.getContext("2d",{alpha:!1,desynchronized:!0,willReadFrequently:!1});if(!r)throw Error("Failed to get OffscreenCanvas context");this.canvasRenderer=new Za(r),this.videoElementManager.create(e),this.videoElementManager.setActive(!0),await this.videoElementManager.waitForReady(),this.currentVideoStream=e;const i=this.outputManager.create();if("number"!=typeof t.fps||0>=t.fps)throw Error("fps must be a positive number");const a=t.fps;if(!this.offscreenCanvas)throw Error("OffscreenCanvas not initialized");if(!this.offscreenCanvas)throw Error("Cannot create CanvasSource: not initialized");this.canvasSource=new xa(this.offscreenCanvas,{codec:"avc",bitrate:t.bitrate,keyFrameInterval:5,latencyMode:"realtime"}),i.addVideoTrack(this.canvasSource);const s=await this.audioTrackManager.setupAudioTrack(e,t);if(s&&i.addAudioTrack(s),await i.start(),!this.canvasRenderer)throw Error("CanvasRenderer not initialized");const n=this.videoElementManager.getElement();if(!n)throw Error("Video element not available");if(!this.canvasSource)throw Error("CanvasSource not initialized");this.frameCapturer.start(this.canvasSource,this.canvasRenderer,n,a)}pause(){this.frameCapturer.pause(),this.audioTrackManager.pause(),this.videoElementManager.pause()}resume(){if(!this.canvasSource)throw Error("CanvasSource not initialized - cannot resume");this.frameCapturer.resume(),this.audioTrackManager.resume(),this.videoElementManager.resume()}isPausedState(){return this.frameCapturer.isPausedState()}async finalize(){return this.frameCapturer.stop(),await this.frameCapturer.waitForPendingFrames(),this.videoElementManager.cleanup(),this.audioTrackManager.cleanup(),this.canvasSource&&(this.canvasSource.close(),this.canvasSource=null),await this.outputManager.finalize()}toggleMute(){this.audioTrackManager.toggleMute()}isMutedState(){return this.audioTrackManager.isMutedState()}getClonedAudioTrack(){return this.audioTrackManager.getClonedAudioTrack()}getAudioStreamForAnalysis(){return this.audioTrackManager.getAudioStreamForAnalysis()}async switchVideoSource(e){await this.videoElementManager.switchSource(e),this.currentVideoStream=e,this.onSourceChange&&this.onSourceChange(e)}getCurrentVideoSource(){return this.currentVideoStream}getBufferSize(){return this.outputManager.getTotalSize()}setOnMuteStateChange(e){this.audioTrackManager.setOnMuteStateChange(e)}setOnSourceChange(e){this.onSourceChange=e}async cancel(){this.frameCapturer.stop(),await this.outputManager.cancel(),this.videoElementManager.cleanup(),this.audioTrackManager.cleanup(),this.canvasSource&&(this.canvasSource.close(),this.canvasSource=null)}}var rs=["Bytes","KB","MB","GB"],is="recording",as="idle";class ss{recordingState=as;countdownDuration=5e3;countdownRemaining=0;countdownTimeoutId=null;countdownIntervalId=null;countdownStartTime=null;isPaused=!1;maxRecordingTime=null;maxTimeTimer=null;recordingSeconds=0;recordingIntervalId=null;pauseStartTime=null;totalPausedTime=0;streamManager;callbacks;streamProcessor=null;originalCameraStream=null;constructor(e,t){this.streamManager=e,this.callbacks=t}setCountdownDuration(e){this.countdownDuration=e}setMaxRecordingTime(e){this.maxRecordingTime=e}getRecordingState(){return this.recordingState}isPausedState(){return this.isPaused}getRecordingSeconds(){return this.recordingSeconds}getStreamProcessor(){return this.streamProcessor}setOriginalCameraStream(e){this.originalCameraStream=e}getOriginalCameraStream(){return this.originalCameraStream}async startRecording(){try{this.callbacks.onClearUploadStatus(),this.countdownDuration>0?this.startCountdown():await this.doStartRecording()}catch(e){this.handleError(e),this.recordingState=as,this.cancelCountdown()}}startCountdown(){this.recordingState="countdown",this.countdownRemaining=Math.ceil(this.countdownDuration/1e3),this.countdownStartTime=Date.now(),this.callbacks.onCountdownUpdate(this.recordingState,this.countdownRemaining),this.countdownIntervalId=window.setInterval(()=>{if(!this.countdownStartTime)return;const e=Date.now()-this.countdownStartTime,t=Math.max(0,Math.ceil((this.countdownDuration-e)/1e3));this.countdownRemaining=t,this.callbacks.onCountdownUpdate(this.recordingState,this.countdownRemaining)},100),this.countdownTimeoutId=window.setTimeout(async()=>{await this.doStartRecording()},this.countdownDuration)}async doStartRecording(){try{this.cancelCountdown(),this.recordingState=is,this.callbacks.onStateChange(this.recordingState),this.resetRecordingState();const e=this.streamManager.getStream();if(!e)throw Error("No stream available for recording");this.originalCameraStream=e,this.streamProcessor=new ts;const t=await this.callbacks.onGetConfig();await this.streamManager.startRecording(this.streamProcessor,t),this.startRecordingTimer(),this.maxRecordingTime&&this.maxRecordingTime>0&&(this.maxTimeTimer=window.setTimeout(async()=>{this.recordingState===is&&await this.stopRecording()},this.maxRecordingTime))}catch(e){this.handleError(e),this.recordingState=as,this.callbacks.onStateChange(this.recordingState)}}async stopRecording(){try{this.cancelCountdown(),this.clearTimer(this.recordingIntervalId,clearInterval),this.recordingIntervalId=null,this.clearTimer(this.maxTimeTimer,clearTimeout),this.maxTimeTimer=null,this.resetPauseState(),this.callbacks.onStopAudioTracking();const e=await this.streamManager.stopRecording();return this.recordingState=as,this.callbacks.onStateChange(this.recordingState),this.recordingSeconds=0,this.streamProcessor=null,this.callbacks.onRecordingComplete(e),e}catch(e){throw this.handleError(e),this.recordingState=as,this.callbacks.onStateChange(this.recordingState),e}}pauseRecording(){this.recordingState!==is||this.isPaused||(this.streamManager.pauseRecording(),this.isPaused=!0,this.clearTimer(this.recordingIntervalId,clearInterval),this.recordingIntervalId=null,this.pauseStartTime=Date.now())}resumeRecording(){this.recordingState===is&&this.isPaused&&(this.streamManager.resumeRecording(),this.isPaused=!1,this.updatePausedDuration(),this.startRecordingTimer())}cancelCountdown(){this.clearTimer(this.countdownTimeoutId,clearTimeout),this.countdownTimeoutId=null,this.clearTimer(this.countdownIntervalId,clearInterval),this.countdownIntervalId=null,this.recordingState=as,this.countdownRemaining=0,this.countdownStartTime=null,this.callbacks.onCountdownUpdate(this.recordingState,this.countdownRemaining)}cleanup(){this.cancelCountdown(),this.clearTimer(this.recordingIntervalId,clearInterval),this.recordingIntervalId=null,this.clearTimer(this.maxTimeTimer,clearTimeout),this.maxTimeTimer=null}resetRecordingState(){this.isPaused=!1,this.recordingSeconds=0,this.totalPausedTime=0,this.pauseStartTime=null}resetPauseState(){this.isPaused=!1,this.pauseStartTime=null,this.totalPausedTime=0}updatePausedDuration(){if(null===this.pauseStartTime)throw Error("Pause start time not set");const e=Date.now()-this.pauseStartTime;this.totalPausedTime+=e,this.pauseStartTime=null}startRecordingTimer(){null===this.recordingIntervalId&&(this.recordingIntervalId=window.setInterval(()=>{this.recordingSeconds+=1,this.callbacks.onTimerUpdate(function(e){const t=Math.floor(e/3600),r=Math.floor(e%3600/60),i=e%60;return t>0?`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`:`${r.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}`}(this.recordingSeconds))},1e3))}clearTimer(e,t){null!==e&&t(e)}handleError(e){const t=e instanceof Error?e:Error(Na(e));this.callbacks.onError(t)}}class ns{storageService;uploadService;processingIntervalId;networkOnlineHandler;isProcessing=!1;retryTimeoutId=null;callbacks={};constructor(e,t){this.storageService=e,this.uploadService=t,this.networkOnlineHandler=()=>{this.processQueue().catch(e=>{const t=Na(e);this.callbacks.onUploadError?.("network-recovery",Error(t))})},window.addEventListener("online",this.networkOnlineHandler),this.processingIntervalId=window.setInterval(()=>{this.processQueue().catch(e=>{const t=Na(e);this.callbacks.onUploadError?.("processing-loop",Error(t))})},5e3)}destroy(){this.clearTimer(this.processingIntervalId,clearInterval),this.clearTimer(this.retryTimeoutId,clearTimeout),window.removeEventListener("online",this.networkOnlineHandler)}setCallbacks(e){this.callbacks=e}async queueUpload(e){const t=await this.storageService.savePendingUpload(e);return this.processQueue(),t}async processQueue(){if(!this.isProcessing){this.isProcessing=!0;try{if(!this.storageService.isInitialized())throw Error("Database not initialized");const e=await this.storageService.getPendingUploads("pending");if(e.length>0){const t=this.getOldestUpload(e);return await this.processUpload(t),void(this.isProcessing=!1)}const t=(await this.storageService.getPendingUploads("failed")).filter(e=>10>e.retryCount);if(t.length>0){const e=this.getOldestFailedUpload(t),r=this.calculateRetryDelay(e.retryCount),i=Date.now()-e.updatedAt;if(r>i){const e=r-i;this.scheduleRetry(e)}else await this.storageService.updateUploadStatus(e.id,{status:"pending",retryCount:e.retryCount}),await this.processUpload(e)}this.isProcessing=!1}catch(e){throw this.isProcessing=!1,Error("Error processing upload queue: "+Na(e))}}}getPendingUploads(){return this.storageService.getPendingUploads()}async getStats(){const e=await this.storageService.getPendingUploads(),t={pending:0,uploading:0,failed:0,total:e.length};for(const r of e)"pending"===r.status?t.pending+=1:"uploading"===r.status?t.uploading+=1:"failed"===r.status&&(t.failed+=1);return t}getOldestUpload(e){if(0===e.length)throw Error("Cannot get oldest upload from empty array");return e.sort((e,t)=>e.createdAt-t.createdAt)[0]}getOldestFailedUpload(e){if(0===e.length)throw Error("Cannot get oldest failed upload from empty array");return e.sort((e,t)=>e.updatedAt-t.updatedAt)[0]}async processUpload(e){try{await this.storageService.updateUploadStatus(e.id,{status:"uploading"});const t=await this.uploadService.uploadVideo(e.blob,{apiKey:e.apiKey,backendUrl:e.backendUrl,filename:e.filename,duration:e.duration,metadata:e.metadata,userMetadata:e.userMetadata,onProgress:t=>{this.callbacks.onUploadProgress?.(e.id,t)}});await this.storageService.deleteUpload(e.id),this.callbacks.onUploadComplete?.(e.id,t)}catch(t){const r=Na(t),i=e.retryCount+1;if(await this.storageService.updateUploadStatus(e.id,{status:"failed",retryCount:i,lastError:r}),10>i){const e=this.calculateRetryDelay(i);this.scheduleRetry(e)}else this.callbacks.onUploadError?.(e.id,Error("Upload failed after 10 attempts: "+r))}}calculateRetryDelay(e){return Math.min(2e3*1.5**(e-1),3e5)}scheduleRetry(e){this.clearTimer(this.retryTimeoutId,clearTimeout),this.retryTimeoutId=window.setTimeout(()=>{this.retryTimeoutId=null,this.processQueue()},e)}clearTimer(e,t){null!==e&&t(e)}}var os="pending-uploads",cs="status",ds="createdAt";class ls{db=null;init(){return this.db?Promise.resolve():new Promise((e,t)=>{const r=indexedDB.open("vidtreo-recorder",1);r.onerror=()=>{r.error?t(r.error):t(Error("Failed to open database"))},r.onsuccess=()=>{r.result?(this.db=r.result,e()):t(Error("Database result is null"))},r.onupgradeneeded=e=>{const r=e.target.result;if(r){if(!r.objectStoreNames.contains(os)){const e=r.createObjectStore(os,{keyPath:"id"});e.createIndex(cs,cs,{unique:!1}),e.createIndex(ds,ds,{unique:!1})}}else t(Error("Database upgrade result is null"))}})}isInitialized(){return null!==this.db}savePendingUpload(e){const t=this.generateUploadId(),r={...e,id:t,status:"pending",retryCount:0,createdAt:Date.now(),updatedAt:Date.now()};return this.executeTransaction("readwrite",e=>{const i=e.add(r);return new Promise((e,r)=>{i.onsuccess=()=>e(t),i.onerror=()=>{i.error?"QuotaExceededError"===i.error.name?r(Error("Storage quota exceeded. Please free up space or delete old uploads.")):r(i.error):r(Error("Failed to save upload"))}})})}getPendingUploads(e){return this.executeTransaction("readonly",t=>{const r=e?t.index(cs).getAll(e):t.getAll();return new Promise((e,t)=>{r.onsuccess=()=>{void 0!==r.result?e(r.result):t(Error("Failed to get uploads: result is undefined"))},r.onerror=()=>{r.error?t(r.error):t(Error("Failed to get uploads"))}})})}updateUploadStatus(e,t){return this.executeTransaction("readwrite",r=>{const i=r.get(e);return new Promise((e,a)=>{i.onsuccess=()=>{const s=i.result;if(!s)return void a(Error("Upload not found"));const n={...s,...t,updatedAt:Date.now()},o=r.put(n);o.onsuccess=()=>e(),o.onerror=()=>{o.error?a(o.error):a(Error("Failed to update upload"))}},i.onerror=()=>{i.error?a(i.error):a(Error("Failed to get upload"))}})})}deleteUpload(e){return this.executeTransaction("readwrite",t=>{const r=t.delete(e);return new Promise((e,t)=>{r.onsuccess=()=>e(),r.onerror=()=>{r.error?t(r.error):t(Error("Failed to delete upload"))}})})}async cleanupPermanentlyFailedUploads(e){const t=void 0!==e?e:24;if("number"!=typeof t||0>t)throw Error("retentionHours must be a non-negative number");const r=Date.now()-36e5*t,i=(await this.getPendingUploads()).filter(e=>"failed"===e.status&&e.retryCount>=10&&e.updatedAt<r);for(const a of i)await this.deleteUpload(a.id);return i.length}async getTotalStorageSize(){return(await this.getPendingUploads()).reduce((e,t)=>e+t.blob.size,0)}generateUploadId(){return`upload-${Date.now()}-${Math.random().toString(36).substring(2,11)}`}executeTransaction(e,t){if(!this.db)throw Error("Database not initialized");return t(this.db.transaction([os],e).objectStore(os))}}var hs=36e5;class us{storageService=null;uploadQueueManager=null;cleanupIntervalId=null;async initialize(e,t,r){if(this.storageService||(this.storageService=new ls),this.storageService.isInitialized()||await this.storageService.init(),e){if(this.uploadQueueManager)return this.uploadQueueManager.setCallbacks(t),void(null===this.cleanupIntervalId&&(this.cleanupIntervalId=window.setInterval(()=>{this.performCleanup().catch(e=>{r(Na(e))})},hs)));this.uploadQueueManager=new ns(this.storageService,e),this.uploadQueueManager.setCallbacks(t),null===this.cleanupIntervalId&&(this.cleanupIntervalId=window.setInterval(()=>{this.performCleanup().catch(e=>{r(Na(e))})},hs))}}async checkPendingUploads(){if(!this.uploadQueueManager)throw Error("UploadQueueManager not initialized");return await this.uploadQueueManager.getStats()}async performCleanup(){if(!this.storageService)throw Error("StorageService not initialized");await this.storageService.cleanupPermanentlyFailedUploads(24)}getUploadQueueManager(){return this.uploadQueueManager}getStorageService(){return this.storageService}destroy(){this.uploadQueueManager&&(this.uploadQueueManager.destroy(),this.uploadQueueManager=null),null!==this.cleanupIntervalId&&(clearInterval(this.cleanupIntervalId),this.cleanupIntervalId=null)}}var ms="live";class ps{currentSourceType="camera";originalCameraStream=null;originalCameraConstraints=null;screenShareStream=null;screenShareTrackEndHandler=null;streamManager;callbacks;constructor(e,t={}){this.streamManager=e,this.callbacks=t}getCurrentSourceType(){return this.currentSourceType}getOriginalCameraStream(){return this.originalCameraStream}stopStreamTracks(e){const t=e.getTracks();for(const r of t)r.readyState===ms&&r.stop()}isTrackLive(e){return void 0!==e&&e.readyState===ms}areTracksLive(e,t){return this.isTrackLive(e)&&this.isTrackLive(t)}storeOriginalCameraConstraints(e){const t=e.getVideoTracks()[0];if(!t)return;const r=t.getSettings();this.originalCameraConstraints={width:r.width,height:r.height,aspectRatio:r.aspectRatio,frameRate:r.frameRate,deviceId:r.deviceId,facingMode:r.facingMode}}storeOriginalCameraStream(e){const t=e.getVideoTracks()[0],r=e.getAudioTracks()[0];this.areTracksLive(t,r)?this.originalCameraStream=new MediaStream([t,r]):this.originalCameraStream=e}createError(e){return e instanceof Error?e:Error(Na(e))}waitForTracksToEnd(e){return new Promise(t=>{setTimeout(()=>{this.screenShareStream=null,t()},e)})}async switchToScreenCapture(){const e=this.streamManager.getStream();e&&(this.storeOriginalCameraConstraints(e),this.storeOriginalCameraStream(e)),this.callbacks.onTransitionStart&&this.callbacks.onTransitionStart("Select screen to share...");try{const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!0});return this.screenShareStream=t,e&&e!==this.originalCameraStream&&this.stopStreamTracks(e),this.currentSourceType="screen",this.callbacks.onSourceChange&&this.callbacks.onSourceChange(this.currentSourceType),this.setupScreenShareTrackHandler(t),t}catch(t){throw this.callbacks.onTransitionEnd&&this.callbacks.onTransitionEnd(),t}}setupScreenShareTrackHandler(e){const t=e.getVideoTracks()[0];if(!t)throw Error("No video track found in screen share stream");const r=this.screenShareTrackEndHandler;if(r){const e=this.streamManager.getStream();if(e){const t=e.getVideoTracks()[0];t&&t.removeEventListener("ended",r)}}this.screenShareTrackEndHandler=async()=>{if("screen"===this.currentSourceType)try{await this.switchToCamera()}catch(e){this.callbacks.onError&&this.callbacks.onError(this.createError(e))}},t.addEventListener("ended",this.screenShareTrackEndHandler)}removeScreenShareTrackHandler(e){if(!this.screenShareTrackEndHandler||!e)return;const t=e.getVideoTracks()[0];t&&t.removeEventListener("ended",this.screenShareTrackEndHandler),this.screenShareTrackEndHandler=null}canReuseOriginalStream(){if(!this.originalCameraStream)return!1;const e=this.originalCameraStream.getVideoTracks()[0],t=this.originalCameraStream.getAudioTracks()[0];return this.areTracksLive(e,t)}canReuseManagerStream(){const e=this.streamManager.getStream();if(!e||!this.originalCameraStream||e!==this.originalCameraStream)return!1;const t=e.getVideoTracks()[0],r=e.getAudioTracks()[0];return this.areTracksLive(t,r)}buildVideoConstraints(e){const t={};return e&&(t.deviceId={exact:e}),this.originalCameraConstraints&&Object.assign(t,this.originalCameraConstraints),t}buildAudioConstraints(e){return!e||{deviceId:{exact:e}}}async createNewCameraStreamForRecording(){const e=this.callbacks.getSelectedCameraDeviceId?this.callbacks.getSelectedCameraDeviceId():null,t=this.callbacks.getSelectedMicDeviceId?this.callbacks.getSelectedMicDeviceId():null,r=this.buildVideoConstraints(e),i=this.buildAudioConstraints(t),a={video:0>=Object.keys(r).length||r,audio:i},s=await navigator.mediaDevices.getUserMedia(a),n=s.getVideoTracks()[0],o=s.getAudioTracks()[0];if(!this.isTrackLive(n)){this.stopStreamTracks(s);const e=n?n.readyState:"undefined";throw Error("Failed to get live camera video track. ReadyState: "+e)}if(!this.isTrackLive(o)){this.stopStreamTracks(s);const e=o?o.readyState:"undefined";throw Error("Failed to get live camera audio track. ReadyState: "+e)}return this.originalCameraStream=s,s}async getCameraStream(){const e=this.streamManager.isRecording();if(this.canReuseOriginalStream()){const e=this.originalCameraStream;if(!e)throw Error("Original camera stream is null");return e}if(this.canReuseManagerStream()){const e=this.streamManager.getStream();if(!e)throw Error("Manager stream is null");return e}this.originalCameraStream&&(this.originalCameraStream=null);const t=this.streamManager.getStream();if(!e&&t&&t!==this.originalCameraStream&&(this.stopStreamTracks(t),this.streamManager.setMediaStream(null)),this.callbacks.getSelectedCameraDeviceId){const e=this.callbacks.getSelectedCameraDeviceId();this.streamManager.setVideoDevice(e)}if(this.callbacks.getSelectedMicDeviceId){const e=this.callbacks.getSelectedMicDeviceId();this.streamManager.setAudioDevice(e)}if(e)return this.createNewCameraStreamForRecording();const r=await this.streamManager.startStream();return this.originalCameraStream=r,r}async switchToCamera(){const e=this.streamManager.isRecording();if(e||"camera"!==this.currentSourceType)try{this.notifyTransitionStart("Switching to camera..."),await this.handleScreenShareStop();const t=await this.getCameraStream();if(!t)throw Error("Failed to get camera stream");await this.applyCameraStream(t,e),this.notifyTransitionEnd()}catch(t){throw this.notifyTransitionEnd(),t}}notifyTransitionStart(e){this.callbacks.onTransitionStart&&this.callbacks.onTransitionStart(e)}notifyTransitionEnd(){this.callbacks.onTransitionEnd&&this.callbacks.onTransitionEnd()}async handleScreenShareStop(){if("screen"!==this.currentSourceType)return;const e=this.screenShareStream,t=this.streamManager.getStream();e&&(this.removeScreenShareTrackHandler(e),this.stopStreamTracks(e),await this.waitForTracksToEnd(100)),!t||e&&t.id===e.id||this.stopStreamTracks(t)}async applyCameraStream(e,t){this.streamManager.setMediaStream(e),this.currentSourceType="camera",this.callbacks.onSourceChange&&this.callbacks.onSourceChange(this.currentSourceType),t&&await this.streamManager.switchVideoSource(e),this.callbacks.onPreviewUpdate&&await this.callbacks.onPreviewUpdate(e)}async toggleSource(){if(this.streamManager.isRecording())try{"camera"===this.currentSourceType?await this.switchToScreen():await this.switchToCamera()}catch(e){this.handleToggleError(e)}}async switchToScreen(){const e=await this.switchToScreenCapture();this.notifyTransitionStart("Switching to screen..."),await this.streamManager.switchVideoSource(e),this.callbacks.onPreviewUpdate&&await this.callbacks.onPreviewUpdate(e),this.notifyTransitionEnd()}handleToggleError(e){this.notifyTransitionEnd();const t=Na(e);t.includes("NotAllowedError")||t.includes("AbortError")?"screen"===this.currentSourceType&&this.switchToCamera().catch(e=>{this.callbacks.onError&&this.callbacks.onError(this.createError(e))}):this.callbacks.onError&&this.callbacks.onError(this.createError(e))}async handleRecordingStop(){if("screen"===this.currentSourceType){try{const e=this.streamManager.getStream();e&&(this.removeScreenShareTrackHandler(e),this.stopStreamTracks(e));const t=await this.getCameraStream();if(!t)throw Error("Failed to get camera stream");this.streamManager.setMediaStream(t),this.currentSourceType="camera",this.callbacks.onSourceChange&&this.callbacks.onSourceChange(this.currentSourceType),this.callbacks.onPreviewUpdate&&await this.callbacks.onPreviewUpdate(t)}catch(e){throw this.callbacks.onError&&this.callbacks.onError(this.createError(e)),e}this.cleanup()}else this.cleanup()}cleanup(){this.screenShareStream&&(this.removeScreenShareTrackHandler(this.screenShareStream),this.stopStreamTracks(this.screenShareStream),this.screenShareStream=null);const e=this.streamManager.getStream();e&&this.removeScreenShareTrackHandler(e),this.screenShareTrackEndHandler=null,this.originalCameraStream=null,this.originalCameraConstraints=null}setCallbacks(e){this.callbacks={...this.callbacks,...e}}}var fs=Object.freeze({width:{ideal:Ha.width},height:{ideal:Ha.height},frameRate:{ideal:Ha.fps}}),gs=Object.freeze({video:fs,audio:!0}),ws=Object.freeze({mimeType:"video/webm;codecs=vp9,opus"});class bs{mediaStream=null;mediaRecorder=null;recordedChunks=[];recordedMimeType=null;state="idle";recordingStartTime=0;recordingTimer=null;pauseStartTime=null;totalPausedTime=0;eventListeners=new Map;streamConfig;recordingOptions;streamProcessor=null;bufferSizeUpdateInterval=null;selectedAudioDeviceId=null;selectedVideoDeviceId=null;constructor(e={},t={}){this.streamConfig={...gs,...e},this.recordingOptions={...ws,...t}}getState(){return this.state}getStream(){return this.mediaStream}getAudioStreamForAnalysis(){if(this.streamProcessor){const e=this.streamProcessor.getAudioStreamForAnalysis();if(e)return e}return this.mediaStream&&this.mediaStream.getAudioTracks().length>0?this.mediaStream:null}getRecorder(){return this.mediaRecorder}isRecording(){return"recording"===this.state}isActive(){return"active"===this.state||"recording"===this.state}on(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set);const r=this.eventListeners.get(e);return r&&r.add(t),()=>{this.off(e,t)}}off(e,t){const r=this.eventListeners.get(e);r&&r.delete(t)}once(e,t){const r=i=>{t(i),this.off(e,r)};return this.on(e,r)}emit(e,t){const r=this.eventListeners.get(e);if(r)for(const i of r)try{i(t)}catch{}}setState(e){if(this.state===e)return;const t=this.state;this.state=e,this.emit("statechange",{state:e,previousState:t})}setAudioDevice(e){this.selectedAudioDeviceId=e}setVideoDevice(e){this.selectedVideoDeviceId=e}getAudioDevice(){return this.selectedAudioDeviceId}getVideoDevice(){return this.selectedVideoDeviceId}async getAvailableDevices(){try{const e=await navigator.mediaDevices.enumerateDevices();return{audioinput:e.filter(e=>"audioinput"===e.kind),videoinput:e.filter(e=>"videoinput"===e.kind)}}catch(e){throw Error("Failed to enumerate devices: "+Na(e))}}buildVideoConstraints(e){return e?"object"==typeof this.streamConfig.video?{...this.streamConfig.video,deviceId:{exact:e}}:{deviceId:{exact:e}}:this.streamConfig.video}buildAudioConstraints(e){return e?"object"==typeof this.streamConfig.audio?{...this.streamConfig.audio,deviceId:{exact:e}}:{deviceId:{exact:e}}:this.streamConfig.audio}async startStream(){if(this.mediaStream)return this.mediaStream;this.setState("starting");try{const e={video:this.buildVideoConstraints(this.selectedVideoDeviceId),audio:this.buildAudioConstraints(this.selectedAudioDeviceId)};return this.mediaStream=await navigator.mediaDevices.getUserMedia(e),this.setState("active"),this.emit("streamstart",{stream:this.mediaStream}),this.mediaStream}catch(e){const t=e instanceof Error?e:Error(Na(e));throw this.setState("error"),this.emit("error",{error:t}),t}}stopStream(){if(this.mediaStream){for(const e of this.mediaStream.getTracks())e.stop();this.mediaStream=null}"idle"!==this.state&&(this.setState("idle"),this.emit("streamstop",void 0))}stopStreamTracks(e){for(const t of e.getTracks())t.stop()}isTrackLive(e){return void 0!==e&&"live"===e.readyState}async tryReplaceTrack(e,t,r){const i=e.replaceTrack;if("function"!=typeof i)return!1;try{await i.call(e,t),e.stop();for(const e of r.getTracks())e!==t&&e.stop();return t.stop(),!0}catch{return!1}}recreateStreamWithNewTrack(e,t,r){for(const s of r.getTracks())s!==e&&s.stop();const i=[e];this.isTrackLive(t)&&t&&i.push(t);const a=new MediaStream(i);if(this.mediaStream)for(const s of this.mediaStream.getTracks())s!==t&&s.stop();return a}async switchVideoDevice(e){if(!this.mediaStream)throw Error("No active stream to switch device");const t=this.mediaStream.getVideoTracks()[0],r=this.mediaStream.getAudioTracks()[0];if(!t)throw Error("No video track in current stream");const i={video:e?{..."object"==typeof this.streamConfig.video?this.streamConfig.video:{},deviceId:{exact:e}}:this.streamConfig.video},a=await navigator.mediaDevices.getUserMedia(i),s=a.getVideoTracks()[0];if(!s)throw this.stopStreamTracks(a),Error("Failed to get new video track");return await this.tryReplaceTrack(t,s,a)||(t.stop(),this.mediaStream=this.recreateStreamWithNewTrack(s,r,a)),this.selectedVideoDeviceId=e,this.emit("videosourcechange",{stream:this.mediaStream}),this.mediaStream}async switchAudioDevice(e){if(!this.mediaStream)throw Error("No active stream to switch device");const t=this.mediaStream.getAudioTracks()[0],r=this.mediaStream.getVideoTracks()[0];if(!t)throw Error("No audio track in current stream");const i={audio:e?{..."object"==typeof this.streamConfig.audio?this.streamConfig.audio:{},deviceId:{exact:e}}:this.streamConfig.audio},a=await navigator.mediaDevices.getUserMedia(i),s=a.getAudioTracks()[0];if(!s)throw this.stopStreamTracks(a),Error("Failed to get new audio track");return await this.tryReplaceTrack(t,s,a)||(t.stop(),this.mediaStream=this.recreateStreamWithNewTrack(s,r,a)),this.selectedAudioDeviceId=e,this.mediaStream}startRecordingWithMediaRecorder(){if(!this.mediaStream)throw Error("Stream must be started before recording");if(!this.isRecording()){this.recordedChunks=[],this.recordedMimeType=null;try{this.mediaRecorder=new MediaRecorder(this.mediaStream,this.recordingOptions)}catch{this.mediaRecorder=new MediaRecorder(this.mediaStream)}this.mediaRecorder.ondataavailable=e=>{e.data&&e.data.size>0&&(this.recordedChunks.push(e.data),this.emit("recordingdata",{data:e.data}))},this.mediaRecorder.onstop=()=>{if(!this.mediaRecorder)throw Error("MediaRecorder is missing in onstop handler");const e=this.mediaRecorder.mimeType;if(!e)throw Error("MediaRecorder mimeType is missing");this.recordedMimeType=e;const t=new Blob(this.recordedChunks,{type:e});this.setState("active"),this.emit("recordingstop",{blob:t,mimeType:e}),this.mediaRecorder=null,this.recordedChunks=[]},this.mediaRecorder.start(),this.resetRecordingState(),this.setState("recording"),this.emit("recordingstart",{recorder:this.mediaRecorder}),this.startRecordingTimer()}}stopRecordingWithMediaRecorder(){this.mediaRecorder&&this.isRecording()&&(this.setState("stopping"),this.clearRecordingTimer(),this.resetPauseState(),this.mediaRecorder.stop())}async startRecording(e,t){if(!this.mediaStream)throw Error("Stream must be started before recording");this.isRecording()||(this.streamProcessor=e,await e.startProcessing(this.mediaStream,t),this.bufferSizeUpdateInterval=window.setInterval(()=>{if(!this.streamProcessor)return;const e=this.streamProcessor.getBufferSize(),t=function(e){if(0===e)return"0 Bytes";const t=Math.floor(Math.log(e)/Math.log(1024));return`${Math.round(e/1024**t*100)/100} ${rs[t]}`}(e);this.emit("recordingbufferupdate",{size:e,formatted:t})},1e3),e.setOnMuteStateChange(e=>{this.emit("audiomutetoggle",{muted:e})}),e.setOnSourceChange(e=>{this.emit("videosourcechange",{stream:e})}),this.resetRecordingState(),this.setState("recording"),this.emit("recordingstart",{recorder:null}),this.startRecordingTimer())}async stopRecording(){if(!this.streamProcessor||!this.isRecording())throw Error("Not currently recording");this.setState("stopping"),this.clearRecordingTimer(),this.clearBufferSizeInterval(),this.resetPauseState();const e=await this.streamProcessor.finalize();return this.setState("active"),this.emit("recordingstop",{blob:e.blob,mimeType:"video/mp4"}),this.streamProcessor=null,e.blob}pauseRecording(){this.clearRecordingTimer(),null===this.pauseStartTime&&(this.pauseStartTime=Date.now()),this.streamProcessor&&this.isRecording()?this.streamProcessor.pause():this.mediaRecorder&&this.isRecording()&&"recording"===this.mediaRecorder.state&&this.mediaRecorder.pause()}resumeRecording(){if(null!==this.pauseStartTime){const e=Date.now()-this.pauseStartTime;this.totalPausedTime+=e,this.pauseStartTime=null}this.startRecordingTimer(),this.streamProcessor&&this.isRecording()?this.streamProcessor.resume():this.mediaRecorder&&this.isRecording()&&"paused"===this.mediaRecorder.state&&this.mediaRecorder.resume()}toggleMute(){if(!this.streamProcessor)throw Error("StreamProcessor is required to toggle mute");this.streamProcessor.toggleMute()}setAudioTracksEnabled(e){if(!this.mediaStream)return;const t=this.mediaStream.getAudioTracks();for(const r of t)r.enabled=e}muteAudio(){this.streamProcessor?(this.streamProcessor.isMutedState()||this.streamProcessor.toggleMute(),this.setAudioTracksEnabled(!1)):this.mediaStream&&(this.setAudioTracksEnabled(!1),this.emit("audiomutetoggle",{muted:!0}))}unmuteAudio(){this.streamProcessor?(this.streamProcessor.isMutedState()&&this.streamProcessor.toggleMute(),this.setAudioTracksEnabled(!0)):this.mediaStream&&(this.setAudioTracksEnabled(!0),this.emit("audiomutetoggle",{muted:!1}))}isMuted(){if(this.streamProcessor)return this.streamProcessor.isMutedState();if(this.mediaStream){const e=this.mediaStream.getAudioTracks();return e.length>0&&e.every(e=>!e.enabled)}return!1}async switchVideoSource(e){if(!this.streamProcessor)throw Error("StreamProcessor is required to switch video source");await this.streamProcessor.switchVideoSource(e)}setMediaStream(e){this.mediaStream=e}getCurrentVideoSource(){if(!this.streamProcessor)throw Error("StreamProcessor is required to get current video source");const e=this.streamProcessor.getCurrentVideoSource();if(!e)throw Error("Current video source is not available");return e}formatTimeElapsed(e){const t=Math.floor(e/60),r=Math.floor(e%60);return`${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`}startRecordingTimer(){this.recordingTimer=window.setInterval(()=>{const e=(Date.now()-this.recordingStartTime-this.totalPausedTime)/1e3,t=this.formatTimeElapsed(e);this.emit("recordingtimeupdate",{elapsed:e,formatted:t})},1e3)}clearRecordingTimer(){null!==this.recordingTimer&&(clearInterval(this.recordingTimer),this.recordingTimer=null)}clearBufferSizeInterval(){null!==this.bufferSizeUpdateInterval&&(clearInterval(this.bufferSizeUpdateInterval),this.bufferSizeUpdateInterval=null)}resetRecordingState(){this.recordingStartTime=Date.now(),this.totalPausedTime=0,this.pauseStartTime=null}resetPauseState(){this.totalPausedTime=0,this.pauseStartTime=null}getRecordedBlob(){if(0===this.recordedChunks.length)throw Error("No recorded chunks available");if(!this.recordedMimeType)throw Error("Recorded mimeType is missing");return new Blob(this.recordedChunks,{type:this.recordedMimeType})}destroy(){this.stopRecordingWithMediaRecorder(),this.streamProcessor&&(this.streamProcessor.cancel().catch(()=>{}),this.streamProcessor=null),this.stopStream(),this.clearRecordingTimer(),this.clearBufferSizeInterval(),this.eventListeners.clear(),this.setState("idle")}}class vs{callbacks;uploadQueueManager=null;constructor(e){this.callbacks=e}setUploadQueueManager(e){this.uploadQueueManager=e}async uploadVideo(e,t,r,i){if(!this.uploadQueueManager)throw Error("Upload queue manager not initialized");try{this.callbacks.onClearStatus();const a=await async function(e){try{const t=new Qt(e),r=new Yt({formats:[Ht],source:t});if("function"!=typeof r.computeDuration)throw Error("computeDuration method is not available");const i=await r.computeDuration();if(!i)throw Error("Duration is missing from computeDuration");if(0>=i)throw Error("Invalid duration: must be greater than 0");return i}catch{return function(e){return new Promise((t,r)=>{const i=document.createElement("video"),a=URL.createObjectURL(e),s=()=>{URL.revokeObjectURL(a)};i.addEventListener("loadedmetadata",()=>{s();const e=i.duration;Number.isFinite(e)&&e>0?t(e):r(Error("Invalid video duration"))}),i.addEventListener("error",()=>{s(),r(Error("Failed to load video metadata"))}),i.src=a,i.load()})}(e)}}(e),s=Object.keys(i).length>0?i:void 0;await this.uploadQueueManager.queueUpload({blob:e,apiKey:t,backendUrl:r,filename:`recording-${Date.now()}.mp4`,duration:a,metadata:void 0,userMetadata:s})}catch(a){throw this.callbacks.onError(a instanceof Error?a:Error(Na(a))),a}}updateProgress(e){this.callbacks.onProgress(e)}showSuccess(e){this.callbacks.onSuccess(e)}showError(e){this.callbacks.onError(Error(e))}clearStatus(){this.callbacks.onClearStatus()}}var ys="Bearer ",ks="Authorization",Ss="Content-Type";class Ts{async uploadVideo(e,t){if(!t.filename)throw Error("Filename is required");if(!e.type||""===e.type.trim())throw Error("Blob type is required");const r=await this.initVideoUpload({apiKey:t.apiKey,backendUrl:t.backendUrl,filename:t.filename,fileSize:e.size,mimeType:e.type,metadata:t.metadata,userMetadata:t.userMetadata});return this.uploadVideoFile(e,r.uploadUrl,{apiKey:t.apiKey,duration:t.duration,onProgress:t.onProgress})}async initVideoUpload(e){const t=e.backendUrl+"/api/v1/videos/init",r={filename:e.filename,fileSize:e.fileSize,mimeType:e.mimeType,preProcessed:!0};e.metadata&&(r.metadata=e.metadata),e.userMetadata&&(r.userMetadata=e.userMetadata);const i=await fetch(t,{method:"POST",headers:{[ks]:`${ys}${e.apiKey}`,[Ss]:"application/json"},body:JSON.stringify(r)});if(!i.ok){const e=await this.extractErrorFromResponse(i,"Failed to initialize video upload");throw Error(e)}return await i.json()}async extractErrorFromResponse(e,t){try{const t=await e.json();if(t.error&&"string"==typeof t.error)return t.error}catch{}return`${t}: ${e.status} ${e.statusText}`}uploadVideoFile(e,t,r){return new Promise((i,a)=>{const s=new XMLHttpRequest;if(r.onProgress){const e=r.onProgress;s.upload.addEventListener("progress",t=>{if(t.lengthComputable){const r=t.loaded/t.total;e(r)}})}s.addEventListener("load",()=>{200>s.status||s.status>299?this.parseErrorResponse(s,a):this.parseSuccessResponse(s,i,a)}),s.addEventListener("error",()=>{a(Error("Network error during upload"))}),s.addEventListener("abort",()=>{a(Error("Upload was aborted"))}),s.open("PUT",t),s.setRequestHeader(ks,`${ys}${r.apiKey}`),s.setRequestHeader(Ss,e.type),void 0!==r.duration&&s.setRequestHeader("X-Video-Duration",r.duration.toString()),s.send(e)})}parseSuccessResponse(e,t,r){try{t(JSON.parse(e.responseText))}catch(i){const e=Na(i);r(Error("Failed to parse upload response: "+e))}}parseErrorResponse(e,t){let r=`Upload failed: ${e.status} ${e.statusText}`;try{const t=JSON.parse(e.responseText);t.error&&"string"==typeof t.error&&(r=t.error)}catch{}t(Error(r))}}var Cs=()=>{};class Es{isMuted=!1;streamManager;constructor(e){this.streamManager=e}mute(){this.streamManager.muteAudio(),this.isMuted=!0}unmute(){this.streamManager.unmuteAudio(),this.isMuted=!1}toggle(){this.streamManager.isMuted()?this.unmute():this.mute()}getIsMuted(){const e=this.streamManager.isMuted();return this.isMuted!==e&&(this.isMuted=e),this.isMuted}getMutedStateCallback(){return()=>{const e=this.streamManager.isMuted();return this.isMuted!==e&&(this.isMuted=e),e}}}class xs{streamManager;configManager;storageManager;deviceManager;audioLevelAnalyzer;uploadManager;recordingManager;sourceSwitchManager;uploadService=null;muteStateManager;isInitialized=!1;constructor(e={}){this.streamManager=new bs,this.configManager=new Qa,this.storageManager=new us,this.deviceManager=new Ka(this.streamManager,e.device),this.audioLevelAnalyzer=new Wa,this.uploadService=new Ts;const t=e.upload?e.upload:{onProgress:()=>{},onSuccess:()=>{},onError:()=>{},onClearStatus:()=>{}};this.uploadManager=new vs(t);const r=function(e,t,r){const i=e.recording;return{onStateChange:i?.onStateChange??Cs,onCountdownUpdate:i?.onCountdownUpdate??Cs,onTimerUpdate:i?.onTimerUpdate??Cs,onError:i?.onError??Cs,onRecordingComplete:i?.onRecordingComplete??Cs,onClearUploadStatus:i?.onClearUploadStatus??Cs,onStopAudioTracking:()=>{t.stopTracking()},onGetConfig:()=>r.getConfig()}}(e,this.audioLevelAnalyzer,this.configManager);this.recordingManager=new ss(this.streamManager,r);const i=function(e,t){const r=e.sourceSwitch;return{onSourceChange:r?.onSourceChange,onPreviewUpdate:r?.onPreviewUpdate,onError:r?.onError,onTransitionStart:r?.onTransitionStart,onTransitionEnd:r?.onTransitionEnd,getSelectedCameraDeviceId:()=>t.getSelectedCameraDeviceId(),getSelectedMicDeviceId:()=>t.getSelectedMicDeviceId()}}(e,this.deviceManager);this.sourceSwitchManager=new ps(this.streamManager,i),this.muteStateManager=new Es(this.streamManager)}async initialize(e){if(this.isInitialized)return;e.apiKey&&e.backendUrl&&this.configManager.initialize(e.apiKey,e.backendUrl),void 0!==e.countdownDuration&&this.recordingManager.setCountdownDuration(e.countdownDuration),void 0!==e.maxRecordingTime&&this.recordingManager.setMaxRecordingTime(e.maxRecordingTime),await this.storageManager.initialize(this.uploadService,{onUploadProgress:(e,t)=>{this.uploadManager.updateProgress(t)},onUploadComplete:(e,t)=>{this.uploadManager.showSuccess(t)},onUploadError:(e,t)=>{this.uploadManager.showError(t.message)}},()=>{throw Error("Storage cleanup error")});const t=this.storageManager.getUploadQueueManager();this.uploadManager.setUploadQueueManager(t),this.isInitialized=!0}async startStream(){await this.streamManager.startStream()}async stopStream(){await this.streamManager.stopStream()}async switchVideoDevice(e){return await this.streamManager.switchVideoDevice(e)}async switchAudioDevice(e){return await this.streamManager.switchAudioDevice(e)}async startRecording(){await this.recordingManager.startRecording()}async stopRecording(){const e=await this.recordingManager.stopRecording();return await this.sourceSwitchManager.handleRecordingStop().catch(()=>{throw Error("Source switch cleanup failed")}),e}pauseRecording(){this.recordingManager.pauseRecording()}resumeRecording(){this.recordingManager.resumeRecording()}async switchSource(e){await this.sourceSwitchManager.toggleSource()}setCameraDevice(e){this.deviceManager.setCameraDevice(e)}setMicDevice(e){this.deviceManager.setMicDevice(e)}async getAvailableDevices(){return await this.deviceManager.getAvailableDevices()}muteAudio(){this.muteStateManager.mute()}unmuteAudio(){this.muteStateManager.unmute()}toggleMute(){this.muteStateManager.toggle()}getIsMuted(){return this.muteStateManager.getIsMuted()}startAudioLevelTracking(e,t){if(!t)throw Error("Audio level callbacks are required");return this.audioLevelAnalyzer.startTracking(e,t,this.muteStateManager.getMutedStateCallback()),Promise.resolve()}stopAudioLevelTracking(){this.audioLevelAnalyzer.stopTracking()}getAudioLevel(){return this.audioLevelAnalyzer.getAudioLevel()}async uploadVideo(e,t,r,i){await this.uploadManager.uploadVideo(e,t,r,i)}getStream(){return this.streamManager.getStream()}getRecordingState(){return this.recordingManager.getRecordingState()}isPaused(){return this.recordingManager.isPausedState()}getCurrentSourceType(){return this.sourceSwitchManager.getCurrentSourceType()}getOriginalCameraStream(){return this.sourceSwitchManager.getOriginalCameraStream()}getStreamManager(){return this.streamManager}getAudioStreamForAnalysis(){return this.streamManager.getAudioStreamForAnalysis()}getDeviceManager(){return this.deviceManager}async getConfig(){return await this.configManager.getConfig()}isRecording(){return this.streamManager.isRecording()}isActive(){return this.streamManager.isActive()}cleanup(){this.storageManager.destroy(),this.recordingManager.cleanup(),this.audioLevelAnalyzer.stopTracking(),this.sourceSwitchManager.cleanup()}}function _s(e,t){const r=e.querySelector(t);if(!r)throw Error("Element not found: "+t);return r}function Ps(e,t){const r=e.querySelector("#previewSkeleton"),i=e.querySelector(".skeleton-text");if(!r)throw Error("Preview skeleton element not found");if(r.style.display="flex",!i)throw Error("Skeleton text element not found");i.textContent=t}function Ms(e){const t=e.querySelector("#previewSkeleton");if(!t)throw Error("Preview skeleton element not found");t.style.display="none"}const Is=/[:.]/g;class As{constructor(){this.barsContainer=null}initializeBars(e){this.barsContainer=this.queryElement(e,"#audioLevelBars"),this.barsContainer.innerHTML="";for(let t=0;15>t;t++){const e=this.createBar();this.barsContainer.appendChild(e)}}updateBars(e,t){if(!this.barsContainer)throw Error("Bars container not initialized");this.barsContainer.querySelectorAll(".audio-level-bar").forEach((r,i)=>{this.updateBar(r,i,e,t)})}queryElement(e,t){const r=e.querySelector(t);if(!r)throw Error("Element not found: "+t);return r}createBar(){const e=document.createElement("div");return e.className="audio-level-bar",e.style.height="15%",e}updateBar(e,t,r,i){const a=r>=this.calculateThreshold(t)&&!i;this.setBarHeight(e,t,a),this.setBarStyle(e,t,a,i)}calculateThreshold(e){return(e+1)/15*100}setBarHeight(e,t,r){if(r){const r=30+t/15*70;e.style.height=r+"%"}else e.style.height="15%"}setBarStyle(e,t,r,i){if(i||!r)e.style.backgroundColor="",e.style.opacity="1";else{const r=t/15,i=.7+t/15*(1-.7);e.style.backgroundColor=function(e){if(.25>e)return`rgb(255, ${Math.round(165+e/.25*50)}, 0)`;if(.5>e){const t=(e-.25)/.25;return`rgb(${Math.round(255- -205*t)}, ${Math.round(215+-10*t)}, ${Math.round(0+50*t)})`}if(.75>e){const t=(e-.5)/.25;return`rgb(${Math.round(50- -50*t)}, ${Math.round(205+-77*t)}, ${Math.round(50+78*t)})`}const t=(e-.75)/.25;return`rgb(0, ${Math.round(128- -28*t)}, ${Math.round(128+72*t)})`}(r),e.style.opacity=i+""}}}class Rs extends Ka{updateDeviceSelects(e){const t=e.querySelector("#cameraSelect"),r=e.querySelector("#micSelect"),i=this.getAvailableDevicesList(),a=this.getSelectedCameraDeviceId(),s=this.getSelectedMicDeviceId();if(t){t.innerHTML='<option value="default">Default Camera</option>';for(const e of i.videoinput.filter(e=>e.deviceId&&""!==e.deviceId.trim())){const r=document.createElement("option");r.value=e.deviceId,r.textContent=e.label||"Camera "+e.deviceId.slice(0,8),e.deviceId===a&&(r.selected=!0),t.appendChild(r)}}if(r){r.innerHTML='<option value="default">Default Microphone</option>';for(const e of i.audioinput.filter(e=>e.deviceId&&""!==e.deviceId.trim())){const t=document.createElement("option");t.value=e.deviceId,t.textContent=e.label||"Microphone "+e.deviceId.slice(0,8),e.deviceId===s&&(t.selected=!0),r.appendChild(t)}}}}class Bs{constructor(e){this.shadowRoot=e}queryElement(e){const t=this.shadowRoot.querySelector(e);if(!t)throw Error("Element not found: "+e);return t}setText(e,t){e.textContent=t}toggleClass(e,t,r){r?e.classList.add(t):e.classList.remove(t)}setStyle(e,t,r){e.style.setProperty(t,r)}setDisplay(e,t){this.setStyle(e,"display",t)}setDisabled(e,t){e.disabled=t}showError(e){const t=this.queryElement("#error");this.setText(t,e),this.toggleClass(t,"active",!0)}hideError(){const e=this.queryElement("#error");this.toggleClass(e,"active",!1)}showProgress(){const e=this.queryElement("#progress");this.toggleClass(e,"active",!0)}hideProgress(){const e=this.queryElement("#progress");this.toggleClass(e,"active",!1)}updateProgress(e,t){const r=Math.round(100*e),i=this.queryElement("#progressFill"),a=this.queryElement("#progressText");this.setStyle(i,"width",r+"%"),this.setText(a,t)}updateRecordingTimer(e){const t=this.queryElement("#recordingTimer");this.setText(t,e)}updateMuteState(e,t,r){const i=this.queryElement("#muteButton"),a=this.shadowRoot.querySelector("#muteIcon");if(!a)throw Error("Mute icon element not found");e?(this.toggleClass(i,"muted",!0),a.innerHTML='<path d="M211,221.31,51,45.31A4,4,0,0,0,45,50.69L84,93.55V128a44,44,0,0,0,66,38.12l16.38,18A67.21,67.21,0,0,1,128,196a68.07,68.07,0,0,1-68-68,4,4,0,0,0-8,0,76.09,76.09,0,0,0,72,75.89V240a4,4,0,0,0,8,0V203.89a75.1,75.1,0,0,0,39.79-13.77L205,226.69a4,4,0,1,0,5.92-5.38ZM128,164a36,36,0,0,1-36-36V102.35L144.43,160A35.83,35.83,0,0,1,128,164Zm61.12-6.15A67.44,67.44,0,0,0,196,128a4,4,0,0,1,8,0,75.28,75.28,0,0,1-7.7,33.37,4,4,0,0,1-7.18-3.52ZM87.63,46.46A44,44,0,0,1,172,64v64a44.2,44.2,0,0,1-.24,4.61,4,4,0,0,1-4,3.58l-.42,0a4,4,0,0,1-3.57-4.39A36.67,36.67,0,0,0,164,128V64A36,36,0,0,0,95,49.66a4,4,0,0,1-7.34-3.2Z"></path>'):(this.toggleClass(i,"muted",!1),a.innerHTML='<path d="M128,172a44.05,44.05,0,0,0,44-44V64a44,44,0,0,0-88,0v64A44.05,44.05,0,0,0,128,172ZM92,64a36,36,0,0,1,72,0v64a36,36,0,0,1-72,0Zm40,139.89V240a4,4,0,0,1-8,0V203.89A76.09,76.09,0,0,1,52,128a4,4,0,0,1,8,0,68,68,0,0,0,136,0,4,4,0,0,1,8,0A76.09,76.09,0,0,1,132,203.89Z"></path>'),t(r,e)}updatePauseState(e){const t=this.queryElement("#pauseButton"),r=this.queryElement("#resumeButton");this.setDisplay(t,e?"none":"flex"),this.setDisplay(r,e?"flex":"none")}updateCountdownOverlay(e,t){const r=this.queryElement("#countdownOverlay"),i=this.queryElement("#countdownNumber");"countdown"===e&&t>0?(this.setDisplay(r,"flex"),this.setText(i,t.toString())):this.setDisplay(r,"none")}showSourceTransition(e){const t=this.queryElement("#videoPreview");this.toggleClass(t,"transitioning",!0);const r=this.queryElement("#sourceTransitionOverlay");this.toggleClass(r,"active",!0);const i=r.querySelector(".transition-message");if(!i)throw Error("Transition message element not found");this.setText(i,e)}hideSourceTransition(){const e=this.queryElement("#videoPreview");this.toggleClass(e,"transitioning",!1);const t=this.queryElement("#sourceTransitionOverlay");this.toggleClass(t,"active",!1)}handleStreamStart(e,t){const r=this.queryElement("#startButton"),i=this.queryElement("#stopButton"),a=this.queryElement("#cameraArea"),s=this.queryElement("#startCameraArea"),n=this.queryElement("#audioLevelBars");if(this.setDisabled(r,!1),this.setDisplay(r,"flex"),this.setDisabled(i,!0),this.setDisplay(i,"none"),this.toggleClass(a,"active",!0),this.setDisplay(s,"none"),"idle"===e){const e=this.queryElement("#settingsButton"),t=this.queryElement("#muteButton"),r=this.queryElement("#pauseButton"),i=this.queryElement("#resumeButton"),a=this.queryElement("#switchSourceButton");this.setDisplay(e,"flex"),this.setDisplay(t,"none"),this.setDisplay(r,"none"),this.setDisplay(i,"none"),this.setDisplay(a,"none")}t(),this.setDisplay(n,"flex")}handleStreamStop(e){this.queryElement("#videoPreview").srcObject=null;const t=this.queryElement("#cameraArea"),r=this.queryElement("#audioLevelBars");this.toggleClass(t,"active",!1),e(),this.setDisplay(r,"none")}handleRecordingStart(e){const t=this.queryElement("#startButton"),r=this.queryElement("#stopButton"),i=this.queryElement("#muteButton"),a=this.queryElement("#switchSourceButton"),s=this.queryElement("#settingsButton"),n=this.queryElement("#pauseButton"),o=this.queryElement("#resumeButton"),c=this.queryElement("#recIndicatorTop"),d=this.queryElement("#recordingTimerRow");this.setDisplay(t,"none"),this.setDisplay(r,"flex"),this.setDisabled(r,!1),this.setDisplay(c,"flex"),this.setDisplay(d,"flex"),this.setDisplay(s,"none"),this.setDisabled(i,!1),this.setDisplay(i,"flex"),this.setDisabled(a,!1),this.setDisplay(a,"flex"),this.setDisplay(n,e?"none":"flex"),this.setDisplay(o,e?"flex":"none"),this.hideError()}updateRecordingControlsAfterStop(){const e=this.queryElement("#startButton"),t=this.queryElement("#stopButton"),r=this.queryElement("#processButton"),i=this.queryElement("#muteButton"),a=this.queryElement("#switchSourceButton"),s=this.queryElement("#settingsButton"),n=this.queryElement("#pauseButton"),o=this.queryElement("#resumeButton"),c=this.queryElement("#recIndicatorTop"),d=this.queryElement("#recordingTimerRow");this.setDisplay(e,"flex"),this.setDisabled(e,!1),this.setDisplay(t,"none"),this.setDisabled(t,!0),this.setDisplay(c,"none"),this.setDisplay(d,"none"),this.setDisplay(r,"none"),this.setDisplay(i,"none"),this.setDisplay(a,"none"),this.setDisplay(s,"flex"),this.setDisplay(n,"none"),this.setDisplay(o,"none")}updateSwitchButtonText(e){const t=this.queryElement("#switchSourceButton"),r=this.shadowRoot.querySelector("#switchSourceIcon");if(!r)throw Error("Switch source icon element not found");"camera"===e?(r.innerHTML='<rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/>',t.title="Switch to Screen"):(r.innerHTML='<path d="M17 17H4a2 2 0 0 1-2-2V5c0-1.5 1-2 1-2"/><path d="M22 15V5a2 2 0 0 0-2-2H9"/><path d="M8 21h8"/><path d="M12 17v4"/><path d="m2 2 20 20"/>',t.title="Switch to Camera")}toggleSettings(e){const t=this.queryElement("#settingsPanel"),r=!e;return this.setDisplay(t,r?"block":"none"),r}showUploadProgress(){const e=this.queryElement("#uploadProgress");this.toggleClass(e,"active",!0),this.updateUploadProgress(0)}updateUploadProgress(e){const t=this.queryElement("#uploadProgressFill"),r=this.queryElement("#uploadProgressText"),i=Math.round(100*e);this.setStyle(t,"width",i+"%"),this.setText(r,`Uploading... ${i}%`)}hideUploadProgress(){const e=this.queryElement("#uploadProgress");this.toggleClass(e,"active",!1)}showUploadSuccess(e){const t=this.queryElement("#uploadStatus"),r=this.queryElement("#uploadStatusText");this.toggleClass(t,"active",!0),this.toggleClass(t,"success",!0),this.toggleClass(t,"error",!1),this.setText(r,"✅ Video uploaded successfully! Video ID: "+e.videoId)}showUploadError(e){const t=this.queryElement("#uploadStatus"),r=this.queryElement("#uploadStatusText");this.toggleClass(t,"active",!0),this.toggleClass(t,"error",!0),this.toggleClass(t,"success",!1),this.setText(r,"❌ Upload failed: "+e)}clearUploadStatus(){const e=this.queryElement("#uploadStatus");this.toggleClass(e,"active",!1),this.toggleClass(e,"success",!1),this.toggleClass(e,"error",!1),this.hideUploadProgress()}updateVideoPreview(e){const t=this.queryElement("#videoPreview");t.pause(),e?(t.srcObject=e,t.play().catch(e=>{const t=e instanceof Error?e.message:e+"";t.includes("abort")||t.includes("NotAllowedError")||t.includes("interrupted")||this.showError("Failed to play preview video: "+t)})):t.srcObject=null}getShadowRoot(){return this.shadowRoot}}const zs=/^https?:\/\//i;function Fs(e){return e?zs.test(e)?e:"https://"+e:"https://api.vidtreo.com"}function Ds(e,t){const r={apiKey:e.getAttribute("api-key"),backendUrl:Fs(e.getAttribute("backend-url"))},i=e.getAttribute("countdown-duration");if(i){const e=Number.parseInt(i,10);Number.isNaN(e)||(r.countdownDuration=e)}const a=e.getAttribute("max-recording-time");if(a){const e=Number.parseInt(a,10);Number.isNaN(e)||(r.maxRecordingTime=e)}const s=e.getAttribute("user-metadata");if(s)try{const e=JSON.parse(s);Object.assign(t,e),r.userMetadata=t}catch(l){throw Error("Invalid user-metadata JSON: "+Na(l))}const n=e.getAttribute("enable-source-switching");r.enableSourceSwitching=null===n||"false"!==n;const o=e.getAttribute("enable-mute");r.enableMute=null===o||"false"!==o;const c=e.getAttribute("enable-pause");r.enablePause=null===c||"false"!==c;const d=e.getAttribute("enable-device-change");return r.enableDeviceChange=null===d||"false"!==d,r}const Os=class extends HTMLElement{constructor(){if(super(),this.recordedBlob=null,this.processedBlob=null,this.isProcessing=!1,this.isMuted=!1,this.showSettings=!1,this.userMetadata={},this.enableSourceSwitching=!0,this.enableMute=!0,this.enablePause=!0,this.enableDeviceChange=!0,this.attachShadow({mode:"open"}),!this.shadowRoot)throw Error("Shadow root not initialized");this.uiStateManager=new Bs(this.shadowRoot),this.audioLevelVisualizer=new As;const e=(t=this,{recording:{onStateChange:()=>{},onCountdownUpdate:(e,r)=>{t.getUIStateManager().updateCountdownOverlay(e,r)},onTimerUpdate:e=>{t.getUIStateManager().updateRecordingTimer(e)},onError:e=>{t.getUIStateManager().showError(e.message)},onRecordingComplete:e=>{},onClearUploadStatus:()=>{t.getUIStateManager().clearUploadStatus()},onStopAudioTracking:()=>{},onGetConfig:async()=>({format:"mp4",fps:30,width:1280,height:720,bitrate:25e5,audioCodec:"aac",preset:"medium",packetCount:0,audioBitrate:128e3})},upload:{onProgress:e=>{t.getUIStateManager().showUploadProgress(),t.getUIStateManager().updateUploadProgress(e)},onSuccess:e=>{t.getUIStateManager().hideUploadProgress(),t.getUIStateManager().showUploadSuccess(e)},onError:e=>{t.getUIStateManager().hideUploadProgress(),t.getUIStateManager().showUploadError(e.message)},onClearStatus:()=>{t.getUIStateManager().clearUploadStatus()}},sourceSwitch:{onSourceChange:async e=>{if(t.getUIStateManager().updateSwitchButtonText(e),"camera"===e){const e=t.getController().getStream();if(!e)return;if(0===e.getAudioTracks().length)return;t.getController().stopAudioLevelTracking(),await t.getController().startAudioLevelTracking(e,{onLevelUpdate:(e,r)=>{t.getAudioLevelVisualizer().updateBars(e,r)}})}},onPreviewUpdate:async e=>{const r=t.getController().getCurrentSourceType();if("screen"===r){const e=t.getController().getAudioStreamForAnalysis();if(!e)return;if(0===e.getAudioTracks().length)return;t.getController().stopAudioLevelTracking(),await t.getController().startAudioLevelTracking(e,{onLevelUpdate:(e,r)=>{t.getAudioLevelVisualizer().updateBars(e,r)}})}else e.getAudioTracks().length>0&&(t.getController().stopAudioLevelTracking(),await t.getController().startAudioLevelTracking(e,{onLevelUpdate:(e,r)=>{t.getAudioLevelVisualizer().updateBars(e,r)}}));const i=_s(t.getShadowRoot(),"#videoPreview");await async function(e,t,r){e.pause(),e.srcObject=null,e.load(),"screen"===r?e.classList.add("screen-share"):e.classList.remove("screen-share"),await new Promise(e=>{setTimeout(()=>e(),100)}),e.srcObject=t,await new Promise((t,r)=>{const i=setTimeout(()=>{a||(a=!0,s(),r(Error("Timeout waiting for video to load")))},1e4);let a=!1;const s=()=>{!a&&e&&(e.removeEventListener("loadedmetadata",l),e.removeEventListener("loadeddata",h),e.removeEventListener("canplay",u),e.removeEventListener("playing",m),e.removeEventListener("error",p))},n=()=>{a||(a=!0,clearTimeout(i),s(),t())},o=e=>{a||(a=!0,clearTimeout(i),s(),r(Error("Failed to play preview video: "+e)))},c=async()=>{if(!a&&e)try{await e.play(),n()}catch(t){const e=Na(t);o("Failed to play preview video: "+e)}},d=async()=>{if(!a&&e)try{await e.play(),n()}catch(t){(t=>{if(a||!e)return;const r=Na(t);r.includes("interrupted")||r.includes("abort")?setTimeout(c,200):o(r)})(t)}},l=()=>{!a&&e&&d()},h=()=>{!a&&e&&(2>e.readyState||d())},u=()=>{!a&&e&&(3>e.readyState||d())},m=()=>{!a&&e&&(a=!0,clearTimeout(i),s(),t())},p=e=>{if(a)return;a=!0,clearTimeout(i),s();const t=e instanceof ErrorEvent?e.error:Error("Video element error");r(Error("Failed to load preview: "+Na(t)))};1>e.readyState?(e.addEventListener("loadedmetadata",l,{once:!0}),e.addEventListener("loadeddata",h,{once:!0}),e.addEventListener("canplay",u,{once:!0}),e.addEventListener("playing",m,{once:!0}),e.addEventListener("error",p,{once:!0}),setTimeout(()=>{a||!e||1>e.readyState||d()},500)):d()})}(i,e,r)},onError:e=>{t.getUIStateManager().showError(Na(e))},onTransitionStart:e=>{t.getUIStateManager().showSourceTransition(e)},onTransitionEnd:()=>{t.getUIStateManager().hideSourceTransition()}},storage:{onUploadProgress:()=>{},onUploadComplete:()=>{t.checkPendingUploads()},onUploadError:()=>{t.checkPendingUploads()}},onStorageCleanupError:e=>{t.getUIStateManager().showError(e)}});var t;if(this.controller=new xs(e),this.deviceManager=new Rs(this.controller.getStreamManager(),void 0),function(e){const t=e.getStreamManager();t.on("statechange",({state:t,previousState:r})=>{e.handleStateChange(t,r)}),t.on("streamstart",({stream:t})=>{e.handleStreamStart(t)}),t.on("streamstop",()=>{e.handleStreamStop()}),t.on("recordingstart",()=>{e.handleRecordingStart()}),t.on("recordingstop",({blob:t})=>{e.handleRecordingStop(t).catch(t=>{e.showError(e.extractErrorMessage(t))})}),t.on("recordingtimeupdate",({formatted:t})=>{e.updateRecordingTimer(t)}),t.on("recordingbufferupdate",()=>{}),t.on("audiomutetoggle",({muted:t})=>{e.updateMuteState(t)}),t.on("videosourcechange",({stream:t})=>{e.updateVideoPreview(t)}),t.on("error",({error:t})=>{e.showError(t.message)})}(this),!this.shadowRoot)throw Error("Shadow root not initialized");const r=function(e,t="camera"){const r="camera"===t?'<rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/>':'<path d="M17 17H4a2 2 0 0 1-2-2V5c0-1.5 1-2 1-2"/><path d="M22 15V5a2 2 0 0 0-2-2H9"/><path d="M8 21h8"/><path d="M12 17v4"/><path d="m2 2 20 20"/>';return'<div class="container">\n <h1>Video Recorder</h1>\n <p class="subtitle">\n Record video from your camera and transcode it to MP4 format\n </p>\n\n <div class="start-camera-area" id="startCameraArea">\n <div class="camera-icon">\n <svg\n width="48"\n height="48"\n viewBox="0 0 256 256"\n fill="none"\n stroke="currentColor"\n stroke-width="12"\n stroke-linecap="round"\n stroke-linejoin="round"\n >\n <path\n d="M208,56H180.28L166.65,35.56A8,8,0,0,0,160,32H96a8,8,0,0,0-6.65,3.56L75.71,56H48A24,24,0,0,0,24,80V192a24,24,0,0,0,24,24H208a24,24,0,0,0,24-24V80A24,24,0,0,0,208,56Z"\n fill="none"\n />\n <circle cx="128" cy="132" r="36" fill="none"/>\n </svg>\n </div>\n <div class="camera-text">Initializing camera...</div>\n <div class="camera-hint">\n Grant camera and microphone permissions when prompted\n </div>\n <button id="startCameraButton" style="display: none;">Retry Camera</button>\n </div>\n\n <div class="camera-area" id="cameraArea">\n <div class="preview-container">\n <div class="preview-skeleton" id="previewSkeleton" style="display: none;">\n <div class="skeleton-spinner"></div>\n <div class="skeleton-text">Switching device...</div>\n </div>\n <video\n id="videoPreview"\n class="video-preview"\n autoplay\n muted\n playsinline\n ></video>\n <div class="countdown-overlay" id="countdownOverlay">\n <div class="countdown-content">\n <div class="countdown-number" id="countdownNumber">5</div>\n <p class="countdown-text">Recording starts in...</p>\n </div>\n </div>\n <div class="source-transition-overlay" id="sourceTransitionOverlay">\n <div class="transition-spinner"></div>\n <div class="transition-message">Switching source...</div>\n </div>\n <div\n class="rec-indicator-top"\n id="recIndicatorTop"\n style="display: none;"\n >\n <div class="recording-dot-small"></div>\n <span>REC</span>\n </div>\n <div\n class="recording-timer-badge"\n id="recordingTimerRow"\n style="display: none;"\n >\n <div class="recording-dot-small"></div>\n <span class="recording-timer-text" id="recordingTimer">00:00</span>\n </div>\n <div\n class="audio-level-bars"\n id="audioLevelBars"\n style="display: none;"\n ></div>\n <div class="recording-controls">\n <div class="recording-controls-row">\n <div class="control-buttons-row">\n \x3c!-- When not recording: settings - record - mute --\x3e\n <button\n class="control-button"\n id="settingsButton"\n style="display: none;"\n title="Settings"\n >\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="20"\n height="20"\n fill="#1f2023"\n viewBox="0 0 256 256"\n >\n <path\n d="M128,84a44,44,0,1,0,44,44A44.05,44.05,0,0,0,128,84Zm0,80a36,36,0,1,1,36-36A36,36,0,0,1,128,164Zm83.93-32.49q.13-3.51,0-7l15.83-19.79a4,4,0,0,0,.75-3.53A103.64,103.64,0,0,0,218,75.9a4,4,0,0,0-3-2l-25.19-2.8c-1.58-1.71-3.24-3.37-4.95-4.95L182.07,41a4,4,0,0,0-2-3A104,104,0,0,0,154.82,27.5a4,4,0,0,0-3.53.74L131.51,44.07q-3.51-.14-7,0L104.7,28.24a4,4,0,0,0-3.53-.75A103.64,103.64,0,0,0,75.9,38a4,4,0,0,0-2,3l-2.8,25.19c-1.71,1.58-3.37,3.24-4.95,4.95L41,73.93a4,4,0,0,0-3,2A104,104,0,0,0,27.5,101.18a4,4,0,0,0,.74,3.53l15.83,19.78q-.14,3.51,0,7L28.24,151.3a4,4,0,0,0-.75,3.53A103.64,103.64,0,0,0,38,180.1a4,4,0,0,0,3,2l25.19,2.8c1.58,1.71,3.24,3.37,4.95,4.95l2.8,25.2a4,4,0,0,0,2,3,104,104,0,0,0,25.28,10.46,4,4,0,0,0,3.53-.74l19.78-15.83q3.51.13,7,0l19.79,15.83a4,4,0,0,0,2.5.88,4,4,0,0,0,1-.13A103.64,103.64,0,0,0,180.1,218a4,4,0,0,0,2-3l2.8-25.19c1.71-1.58,3.37-3.24,4.95-4.95l25.2-2.8a4,4,0,0,0,3-2,104,104,0,0,0,10.46-25.28,4,4,0,0,0-.74-3.53Zm.17,42.83-24.67,2.74a4,4,0,0,0-2.55,1.32,76.2,76.2,0,0,1-6.48,6.48,4,4,0,0,0-1.32,2.55l-2.74,24.66a95.45,95.45,0,0,1-19.64,8.15l-19.38-15.51a4,4,0,0,0-2.5-.87h-.24a73.67,73.67,0,0,1-9.16,0,4,4,0,0,0-2.74.87l-19.37,15.5a95.33,95.33,0,0,1-19.65-8.13l-2.74-24.67a4,4,0,0,0-1.32-2.55,76.2,76.2,0,0,1-6.48-6.48,4,4,0,0,0-2.55-1.32l-24.66-2.74a95.45,95.45,0,0,1-8.15-19.64l15.51-19.38a4,4,0,0,0,.87-2.74,77.76,77.76,0,0,1,0-9.16,4,4,0,0,0-.87-2.74l-15.5-19.37A95.33,95.33,0,0,1,43.9,81.66l24.67-2.74a4,4,0,0,0,2.55-1.32,76.2,76.2,0,0,1,6.48-6.48,4,4,0,0,0,1.32-2.55l2.74-24.66a95.45,95.45,0,0,1,19.64-8.15l19.38,15.51a4,4,0,0,0,2.74.87,73.67,73.67,0,0,1,9.16,0,4,4,0,0,0,2.74-.87l19.37-15.5a95.33,95.33,0,0,1,19.65,8.13l2.74,24.67a4,4,0,0,0,1.32,2.55,76.2,76.2,0,0,1,6.48,6.48,4,4,0,0,0,2.55,1.32l24.66,2.74a95.45,95.45,0,0,1,8.15,19.64l-15.51,19.38a4,4,0,0,0-.87,2.74,77.76,77.76,0,0,1,0,9.16,4,4,0,0,0,.87,2.74l15.5,19.37A95.33,95.33,0,0,1,212.1,174.34Z"\n ></path>\n </svg>\n </button>\n <button class="record-button" id="startButton" disabled>\n <svg\n width="24"\n height="24"\n viewBox="0 0 256 256"\n fill="currentColor"\n style="margin-right: 0.375rem;"\n >\n <circle\n cx="128"\n cy="128"\n r="96"\n fill="none"\n stroke="currentColor"\n stroke-width="16"\n />\n <circle cx="128" cy="128" r="64" fill="currentColor"/>\n </svg>\n Record\n </button>\n <button\n class="control-button"\n id="muteButton"\n disabled\n style="display: none;"\n title="Mute/Unmute"\n >\n <svg\n width="24"\n height="24"\n viewBox="0 0 256 256"\n fill="currentColor"\n id="muteIcon"\n >\n {{MUTE_ICON_PLACEHOLDER}}\n </svg>\n </button>\n \x3c!-- When recording: pause/resume - stop - mute - share screen --\x3e\n <button\n class="control-button"\n id="pauseButton"\n style="display: none;"\n title="Pause"\n >\n <svg\n width="24"\n height="24"\n viewBox="0 0 256 256"\n fill="currentColor"\n >\n <rect\n x="72"\n y="56"\n width="32"\n height="144"\n rx="8"\n fill="currentColor"\n />\n <rect\n x="152"\n y="56"\n width="32"\n height="144"\n rx="8"\n fill="currentColor"\n />\n </svg>\n </button>\n <button\n class="control-button"\n id="resumeButton"\n style="display: none;"\n title="Resume"\n >\n <svg\n width="24"\n height="24"\n viewBox="0 0 256 256"\n fill="currentColor"\n >\n <path\n d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Z"\n fill="currentColor"\n />\n <path\n d="M160,128a8,8,0,0,1-3.71,6.75l-40,28A8,8,0,0,1,104,156V100a8,8,0,0,1,12.29-6.75l40,28A8,8,0,0,1,160,128Z"\n fill="currentColor"\n />\n </svg>\n </button>\n <button\n class="record-button"\n id="stopButton"\n disabled\n style="display: none;"\n >\n <svg\n width="24"\n height="24"\n viewBox="0 0 256 256"\n fill="currentColor"\n style="margin-right: 0.375rem;"\n >\n <rect\n x="64"\n y="64"\n width="128"\n height="128"\n rx="8"\n fill="currentColor"\n />\n </svg>\n Stop\n </button>\n <button\n class="control-button"\n id="switchSourceButton"\n disabled\n style="display: none;"\n title="Switch Source"\n >\n <svg\n width="24"\n height="24"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n id="switchSourceIcon"\n >\n {{SWITCH_SOURCE_ICON_PLACEHOLDER}}\n </svg>\n </button>\n </div>\n </div>\n </div>\n </div>\n <div class="settings-panel" id="settingsPanel">\n <h3 class="settings-title">Settings</h3>\n <div class="device-select-group">\n <div class="device-select-label">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="20"\n height="20"\n fill="#1f2023"\n viewBox="0 0 256 256"\n >\n <path\n d="M208,60H178.13L163.32,37.78A4,4,0,0,0,160,36H96a4,4,0,0,0-3.32,1.78L77.85,60H48A20,20,0,0,0,28,80V192a20,20,0,0,0,20,20H208a20,20,0,0,0,20-20V80A20,20,0,0,0,208,60Zm12,132a12,12,0,0,1-12,12H48a12,12,0,0,1-12-12V80A12,12,0,0,1,48,68H80a4,4,0,0,0,3.33-1.78L98.13,44h59.72l14.82,22.22A4,4,0,0,0,176,68h32a12,12,0,0,1,12,12ZM128,92a40,40,0,1,0,40,40A40,40,0,0,0,128,92Zm0,72a32,32,0,1,1,32-32A32,32,0,0,1,128,164Z"\n ></path>\n </svg>\n <span>Camera</span>\n </div>\n <select class="device-select" id="cameraSelect">\n <option value="default">Default Camera</option>\n </select>\n </div>\n <div class="device-select-group">\n <div class="device-select-label">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="20"\n height="20"\n fill="#1f2023"\n viewBox="0 0 256 256"\n >\n <path\n d="M128,172a44.05,44.05,0,0,0,44-44V64a44,44,0,0,0-88,0v64A44.05,44.05,0,0,0,128,172ZM92,64a36,36,0,0,1,72,0v64a36,36,0,0,1-72,0Zm40,139.89V240a4,4,0,0,1-8,0V203.89A76.09,76.09,0,0,1,52,128a4,4,0,0,1,8,0,68,68,0,0,0,136,0,4,4,0,0,1,8,0A76.09,76.09,0,0,1,132,203.89Z"\n ></path>\n </svg>\n <span>Microphone</span>\n </div>\n <select class="device-select" id="micSelect">\n <option value="default">Default Microphone</option>\n </select>\n </div>\n </div>\n </div>\n\n <button id="processButton" disabled>Process Video</button>\n\n <div class="progress" id="progress">\n <div class="progress-bar">\n <div class="progress-fill" id="progressFill"></div>\n </div>\n <div class="progress-text" id="progressText">Processing...</div>\n </div>\n\n <div class="error" id="error"></div>\n\n <div class="upload-progress" id="uploadProgress">\n <div class="progress-bar">\n <div class="progress-fill" id="uploadProgressFill"></div>\n </div>\n <div class="progress-text" id="uploadProgressText">Uploading... 0%</div>\n </div>\n\n <div class="upload-status" id="uploadStatus">\n <div class="upload-status-text" id="uploadStatusText"></div>\n </div>\n</div>\n'.replace("{{MUTE_ICON_PLACEHOLDER}}",e?'<path d="M211,221.31,51,45.31A4,4,0,0,0,45,50.69L84,93.55V128a44,44,0,0,0,66,38.12l16.38,18A67.21,67.21,0,0,1,128,196a68.07,68.07,0,0,1-68-68,4,4,0,0,0-8,0,76.09,76.09,0,0,0,72,75.89V240a4,4,0,0,0,8,0V203.89a75.1,75.1,0,0,0,39.79-13.77L205,226.69a4,4,0,1,0,5.92-5.38ZM128,164a36,36,0,0,1-36-36V102.35L144.43,160A35.83,35.83,0,0,1,128,164Zm61.12-6.15A67.44,67.44,0,0,0,196,128a4,4,0,0,1,8,0,75.28,75.28,0,0,1-7.7,33.37,4,4,0,0,1-7.18-3.52ZM87.63,46.46A44,44,0,0,1,172,64v64a44.2,44.2,0,0,1-.24,4.61,4,4,0,0,1-4,3.58l-.42,0a4,4,0,0,1-3.57-4.39A36.67,36.67,0,0,0,164,128V64A36,36,0,0,0,95,49.66a4,4,0,0,1-7.34-3.2Z"></path>':'<path d="M128,172a44.05,44.05,0,0,0,44-44V64a44,44,0,0,0-88,0v64A44.05,44.05,0,0,0,128,172ZM92,64a36,36,0,0,1,72,0v64a36,36,0,0,1-72,0Zm40,139.89V240a4,4,0,0,1-8,0V203.89A76.09,76.09,0,0,1,52,128a4,4,0,0,1,8,0,68,68,0,0,0,136,0,4,4,0,0,1,8,0A76.09,76.09,0,0,1,132,203.89Z"></path>').replace("{{SWITCH_SOURCE_ICON_PLACEHOLDER}}",r)}(this.isMuted,"camera");this.shadowRoot.innerHTML='<style>:host {\n display: block;\n font-family:\n -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,\n Cantarell, sans-serif;\n --background: 0 0% 100%;\n --foreground: 0 0% 3.9%;\n --card: 0 0% 100%;\n --card-foreground: 0 0% 3.9%;\n --primary: 0 0% 9%;\n --primary-foreground: 0 0% 98%;\n --secondary: 0 0% 96.1%;\n --secondary-foreground: 0 0% 9%;\n --muted: 0 0% 96.1%;\n --muted-foreground: 0 0% 45.1%;\n --accent: 0 0% 96.1%;\n --accent-foreground: 0 0% 9%;\n --destructive: 0 84.2% 60.2%;\n --destructive-foreground: 0 0% 98%;\n --border: 0 0% 89.8%;\n --input: 0 0% 89.8%;\n --ring: 0 0% 3.9%;\n --radius: 0.5rem;\n --preview-bg: 0 0% 98%;\n}\n\n.container {\n background: hsl(var(--background));\n border-radius: 16px;\n padding: 40px;\n max-width: 600px;\n width: 100%;\n box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);\n}\n\nh1 {\n color: #333;\n margin-bottom: 10px;\n font-size: 28px;\n}\n\n.subtitle {\n color: #666;\n margin-bottom: 30px;\n font-size: 14px;\n}\n\n.preview-container {\n position: relative;\n width: 100%;\n aspect-ratio: 9 / 16;\n border-radius: 0.5rem;\n overflow: hidden;\n border: 1px solid hsl(var(--border));\n background: hsl(var(--preview-bg));\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n@media (min-width: 768px) {\n .preview-container {\n aspect-ratio: 16 / 9;\n }\n}\n\n.camera-area {\n border: 2px solid #667eea;\n border-radius: 12px;\n padding: 20px;\n background: #f8f9ff;\n margin-bottom: 20px;\n display: none;\n position: relative;\n}\n\n.source-transition-overlay {\n position: absolute;\n top: 20px;\n left: 20px;\n right: 20px;\n bottom: 20px;\n background: rgba(0, 0, 0, 0.7);\n display: none;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n border-radius: 8px;\n z-index: 10;\n backdrop-filter: blur(4px);\n transition: opacity 0.3s ease;\n}\n\n.source-transition-overlay.active {\n display: flex;\n animation: fadeIn 0.2s ease;\n}\n\n@keyframes fadeIn {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n.transition-spinner {\n width: 40px;\n height: 40px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #667eea;\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n margin-bottom: 12px;\n}\n\n@keyframes spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.transition-message {\n color: white;\n font-size: 14px;\n font-weight: 500;\n text-align: center;\n}\n\n.camera-area.active {\n display: block;\n}\n\n.preview-container {\n position: relative;\n width: 100%;\n height: 100%;\n}\n\n.preview-skeleton {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background: hsl(var(--background) / 0.95);\n border-radius: 0.5rem;\n z-index: 10;\n gap: 1rem;\n}\n\n.skeleton-spinner {\n width: 40px;\n height: 40px;\n border: 4px solid hsl(var(--muted) / 0.3);\n border-top-color: hsl(var(--primary));\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n}\n\n.skeleton-text {\n color: hsl(var(--muted-foreground));\n font-size: 0.875rem;\n font-weight: 500;\n}\n\n.video-preview {\n width: 100%;\n height: 100%;\n border-radius: 0.5rem;\n background: #000;\n display: block;\n object-fit: contain;\n transition:\n opacity 0.3s ease,\n transform 0.3s ease;\n position: absolute;\n inset: 0;\n}\n\n.video-preview.screen-share {\n object-fit: cover;\n}\n\n.video-preview.transitioning {\n opacity: 0.5;\n transform: scale(0.98);\n}\n\n.countdown-overlay {\n position: absolute;\n inset: 0;\n background: hsl(var(--background) / 0.95);\n display: none;\n align-items: center;\n justify-content: center;\n border-radius: 0.5rem;\n z-index: 20;\n}\n\n.countdown-overlay.active {\n display: flex;\n}\n\n.countdown-number {\n font-size: 9rem;\n font-weight: bold;\n color: hsl(var(--foreground));\n animation: zoomIn 0.3s ease;\n}\n\n@keyframes zoomIn {\n from {\n transform: scale(0.5);\n opacity: 0;\n }\n to {\n transform: scale(1);\n opacity: 1;\n }\n}\n\n.countdown-text {\n font-size: 0.875rem;\n color: hsl(var(--muted-foreground));\n margin-top: 1rem;\n font-weight: 500;\n}\n\n.settings-panel {\n margin-top: 1rem;\n background: hsl(var(--background));\n border: 1px solid hsl(var(--border));\n border-radius: 0.5rem;\n padding: 1.25rem;\n display: none;\n animation: slideIn 0.3s ease;\n}\n\n.settings-panel.active {\n display: block;\n}\n\n@keyframes slideIn {\n from {\n transform: translateY(1rem);\n opacity: 0;\n }\n to {\n transform: translateY(0);\n opacity: 1;\n }\n}\n\n.settings-title {\n font-size: 0.875rem;\n font-weight: 600;\n margin-bottom: 1.25rem;\n}\n\n.device-select-group {\n margin-bottom: 1.25rem;\n}\n\n.device-select-label {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n font-size: 0.75rem;\n color: hsl(var(--muted-foreground));\n font-weight: 500;\n margin-bottom: 0.5rem;\n}\n\n.device-select {\n width: 100%;\n height: 2.25rem;\n border-radius: 0.375rem;\n border: 1px solid hsl(var(--input));\n background: hsl(var(--background));\n padding: 0 0.75rem;\n font-size: 0.875rem;\n}\n\n.audio-level-bars {\n position: absolute;\n bottom: 0.75rem;\n right: 0.75rem;\n display: flex;\n align-items: center;\n gap: 0.125rem;\n height: 1rem;\n z-index: 10;\n}\n\n@media (min-width: 768px) {\n .audio-level-bars {\n height: 1.25rem;\n }\n}\n\n.audio-level-bar {\n width: 0.125rem;\n border-radius: 9999px;\n background: hsl(var(--border));\n transition: all 0.1s ease;\n align-self: flex-end;\n}\n\n.recording-controls {\n display: flex;\n gap: 12px;\n align-items: center;\n justify-content: center;\n}\n\n.recording-indicator {\n display: flex;\n align-items: center;\n gap: 8px;\n color: #c33;\n font-weight: 600;\n display: none;\n}\n\n.recording-indicator.active {\n display: flex;\n}\n\n.recording-dot {\n width: 12px;\n height: 12px;\n background: #c33;\n border-radius: 50%;\n animation: pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes pulse {\n 0%,\n 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.3;\n }\n}\n\n.recording-timer {\n font-family: monospace;\n font-size: 18px;\n color: #333;\n}\n\n.start-camera-area {\n border: 2px dashed #667eea;\n border-radius: 12px;\n padding: 40px;\n text-align: center;\n background: #f8f9ff;\n transition: all 0.3s ease;\n cursor: pointer;\n margin-bottom: 20px;\n}\n\n.start-camera-area:hover:not(.loading) {\n border-color: #764ba2;\n background: #f0f2ff;\n}\n\n.start-camera-area.loading {\n cursor: wait;\n opacity: 0.7;\n}\n\n.start-camera-area.loading .camera-text {\n color: #999;\n}\n\n.camera-icon {\n font-size: 48px;\n margin-bottom: 16px;\n}\n\n.camera-text {\n color: #667eea;\n font-weight: 600;\n margin-bottom: 8px;\n}\n\n.camera-hint {\n color: #999;\n font-size: 12px;\n}\n\n.recording-info {\n margin-top: 20px;\n padding: 16px;\n background: #f5f5f5;\n border-radius: 8px;\n display: none;\n}\n\n.recording-info.active {\n display: block;\n}\n\n.recording-size {\n color: #666;\n font-size: 14px;\n}\n\nbutton {\n width: 100%;\n padding: 16px;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n border: none;\n border-radius: 8px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition:\n transform 0.2s ease,\n box-shadow 0.2s ease;\n margin-top: 20px;\n}\n\nbutton:hover:not(:disabled) {\n transform: translateY(-2px);\n box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);\n}\n\nbutton:disabled {\n opacity: 0.6;\n cursor: not-allowed;\n}\n\n.recording-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n padding: 0.75rem 1rem;\n}\n\n.recording-controls-row {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 0.5rem;\n}\n\n.recording-timer-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 0.5rem;\n}\n\n.recording-timer-badge {\n position: absolute;\n top: 0.75rem;\n right: 0.75rem;\n display: flex;\n align-items: center;\n gap: 0.375rem;\n background: hsl(var(--background) / 0.9);\n border: 1px solid hsl(var(--border));\n padding: 0.25rem 0.5rem;\n border-radius: 9999px;\n box-shadow:\n 0 1px 3px 0 rgb(0 0 0 / 0.1),\n 0 1px 2px -1px rgb(0 0 0 / 0.1);\n z-index: 10;\n}\n\n.recording-dot-small {\n width: 0.375rem;\n height: 0.375rem;\n background: hsl(var(--destructive));\n border-radius: 50%;\n animation: pulse 1.5s ease-in-out infinite;\n}\n\n.recording-timer-text {\n font-size: 0.75rem;\n font-family: monospace;\n font-weight: 500;\n color: hsl(var(--foreground));\n}\n\n.control-buttons-row {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 0.375rem;\n}\n\n.control-button {\n width: 2rem;\n height: 2rem;\n border-radius: 9999px;\n border: 1px solid hsl(var(--border));\n background: hsl(var(--background) / 0.9);\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: all 0.2s ease;\n color: hsl(var(--foreground));\n}\n\n.control-button svg {\n width: 24px !important;\n height: 24px !important;\n color: inherit;\n fill: currentColor;\n flex-shrink: 0;\n}\n\n@media (min-width: 768px) {\n .control-button svg {\n width: 26px !important;\n height: 26px !important;\n }\n}\n\n@media (min-width: 768px) {\n .control-button {\n width: 2.25rem;\n height: 2.25rem;\n }\n}\n\n.control-button:hover:not(:disabled) {\n background: hsl(var(--accent));\n}\n\n.control-button:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.control-button.muted {\n background: hsl(var(--muted));\n color: hsl(var(--foreground));\n}\n\n.record-button {\n height: 2rem;\n padding: 0 0.75rem;\n border-radius: 9999px;\n font-weight: 500;\n font-size: 0.75rem;\n background: hsl(var(--destructive));\n color: hsl(var(--destructive-foreground));\n border: none;\n display: flex;\n align-items: center;\n gap: 0.375rem;\n transition: all 0.2s ease;\n}\n\n@media (min-width: 768px) {\n .record-button {\n height: 2.25rem;\n font-size: 0.875rem;\n }\n}\n\n.record-button:hover:not(:disabled) {\n background: hsl(var(--destructive) / 0.9);\n}\n\n.rec-indicator-top {\n position: absolute;\n top: 0.75rem;\n left: 0.75rem;\n display: flex;\n align-items: center;\n gap: 0.375rem;\n background: hsl(var(--background) / 0.9);\n border: 1px solid hsl(var(--border));\n padding: 0.25rem 0.5rem;\n border-radius: 9999px;\n box-shadow:\n 0 1px 3px 0 rgb(0 0 0 / 0.1),\n 0 1px 2px -1px rgb(0 0 0 / 0.1);\n}\n\n.rec-indicator-top span {\n font-size: 0.75rem;\n font-weight: 500;\n}\n\n.progress {\n margin-top: 20px;\n display: none;\n}\n\n.progress.active {\n display: block;\n}\n\n.progress-bar {\n width: 100%;\n height: 8px;\n background: #e0e0e0;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 8px;\n}\n\n.progress-fill {\n height: 100%;\n background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);\n width: 0%;\n transition: width 0.3s ease;\n}\n\n.progress-text {\n text-align: center;\n color: #666;\n font-size: 14px;\n}\n\n.result {\n margin-top: 20px;\n padding: 20px;\n background: #f0f9ff;\n border: 2px solid #667eea;\n border-radius: 8px;\n display: none;\n}\n\n.result.active {\n display: block;\n}\n\n.result-title {\n font-weight: 600;\n color: #333;\n margin-bottom: 12px;\n}\n\n.result-info {\n color: #666;\n font-size: 14px;\n margin-bottom: 12px;\n}\n\n.result-actions {\n display: flex;\n gap: 12px;\n}\n\n.result-actions button {\n flex: 1;\n margin-top: 0;\n padding: 12px;\n font-size: 14px;\n}\n\n.error {\n margin-top: 20px;\n padding: 16px;\n background: #fee;\n border: 2px solid #fcc;\n border-radius: 8px;\n color: #c33;\n display: none;\n}\n\n.error.active {\n display: block;\n}\n\n.upload-progress {\n margin-top: 20px;\n display: none;\n}\n\n.upload-progress.active {\n display: block;\n}\n\n.upload-status {\n margin-top: 20px;\n padding: 16px;\n border-radius: 8px;\n display: none;\n}\n\n.upload-status.active {\n display: block;\n}\n\n.upload-status.success {\n background: #f0f9ff;\n border: 2px solid #48bb78;\n color: #22543d;\n}\n\n.upload-status.error {\n background: #fee;\n border: 2px solid #fcc;\n color: #c33;\n}\n\n.upload-status-text {\n font-size: 14px;\n font-weight: 500;\n}\n</style>'+r,function(e){const t=e.getShadowRoot(),r=t.querySelector("#startCameraButton"),i=t.querySelector("#startButton"),a=t.querySelector("#stopButton"),s=t.querySelector("#processButton"),n=t.querySelector("#muteButton"),o=t.querySelector("#switchSourceButton"),c=t.querySelector("#settingsButton"),d=t.querySelector("#pauseButton"),l=t.querySelector("#resumeButton"),h=t.querySelector("#cameraSelect"),u=t.querySelector("#micSelect");if(!(r&&i&&a&&s&&n&&o))throw Error("Required UI elements not found");r.addEventListener("click",()=>{e.startCamera().catch(t=>{e.showError(e.extractErrorMessage(t))})}),i.addEventListener("click",()=>{e.startRecording().catch(t=>{e.showError(e.extractErrorMessage(t))})}),a.addEventListener("click",()=>{e.stopRecording().catch(t=>{e.showError(e.extractErrorMessage(t))})}),s&&(s.style.display="none",s.addEventListener("click",()=>{e.processVideo().catch(t=>{e.showError(e.extractErrorMessage(t))})})),n.addEventListener("click",()=>{e.toggleMute()}),o.addEventListener("click",()=>{e.toggleSource().catch(t=>{e.showError(e.extractErrorMessage(t))})}),c&&c.addEventListener("click",()=>{e.toggleSettings()}),d&&d.addEventListener("click",()=>{e.pauseRecording()}),l&&l.addEventListener("click",()=>{e.resumeRecording()}),h&&h.addEventListener("change",t=>{const r=t.target;e.handleCameraChange(r.value).catch(t=>{e.showError(e.extractErrorMessage(t))})}),u&&u.addEventListener("change",t=>{const r=t.target;e.handleMicChange(r.value).catch(t=>{e.showError(e.extractErrorMessage(t))})})}(this)}async connectedCallback(){this.updateFeatureFlags();const e=Ds(this,this.userMetadata);await this.controller.initialize(e),await this.checkPendingUploads(),this.initializeUIState(),this.startCamera().catch(e=>{this.uiStateManager.showError(Na(e))})}attributeChangedCallback(e,t,r){if(t===r)return;if("enable-source-switching"===e||"enable-mute"===e||"enable-pause"===e||"enable-device-change"===e)return this.updateFeatureFlags(),void this.updateUIForFeatureFlags();const i=Ds(this,this.userMetadata);this.controller.initialize(i).catch(e=>{this.uiStateManager.showError(Na(e))})}disconnectedCallback(){this.controller.cleanup(),this.controller.getStreamManager().destroy()}get shadow(){if(!this.shadowRoot)throw Error("Shadow root not initialized");return this.shadowRoot}checkPendingUploads(){return Promise.resolve()}async startCamera(){_s(this.shadow,"#startCameraArea").classList.add("loading");try{const e=this.controller.getDeviceManager(),t=e.getSelectedCameraDeviceId(),r=e.getSelectedMicDeviceId();this.deviceManager.setCameraDevice(t),this.deviceManager.setMicDevice(r),await this.controller.startStream(),await this.deviceManager.getAvailableDevices(),this.deviceManager.updateDeviceSelects(this.shadow)}catch(e){const t=_s(this.shadow,"#startCameraArea"),r=_s(this.shadow,"#startCameraButton"),i=t.querySelector(".camera-text");if(!i)throw Error("Camera text element not found");t.classList.remove("loading"),t.style.display="block",r.style.display="block",i.textContent="Failed to start camera: "+Na(e)}}async startRecording(){await async function(e){if(e.getShowSettings()){e.setShowSettings(!1);const t=e.getShadowRoot().querySelector("#settingsPanel");if(!t)throw Error("Settings panel element not found");t.style.display="none"}await e.getController().startRecording()}(this)}async stopRecording(){await async function(e){const t=await e.getController().stopRecording();return e.setProcessedBlob(t),e.setRecordedBlob(t),e.getUIStateManager().updateRecordingControlsAfterStop(),await async function(e,t){const r=e.getAttribute("api-key"),i=e.getNormalizedBackendUrl(e.getAttribute("backend-url"));r&&await e.getController().uploadVideo(t,r,i,e.getUserMetadata())}(e,t),t}(this)}pauseRecording(){var e;this.enablePause&&((e=this).getController().pauseRecording(),e.getUIStateManager().updatePauseState(e.getController().isPaused()))}resumeRecording(){var e;this.enablePause&&((e=this).getController().resumeRecording(),e.getUIStateManager().updatePauseState(e.getController().isPaused()))}async processVideo(){await async function(e){const t=e.getRecordedBlob();if(!t)throw Error("No recording available");e.setIsProcessing(!0);const r=_s(e.getShadowRoot(),"#processButton");r.disabled=!0,e.getUIStateManager().hideError(),e.getUIStateManager().showProgress(),e.getUIStateManager().updateProgress(0,"Starting transcoding...");try{const i=await e.getController().getConfig(),a=await async function(e,t={},r){const i={...Ha,...t},a=function(e){if("string"==typeof e)return new Kt(e);if(e instanceof Blob)return new Qt(e);throw Error("Invalid input type. Expected Blob, File, or file path string.")}(e),s=new Yt({formats:[Ht],source:a}),n=new za({format:new da,target:new ea}),o=await Ua.init({input:s,output:n,...Ga(i)});!function(e){if(!e.isValid){const t=e.discardedTracks.map(e=>e.reason).join(", ");throw Error("Conversion is invalid. Discarded tracks: "+t)}}(o),r&&(o.onProgress=r),await o.execute();const c=n.target.buffer;if(!c)throw Error("Transcoding completed but no output buffer was generated");return{buffer:c,blob:new Blob([c],{type:"video/mp4"})}}(t,i,t=>{e.getUIStateManager().updateProgress(t,`Transcoding... ${Math.round(100*t)}%`)});e.setProcessedBlob(a.blob),e.getUIStateManager().updateProgress(1,"Complete!"),setTimeout(()=>{e.getUIStateManager().hideProgress(),r.disabled=!1,e.setIsProcessing(!1)},500)}catch(i){e.getUIStateManager().hideProgress(),e.getUIStateManager().showError(Na(i)),r.disabled=!1,e.setIsProcessing(!1)}}(this)}downloadVideo(){if(!this.processedBlob)throw Error("No processed video available");!function(e){const t=URL.createObjectURL(e),r=document.createElement("a"),i=(new Date).toISOString().replace(Is,"-").slice(0,-5);r.href=t,r.download=`vidtreo-recording-${i}.mp4`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(t)}(this.processedBlob)}playVideo(){if(!this.processedBlob)throw Error("No processed video available");!function(e){const t=URL.createObjectURL(e),r=window.open();if(!r)throw Error("Failed to open video player window");r.document.write(`\n <html>\n <head><title>Recorded Video</title></head>\n <body style="margin:0;background:#000;display:flex;align-items:center;justify-content:center;min-height:100vh;">\n <video controls autoplay style="max-width:100%;max-height:100vh;">\n <source src="${t}" type="video/mp4">\n </video>\n </body>\n </html>\n `)}(this.processedBlob)}toggleMute(){this.enableMute&&(this.isMuted?(this.controller.unmuteAudio(),this.isMuted=!1):(this.controller.muteAudio(),this.isMuted=!0),this.uiStateManager.updateMuteState(this.isMuted,(e,t)=>this.audioLevelVisualizer.updateBars(e,t),this.controller.getAudioLevel()))}async toggleSource(){this.enableSourceSwitching&&await this.controller.switchSource("camera"===this.controller.getCurrentSourceType()?"screen":"camera")}toggleSettings(){if(!this.enableDeviceChange)return;this.showSettings=!this.showSettings;const e=this.shadow.querySelector("#settingsPanel");if(!e)throw Error("Settings panel element not found");e.style.display=this.showSettings?"block":"none"}async handleCameraChange(e){this.enableDeviceChange&&await async function(e,t){const r="default"===t?null:t;if(e.getController().setCameraDevice(r),e.getDeviceManager().setCameraDevice(r),e.getController().isActive()&&!e.getController().isRecording()){Ps(e.getShadowRoot(),"Switching camera...");try{const t=await e.getController().switchVideoDevice(r),i=_s(e.getShadowRoot(),"#videoPreview");await async function(e,t){e.pause(),e.srcObject=t,await new Promise(t=>{const r=()=>{e.removeEventListener("loadedmetadata",r),t()};e.addEventListener("loadedmetadata",r),e.load(),setTimeout(()=>t(),500)});try{await e.play()}catch(r){const e=r instanceof Error?r.message:r+"";if(!e.includes("abort")&&!e.includes("interrupted"))throw Error("Failed to play preview after device switch: "+e)}}(i,t),Ms(e.getShadowRoot())}catch(i){Ms(e.getShadowRoot()),e.showError(Na(i));const t=e.getDeviceManager().getSelectedCameraDeviceId(),r=e.getShadowRoot().querySelector("#cameraSelect");if(!r)throw Error("Camera select element not found");if(!t)throw Error("Camera device ID is required");r.value=t}}}(this,e)}async handleMicChange(e){this.enableDeviceChange&&await async function(e,t){const r="default"===t?null:t;if(e.getController().setMicDevice(r),e.getDeviceManager().setMicDevice(r),e.getController().isActive()&&!e.getController().isRecording()){Ps(e.getShadowRoot(),"Switching microphone...");try{await e.getController().switchAudioDevice(r);const t=e.getController().getStream();if(!t)throw Error("Stream is required");e.getController().stopAudioLevelTracking(),await e.getController().startAudioLevelTracking(t,{onLevelUpdate:(t,r)=>{e.getAudioLevelVisualizer().updateBars(t,r)}}),setTimeout(()=>{Ms(e.getShadowRoot())},200)}catch(i){Ms(e.getShadowRoot()),e.showError(Na(i));const t=e.getDeviceManager().getSelectedMicDeviceId(),r=e.getShadowRoot().querySelector("#micSelect");if(!r)throw Error("Microphone select element not found");if(!t)throw Error("Microphone device ID is required");r.value=t}}}(this,e)}handleStateChange(e,t){"active"===e&&"starting"===t&&this.uiStateManager.hideError()}handleStreamStart(e){this.uiStateManager.updateVideoPreview(e),this.uiStateManager.handleStreamStart(this.controller.getRecordingState(),()=>{this.audioLevelVisualizer.initializeBars(this.shadow)}),this.updateUIForFeatureFlags();try{this.controller.startAudioLevelTracking(e,{onLevelUpdate:(e,t)=>{this.audioLevelVisualizer.updateBars(e,t)}}),this.uiStateManager.updateMuteState(this.isMuted,(e,t)=>this.audioLevelVisualizer.updateBars(e,t),this.controller.getAudioLevel())}catch(t){this.uiStateManager.showError(Na(t))}}handleStreamStop(){this.uiStateManager.handleStreamStop(()=>this.controller.stopAudioLevelTracking())}handleRecordingStart(){if(this.showSettings){this.showSettings=!1;const e=this.shadow.querySelector("#settingsPanel");if(!e)throw Error("Settings panel element not found");e.style.display="none"}this.uiStateManager.handleRecordingStart(this.controller.isPaused()),this.updateUIForFeatureFlags()}handleRecordingStop(e){return this.recordedBlob=e,this.uiStateManager.updateRecordingControlsAfterStop(),this.updateUIForFeatureFlags(),Promise.resolve()}updateRecordingTimer(e){this.uiStateManager.updateRecordingTimer(e)}updateMuteState(e){this.isMuted=e,this.uiStateManager.updateMuteState(e,(e,t)=>this.audioLevelVisualizer.updateBars(e,t),this.controller.getAudioLevel())}updateVideoPreview(e){this.uiStateManager.updateVideoPreview(e)}showError(e){this.uiStateManager.showError(e)}extractErrorMessage(e){return Na(e)}getStreamManager(){return this.controller.getStreamManager()}getShadowRoot(){return this.shadow}getController(){return this.controller}getUIStateManager(){return this.uiStateManager}getDeviceManager(){return this.deviceManager}getAudioLevelVisualizer(){return this.audioLevelVisualizer}getRecordedBlob(){return this.recordedBlob}setRecordedBlob(e){this.recordedBlob=e}getProcessedBlob(){return this.processedBlob}setProcessedBlob(e){this.processedBlob=e}getIsProcessing(){return this.isProcessing}setIsProcessing(e){this.isProcessing=e}getIsMuted(){return this.isMuted}setIsMuted(e){this.isMuted=e}getShowSettings(){return this.showSettings}setShowSettings(e){this.showSettings=e}getUserMetadata(){return this.userMetadata}getNormalizedBackendUrl(e){return Fs(e)}updateFeatureFlags(){const e=this.getAttribute("enable-source-switching");this.enableSourceSwitching=null===e||"false"!==e;const t=this.getAttribute("enable-mute");this.enableMute=null===t||"false"!==t;const r=this.getAttribute("enable-pause");this.enablePause=null===r||"false"!==r;const i=this.getAttribute("enable-device-change");this.enableDeviceChange=null===i||"false"!==i}initializeUIState(){const e=this.shadow.querySelector("#muteButton"),t=this.shadow.querySelector("#pauseButton"),r=this.shadow.querySelector("#resumeButton"),i=this.shadow.querySelector("#switchSourceButton"),a=this.shadow.querySelector("#stopButton"),s=this.shadow.querySelector("#settingsButton");e&&(e.style.display="none"),t&&(t.style.display="none"),r&&(r.style.display="none"),i&&(i.style.display="none"),a&&(a.style.display="none"),s&&(s.style.display=this.enableDeviceChange?"flex":"none")}updateUIForFeatureFlags(){const e=this.controller.getRecordingState(),t="recording"===e||"paused"===e,r=this.controller.isPaused();this.updateButtonVisibility("#switchSourceButton",t&&this.enableSourceSwitching),this.updateButtonVisibility("#muteButton",t&&this.enableMute),this.updateButtonVisibility("#pauseButton",t&&this.enablePause&&!r),this.updateButtonVisibility("#resumeButton",t&&this.enablePause&&r),this.updateButtonVisibility("#settingsButton",!t&&this.enableDeviceChange)}updateButtonVisibility(e,t){const r=this.shadow.querySelector(e);r&&(r.style.display=t?"flex":"none")}getEnableSourceSwitching(){return this.enableSourceSwitching}getEnableMute(){return this.enableMute}getEnablePause(){return this.enablePause}getEnableDeviceChange(){return this.enableDeviceChange}};Os.observedAttributes=["api-key","backend-url","countdown-duration","max-recording-time","user-metadata","enable-source-switching","enable-mute","enable-pause","enable-device-change"];let Us=Os;return customElements.get("vidtreo-recorder")||customElements.define("vidtreo-recorder",Us),e.VidtreoRecorder=Us,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),e}({});
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vidtreo/recorder-wc",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Web component for @vidtreo/recorder - video recording SDK",
|
|
6
|
+
"main": "./dist/vidtreo-recorder.js",
|
|
7
|
+
"files": [
|
|
8
|
+
"dist"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"build": "vite build --config vite.wc.config.ts",
|
|
12
|
+
"build:dev": "vite build --config vite.wc.config.ts --mode development",
|
|
13
|
+
"dev": "vite --config demo/vite.config.ts",
|
|
14
|
+
"demo": "vite --config demo/vite.config.ts",
|
|
15
|
+
"prepublishOnly": "npm run build"
|
|
16
|
+
},
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=18.0.0"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"video",
|
|
22
|
+
"recording",
|
|
23
|
+
"web-component",
|
|
24
|
+
"custom-element"
|
|
25
|
+
],
|
|
26
|
+
"author": "cfonseca@vidtreo.com",
|
|
27
|
+
"license": "MIT",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@vidtreo/recorder": "workspace:*"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "^24.10.1",
|
|
33
|
+
"autoprefixer": "^10.4.22",
|
|
34
|
+
"postcss": "^8.5.6",
|
|
35
|
+
"terser": "^5.44.1",
|
|
36
|
+
"vite": "^7.2.4"
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
}
|
|
41
|
+
}
|