@1agh/maude 0.58.1 → 0.58.3
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/apps/studio/.ai/cache/_stats.json +1 -1
- package/apps/studio/acp/bridge.ts +165 -15
- package/apps/studio/annotations-bindings.ts +83 -4
- package/apps/studio/api.ts +6 -1
- package/apps/studio/bin/_fetch-asset.mjs +169 -5
- package/apps/studio/bin/_import-asset.mjs +72 -0
- package/apps/studio/bin/_import-figma.mjs +1121 -0
- package/apps/studio/bin/_video-playwright.mjs +86 -3
- package/apps/studio/bin/import-figma.sh +38 -0
- package/apps/studio/bin/read-annotations.mjs +11 -1
- package/apps/studio/bun.lock +16 -22
- package/apps/studio/canvas-edit.ts +29 -5
- package/apps/studio/client/app.jsx +129 -23
- package/apps/studio/client/export-center.jsx +42 -4
- package/apps/studio/client/panels/ChatPanel.jsx +25 -2
- package/apps/studio/client/panels/CloudBar.jsx +92 -1
- package/apps/studio/client/panels/FigmaImportPanel.jsx +264 -0
- package/apps/studio/client/panels/GitPanel.jsx +26 -6
- package/apps/studio/client/panels/SettingsPanel.jsx +181 -0
- package/apps/studio/client/panels/SetupChecklist.jsx +26 -2
- package/apps/studio/client/panels/TimelinePanel.jsx +2 -2
- package/apps/studio/client/panels/timeline-parse.js +3 -3
- package/apps/studio/client/styles/3-shell-maude.css +7 -0
- package/apps/studio/client/styles/4-components.css +134 -0
- package/apps/studio/client/styles/6-acp-chat.css +12 -0
- package/apps/studio/clip-ops.ts +93 -17
- package/apps/studio/cloud/endpoints.ts +78 -10
- package/apps/studio/cloud/renew.ts +183 -0
- package/apps/studio/context.ts +2 -1
- package/apps/studio/dist/client.bundle.js +1491 -1491
- package/apps/studio/dist/runtime/@remotion_media.js +56 -136
- package/apps/studio/dist/runtime/@remotion_player.js +18 -18
- package/apps/studio/dist/runtime/@remotion_transitions.js +9 -9
- package/apps/studio/dist/runtime/@remotion_transitions_clock-wipe.js +1 -1
- package/apps/studio/dist/runtime/remotion.js +12 -12
- package/apps/studio/dist/styles.css +1 -1
- package/apps/studio/exporters/_browser-bundles.ts +20 -6
- package/apps/studio/exporters/_runtime.ts +19 -0
- package/apps/studio/exporters/degraded.ts +92 -0
- package/apps/studio/exporters/index.ts +5 -0
- package/apps/studio/exporters/jobs.ts +19 -0
- package/apps/studio/exporters/unsupported-media.ts +170 -0
- package/apps/studio/exporters/video-encode-lib.ts +27 -1
- package/apps/studio/exporters/video-render-lib.ts +6 -0
- package/apps/studio/exporters/video.ts +62 -1
- package/apps/studio/figma/assets.test.ts +372 -0
- package/apps/studio/figma/assets.ts +398 -0
- package/apps/studio/figma/client.test.ts +395 -0
- package/apps/studio/figma/client.ts +513 -0
- package/apps/studio/figma/comments-to-strokes.test.ts +194 -0
- package/apps/studio/figma/comments-to-strokes.ts +173 -0
- package/apps/studio/figma/endpoints.ts +200 -0
- package/apps/studio/figma/sanitize.test.ts +256 -0
- package/apps/studio/figma/sanitize.ts +315 -0
- package/apps/studio/figma/style-map.ts +352 -0
- package/apps/studio/figma/to-artboard.test.ts +808 -0
- package/apps/studio/figma/to-artboard.ts +701 -0
- package/apps/studio/figma/to-render.test.ts +180 -0
- package/apps/studio/figma/to-render.ts +306 -0
- package/apps/studio/figma/to-strokes-roundtrip.test.ts +152 -0
- package/apps/studio/figma/to-strokes.test.ts +705 -0
- package/apps/studio/figma/to-strokes.ts +749 -0
- package/apps/studio/figma/to-tokens.test.ts +321 -0
- package/apps/studio/figma/to-tokens.ts +305 -0
- package/apps/studio/figma/types.ts +539 -0
- package/apps/studio/figma/url.test.ts +167 -0
- package/apps/studio/figma/url.ts +160 -0
- package/apps/studio/http.ts +129 -0
- package/apps/studio/sync/asset-push.ts +124 -0
- package/apps/studio/sync/canvas-path.ts +329 -0
- package/apps/studio/sync/codec.ts +42 -0
- package/apps/studio/sync/connection-state.ts +11 -0
- package/apps/studio/sync/hub-link.ts +63 -7
- package/apps/studio/sync/hubs-config.ts +31 -3
- package/apps/studio/sync/index.ts +755 -32
- package/apps/studio/sync/migrate-flat-fallback.ts +121 -0
- package/apps/studio/sync/presentation.ts +45 -1
- package/apps/studio/sync/projection.ts +11 -1
- package/apps/studio/sync/remote-docs.ts +122 -15
- package/apps/studio/sync/supervisor.ts +5 -1
- package/apps/studio/sync/workspace-signin.ts +7 -3
- package/apps/studio/test/acp-bridge-lifetime.test.ts +106 -0
- package/apps/studio/test/annotations-bindings.test.ts +150 -12
- package/apps/studio/test/canvas-create-api.test.ts +4 -1
- package/apps/studio/test/canvas-origin-gate.test.ts +13 -0
- package/apps/studio/test/capture-determinism-shape.test.ts +135 -0
- package/apps/studio/test/clip-addressing.test.ts +6 -1
- package/apps/studio/test/clip-ops.test.ts +5 -1
- package/apps/studio/test/cloud-endpoints.test.ts +96 -0
- package/apps/studio/test/cloud-renew.test.ts +205 -0
- package/apps/studio/test/cloud-shell-surfaces.test.ts +11 -2
- package/apps/studio/test/comment-relay-origin-gate.test.ts +117 -0
- package/apps/studio/test/comments-fs-rebroadcast.test.ts +155 -0
- package/apps/studio/test/exporters/degraded-propagation.test.ts +123 -0
- package/apps/studio/test/exporters/unsupported-media.test.ts +123 -0
- package/apps/studio/test/fetch-asset-gate.test.ts +189 -0
- package/apps/studio/test/figma-provenance.test.ts +108 -0
- package/apps/studio/test/figma-routes.test.ts +294 -0
- package/apps/studio/test/fixtures/mock-acp-agent-wedged.mjs +37 -0
- package/apps/studio/test/git-cloud-posture.test.ts +50 -0
- package/apps/studio/test/hub-link.test.ts +11 -0
- package/apps/studio/test/import-figma.test.ts +479 -0
- package/apps/studio/test/sync-asset-push.test.ts +124 -0
- package/apps/studio/test/sync-canvas-path.test.ts +200 -0
- package/apps/studio/test/sync-connection-state.test.ts +13 -0
- package/apps/studio/test/sync-hubs-config.test.ts +5 -0
- package/apps/studio/test/sync-migrate-flat-fallback.test.ts +98 -0
- package/apps/studio/test/sync-path-pull.test.ts +465 -0
- package/apps/studio/test/sync-presentation.test.ts +77 -0
- package/apps/studio/test/sync-remote-docs.test.ts +55 -3
- package/apps/studio/test/sync-runtime.test.ts +434 -1
- package/apps/studio/test/video-comp.test.ts +23 -1
- package/apps/studio/test/workspace-containment.test.ts +1 -0
- package/apps/studio/video-comp.tsx +70 -6
- package/apps/studio/whats-new.json +36 -0
- package/apps/studio/workspace-mode.ts +4 -0
- package/cli/commands/design.mjs +8 -0
- package/package.json +8 -8
- package/plugins/flow/.claude-plugin/config.schema.json +3 -3
|
@@ -1,214 +1,220 @@
|
|
|
1
|
-
var
|
|
1
|
+
var SZ=Object.defineProperty;var hZ=($,J)=>{for(var Y in J)SZ($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:(X)=>J[Y]=()=>X})};var EJ={};hZ(EJ,{getTargetSampleRate:()=>R8,experimental_Video:()=>lK,experimental_Audio:()=>mK,Video:()=>CZ,AudioForPreview:()=>qZ,Audio:()=>OZ});import{useMemo as E5,useState as U9}from"react";import{Freeze as j9,Internals as H8,Interactive as q9,Sequence as N9,useRemotionEnvironment as V9,useVideoConfig as _9}from"remotion";import{Internals as H9}from"remotion";import{useContext as N7,useEffect as z9,useMemo as R9,useRef as K1,useState as V7}from"react";import{Internals as b1,Audio as A9,useBufferState as M9,useCurrentFrame as t5,useVideoConfig as F9}from"remotion";import{Internals as F7}from"remotion";import{Internals as RJ}from"remotion";/*!
|
|
2
2
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
3
3
|
*
|
|
4
4
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
5
5
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
6
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
|
-
*/function
|
|
7
|
+
*/function F($){if(!$)throw Error("Assertion failed.")}var J8=($)=>{let J=($%360+360)%360;if(J===0||J===90||J===180||J===270)return J;else throw Error(`Invalid rotation ${$}.`)},W0=($)=>{return $&&$[$.length-1]};var h=($)=>{let J=0;while($.readBits(1)===0&&J<32)J++;if(J>=32)throw Error("Invalid exponential-Golomb code.");return(1<<J)-1+$.readBits(J)},M1=($)=>{let J=h($);return(J&1)===0?-(J>>1):J+1>>1};var O0=($)=>{if($.constructor===Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else return new Uint8Array($)},l=($)=>{if($.constructor===DataView)return $;else if(ArrayBuffer.isView($))return new DataView($.buffer,$.byteOffset,$.byteLength);else return new DataView($)},A0=new TextDecoder;var yJ=($)=>{return Object.fromEntries(Object.entries($).map(([J,Y])=>[Y,J]))},A8={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},M8=yJ(A8),F8={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},L8=yJ(F8),w8={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},O8=yJ(w8);var k6=($)=>{return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)};class X1{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let $,J=new Promise((X)=>{let Q=!1;$=()=>{if(Q)return;X(),this.pending--,Q=!0}}),Y=this.currentPromise;return this.currentPromise=J,this.pending++,await Y,$}}var T7=/^[0-9a-fA-F]+$/,Y8=($)=>{return[...$].map((J)=>J.toString(16).padStart(2,"0")).join("")},v7=($)=>{F($.length%2===0);let J=new Uint8Array($.length/2);for(let Y=0;Y<$.length;Y+=2)J[Y/2]=parseInt($.slice(Y,Y+2),16);return J},SJ=($)=>{return $=$>>1&1431655765|($&1431655765)<<1,$=$>>2&858993459|($&858993459)<<2,$=$>>4&252645135|($&252645135)<<4,$=$>>8&16711935|($&16711935)<<8,$=$>>16&65535|($&65535)<<16,$>>>0},I1=($,J,Y)=>{let X=0,Q=$.length-1,Z=-1;while(X<=Q){let K=X+Q>>1,G=Y($[K]);if(G===J)Z=K,Q=K-1;else if(G<J)X=K+1;else Q=K-1}return Z},p=($,J,Y)=>{let X=0,Q=$.length-1,Z=-1;while(X<=Q){let K=X+(Q-X+1)/2|0;if(Y($[K])<=J)Z=K,X=K+1;else Q=K-1}return Z},hJ=($,J,Y)=>{let X=p($,Y(J),Y);$.splice(X+1,0,J)},q0=()=>{let $,J;return{promise:new Promise((X,Q)=>{$=X,J=Q}),resolve:$,reject:J}},u6=($,J)=>{let Y=$.indexOf(J);if(Y!==-1)$.splice(Y,1)},fJ=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return $[Y];return},B8=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return Y;return-1},x7=async function*($){if(Symbol.iterator in $)yield*$[Symbol.iterator]();else yield*$[Symbol.asyncIterator]()},I7=($)=>{if(!(Symbol.iterator in $)&&!(Symbol.asyncIterator in $))throw TypeError("Argument must be an iterable or async iterable.")},v0=($)=>{throw Error(`Unexpected value: ${$}`)},D8=($,J,Y)=>{let X=$.getUint8(J),Q=$.getUint8(J+1),Z=$.getUint8(J+2);if(Y)return X|Q<<8|Z<<16;else return X<<16|Q<<8|Z},y7=($,J,Y)=>{return D8($,J,Y)<<8>>8},C$=($,J,Y,X)=>{if(Y=Y>>>0,Y=Y&16777215,X)$.setUint8(J,Y&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y>>>16&255);else $.setUint8(J,Y>>>16&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y&255)};var m6=($,J)=>{return{async next(){let Y=await $.next();if(Y.done)return{value:void 0,done:!0};else return{value:J(Y.value),done:!1}},return(){return $.return()},throw(Y){return $.throw(Y)},[Symbol.asyncIterator](){return this}}},r0=($,J,Y)=>{return Math.max(J,Math.min(Y,$))},K0="und",y1=($)=>{let J=Math.round($);if(Math.abs($/J-1)<10*Number.EPSILON)return J;else return $},l6=($,J)=>{return Math.round($/J)*J},i8=($,J)=>{return Math.round($*J)/J},E$=($,J)=>{return Math.floor($/J)*J};var S7=($)=>{let J=0;while($)J++,$>>=1;return J},fZ=/^[a-z]{3}$/,a8=($)=>{return fZ.test($)},F1=1e6*(1+Number.EPSILON),h7=($,J)=>{let Y={...$,...J};if($.headers||J.headers){let X=$.headers?D$($.headers):{},Q=J.headers?D$(J.headers):{},Z={...X};Object.entries(Q).forEach(([K,G])=>{let W=Object.keys(Z).find((j)=>j.toLowerCase()===K.toLowerCase());if(W)delete Z[W];Z[K]=G}),Y.headers=Z}return Y},D$=($)=>{if($ instanceof Headers){let J={};return $.forEach((Y,X)=>{J[X]=Y}),J}if(Array.isArray($)){let J={};return $.forEach(([Y,X])=>{J[Y]=X}),J}return $},f7=async($,J,Y,X,Q)=>{let Z=0;while(!0)try{return await $(J,Y)}catch(K){if(Q())throw K;Z++;let G=X(Z,K,J);if(G===null)throw K;if(k._error("Retrying failed fetch. Error:",K),!Number.isFinite(G)||G<0)throw TypeError("Retry delay must be a non-negative finite number.");if(G>0)await J6(1000*G);if(Q())throw K}};class p6{constructor(){this.currentPromise=Promise.resolve()}call($){return this.currentPromise=this.currentPromise.then($)}}var TJ=null,C8=()=>{if(TJ!==null)return TJ;return TJ=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))},vJ=null,t8=()=>{if(vJ!==null)return vJ;return vJ=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox")},xJ=null,d6=()=>{if(xJ!==null)return xJ;return xJ=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))},IJ=null,g7=()=>{if(IJ!==null)return IJ;if(typeof navigator>"u")return null;let $=/\bChrome\/(\d+)/.exec(navigator.userAgent);if(!$)return null;return IJ=Number($[1])},E8=($,J)=>{return $!==-1?$:J},P$=($,J,Y,X)=>{return $<=X&&Y<=J};var c6=($)=>{let J=atob($),Y=new Uint8Array(J.length);for(let X=0;X<J.length;X++)Y[X]=J.charCodeAt(X);return Y};var gJ=($,J)=>{if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if($[Y]!==J[Y])return!1;return!0},e8=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},n6=($)=>{return typeof $==="number"&&!Number.isNaN($)},U1=($,J)=>{if(J.includes("://"))return J;if($.includes("://")){let G=$.indexOf("?");if(G!==-1)$=$.slice(0,G)}let Y;if(J.startsWith("/")){let G=$.indexOf("://");if(G===-1)Y=J;else{let W=$.indexOf("/",G+3);if(W===-1)Y=$+J;else Y=$.slice(0,W)+J}}else{let G=$.lastIndexOf("/");if(G===-1)Y=J;else Y=$.slice(0,G+1)+J}let X="",Q=Y.indexOf("://");if(Q!==-1){let G=Y.indexOf("/",Q+3);if(G!==-1)X=Y.slice(0,G),Y=Y.slice(G)}let Z=Y.split("/"),K=[];for(let G of Z)if(G==="..")K.pop();else if(G!==".")K.push(G);return X+K.join("/")},P8=($,J)=>{let Y=0;for(let X=0;X<$.length;X++)if(J($[X]))Y++;return Y},$6=($,J)=>{let Y=-1,X=1/0;for(let Q=0;Q<$.length;Q++){let Z=J($[Q]);if(Z<X)X=Z,Y=Q}return Y};var b8=($)=>{F(Number.isInteger($.num)),F(Number.isInteger($.den)),F($.den!==0);let J=Math.abs($.num),Y=Math.abs($.den);while(Y!==0){let Q=J%Y;J=Y,Y=Q}let X=J||1;return{num:$.num/X,den:$.den/X}},kJ=($,J)=>{if(typeof $!=="object"||!$)throw TypeError(`${J} must be an object.`);if(!Number.isInteger($.left)||$.left<0)throw TypeError(`${J}.left must be a non-negative integer.`);if(!Number.isInteger($.top)||$.top<0)throw TypeError(`${J}.top must be a non-negative integer.`);if(!Number.isInteger($.width)||$.width<0)throw TypeError(`${J}.width must be a non-negative integer.`);if(!Number.isInteger($.height)||$.height<0)throw TypeError(`${J}.height must be a non-negative integer.`)};var J6=($)=>{return new Promise((J)=>setTimeout(J,$))};class L1{constructor(){this._listeners=new Map}on($,J,Y){if(!this._listeners.has($))this._listeners.set($,new Set);let X={fn:J,once:Y?.once??!1};return this._listeners.get($).add(X),()=>{this._listeners.get($)?.delete(X)}}_emit(...$){let[J,Y]=$,X=this._listeners.get(J);if(!X)return;for(let Q of X){try{Q.fn(Y)}catch(Z){console.error(Z)}if(Q.once)X.delete(Q)}}}/*!
|
|
8
8
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
9
9
|
*
|
|
10
10
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
11
11
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
12
12
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
13
|
-
*/class
|
|
13
|
+
*/var j1;(function($){$[$.Silent=0]="Silent",$[$.Errors=1]="Errors",$[$.Warnings=2]="Warnings",$[$.Info=3]="Info"})(j1||(j1={}));class k{constructor(){}static get level(){return k._level}static set level($){if($!==j1.Silent&&$!==j1.Errors&&$!==j1.Warnings&&$!==j1.Info)throw TypeError("Invalid log level. Use one of the values of the LogLevel enum.");k._level=$}static get _emitter(){return k._emitterInstance??=new L1}static on($,J,Y){return k._emitter.on($,J,Y)}static _error(...$){if(k._emitter._emit("error",$),k._level>=j1.Errors)console.error(...$)}static _warn(...$){if(k._emitter._emit("warn",$),k._level>=j1.Warnings)console.warn(...$)}static _info(...$){if(k._emitter._emit("info",$),k._level>=j1.Info)console.info(...$)}}k._level=j1.Info;k._emitterInstance=null;/*!
|
|
14
14
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
15
15
|
*
|
|
16
16
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
17
17
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
18
18
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
19
|
-
*/class
|
|
19
|
+
*/class S1{constructor($,J){if(this.data=$,this.mimeType=J,!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(typeof J!=="string")throw TypeError("mimeType must be a string.")}}class s6{constructor($,J,Y,X){if(this.data=$,this.mimeType=J,this.name=Y,this.description=X,!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(J!==void 0&&typeof J!=="string")throw TypeError("mimeType, when provided, must be a string.");if(Y!==void 0&&typeof Y!=="string")throw TypeError("name, when provided, must be a string.");if(X!==void 0&&typeof X!=="string")throw TypeError("description, when provided, must be a string.")}}var x0={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};/*!
|
|
20
20
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
21
21
|
*
|
|
22
22
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
23
23
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
24
24
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
25
|
-
*/
|
|
25
|
+
*/class n{constructor($){this.bytes=$,this.pos=0}seekToByte($){this.pos=8*$}readBit(){let $=Math.floor(this.pos/8),J=this.bytes[$]??0,Y=7-(this.pos&7),X=(J&1<<Y)>>Y;return this.pos++,X}readBits($){if($===1)return this.readBit();let J=0;for(let Y=0;Y<$;Y++)J<<=1,J|=this.readBit();return J}writeBits($,J){let Y=this.pos+$;for(let X=this.pos;X<Y;X++){let Q=Math.floor(X/8),Z=this.bytes[Q],K=7-(X&7);Z&=~(1<<K),Z|=(J&1<<Y-X-1)>>Y-X-1<<K,this.bytes[Q]=Z}this.pos=Y}readAlignedByte(){if(this.pos%8!==0)throw Error("Bitstream is not byte-aligned.");let $=this.pos/8,J=this.bytes[$]??0;return this.pos+=8,J}skipBits($){this.pos+=$}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let $=new n(this.bytes);return $.pos=this.pos,$}}/*!
|
|
26
26
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
27
27
|
*
|
|
28
28
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
29
29
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
30
30
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
31
|
-
*/var
|
|
31
|
+
*/var h1=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],T8=[-1,1,2,3,4,5,6,8],v8=($)=>{if(!$||$.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let J=new n($),Y=J.readBits(5);if(Y===31)Y=32+J.readBits(6);let X=J.readBits(4),Q=null;if(X===15)Q=J.readBits(24);else if(X<h1.length)Q=h1[X];let Z=J.readBits(4),K=null;if(Z>=1&&Z<=7)K=T8[Z];return{objectType:Y,frequencyIndex:X,sampleRate:Q,channelConfiguration:Z,numberOfChannels:K}};/*!
|
|
32
32
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
33
33
|
*
|
|
34
34
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
35
35
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
36
36
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
37
|
-
*/var
|
|
37
|
+
*/var f1=["avc","hevc","vp9","av1","vp8","prores"],S0=["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"],b$=["aac","opus","mp3","vorbis","flac","ac3","eac3"],g1=[...b$,...S0];var uJ=[{maxMacroblocks:99,maxBitrate:64000,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192000,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384000,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768000,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2000000,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4000000,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4000000,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14000000,maxDpbMbs:18000,level:31},{maxMacroblocks:5120,maxBitrate:20000000,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:20000000,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:50000000,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:50000000,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135000000,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:240000000,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:240000000,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:240000000,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:480000000,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:800000000,maxDpbMbs:696320,level:62}];var x8=[{maxPictureSize:36864,maxBitrate:200000,level:10},{maxPictureSize:73728,maxBitrate:800000,level:11},{maxPictureSize:122880,maxBitrate:1800000,level:20},{maxPictureSize:245760,maxBitrate:3600000,level:21},{maxPictureSize:552960,maxBitrate:7200000,level:30},{maxPictureSize:983040,maxBitrate:12000000,level:31},{maxPictureSize:2228224,maxBitrate:18000000,level:40},{maxPictureSize:2228224,maxBitrate:30000000,level:41},{maxPictureSize:8912896,maxBitrate:60000000,level:50},{maxPictureSize:8912896,maxBitrate:120000000,level:51},{maxPictureSize:8912896,maxBitrate:180000000,level:52},{maxPictureSize:35651584,maxBitrate:180000000,level:60},{maxPictureSize:35651584,maxBitrate:240000000,level:61},{maxPictureSize:35651584,maxBitrate:480000000,level:62}];var k7=".01.01.01.01.00",u7=".0.110.01.01.01.0",Y6=["ap4x","ap4h","apch","apcn","apcs","apco"];var X6=($)=>{let{codec:J,codecDescription:Y,colorSpace:X,avcCodecInfo:Q,hevcCodecInfo:Z,vp9CodecInfo:K,av1CodecInfo:G,proresFormat:W}=$;if(J==="avc"){if(F($.avcType!==null),Q){let j=new Uint8Array([Q.avcProfileIndication,Q.profileCompatibility,Q.avcLevelIndication]);return`avc${$.avcType}.${Y8(j)}`}if(!Y||Y.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${$.avcType}.${Y8(Y.subarray(1,4))}`}else if(J==="hevc"){let j,U,q,N,_,V;if(Z)j=Z.generalProfileSpace,U=Z.generalProfileIdc,q=SJ(Z.generalProfileCompatibilityFlags),N=Z.generalTierFlag,_=Z.generalLevelIdc,V=[...Z.generalConstraintIndicatorFlags];else{if(!Y||Y.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let R=l(Y),H=R.getUint8(1);j=H>>6&3,U=H&31,q=SJ(R.getUint32(2)),N=H>>5&1,_=R.getUint8(12),V=[];for(let A=0;A<6;A++)V.push(R.getUint8(6+A))}let z="hev1.";z+=["","A","B","C"][j]+U,z+=".",z+=q.toString(16).toUpperCase(),z+=".",z+=N===0?"L":"H",z+=_;while(V.length>0&&V[V.length-1]===0)V.pop();if(V.length>0)z+=".",z+=V.map((R)=>R.toString(16).toUpperCase()).join(".");return z}else if(J==="vp8")return"vp8";else if(J==="vp9"){if(!K){let A=$.width*$.height,M=W0(x8).level;for(let L of x8)if(A<=L.maxPictureSize){M=L.level;break}return`vp09.00.${M.toString().padStart(2,"0")}.08`}let j=K.profile.toString().padStart(2,"0"),U=K.level.toString().padStart(2,"0"),q=K.bitDepth.toString().padStart(2,"0"),N=K.chromaSubsampling.toString().padStart(2,"0"),_=K.colourPrimaries.toString().padStart(2,"0"),V=K.transferCharacteristics.toString().padStart(2,"0"),z=K.matrixCoefficients.toString().padStart(2,"0"),R=K.videoFullRangeFlag.toString().padStart(2,"0"),H=`vp09.${j}.${U}.${q}.${N}`;if(H+=`.${_}.${V}.${z}.${R}`,H.endsWith(k7))H=H.slice(0,-k7.length);return H}else if(J==="av1"){if(!G){let L=$.width*$.height,w=W0(x8).level;for(let O of x8)if(L<=O.maxPictureSize){w=O.level;break}return`av01.0.${w.toString().padStart(2,"0")}M.08`}let j=G.profile,U=G.level.toString().padStart(2,"0"),q=G.tier?"H":"M",N=G.bitDepth.toString().padStart(2,"0"),_=G.monochrome?"1":"0",V=100*G.chromaSubsamplingX+10*G.chromaSubsamplingY+1*(G.chromaSubsamplingX&&G.chromaSubsamplingY?G.chromaSamplePosition:0),z=X?.primaries?A8[X.primaries]:1,R=X?.transfer?F8[X.transfer]:1,H=X?.matrix?w8[X.matrix]:1,A=X?.fullRange?1:0,M=`av01.${j}.${U}${q}.${N}`;if(M+=`.${_}.${V.toString().padStart(3,"0")}`,M+=`.${z.toString().padStart(2,"0")}`,M+=`.${R.toString().padStart(2,"0")}`,M+=`.${H.toString().padStart(2,"0")}`,M+=`.${A}`,M.endsWith(u7))M=M.slice(0,-u7.length);return M}else if(J==="prores")return W??"apch";else if(J!==null)v0(J);throw TypeError(`Unhandled codec '${J}'.`)};var Z6=($)=>{let{codec:J,codecDescription:Y,aacCodecInfo:X}=$;if(J==="aac"){if(!X)throw TypeError("AAC codec info must be provided.");if(X.isMpeg2)return"mp4a.67";else{let Q;if(X.objectType!==null)Q=X.objectType;else Q=v8(Y).objectType;return`mp4a.40.${Q}`}}else if(J==="mp3")return"mp3";else if(J==="opus")return"opus";else if(J==="vorbis")return"vorbis";else if(J==="flac")return"flac";else if(J==="ac3")return"ac-3";else if(J==="eac3")return"ec-3";else if(J&&S0.includes(J))return J;throw TypeError(`Unhandled codec '${J}'.`)};var k1=48000,m7=/^pcm-([usf])(\d+)(be)?$/,u1=($)=>{if(F(S0.includes($)),$==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};else if($==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let J=m7.exec($);F(J);let Y;if(J[1]==="u")Y="unsigned";else if(J[1]==="s")Y="signed";else Y="float";let X=Number(J[2])/8,Q=J[3]!=="be";return{dataType:Y,sampleSize:X,littleEndian:Q,silentValue:$==="pcm-u8"?128:0}},X8=($)=>{if($.startsWith("avc1")||$.startsWith("avc3"))return"avc";else if($.startsWith("hev1")||$.startsWith("hvc1"))return"hevc";else if($==="vp8")return"vp8";else if($.startsWith("vp09"))return"vp9";else if($.startsWith("av01"))return"av1";else if(Y6.includes($))return"prores";if($==="mp3"||$==="mp4a.69"||$==="mp4a.6B"||$==="mp4a.6b"||$==="mp4a.40.34")return"mp3";else if($.startsWith("mp4a.40.")||$==="mp4a.67")return"aac";else if($==="opus")return"opus";else if($==="vorbis")return"vorbis";else if($==="flac")return"flac";else if($==="ac-3"||$==="ac3")return"ac3";else if($==="ec-3"||$==="eac3")return"eac3";else if($==="ulaw")return"ulaw";else if($==="alaw")return"alaw";else if(m7.test($))return $;if($==="webvtt")return"webvtt";return null};var J3=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Y6];/*!
|
|
38
38
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
39
39
|
*
|
|
40
40
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
41
41
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
42
42
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
43
|
-
*/var
|
|
43
|
+
*/var w1=4,kZ=[44100,48000,32000],l7=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],K6=1483304551,o6=1231971951,p7=($,J,Y,X,Q)=>{if(J===0)return 0;else if(J===1)return Math.floor(144*Y/(X<<$))+Q;else if(J===2)return Math.floor(144*Y/X)+Q;else return(Math.floor(12*Y/X)+Q)*4},d7=($,J,Y,X)=>{if(J===0)return 0;else if(J===1)return 144*Y/(X<<$);else if(J===2)return 144*Y/X;else return 12*Y/X*4},G6=($,J)=>{return $===3?J===3?21:36:J===3?13:21},W6=($,J)=>{let Y=$>>>24,X=$>>>16&255,Q=$>>>8&255,Z=$&255;if(Y!==255&&X!==255&&Q!==255&&Z!==255)return{header:null,bytesAdvanced:4};if(Y!==255)return{header:null,bytesAdvanced:1};if((X&224)!==224)return{header:null,bytesAdvanced:1};let K=0,G=0;if(X&16)K=X&8?0:1;else K=1,G=1;let W=X>>3&3,j=X>>1&3,U=Q>>4&15,q=(Q>>2&3)%3,N=Q>>1&1,_=Z>>6&3,V=Z>>4&3,z=Z>>3&1,R=Z>>2&1,H=Z&3,A=l7[K*16*4+j*16+U];if(A===-1)return{header:null,bytesAdvanced:1};let M=A*1000,L=kZ[q]>>K+G,w=p7(K,j,M,L,N);if(J!==null&&J<w)return{header:null,bytesAdvanced:1};let O;if(W===3)O=j===3?384:1152;else if(j===3)O=384;else if(j===2)O=1152;else O=576;return{header:{totalSize:w,mpegVersionId:W,lowSamplingFrequency:K,layer:j,bitrate:M,frequencyIndex:q,sampleRate:L,channel:_,modeExtension:V,copyright:z,original:R,emphasis:H,audioSamplesInFrame:O},bytesAdvanced:1}};var T$=($)=>{let J=2130706432,Y=0;while(J!==0)Y>>=1,Y|=$&J,J>>=8;return Y},Q6;(function($){$[$.FrameCount=1]="FrameCount",$[$.FileSize=2]="FileSize",$[$.Toc=4]="Toc"})(Q6||(Q6={}));var Z8=($)=>{return $===3?1:2};/*!
|
|
44
44
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
45
45
|
*
|
|
46
46
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
47
47
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
48
48
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
49
|
-
*/var S0;(function($){$[$.NON_IDR_SLICE=1]="NON_IDR_SLICE",$[$.SLICE_DPA=2]="SLICE_DPA",$[$.SLICE_DPB=3]="SLICE_DPB",$[$.SLICE_DPC=4]="SLICE_DPC",$[$.IDR=5]="IDR",$[$.SEI=6]="SEI",$[$.SPS=7]="SPS",$[$.PPS=8]="PPS",$[$.AUD=9]="AUD",$[$.SPS_EXT=13]="SPS_EXT"})(S0||(S0={}));var z0;(function($){$[$.RASL_N=8]="RASL_N",$[$.RASL_R=9]="RASL_R",$[$.BLA_W_LP=16]="BLA_W_LP",$[$.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",$[$.VPS_NUT=32]="VPS_NUT",$[$.SPS_NUT=33]="SPS_NUT",$[$.PPS_NUT=34]="PPS_NUT",$[$.AUD_NUT=35]="AUD_NUT",$[$.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",$[$.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(z0||(z0={}));var X6=function*($){let J=0,Y=-1;while(J<$.length-2){let X=$.indexOf(0,J);if(X===-1||X>=$.length-2)break;J=X;let Q=0;if(J+3<$.length&&$[J+1]===0&&$[J+2]===0&&$[J+3]===1)Q=4;else if($[J+1]===0&&$[J+2]===1)Q=3;if(Q===0){J++;continue}if(Y!==-1&&J>Y)yield{offset:Y,length:J-Y};Y=J+Q,J=Y}if(Y!==-1&&Y<$.length)yield{offset:Y,length:$.length-Y}},SJ=function*($,J){let Y=0,X=new DataView($.buffer,$.byteOffset,$.byteLength);while(Y+J<=$.length){let Q;if(J===1)Q=X.getUint8(Y);else if(J===2)Q=X.getUint16(Y,!1);else if(J===3)Q=M8(X,Y,!1);else L(J===4),Q=X.getUint32(Y,!1);Y+=J,yield{offset:Y,length:Q},Y+=Q}},hJ=($,J)=>{if(J.description){let Q=(_0(J.description)[4]&3)+1;return SJ($,Q)}else return X6($)},b8=($)=>{return $&31},C$=($)=>{let J=[],Y=$.length;for(let X=0;X<Y;X++)if(X+2<Y&&$[X]===0&&$[X+1]===0&&$[X+2]===3)J.push(0,0),X+=2;else J.push($[X]);return new Uint8Array(J)},yJ=new Uint8Array([0,0,0,1]),fJ=($)=>{let J=$.reduce((Q,Z)=>Q+yJ.byteLength+Z.byteLength,0),Y=new Uint8Array(J),X=0;for(let Q of $)Y.set(yJ,X),X+=yJ.byteLength,Y.set(Q,X),X+=Q.byteLength;return Y},gJ=($,J)=>{let Y=$.reduce((Z,K)=>Z+J+K.byteLength,0),X=new Uint8Array(Y),Q=0;for(let Z of $){let K=new DataView(X.buffer,X.byteOffset,X.byteLength);switch(J){case 1:K.setUint8(Q,Z.byteLength);break;case 2:K.setUint16(Q,Z.byteLength,!1);break;case 3:M$(K,Q,Z.byteLength,!1);break;case 4:K.setUint32(Q,Z.byteLength,!1);break}Q+=J,X.set(Z,Q),Q+=Z.byteLength}return X},n7=($,J)=>{if(J.description){let Q=(_0(J.description)[4]&3)+1;return gJ($,Q)}else return fJ($)},p6=($)=>{try{let J=[],Y=[],X=[];for(let G of X6($)){let W=$.subarray(G.offset,G.offset+G.length),j=b8(W[0]);if(j===S0.SPS)J.push(W);else if(j===S0.PPS)Y.push(W);else if(j===S0.SPS_EXT)X.push(W)}if(J.length===0)return null;if(Y.length===0)return null;let Q=J[0],Z=d6(Q);L(Z!==null);let K=Z.profileIdc===100||Z.profileIdc===110||Z.profileIdc===122||Z.profileIdc===144;return{configurationVersion:1,avcProfileIndication:Z.profileIdc,profileCompatibility:Z.constraintFlags,avcLevelIndication:Z.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:J,pictureParameterSets:Y,chromaFormat:K?Z.chromaFormatIdc:null,bitDepthLumaMinus8:K?Z.bitDepthLumaMinus8:null,bitDepthChromaMinus8:K?Z.bitDepthChromaMinus8:null,sequenceParameterSetExt:K?X:null}}catch(J){return console.error("Error building AVC Decoder Configuration Record:",J),null}};var kJ=($)=>{try{let J=u($),Y=0,X=J.getUint8(Y++),Q=J.getUint8(Y++),Z=J.getUint8(Y++),K=J.getUint8(Y++),G=J.getUint8(Y++)&3,W=J.getUint8(Y++)&31,j=[];for(let _=0;_<W;_++){let N=J.getUint16(Y,!1);Y+=2,j.push($.subarray(Y,Y+N)),Y+=N}let U=J.getUint8(Y++),q=[];for(let _=0;_<U;_++){let N=J.getUint16(Y,!1);Y+=2,q.push($.subarray(Y,Y+N)),Y+=N}let V={configurationVersion:X,avcProfileIndication:Q,profileCompatibility:Z,avcLevelIndication:K,lengthSizeMinusOne:G,sequenceParameterSets:j,pictureParameterSets:q,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((Q===100||Q===110||Q===122||Q===144)&&Y+4<=$.length){let _=J.getUint8(Y++)&3,N=J.getUint8(Y++)&7,R=J.getUint8(Y++)&7,z=J.getUint8(Y++);V.chromaFormat=_,V.bitDepthLumaMinus8=N,V.bitDepthChromaMinus8=R;let H=[];for(let A=0;A<z;A++){let M=J.getUint16(Y,!1);Y+=2,H.push($.subarray(Y,Y+M)),Y+=M}V.sequenceParameterSetExt=H}return V}catch(J){return console.error("Error deserializing AVC Decoder Configuration Record:",J),null}},o7={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},d6=($)=>{try{let J=new c(C$($));if(J.skipBits(1),J.skipBits(2),J.readBits(5)!==7)return null;let X=J.readAlignedByte(),Q=J.readAlignedByte(),Z=J.readAlignedByte();y(J);let K=1,G=0,W=0,j=0;if(X===100||X===110||X===122||X===244||X===44||X===83||X===86||X===118||X===128){if(K=y(J),K===3)j=J.readBits(1);if(G=y(J),W=y(J),J.skipBits(1),J.readBits(1)){for(let E=0;E<(K!==3?8:12);E++)if(J.readBits(1)){let x=E<6?16:64,S=8,k=8;for(let m=0;m<x;m++){if(k!==0){let f=q1(J);k=(S+f+256)%256}S=k===0?S:k}}}}y(J);let U=y(J);if(U===0)y(J);else if(U===1){J.skipBits(1),q1(J),q1(J);let C=y(J);for(let E=0;E<C;E++)q1(J)}y(J),J.skipBits(1);let q=y(J),V=y(J),_=16*(q+1),N=16*(V+1),R=_,z=N,H=J.readBits(1);if(!H)J.skipBits(1);if(J.skipBits(1),J.readBits(1)){let C=y(J),E=y(J),v=y(J),x=y(J),S,k;if((j===0?K:0)===0)S=1,k=2-H;else{let f=K===3?1:2,n=K===1?2:1;S=f,k=n*(2-H)}R-=S*(C+E),z-=k*(v+x)}let M=2,F=2,O=2,B=0,D={num:1,den:1},w=null,P=null;if(J.readBits(1)){if(J.readBits(1)){let n=J.readBits(8);if(n===255)D={num:J.readBits(16),den:J.readBits(16)};else{let o=o7[n];if(o)D=o}}if(J.readBits(1))J.skipBits(1);if(J.readBits(1)){if(J.skipBits(3),B=J.readBits(1),J.readBits(1))M=J.readBits(8),F=J.readBits(8),O=J.readBits(8)}if(J.readBits(1))y(J),y(J);if(J.readBits(1))J.skipBits(32),J.skipBits(32),J.skipBits(1);let k=J.readBits(1);if(k)d7(J);let m=J.readBits(1);if(m)d7(J);if(k||m)J.skipBits(1);if(J.skipBits(1),J.readBits(1))J.skipBits(1),y(J),y(J),y(J),y(J),w=y(J),P=y(J)}if(w===null){L(P===null);let C=Q&16;if((X===44||X===86||X===100||X===110||X===122||X===244)&&C)w=0,P=0;else{let E=q+1,v=V+1,x=(2-H)*v,S=xJ.find((m)=>m.level>=Z)??K0(xJ),k=Math.min(Math.floor(S.maxDpbMbs/(E*x)),16);w=k,P=k}}return L(P!==null),{profileIdc:X,constraintFlags:Q,levelIdc:Z,frameMbsOnlyFlag:H,chromaFormatIdc:K,bitDepthLumaMinus8:G,bitDepthChromaMinus8:W,codedWidth:_,codedHeight:N,displayWidth:R,displayHeight:z,pixelAspectRatio:D,colourPrimaries:M,matrixCoefficients:O,transferCharacteristics:F,fullRangeFlag:B,numReorderFrames:w,maxDecFrameBuffering:P}}catch(J){return console.error("Error parsing AVC SPS:",J),null}},d7=($)=>{let J=y($);$.skipBits(4),$.skipBits(4);for(let Y=0;Y<=J;Y++)y($),y($),$.skipBits(1);$.skipBits(5),$.skipBits(5),$.skipBits(5),$.skipBits(5)},IZ=($,J)=>{if(J.description){let Q=(_0(J.description)[21]&3)+1;return gJ($,Q)}else return fJ($)},l6=($,J)=>{if(J.description){let Q=(_0(J.description)[21]&3)+1;return SJ($,Q)}else return X6($)},y1=($)=>{return $>>1&63},uJ=($)=>{try{let J=new c(C$($));J.skipBits(16),J.readBits(4);let Y=J.readBits(3),X=J.readBits(1),{general_profile_space:Q,general_tier_flag:Z,general_profile_idc:K,general_profile_compatibility_flags:G,general_constraint_indicator_flags:W,general_level_idc:j}=yZ(J,Y);y(J);let U=y(J),q=0;if(U===3)q=J.readBits(1);let V=y(J),_=y(J),N=V,R=_;if(J.readBits(1)){let E=y(J),v=y(J),x=y(J),S=y(J),k=1,m=1,f=q===0?U:0;if(f===1)k=2,m=2;else if(f===2)k=2,m=1;N-=(E+v)*k,R-=(x+S)*m}let z=y(J),H=y(J);y(J);let M=J.readBits(1)?0:Y,F=0;for(let E=M;E<=Y;E++)y(J),F=y(J),y(J);if(y(J),y(J),y(J),y(J),y(J),y(J),J.readBits(1)){if(J.readBits(1))SZ(J)}if(J.skipBits(1),J.skipBits(1),J.readBits(1))J.skipBits(4),J.skipBits(4),y(J),y(J),J.skipBits(1);let O=y(J);if(hZ(J,O),J.readBits(1)){let E=y(J);for(let v=0;v<E;v++)y(J),J.skipBits(1)}J.skipBits(1),J.skipBits(1);let B=2,D=2,w=2,P=0,T=0,C={num:1,den:1};if(J.readBits(1)){let E=gZ(J,Y);C=E.pixelAspectRatio,B=E.colourPrimaries,D=E.transferCharacteristics,w=E.matrixCoefficients,P=E.fullRangeFlag,T=E.minSpatialSegmentationIdc}return{displayWidth:N,displayHeight:R,pixelAspectRatio:C,colourPrimaries:B,transferCharacteristics:D,matrixCoefficients:w,fullRangeFlag:P,maxDecFrameBuffering:F+1,spsMaxSubLayersMinus1:Y,spsTemporalIdNestingFlag:X,generalProfileSpace:Q,generalTierFlag:Z,generalProfileIdc:K,generalProfileCompatibilityFlags:G,generalConstraintIndicatorFlags:W,generalLevelIdc:j,chromaFormatIdc:U,bitDepthLumaMinus8:z,bitDepthChromaMinus8:H,minSpatialSegmentationIdc:T}}catch(J){return console.error("Error parsing HEVC SPS:",J),null}},c6=($)=>{try{let J=[],Y=[],X=[],Q=[];for(let j of X6($)){let U=$.subarray(j.offset,j.offset+j.length),q=y1(U[0]);if(q===z0.VPS_NUT)J.push(U);else if(q===z0.SPS_NUT)Y.push(U);else if(q===z0.PPS_NUT)X.push(U);else if(q===z0.PREFIX_SEI_NUT||q===z0.SUFFIX_SEI_NUT)Q.push(U)}if(Y.length===0||X.length===0)return null;let Z=uJ(Y[0]);if(!Z)return null;let K=0;if(X.length>0){let j=X[0],U=new c(C$(j));if(U.skipBits(16),y(U),y(U),U.skipBits(1),U.skipBits(1),U.skipBits(3),U.skipBits(1),U.skipBits(1),y(U),y(U),q1(U),U.skipBits(1),U.skipBits(1),U.readBits(1))y(U);q1(U),q1(U),U.skipBits(1),U.skipBits(1),U.skipBits(1),U.skipBits(1);let q=U.readBits(1),V=U.readBits(1);if(!q&&!V)K=0;else if(q&&!V)K=2;else if(!q&&V)K=3;else K=0}let G=[...J.length?[{arrayCompleteness:1,nalUnitType:z0.VPS_NUT,nalUnits:J}]:[],...Y.length?[{arrayCompleteness:1,nalUnitType:z0.SPS_NUT,nalUnits:Y}]:[],...X.length?[{arrayCompleteness:1,nalUnitType:z0.PPS_NUT,nalUnits:X}]:[],...Q.length?[{arrayCompleteness:1,nalUnitType:y1(Q[0][0]),nalUnits:Q}]:[]];return{configurationVersion:1,generalProfileSpace:Z.generalProfileSpace,generalTierFlag:Z.generalTierFlag,generalProfileIdc:Z.generalProfileIdc,generalProfileCompatibilityFlags:Z.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:Z.generalConstraintIndicatorFlags,generalLevelIdc:Z.generalLevelIdc,minSpatialSegmentationIdc:Z.minSpatialSegmentationIdc,parallelismType:K,chromaFormatIdc:Z.chromaFormatIdc,bitDepthLumaMinus8:Z.bitDepthLumaMinus8,bitDepthChromaMinus8:Z.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:Z.spsMaxSubLayersMinus1+1,temporalIdNested:Z.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:G}}catch(J){return console.error("Error building HEVC Decoder Configuration Record:",J),null}},yZ=($,J)=>{let Y=$.readBits(2),X=$.readBits(1),Q=$.readBits(5),Z=0;for(let U=0;U<32;U++)Z=Z<<1|$.readBits(1);let K=new Uint8Array(6);for(let U=0;U<6;U++)K[U]=$.readBits(8);let G=$.readBits(8),W=[],j=[];for(let U=0;U<J;U++)W.push($.readBits(1)),j.push($.readBits(1));if(J>0)for(let U=J;U<8;U++)$.skipBits(2);for(let U=0;U<J;U++){if(W[U])$.skipBits(88);if(j[U])$.skipBits(8)}return{general_profile_space:Y,general_tier_flag:X,general_profile_idc:Q,general_profile_compatibility_flags:Z,general_constraint_indicator_flags:K,general_level_idc:G}},SZ=($)=>{for(let J=0;J<4;J++)for(let Y=0;Y<(J===3?2:6);Y++)if(!$.readBits(1))y($);else{let Q=Math.min(64,1<<4+(J<<1));if(J>1)q1($);for(let Z=0;Z<Q;Z++)q1($)}},hZ=($,J)=>{let Y=[];for(let X=0;X<J;X++)Y[X]=fZ($,X,J,Y)},fZ=($,J,Y,X)=>{let Q=0,Z=0,K=0;if(J!==0)Z=$.readBits(1);if(Z){if(J===Y){let W=y($);K=J-(W+1)}else K=J-1;$.readBits(1),y($);let G=X[K]??0;for(let W=0;W<=G;W++)if(!$.readBits(1))$.readBits(1);Q=X[K]}else{let G=y($),W=y($);for(let j=0;j<G;j++)y($),$.readBits(1);for(let j=0;j<W;j++)y($),$.readBits(1);Q=G+W}return Q},gZ=($,J)=>{let Y=2,X=2,Q=2,Z=0,K=0,G={num:1,den:1};if($.readBits(1)){let W=$.readBits(8);if(W===255)G={num:$.readBits(16),den:$.readBits(16)};else{let j=o7[W];if(j)G=j}}if($.readBits(1))$.readBits(1);if($.readBits(1)){if($.readBits(3),Z=$.readBits(1),$.readBits(1))Y=$.readBits(8),X=$.readBits(8),Q=$.readBits(8)}if($.readBits(1))y($),y($);if($.readBits(1),$.readBits(1),$.readBits(1),$.readBits(1))y($),y($),y($),y($);if($.readBits(1)){if($.readBits(32),$.readBits(32),$.readBits(1))y($);if($.readBits(1))kZ($,!0,J)}if($.readBits(1))$.readBits(1),$.readBits(1),$.readBits(1),K=y($),y($),y($),y($),y($);return{pixelAspectRatio:G,colourPrimaries:Y,transferCharacteristics:X,matrixCoefficients:Q,fullRangeFlag:Z,minSpatialSegmentationIdc:K}},kZ=($,J,Y)=>{let X=!1,Q=!1,Z=!1;if(J){if(X=$.readBits(1)===1,Q=$.readBits(1)===1,X||Q){if(Z=$.readBits(1)===1,Z)$.readBits(8),$.readBits(5),$.readBits(1),$.readBits(5);if($.readBits(4),$.readBits(4),Z)$.readBits(4);$.readBits(5),$.readBits(5),$.readBits(5)}}for(let K=0;K<=Y;K++){let G=$.readBits(1)===1,W=!0;if(!G)W=$.readBits(1)===1;let j=!1;if(W)y($);else j=$.readBits(1)===1;let U=1;if(!j)U=y($)+1;if(X)c7($,U,Z);if(Q)c7($,U,Z)}},c7=($,J,Y)=>{for(let X=0;X<J;X++){if(y($),y($),Y)y($),y($);$.readBits(1)}};var v0;(function($){$[$.audAllowed=0]="audAllowed",$[$.beforeFirstVcl=1]="beforeFirstVcl",$[$.afterFirstVcl=2]="afterFirstVcl",$[$.eoBitstreamAllowed=3]="eoBitstreamAllowed",$[$.noMoreDataAllowed=4]="noMoreDataAllowed"})(v0||(v0={}));var s7=($,J)=>{let Y=new Set,X=v0.audAllowed;for(let Z of l6($,J)){if(X===v0.noMoreDataAllowed){Y.add(Z.offset);continue}let K=y1($[Z.offset]);if(X===v0.eoBitstreamAllowed&&K!==37){Y.add(Z.offset);continue}let G=!1;if(K===35)if(X>v0.audAllowed)G=!0;else X=v0.beforeFirstVcl;else if(K<=31)if(X>v0.afterFirstVcl)G=!0;else X=v0.afterFirstVcl;else if(K===36)if(X!==v0.afterFirstVcl)G=!0;else X=v0.eoBitstreamAllowed;else if(K===37)if(X<v0.afterFirstVcl)G=!0;else X=v0.noMoreDataAllowed;else if(K===32||K===33||K===34||K===39||K>=41&&K<=44||K>=48&&K<=55)if(X>v0.beforeFirstVcl)G=!0;else X=v0.beforeFirstVcl;else if(K===38||K===40||K>=45&&K<=47||K>=56&&K<=63){if(X<v0.afterFirstVcl)G=!0}if(G)Y.add(Z.offset)}if(Y.size===0)return null;let Q=[];for(let Z of l6($,J))if(!Y.has(Z.offset))Q.push($.subarray(Z.offset,Z.offset+Z.length));return IZ(Q,J)},E$=($)=>{let J=new c($);if(J.readBits(2)!==2)return null;let X=J.readBits(1),Z=(J.readBits(1)<<1)+X;if(Z===3)J.skipBits(1);if(J.readBits(1)===1)return null;if(J.readBits(1)!==0)return null;if(J.skipBits(2),J.readBits(24)!==4817730)return null;let j=8;if(Z>=2)j=J.readBits(1)?12:10;let U=J.readBits(3),q=0,V=0;if(U!==7)if(V=J.readBits(1),Z===1||Z===3){let D=J.readBits(1),w=J.readBits(1);q=!D&&!w?3:D&&!w?2:1,J.skipBits(1)}else q=1;else q=3,V=1;let _=J.readBits(16),N=J.readBits(16),R=_+1,z=N+1,H=R*z,A=K0(E8).level;for(let B of E8)if(H<=B.maxPictureSize){A=B.level;break}return{profile:Z,level:A,bitDepth:j,chromaSubsampling:q,videoFullRangeFlag:V,colourPrimaries:U===2?1:U===1?6:2,transferCharacteristics:U===2?1:U===1?6:2,matrixCoefficients:U===7?0:U===2?1:U===1?6:2}},r7=function*($){let J=new c($),Y=()=>{let X=0;for(let Q=0;Q<8;Q++){let Z=J.readAlignedByte();if(X|=(Z&127)<<Q*7,!(Z&128))break;if(Q===7&&Z&128)return null}if(X>=4294967295)return null;return X};while(J.getBitsLeft()>=8){J.skipBits(1);let X=J.readBits(4),Q=J.readBits(1),Z=J.readBits(1);if(J.skipBits(1),Q)J.skipBits(8);let K;if(Z){let G=Y();if(G===null)return;K=G}else K=Math.floor(J.getBitsLeft()/8);L(J.pos%8===0),yield{type:X,data:$.subarray(J.pos/8,J.pos/8+K)},J.skipBits(K*8)}},P$=($)=>{for(let{type:J,data:Y}of r7($)){if(J!==1)continue;let X=new c(Y),Q=X.readBits(3),Z=X.readBits(1),K=X.readBits(1),G=0,W=0,j=0;if(K)G=X.readBits(5);else{if(X.readBits(1)){if(X.skipBits(32),X.skipBits(32),X.readBits(1))return null}let B=X.readBits(1);if(B)j=X.readBits(5),X.skipBits(32),X.skipBits(5),X.skipBits(5);let D=X.readBits(5);for(let w=0;w<=D;w++){X.skipBits(12);let P=X.readBits(5);if(w===0)G=P;if(P>7){let C=X.readBits(1);if(w===0)W=C}if(B){if(X.readBits(1)){let E=j+1;X.skipBits(E),X.skipBits(E),X.skipBits(1)}}if(X.readBits(1))X.skipBits(4)}}let U=X.readBits(4),q=X.readBits(4),V=U+1;X.skipBits(V);let _=q+1;X.skipBits(_);let N=0;if(K)N=0;else N=X.readBits(1);if(N)X.skipBits(4),X.skipBits(3);if(X.skipBits(1),X.skipBits(1),X.skipBits(1),!K){X.skipBits(1),X.skipBits(1),X.skipBits(1),X.skipBits(1);let O=X.readBits(1);if(O)X.skipBits(1),X.skipBits(1);let B=X.readBits(1),D=0;if(B)D=2;else D=X.readBits(1);if(D>0){if(!X.readBits(1))X.skipBits(1)}if(O)X.skipBits(3)}X.skipBits(1),X.skipBits(1),X.skipBits(1);let R=X.readBits(1),z=8;if(Q===2&&R)z=X.readBits(1)?12:10;else if(Q<=2)z=R?10:8;let H=0;if(Q!==1)H=X.readBits(1);let A=1,M=1,F=0;if(!H){if(Q===0)A=1,M=1;else if(Q===1)A=0,M=0;else if(z===12){if(A=X.readBits(1),A)M=X.readBits(1)}if(A&&M)F=X.readBits(2)}return{profile:Q,level:G,tier:W,bitDepth:z,monochrome:H,chromaSubsamplingX:A,chromaSubsamplingY:M,chromaSamplePosition:F}}return null},n6=($)=>{let J=u($),Y=J.getUint8(9),X=J.getUint16(10,!0),Q=J.getUint32(12,!0),Z=J.getInt16(16,!0),K=J.getUint8(18),G=null;if(K)G=$.subarray(19,21+Y);return{outputChannelCount:Y,preSkip:X,inputSampleRate:Q,outputGain:Z,channelMappingFamily:K,channelMappingTable:G}},uZ=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],i7=($)=>{let J=$[0]>>3;return{durationInSamples:uZ[J]}},mJ=($)=>{if($.length<7)throw Error("Setup header is too short.");if($[0]!==5)throw Error("Wrong packet type in Setup header.");if(String.fromCharCode(...$.slice(1,7))!=="vorbis")throw Error("Invalid packet signature in Setup header.");let Y=$.length,X=new Uint8Array(Y);for(let q=0;q<Y;q++)X[q]=$[Y-1-q];let Q=new c(X),Z=0;while(Q.getBitsLeft()>97)if(Q.readBits(1)===1){Z=Q.pos;break}if(Z===0)throw Error("Invalid Setup header: framing bit not found.");let K=0,G=!1,W=0;while(Q.getBitsLeft()>=97){let q=Q.pos,V=Q.readBits(8),_=Q.readBits(16),N=Q.readBits(16);if(V>63||_!==0||N!==0){Q.pos=q;break}if(Q.skipBits(1),K++,K>64)break;if(Q.clone().readBits(6)+1===K)G=!0,W=K}if(!G)throw Error("Invalid Setup header: mode header not found.");if(W>63)throw Error(`Unsupported mode count: ${W}.`);let j=W;Q.pos=0,Q.skipBits(Z);let U=Array(j).fill(0);for(let q=j-1;q>=0;q--)Q.skipBits(40),U[q]=Q.readBits(1);return{modeBlockflags:U}},T8=($,J,Y)=>{switch($){case"avc":{for(let X of hJ(Y,J)){let Q=Y[X.offset],Z=b8(Q);if(Z>=S0.NON_IDR_SLICE&&Z<=S0.SLICE_DPC)return"delta";if(Z===S0.IDR)return"key";if(Z===S0.SEI&&(!h6()||f7()>=144)){let K=Y.subarray(X.offset,X.offset+X.length),G=C$(K),W=1;do{let j=0;while(!0){let V=G[W++];if(V===void 0)break;if(j+=V,V<255)break}let U=0;while(!0){let V=G[W++];if(V===void 0)break;if(U+=V,V<255)break}if(j===6){let V=new c(G);V.pos=8*W;let _=y(V),N=V.readBits(1);if(_===0&&N===1)return"key"}W+=U}while(W<G.length-1)}}return"delta"}case"hevc":{for(let X of l6(Y,J)){let Q=y1(Y[X.offset]);if(Q<z0.BLA_W_LP)return"delta";if(Q<=z0.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(Y[0]&1)===0?"key":"delta";case"vp9":{let X=new c(Y);if(X.readBits(2)!==2)return null;let Q=X.readBits(1);if((X.readBits(1)<<1)+Q===3)X.skipBits(1);if(X.readBits(1))return null;return X.readBits(1)===0?"key":"delta"}case"av1":{let X=!1;for(let{type:Q,data:Z}of r7(Y))if(Q===1){let K=new c(Z);K.skipBits(4),X=!!K.readBits(1)}else if(Q===3||Q===6||Q===7){if(X)return"key";let K=new c(Z);if(K.readBits(1))return null;return K.readBits(2)===0?"key":"delta"}return null}default:T0($),L(!1)}},_1;(function($){$[$.STREAMINFO=0]="STREAMINFO",$[$.VORBIS_COMMENT=4]="VORBIS_COMMENT",$[$.PICTURE=6]="PICTURE"})(_1||(_1={}));var o6=($,J)=>{let Y=u($),X=0,Q=Y.getUint32(X,!0);X+=4;let Z=H0.decode($.subarray(X,X+Q));if(X+=Q,Q>0)J.raw??={},J.raw.vendor??=Z;let K=Y.getUint32(X,!0);X+=4;for(let G=0;G<K;G++){let W=Y.getUint32(X,!0);X+=4;let j=H0.decode($.subarray(X,X+W));X+=W;let U=j.indexOf("=");if(U===-1)continue;let q=j.slice(0,U).toUpperCase(),V=j.slice(U+1);switch(J.raw??={},J.raw[q]??=V,q){case"TITLE":J.title??=V;break;case"DESCRIPTION":J.description??=V;break;case"ARTIST":J.artist??=V;break;case"ALBUM":J.album??=V;break;case"ALBUMARTIST":J.albumArtist??=V;break;case"COMMENT":J.comment??=V;break;case"LYRICS":J.lyrics??=V;break;case"TRACKNUMBER":{let _=V.split("/"),N=Number.parseInt(_[0],10),R=_[1]&&Number.parseInt(_[1],10);if(Number.isInteger(N)&&N>0)J.trackNumber??=N;if(R&&Number.isInteger(R)&&R>0)J.tracksTotal??=R}break;case"TRACKTOTAL":{let _=Number.parseInt(V,10);if(Number.isInteger(_)&&_>0)J.tracksTotal??=_}break;case"DISCNUMBER":{let _=V.split("/"),N=Number.parseInt(_[0],10),R=_[1]&&Number.parseInt(_[1],10);if(Number.isInteger(N)&&N>0)J.discNumber??=N;if(R&&Number.isInteger(R)&&R>0)J.discsTotal??=R}break;case"DISCTOTAL":{let _=Number.parseInt(V,10);if(Number.isInteger(_)&&_>0)J.discsTotal??=_}break;case"DATE":{let _=new Date(V);if(!Number.isNaN(_.getTime()))J.date??=_}break;case"GENRE":J.genre??=V;break;case"METADATA_BLOCK_PICTURE":{let _=f6(V),N=u(_),R=N.getUint32(0,!1),z=N.getUint32(4,!1),H=String.fromCharCode(..._.subarray(8,8+z)),A=N.getUint32(8+z,!1),M=H0.decode(_.subarray(12+z,12+z+A)),F=N.getUint32(z+A+28),O=_.subarray(z+A+32,z+A+32+F);J.images??=[],J.images.push({data:O,mimeType:H,kind:R===3?"coverFront":R===4?"coverBack":"unknown",name:void 0,description:M||void 0})}break}}};var s6=[2,1,2,3,3,4,4,5],lJ=($)=>{if($.length<7)return null;if($[0]!==11||$[1]!==119)return null;let J=new c($);J.skipBits(16),J.skipBits(16);let Y=J.readBits(2);if(Y===3)return null;let X=J.readBits(6),Q=J.readBits(5);if(Q>8)return null;let Z=J.readBits(3),K=J.readBits(3);if((K&1)!==0&&K!==1)J.skipBits(2);if((K&4)!==0)J.skipBits(2);if(K===2)J.skipBits(2);let G=J.readBits(1),W=Math.floor(X/2);return{fscod:Y,bsid:Q,bsmod:Z,acmod:K,lfeon:G,bitRateCode:W}},a7=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],t7=1536,mZ=new Uint8Array([5,4,65,67,45,51]),lZ=new Uint8Array([5,4,69,65,67,51]),pJ=[1,2,3,6],dJ=($)=>{if($.length<6)return null;if($[0]!==11||$[1]!==119)return null;let J=new c($);J.skipBits(16);let Y=J.readBits(2);if(J.skipBits(3),Y!==0&&Y!==2)return null;let X=J.readBits(11),Q=J.readBits(2),Z=0,K;if(Q===3)Z=J.readBits(2),K=3;else K=J.readBits(2);let G=J.readBits(3),W=J.readBits(1),j=J.readBits(5);if(j<11||j>16)return null;let U=pJ[K],q;if(Q<3)q=P8[Q]/1000;else q=IJ[Z]/1000;return{dataRate:Math.round((X+1)*q/(U*16)),substreams:[{fscod:Q,fscod2:Z,bsid:j,bsmod:0,acmod:G,lfeon:W,numDepSub:0,chanLoc:0}]}},e7=($)=>{if($.length<2)return null;let J=new c($),Y=J.readBits(13),X=J.readBits(3),Q=[];for(let Z=0;Z<=X;Z++){if(Math.ceil(J.pos/8)+3>$.length)break;let K=J.readBits(2),G=J.readBits(5);J.skipBits(1),J.skipBits(1);let W=J.readBits(3),j=J.readBits(3),U=J.readBits(1);J.skipBits(3);let q=J.readBits(4),V=0;if(q>0)V=J.readBits(9);else J.skipBits(1);Q.push({fscod:K,fscod2:null,bsid:G,bsmod:W,acmod:j,lfeon:U,numDepSub:q,chanLoc:V})}if(Q.length===0)return null;return{dataRate:Y,substreams:Q}},b$=($)=>{let J=$.substreams[0];if(L(J),J.fscod<3)return P8[J.fscod];else if(J.fscod2!==null&&J.fscod2<3)return IJ[J.fscod2];return null},T$=($)=>{let J=$.substreams[0];L(J);let Y=s6[J.acmod]+J.lfeon;if(J.numDepSub>0){let X=[2,2,1,1,2,2,2,1,1];for(let Q=0;Q<9;Q++)if(J.chanLoc&1<<8-Q)Y+=X[Q]}return Y};/*!
|
|
49
|
+
*/var I8=[48000,44100,32000],mJ=[24000,22050,16000];/*!
|
|
50
50
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
51
51
|
*
|
|
52
52
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
53
53
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
54
54
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
55
|
-
*/class L0{constructor($){this.input=$}dispose(){}}/*!
|
|
55
|
+
*/var B0;(function($){$[$.NON_IDR_SLICE=1]="NON_IDR_SLICE",$[$.SLICE_DPA=2]="SLICE_DPA",$[$.SLICE_DPB=3]="SLICE_DPB",$[$.SLICE_DPC=4]="SLICE_DPC",$[$.IDR=5]="IDR",$[$.SEI=6]="SEI",$[$.SPS=7]="SPS",$[$.PPS=8]="PPS",$[$.AUD=9]="AUD",$[$.SPS_EXT=13]="SPS_EXT"})(B0||(B0={}));var M0;(function($){$[$.RASL_N=8]="RASL_N",$[$.RASL_R=9]="RASL_R",$[$.BLA_W_LP=16]="BLA_W_LP",$[$.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",$[$.VPS_NUT=32]="VPS_NUT",$[$.SPS_NUT=33]="SPS_NUT",$[$.PPS_NUT=34]="PPS_NUT",$[$.AUD_NUT=35]="AUD_NUT",$[$.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",$[$.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(M0||(M0={}));var j6=function*($){let J=0,Y=-1;while(J<$.length-2){let X=$.indexOf(0,J);if(X===-1||X>=$.length-2)break;J=X;let Q=0;if(J+3<$.length&&$[J+1]===0&&$[J+2]===0&&$[J+3]===1)Q=4;else if($[J+1]===0&&$[J+2]===1)Q=3;if(Q===0){J++;continue}if(Y!==-1&&J>Y)yield{offset:Y,length:J-Y};Y=J+Q,J=Y}if(Y!==-1&&Y<$.length)yield{offset:Y,length:$.length-Y}},pJ=function*($,J){let Y=0,X=new DataView($.buffer,$.byteOffset,$.byteLength);while(Y+J<=$.length){let Q;if(J===1)Q=X.getUint8(Y);else if(J===2)Q=X.getUint16(Y,!1);else if(J===3)Q=D8(X,Y,!1);else F(J===4),Q=X.getUint32(Y,!1);Y+=J,yield{offset:Y,length:Q},Y+=Q}},dJ=($,J)=>{if(J.description){let Q=(O0(J.description)[4]&3)+1;return pJ($,Q)}else return j6($)},y8=($)=>{return $&31},x$=($)=>{let J=[],Y=$.length;for(let X=0;X<Y;X++)if(X+2<Y&&$[X]===0&&$[X+1]===0&&$[X+2]===3)J.push(0,0),X+=2;else J.push($[X]);return new Uint8Array(J)},lJ=new Uint8Array([0,0,0,1]),cJ=($)=>{let J=$.reduce((Q,Z)=>Q+lJ.byteLength+Z.byteLength,0),Y=new Uint8Array(J),X=0;for(let Q of $)Y.set(lJ,X),X+=lJ.byteLength,Y.set(Q,X),X+=Q.byteLength;return Y},nJ=($,J)=>{let Y=$.reduce((Z,K)=>Z+J+K.byteLength,0),X=new Uint8Array(Y),Q=0;for(let Z of $){let K=new DataView(X.buffer,X.byteOffset,X.byteLength);switch(J){case 1:K.setUint8(Q,Z.byteLength);break;case 2:K.setUint16(Q,Z.byteLength,!1);break;case 3:C$(K,Q,Z.byteLength,!1);break;case 4:K.setUint32(Q,Z.byteLength,!1);break}Q+=J,X.set(Z,Q),Q+=Z.byteLength}return X},s7=($,J)=>{if(J.description){let Q=(O0(J.description)[4]&3)+1;return nJ($,Q)}else return cJ($)},i6=($)=>{try{let J=[],Y=[],X=[];for(let G of j6($)){let W=$.subarray(G.offset,G.offset+G.length),j=y8(W[0]);if(j===B0.SPS)J.push(W);else if(j===B0.PPS)Y.push(W);else if(j===B0.SPS_EXT)X.push(W)}if(J.length===0)return null;if(Y.length===0)return null;let Q=J[0],Z=a6(Q);F(Z!==null);let K=Z.profileIdc===100||Z.profileIdc===110||Z.profileIdc===122||Z.profileIdc===144;return{configurationVersion:1,avcProfileIndication:Z.profileIdc,profileCompatibility:Z.constraintFlags,avcLevelIndication:Z.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:J,pictureParameterSets:Y,chromaFormat:K?Z.chromaFormatIdc:null,bitDepthLumaMinus8:K?Z.bitDepthLumaMinus8:null,bitDepthChromaMinus8:K?Z.bitDepthChromaMinus8:null,sequenceParameterSetExt:K?X:null}}catch(J){return k._error("Error building AVC Decoder Configuration Record:",J),null}};var sJ=($)=>{try{let J=l($),Y=0,X=J.getUint8(Y++),Q=J.getUint8(Y++),Z=J.getUint8(Y++),K=J.getUint8(Y++),G=J.getUint8(Y++)&3,W=J.getUint8(Y++)&31,j=[];for(let _=0;_<W;_++){let V=J.getUint16(Y,!1);Y+=2,j.push($.subarray(Y,Y+V)),Y+=V}let U=J.getUint8(Y++),q=[];for(let _=0;_<U;_++){let V=J.getUint16(Y,!1);Y+=2,q.push($.subarray(Y,Y+V)),Y+=V}let N={configurationVersion:X,avcProfileIndication:Q,profileCompatibility:Z,avcLevelIndication:K,lengthSizeMinusOne:G,sequenceParameterSets:j,pictureParameterSets:q,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((Q===100||Q===110||Q===122||Q===144)&&Y+4<=$.length){let _=J.getUint8(Y++)&3,V=J.getUint8(Y++)&7,z=J.getUint8(Y++)&7,R=J.getUint8(Y++);N.chromaFormat=_,N.bitDepthLumaMinus8=V,N.bitDepthChromaMinus8=z;let H=[];for(let A=0;A<R;A++){let M=J.getUint16(Y,!1);Y+=2,H.push($.subarray(Y,Y+M)),Y+=M}N.sequenceParameterSetExt=H}return N}catch(J){return k._error("Error deserializing AVC Decoder Configuration Record:",J),null}},o7={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},a6=($)=>{try{let J=new n(x$($));if(J.skipBits(1),J.skipBits(2),J.readBits(5)!==7)return null;let X=J.readAlignedByte(),Q=J.readAlignedByte(),Z=J.readAlignedByte();h(J);let K=1,G=0,W=0,j=0;if(X===100||X===110||X===122||X===244||X===44||X===83||X===86||X===118||X===128){if(K=h(J),K===3)j=J.readBits(1);if(G=h(J),W=h(J),J.skipBits(1),J.readBits(1)){for(let v=0;v<(K!==3?8:12);v++)if(J.readBits(1)){let x=v<6?16:64,I=8,S=8;for(let u=0;u<x;u++){if(S!==0){let r=M1(J);S=(I+r+256)%256}I=S===0?I:S}}}}h(J);let U=h(J);if(U===0)h(J);else if(U===1){J.skipBits(1),M1(J),M1(J);let P=h(J);for(let v=0;v<P;v++)M1(J)}h(J),J.skipBits(1);let q=h(J),N=h(J),_=16*(q+1),V=16*(N+1),z=_,R=V,H=J.readBits(1);if(!H)J.skipBits(1);if(J.skipBits(1),J.readBits(1)){let P=h(J),v=h(J),T=h(J),x=h(J),I,S;if((j===0?K:0)===0)I=1,S=2-H;else{let r=K===3?1:2,m=K===1?2:1;I=r,S=m*(2-H)}z-=I*(P+v),R-=S*(T+x)}let M=2,L=2,w=2,O=0,D={num:1,den:1},B=null,C=null;if(J.readBits(1)){if(J.readBits(1)){let m=J.readBits(8);if(m===255)D={num:J.readBits(16),den:J.readBits(16)};else{let c=o7[m];if(c)D=c}}if(J.readBits(1))J.skipBits(1);if(J.readBits(1)){if(J.skipBits(3),O=J.readBits(1),J.readBits(1))M=J.readBits(8),L=J.readBits(8),w=J.readBits(8)}if(J.readBits(1))h(J),h(J);if(J.readBits(1))J.skipBits(32),J.skipBits(32),J.skipBits(1);let S=J.readBits(1);if(S)c7(J);let u=J.readBits(1);if(u)c7(J);if(S||u)J.skipBits(1);if(J.skipBits(1),J.readBits(1))J.skipBits(1),h(J),h(J),h(J),h(J),B=h(J),C=h(J)}if(B===null){F(C===null);let P=Q&16;if((X===44||X===86||X===100||X===110||X===122||X===244)&&P)B=0,C=0;else{let v=q+1,T=N+1,x=(2-H)*T,I=uJ.find((u)=>u.level>=Z)??W0(uJ),S=Math.min(Math.floor(I.maxDpbMbs/(v*x)),16);B=S,C=S}}return F(C!==null),{profileIdc:X,constraintFlags:Q,levelIdc:Z,frameMbsOnlyFlag:H,chromaFormatIdc:K,bitDepthLumaMinus8:G,bitDepthChromaMinus8:W,codedWidth:_,codedHeight:V,displayWidth:z,displayHeight:R,pixelAspectRatio:D,colourPrimaries:M,matrixCoefficients:w,transferCharacteristics:L,fullRangeFlag:O,numReorderFrames:B,maxDecFrameBuffering:C}}catch(J){return k._error("Error parsing AVC SPS:",J),null}},c7=($)=>{let J=h($);$.skipBits(4),$.skipBits(4);for(let Y=0;Y<=J;Y++)h($),h($),$.skipBits(1);$.skipBits(5),$.skipBits(5),$.skipBits(5),$.skipBits(5)},uZ=($,J)=>{if(J.description){let Q=(O0(J.description)[21]&3)+1;return nJ($,Q)}else return cJ($)},r6=($,J)=>{if(J.description){let Q=(O0(J.description)[21]&3)+1;return pJ($,Q)}else return j6($)},m1=($)=>{return $>>1&63},oJ=($)=>{try{let J=new n(x$($));J.skipBits(16),J.readBits(4);let Y=J.readBits(3),X=J.readBits(1),{general_profile_space:Q,general_tier_flag:Z,general_profile_idc:K,general_profile_compatibility_flags:G,general_constraint_indicator_flags:W,general_level_idc:j}=mZ(J,Y);h(J);let U=h(J),q=0;if(U===3)q=J.readBits(1);let N=h(J),_=h(J),V=N,z=_;if(J.readBits(1)){let v=h(J),T=h(J),x=h(J),I=h(J),S=1,u=1,r=q===0?U:0;if(r===1)S=2,u=2;else if(r===2)S=2,u=1;V-=(v+T)*S,z-=(x+I)*u}let R=h(J),H=h(J);h(J);let M=J.readBits(1)?0:Y,L=0;for(let v=M;v<=Y;v++)h(J),L=h(J),h(J);if(h(J),h(J),h(J),h(J),h(J),h(J),J.readBits(1)){if(J.readBits(1))lZ(J)}if(J.skipBits(1),J.skipBits(1),J.readBits(1))J.skipBits(4),J.skipBits(4),h(J),h(J),J.skipBits(1);let w=h(J);if(pZ(J,w),J.readBits(1)){let v=h(J);for(let T=0;T<v;T++)h(J),J.skipBits(1)}J.skipBits(1),J.skipBits(1);let O=2,D=2,B=2,C=0,E=0,P={num:1,den:1};if(J.readBits(1)){let v=cZ(J,Y);P=v.pixelAspectRatio,O=v.colourPrimaries,D=v.transferCharacteristics,B=v.matrixCoefficients,C=v.fullRangeFlag,E=v.minSpatialSegmentationIdc}return{displayWidth:V,displayHeight:z,pixelAspectRatio:P,colourPrimaries:O,transferCharacteristics:D,matrixCoefficients:B,fullRangeFlag:C,maxDecFrameBuffering:L+1,spsMaxSubLayersMinus1:Y,spsTemporalIdNestingFlag:X,generalProfileSpace:Q,generalTierFlag:Z,generalProfileIdc:K,generalProfileCompatibilityFlags:G,generalConstraintIndicatorFlags:W,generalLevelIdc:j,chromaFormatIdc:U,bitDepthLumaMinus8:R,bitDepthChromaMinus8:H,minSpatialSegmentationIdc:E}}catch(J){return k._error("Error parsing HEVC SPS:",J),null}},t6=($)=>{try{let J=[],Y=[],X=[],Q=[];for(let j of j6($)){let U=$.subarray(j.offset,j.offset+j.length),q=m1(U[0]);if(q===M0.VPS_NUT)J.push(U);else if(q===M0.SPS_NUT)Y.push(U);else if(q===M0.PPS_NUT)X.push(U);else if(q===M0.PREFIX_SEI_NUT||q===M0.SUFFIX_SEI_NUT)Q.push(U)}if(Y.length===0||X.length===0)return null;let Z=oJ(Y[0]);if(!Z)return null;let K=0;if(X.length>0){let j=X[0],U=new n(x$(j));if(U.skipBits(16),h(U),h(U),U.skipBits(1),U.skipBits(1),U.skipBits(3),U.skipBits(1),U.skipBits(1),h(U),h(U),M1(U),U.skipBits(1),U.skipBits(1),U.readBits(1))h(U);M1(U),M1(U),U.skipBits(1),U.skipBits(1),U.skipBits(1),U.skipBits(1);let q=U.readBits(1),N=U.readBits(1);if(!q&&!N)K=0;else if(q&&!N)K=2;else if(!q&&N)K=3;else K=0}let G=[...J.length?[{arrayCompleteness:1,nalUnitType:M0.VPS_NUT,nalUnits:J}]:[],...Y.length?[{arrayCompleteness:1,nalUnitType:M0.SPS_NUT,nalUnits:Y}]:[],...X.length?[{arrayCompleteness:1,nalUnitType:M0.PPS_NUT,nalUnits:X}]:[],...Q.length?[{arrayCompleteness:1,nalUnitType:m1(Q[0][0]),nalUnits:Q}]:[]];return{configurationVersion:1,generalProfileSpace:Z.generalProfileSpace,generalTierFlag:Z.generalTierFlag,generalProfileIdc:Z.generalProfileIdc,generalProfileCompatibilityFlags:Z.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:Z.generalConstraintIndicatorFlags,generalLevelIdc:Z.generalLevelIdc,minSpatialSegmentationIdc:Z.minSpatialSegmentationIdc,parallelismType:K,chromaFormatIdc:Z.chromaFormatIdc,bitDepthLumaMinus8:Z.bitDepthLumaMinus8,bitDepthChromaMinus8:Z.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:Z.spsMaxSubLayersMinus1+1,temporalIdNested:Z.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:G}}catch(J){return k._error("Error building HEVC Decoder Configuration Record:",J),null}},mZ=($,J)=>{let Y=$.readBits(2),X=$.readBits(1),Q=$.readBits(5),Z=0;for(let U=0;U<32;U++)Z=Z<<1|$.readBits(1);let K=new Uint8Array(6);for(let U=0;U<6;U++)K[U]=$.readBits(8);let G=$.readBits(8),W=[],j=[];for(let U=0;U<J;U++)W.push($.readBits(1)),j.push($.readBits(1));if(J>0)for(let U=J;U<8;U++)$.skipBits(2);for(let U=0;U<J;U++){if(W[U])$.skipBits(88);if(j[U])$.skipBits(8)}return{general_profile_space:Y,general_tier_flag:X,general_profile_idc:Q,general_profile_compatibility_flags:Z,general_constraint_indicator_flags:K,general_level_idc:G}},lZ=($)=>{for(let J=0;J<4;J++)for(let Y=0;Y<(J===3?2:6);Y++)if(!$.readBits(1))h($);else{let Q=Math.min(64,1<<4+(J<<1));if(J>1)M1($);for(let Z=0;Z<Q;Z++)M1($)}},pZ=($,J)=>{let Y=[];for(let X=0;X<J;X++)Y[X]=dZ($,X,J,Y)},dZ=($,J,Y,X)=>{let Q=0,Z=0,K=0;if(J!==0)Z=$.readBits(1);if(Z){if(J===Y){let W=h($);K=J-(W+1)}else K=J-1;$.readBits(1),h($);let G=X[K]??0;for(let W=0;W<=G;W++)if(!$.readBits(1))$.readBits(1);Q=X[K]}else{let G=h($),W=h($);for(let j=0;j<G;j++)h($),$.readBits(1);for(let j=0;j<W;j++)h($),$.readBits(1);Q=G+W}return Q},cZ=($,J)=>{let Y=2,X=2,Q=2,Z=0,K=0,G={num:1,den:1};if($.readBits(1)){let W=$.readBits(8);if(W===255)G={num:$.readBits(16),den:$.readBits(16)};else{let j=o7[W];if(j)G=j}}if($.readBits(1))$.readBits(1);if($.readBits(1)){if($.readBits(3),Z=$.readBits(1),$.readBits(1))Y=$.readBits(8),X=$.readBits(8),Q=$.readBits(8)}if($.readBits(1))h($),h($);if($.readBits(1),$.readBits(1),$.readBits(1),$.readBits(1))h($),h($),h($),h($);if($.readBits(1)){if($.readBits(32),$.readBits(32),$.readBits(1))h($);if($.readBits(1))nZ($,!0,J)}if($.readBits(1))$.readBits(1),$.readBits(1),$.readBits(1),K=h($),h($),h($),h($),h($);return{pixelAspectRatio:G,colourPrimaries:Y,transferCharacteristics:X,matrixCoefficients:Q,fullRangeFlag:Z,minSpatialSegmentationIdc:K}},nZ=($,J,Y)=>{let X=!1,Q=!1,Z=!1;if(J){if(X=$.readBits(1)===1,Q=$.readBits(1)===1,X||Q){if(Z=$.readBits(1)===1,Z)$.readBits(8),$.readBits(5),$.readBits(1),$.readBits(5);if($.readBits(4),$.readBits(4),Z)$.readBits(4);$.readBits(5),$.readBits(5),$.readBits(5)}}for(let K=0;K<=Y;K++){let G=$.readBits(1)===1,W=!0;if(!G)W=$.readBits(1)===1;let j=!1;if(W)h($);else j=$.readBits(1)===1;let U=1;if(!j)U=h($)+1;if(X)n7($,U,Z);if(Q)n7($,U,Z)}},n7=($,J,Y)=>{for(let X=0;X<J;X++){if(h($),h($),Y)h($),h($);$.readBits(1)}};var k0;(function($){$[$.audAllowed=0]="audAllowed",$[$.beforeFirstVcl=1]="beforeFirstVcl",$[$.afterFirstVcl=2]="afterFirstVcl",$[$.eoBitstreamAllowed=3]="eoBitstreamAllowed",$[$.noMoreDataAllowed=4]="noMoreDataAllowed"})(k0||(k0={}));var r7=($,J)=>{let Y=new Set,X=k0.audAllowed;for(let Z of r6($,J)){if(X===k0.noMoreDataAllowed){Y.add(Z.offset);continue}let K=m1($[Z.offset]);if(X===k0.eoBitstreamAllowed&&K!==37){Y.add(Z.offset);continue}let G=!1;if(K===35)if(X>k0.audAllowed)G=!0;else X=k0.beforeFirstVcl;else if(K<=31)if(X>k0.afterFirstVcl)G=!0;else X=k0.afterFirstVcl;else if(K===36)if(X!==k0.afterFirstVcl)G=!0;else X=k0.eoBitstreamAllowed;else if(K===37)if(X<k0.afterFirstVcl)G=!0;else X=k0.noMoreDataAllowed;else if(K===32||K===33||K===34||K===39||K>=41&&K<=44||K>=48&&K<=55)if(X>k0.beforeFirstVcl)G=!0;else X=k0.beforeFirstVcl;else if(K===38||K===40||K>=45&&K<=47||K>=56&&K<=63){if(X<k0.afterFirstVcl)G=!0}if(G)Y.add(Z.offset)}if(Y.size===0)return null;let Q=[];for(let Z of r6($,J))if(!Y.has(Z.offset))Q.push($.subarray(Z.offset,Z.offset+Z.length));return uZ(Q,J)},I$=($)=>{let J=new n($);if(J.readBits(2)!==2)return null;let X=J.readBits(1),Z=(J.readBits(1)<<1)+X;if(Z===3)J.skipBits(1);if(J.readBits(1)===1)return null;if(J.readBits(1)!==0)return null;if(J.skipBits(2),J.readBits(24)!==4817730)return null;let j=8;if(Z>=2)j=J.readBits(1)?12:10;let U=J.readBits(3),q=0,N=0;if(U!==7)if(N=J.readBits(1),Z===1||Z===3){let D=J.readBits(1),B=J.readBits(1);q=!D&&!B?3:D&&!B?2:1,J.skipBits(1)}else q=1;else q=3,N=1;let _=J.readBits(16),V=J.readBits(16),z=_+1,R=V+1,H=z*R,A=W0(x8).level;for(let O of x8)if(H<=O.maxPictureSize){A=O.level;break}return{profile:Z,level:A,bitDepth:j,chromaSubsampling:q,videoFullRangeFlag:N,colourPrimaries:U===2?1:U===1?6:2,transferCharacteristics:U===2?1:U===1?6:2,matrixCoefficients:U===7?0:U===2?1:U===1?6:2}},i7=function*($){let J=new n($),Y=()=>{let X=0;for(let Q=0;Q<8;Q++){let Z=J.readAlignedByte();if(X|=(Z&127)<<Q*7,!(Z&128))break;if(Q===7&&Z&128)return null}if(X>=4294967295)return null;return X};while(J.getBitsLeft()>=8){J.skipBits(1);let X=J.readBits(4),Q=J.readBits(1),Z=J.readBits(1);if(J.skipBits(1),Q)J.skipBits(8);let K;if(Z){let G=Y();if(G===null)return;K=G}else K=Math.floor(J.getBitsLeft()/8);F(J.pos%8===0),yield{type:X,data:$.subarray(J.pos/8,J.pos/8+K)},J.skipBits(K*8)}},y$=($)=>{for(let{type:J,data:Y}of i7($)){if(J!==1)continue;let X=new n(Y),Q=X.readBits(3),Z=X.readBits(1),K=X.readBits(1),G=0,W=0,j=0;if(K)G=X.readBits(5);else{if(X.readBits(1)){if(X.skipBits(32),X.skipBits(32),X.readBits(1))return null}let O=X.readBits(1);if(O)j=X.readBits(5),X.skipBits(32),X.skipBits(5),X.skipBits(5);let D=X.readBits(5);for(let B=0;B<=D;B++){X.skipBits(12);let C=X.readBits(5);if(B===0)G=C;if(C>7){let P=X.readBits(1);if(B===0)W=P}if(O){if(X.readBits(1)){let v=j+1;X.skipBits(v),X.skipBits(v),X.skipBits(1)}}if(X.readBits(1))X.skipBits(4)}}let U=X.readBits(4),q=X.readBits(4),N=U+1;X.skipBits(N);let _=q+1;X.skipBits(_);let V=0;if(K)V=0;else V=X.readBits(1);if(V)X.skipBits(4),X.skipBits(3);if(X.skipBits(1),X.skipBits(1),X.skipBits(1),!K){X.skipBits(1),X.skipBits(1),X.skipBits(1),X.skipBits(1);let w=X.readBits(1);if(w)X.skipBits(1),X.skipBits(1);let O=X.readBits(1),D=0;if(O)D=2;else D=X.readBits(1);if(D>0){if(!X.readBits(1))X.skipBits(1)}if(w)X.skipBits(3)}X.skipBits(1),X.skipBits(1),X.skipBits(1);let z=X.readBits(1),R=8;if(Q===2&&z)R=X.readBits(1)?12:10;else if(Q<=2)R=z?10:8;let H=0;if(Q!==1)H=X.readBits(1);let A=1,M=1,L=0;if(!H){if(Q===0)A=1,M=1;else if(Q===1)A=0,M=0;else if(R===12){if(A=X.readBits(1),A)M=X.readBits(1)}if(A&&M)L=X.readBits(2)}return{profile:Q,level:G,tier:W,bitDepth:R,monochrome:H,chromaSubsamplingX:A,chromaSubsamplingY:M,chromaSamplePosition:L}}return null},e6=($)=>{let J=l($),Y=J.getUint8(9),X=J.getUint16(10,!0),Q=J.getUint32(12,!0),Z=J.getInt16(16,!0),K=J.getUint8(18),G=null;if(K)G=$.subarray(19,21+Y);return{outputChannelCount:Y,preSkip:X,inputSampleRate:Q,outputGain:Z,channelMappingFamily:K,channelMappingTable:G}},sZ=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],a7=($)=>{let J=$[0]>>3;return{durationInSamples:sZ[J]}},rJ=($)=>{if($.length<7)throw Error("Setup header is too short.");if($[0]!==5)throw Error("Wrong packet type in Setup header.");if(String.fromCharCode(...$.slice(1,7))!=="vorbis")throw Error("Invalid packet signature in Setup header.");let Y=$.length,X=new Uint8Array(Y);for(let q=0;q<Y;q++)X[q]=$[Y-1-q];let Q=new n(X),Z=0;while(Q.getBitsLeft()>97)if(Q.readBits(1)===1){Z=Q.pos;break}if(Z===0)throw Error("Invalid Setup header: framing bit not found.");let K=0,G=!1,W=0;while(Q.getBitsLeft()>=97){let q=Q.pos,N=Q.readBits(8),_=Q.readBits(16),V=Q.readBits(16);if(N>63||_!==0||V!==0){Q.pos=q;break}if(Q.skipBits(1),K++,K>64)break;if(Q.clone().readBits(6)+1===K)G=!0,W=K}if(!G)throw Error("Invalid Setup header: mode header not found.");if(W>63)throw Error(`Unsupported mode count: ${W}.`);let j=W;Q.pos=0,Q.skipBits(Z);let U=Array(j).fill(0);for(let q=j-1;q>=0;q--)Q.skipBits(40),U[q]=Q.readBits(1);return{modeBlockflags:U}},S8=($,J,Y)=>{switch($){case"avc":{for(let X of dJ(Y,J)){let Q=Y[X.offset],Z=y8(Q);if(Z>=B0.NON_IDR_SLICE&&Z<=B0.SLICE_DPC)return"delta";if(Z===B0.IDR)return"key";if(Z===B0.SEI&&(!d6()||g7()>=144)){let K=Y.subarray(X.offset,X.offset+X.length),G=x$(K),W=1;do{let j=0;while(!0){let N=G[W++];if(N===void 0)break;if(j+=N,N<255)break}let U=0;while(!0){let N=G[W++];if(N===void 0)break;if(U+=N,N<255)break}if(j===6){let N=new n(G);N.pos=8*W;let _=h(N),V=N.readBits(1);if(_===0&&V===1)return"key"}W+=U}while(W<G.length-1)}}return"delta"}case"hevc":{for(let X of r6(Y,J)){let Q=m1(Y[X.offset]);if(Q<M0.BLA_W_LP)return"delta";if(Q<=M0.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(Y[0]&1)===0?"key":"delta";case"vp9":{let X=new n(Y);if(X.readBits(2)!==2)return null;let Q=X.readBits(1);if((X.readBits(1)<<1)+Q===3)X.skipBits(1);if(X.readBits(1))return null;return X.readBits(1)===0?"key":"delta"}case"av1":{let X=!1;for(let{type:Q,data:Z}of i7(Y))if(Q===1){let K=new n(Z);K.skipBits(4),X=!!K.readBits(1)}else if(Q===3||Q===6||Q===7){if(X)return"key";let K=new n(Z);if(K.readBits(1))return null;return K.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:v0($),F(!1)}},O1;(function($){$[$.STREAMINFO=0]="STREAMINFO",$[$.VORBIS_COMMENT=4]="VORBIS_COMMENT",$[$.PICTURE=6]="PICTURE"})(O1||(O1={}));var $$=($,J)=>{let Y=l($),X=0,Q=Y.getUint32(X,!0);X+=4;let Z=A0.decode($.subarray(X,X+Q));if(X+=Q,Q>0)J.raw??={},J.raw.vendor??=Z;let K=Y.getUint32(X,!0);X+=4;for(let G=0;G<K;G++){let W=Y.getUint32(X,!0);X+=4;let j=A0.decode($.subarray(X,X+W));X+=W;let U=j.indexOf("=");if(U===-1)continue;let q=j.slice(0,U).toUpperCase(),N=j.slice(U+1);switch(J.raw??={},J.raw[q]??=N,q){case"TITLE":J.title??=N;break;case"DESCRIPTION":J.description??=N;break;case"ARTIST":J.artist??=N;break;case"ALBUM":J.album??=N;break;case"ALBUMARTIST":J.albumArtist??=N;break;case"COMMENT":J.comment??=N;break;case"LYRICS":J.lyrics??=N;break;case"TRACKNUMBER":{let _=N.split("/"),V=Number.parseInt(_[0],10),z=_[1]&&Number.parseInt(_[1],10);if(Number.isInteger(V)&&V>0)J.trackNumber??=V;if(z&&Number.isInteger(z)&&z>0)J.tracksTotal??=z}break;case"TRACKTOTAL":{let _=Number.parseInt(N,10);if(Number.isInteger(_)&&_>0)J.tracksTotal??=_}break;case"DISCNUMBER":{let _=N.split("/"),V=Number.parseInt(_[0],10),z=_[1]&&Number.parseInt(_[1],10);if(Number.isInteger(V)&&V>0)J.discNumber??=V;if(z&&Number.isInteger(z)&&z>0)J.discsTotal??=z}break;case"DISCTOTAL":{let _=Number.parseInt(N,10);if(Number.isInteger(_)&&_>0)J.discsTotal??=_}break;case"DATE":{let _=new Date(N);if(!Number.isNaN(_.getTime()))J.date??=_}break;case"GENRE":J.genre??=N;break;case"METADATA_BLOCK_PICTURE":{let _=c6(N),V=l(_),z=V.getUint32(0,!1),R=V.getUint32(4,!1),H=String.fromCharCode(..._.subarray(8,8+R)),A=V.getUint32(8+R,!1),M=A0.decode(_.subarray(12+R,12+R+A)),L=V.getUint32(R+A+28),w=_.subarray(R+A+32,R+A+32+L);J.images??=[],J.images.push({data:w,mimeType:H,kind:z===3?"coverFront":z===4?"coverBack":"unknown",name:void 0,description:M||void 0})}break}}};var J$=[2,1,2,3,3,4,4,5],iJ=($)=>{if($.length<7)return null;if($[0]!==11||$[1]!==119)return null;let J=new n($);J.skipBits(16),J.skipBits(16);let Y=J.readBits(2);if(Y===3)return null;let X=J.readBits(6),Q=J.readBits(5);if(Q>8)return null;let Z=J.readBits(3),K=J.readBits(3);if((K&1)!==0&&K!==1)J.skipBits(2);if((K&4)!==0)J.skipBits(2);if(K===2)J.skipBits(2);let G=J.readBits(1),W=Math.floor(X/2);return{fscod:Y,bsid:Q,bsmod:Z,acmod:K,lfeon:G,bitRateCode:W}},t7=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],e7=1536,oZ=new Uint8Array([5,4,65,67,45,51]),rZ=new Uint8Array([5,4,69,65,67,51]),aJ=[1,2,3,6],tJ=($)=>{if($.length<6)return null;if($[0]!==11||$[1]!==119)return null;let J=new n($);J.skipBits(16);let Y=J.readBits(2);if(J.skipBits(3),Y!==0&&Y!==2)return null;let X=J.readBits(11),Q=J.readBits(2),Z=0,K;if(Q===3)Z=J.readBits(2),K=3;else K=J.readBits(2);let G=J.readBits(3),W=J.readBits(1),j=J.readBits(5);if(j<11||j>16)return null;let U=aJ[K],q;if(Q<3)q=I8[Q]/1000;else q=mJ[Z]/1000;return{dataRate:Math.round((X+1)*q/(U*16)),substreams:[{fscod:Q,fscod2:Z,bsid:j,bsmod:0,acmod:G,lfeon:W,numDepSub:0,chanLoc:0}]}},$X=($)=>{if($.length<2)return null;let J=new n($),Y=J.readBits(13),X=J.readBits(3),Q=[];for(let Z=0;Z<=X;Z++){if(Math.ceil(J.pos/8)+3>$.length)break;let K=J.readBits(2),G=J.readBits(5);J.skipBits(1),J.skipBits(1);let W=J.readBits(3),j=J.readBits(3),U=J.readBits(1);J.skipBits(3);let q=J.readBits(4),N=0;if(q>0)N=J.readBits(9);else J.skipBits(1);Q.push({fscod:K,fscod2:null,bsid:G,bsmod:W,acmod:j,lfeon:U,numDepSub:q,chanLoc:N})}if(Q.length===0)return null;return{dataRate:Y,substreams:Q}},S$=($)=>{let J=$.substreams[0];if(F(J),J.fscod<3)return I8[J.fscod];else if(J.fscod2!==null&&J.fscod2<3)return mJ[J.fscod2];return null},h$=($)=>{let J=$.substreams[0];F(J);let Y=J$[J.acmod]+J.lfeon;if(J.numDepSub>0){let X=[2,2,1,1,2,2,2,1,1];for(let Q=0;Q<9;Q++)if(J.chanLoc&1<<8-Q)Y+=X[Q]}return Y};/*!
|
|
56
56
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
57
57
|
*
|
|
58
58
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
59
59
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
60
60
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
61
|
-
*/
|
|
61
|
+
*/class P0{constructor($){this.input=$}dispose(){}}/*!
|
|
62
62
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
63
63
|
*
|
|
64
64
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
65
65
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
66
66
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
67
|
-
*/var
|
|
67
|
+
*/var w0=new Uint8Array(0);class t{constructor($,J,Y,X,Q=-1,Z,K){if(this.data=$,this.type=J,this.timestamp=Y,this.duration=X,this.sequenceNumber=Q,$===w0&&Z===void 0)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(Z===void 0)Z=$.byteLength;if(!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(J!=="key"&&J!=="delta")throw TypeError('type must be either "key" or "delta".');if(!Number.isFinite(Y))throw TypeError("timestamp must be a number.");if(!Number.isFinite(X)||X<0)throw TypeError("duration must be a non-negative number.");if(!Number.isFinite(Q))throw TypeError("sequenceNumber must be a number.");if(!Number.isInteger(Z)||Z<0)throw TypeError("byteLength must be a non-negative integer.");if(K!==void 0&&(typeof K!=="object"||!K))throw TypeError("sideData, when provided, must be an object.");if(K?.alpha!==void 0&&!(K.alpha instanceof Uint8Array))throw TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(K?.alphaByteLength!==void 0&&(!Number.isInteger(K.alphaByteLength)||K.alphaByteLength<0))throw TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");if(this.byteLength=Z,this.sideData=K??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0)this.sideData.alphaByteLength=this.sideData.alpha.byteLength}get isMetadataOnly(){return this.data===w0}get microsecondTimestamp(){return Math.trunc(F1*this.timestamp)}get microsecondDuration(){return Math.trunc(F1*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk($=this.type){if(!this.sideData.alpha)throw TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:$,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")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($,J){if(!($ instanceof EncodedVideoChunk||$ instanceof EncodedAudioChunk))throw TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let Y=new Uint8Array($.byteLength);return $.copyTo(Y),new t(Y,$.type,$.timestamp/1e6,($.duration??0)/1e6,void 0,void 0,J)}clone($){if($!==void 0&&(typeof $!=="object"||$===null))throw TypeError("options, when provided, must be an object.");if($?.data!==void 0&&!($.data instanceof Uint8Array))throw TypeError("options.data, when provided, must be a Uint8Array.");if($?.type!==void 0&&$.type!=="key"&&$.type!=="delta")throw TypeError('options.type, when provided, must be either "key" or "delta".');if($?.timestamp!==void 0&&!Number.isFinite($.timestamp))throw TypeError("options.timestamp, when provided, must be a number.");if($?.duration!==void 0&&!Number.isFinite($.duration))throw TypeError("options.duration, when provided, must be a number.");if($?.sequenceNumber!==void 0&&!Number.isFinite($.sequenceNumber))throw TypeError("options.sequenceNumber, when provided, must be a number.");if($?.sideData!==void 0&&(typeof $.sideData!=="object"||$.sideData===null))throw TypeError("options.sideData, when provided, must be an object.");return new t($?.data??this.data,$?.type??this.type,$?.timestamp??this.timestamp,$?.duration??this.duration,$?.sequenceNumber??this.sequenceNumber,this.byteLength,$?.sideData??this.sideData)}}/*!
|
|
68
68
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
69
69
|
*
|
|
70
70
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
71
71
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
72
72
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
73
|
-
*/var
|
|
73
|
+
*/var eJ=($)=>{let Y=($.hasVideo?"video/":$.hasAudio?"audio/":"application/")+($.isQuickTime?"quicktime":"mp4");if($.codecStrings.length>0){let X=[...new Set($.codecStrings)];Y+=`; codecs="${X.join(", ")}"`}return Y},f$=($)=>{let J=l($),Y=0,X=J.getUint8(Y);Y+=1,Y+=3;let Q=Y8($.subarray(Y,Y+16));Y+=16;let Z=null;if(X>0){let G=J.getUint32(Y);if(Y+=4,G>0){Z=[];for(let W=0;W<G;W++)Z.push(Y8($.subarray(Y,Y+16))),Y+=16}}let K=J.getUint32(Y);return Y+=4,{systemId:Q,keyIds:Z,data:$.slice(Y,Y+K)}},g$=($,J)=>$.systemId===J.systemId&&gJ($.data,J.data);/*!
|
|
74
74
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
75
75
|
*
|
|
76
76
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
77
77
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
78
78
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
79
|
-
*/var
|
|
79
|
+
*/var Q8=8,h8=16,l1=($)=>{let J=y($),Y=Z0($,4),X=8;if(J===1)J=i0($),X=16;let Z=J-X;if(Z<0)return null;return{name:Y,totalSize:J,headerSize:X,contentSize:Z}},K8=($)=>{return p1($)/65536},k$=($)=>{return p1($)/1073741824},u$=($)=>{let J=0;for(let Y=0;Y<4;Y++){J<<=7;let X=g($);if(J|=X&127,(X&128)===0)break}return J},q1=($)=>{let J=U0($);return $.skip(2),J=Math.min(J,$.remainingLength),A0.decode(f($,J))},JX=($)=>{let J=l1($);if(!J||J.name!=="data")return null;if($.remainingLength<8)return null;let Y=y($);$.skip(4);let X=f($,J.contentSize-8);switch(Y){case 1:return A0.decode(X);case 2:return new TextDecoder("utf-16be").decode(X);case 13:return new S1(X,"image/jpeg");case 14:return new S1(X,"image/png");case 27:return new S1(X,"image/bmp");default:return X}};/*!
|
|
80
80
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
81
81
|
*
|
|
82
82
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
83
83
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
84
84
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
85
|
-
*/class h$ extends L0{constructor($){super($);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.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=$._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(($)=>$.trackBacking)}async getMimeType(){await this.readMetadata();let $=await this.getTrackBackings(),J=await Promise.all($.map((Y)=>Y.getDecoderConfig().then((X)=>X?.codec??null)));return cJ({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some((Y)=>Y.info?.type==="video"),hasAudio:this.tracks.some((Y)=>Y.info?.type==="audio"),codecStrings:J.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let $=0,J=!1;while(!0){let Y=this.reader.requestSliceRange($,e1,v8);if(Y instanceof Promise)Y=await Y;if(!Y)break;let X=$,Q=S1(Y);if(!Q)break;if(Q.name==="ftyp"||Q.name==="styp"){let Z=J0(Y,4);this.isQuickTime=Z==="qt "}else if(Q.name==="moov"){let Z=this.reader.requestSlice(Y.filePos,Q.contentSize);if(Z instanceof Promise)Z=await Z;if(!Z)break;this.moovSlice=Z,this.readContiguousBoxes(this.moovSlice);for(let K of this.tracks){let G=K.editListPreviousSegmentDurations/this.movieTimescale;K.editListOffset-=Math.round(G*K.timescale)}J=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>X+Q.totalSize;break}else if(Q.name==="moof"){if(!this.input._initInput)throw Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');let Z=await this.input._initInput._getDemuxer();if(Z.constructor!==h$)throw Error("Init input must match the input's format.");await Z.readMetadata(),this.movieTimescale=Z.movieTimescale,this.movieDurationInTimescale=Z.movieDurationInTimescale,this.metadataTags=Z.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=Z.fragmentTrackDefaults,this.psshBoxes=Z.psshBoxes;for(let K of Z.tracks){let G={id:K.id,demuxer:this,trackBacking:null,disposition:K.disposition,timescale:K.timescale,durationInMediaTimescale:K.durationInMediaTimescale,durationInMovieTimescale:K.durationInMovieTimescale,rotation:K.rotation,internalCodecId:K.internalCodecId,name:K.name,languageCode:K.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:K.editListPreviousSegmentDurations,editListOffset:K.editListOffset,encryptionInfo:K.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:K.info};if(K.trackBacking){if(L(G.info),G.info.type==="video"&&G.info.width!==-1){let W=G;G.trackBacking=new oJ(W),this.tracks.push(G)}else if(G.info.type==="audio"&&G.info.numberOfChannels!==-1){let W=G;G.trackBacking=new sJ(W),this.tracks.push(G)}}}J=!1;break}$=X+Q.totalSize}if(J){L(this.reader.fileSize!==null);let Y=this.reader.requestSlice(this.reader.fileSize-4,4);if(Y instanceof Promise)Y=await Y;L(Y);let X=I(Y),Q=this.reader.fileSize-X;if(Q>=0&&Q<=this.reader.fileSize-v8){let Z=this.reader.requestSliceRange(Q,e1,v8);if(Z instanceof Promise)Z=await Z;if(Z){let K=S1(Z);if(K&&K.name==="mfra"){let G=this.reader.requestSlice(Z.filePos,K.contentSize);if(G instanceof Promise)G=await G;if(G)this.readContiguousBoxes(G)}}}}})()}getSampleTableForTrack($){if($.sampleTable)return $.sampleTable;let J={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if($.sampleTable=J,$.sampleTableByteOffset===null)return J;L(this.moovSlice);let Y=this.moovSlice.slice($.sampleTableByteOffset);if(this.currentTrack=$,this.traverseBox(Y),this.currentTrack=null,$.info?.type==="audio"&&$.info.codec&&B0.includes($.info.codec)&&J.sampleCompositionTimeOffsets.length===0){L($.info?.type==="audio");let Q=I1($.info.codec),Z=[],K=[];for(let G=0;G<J.sampleToChunk.length;G++){let W=J.sampleToChunk[G],j=J.sampleToChunk[G+1],U=(j?j.startChunkIndex:J.chunkOffsets.length)-W.startChunkIndex;for(let q=0;q<U;q++){let V=W.startSampleIndex+q*W.samplesPerChunk,_=V+W.samplesPerChunk,N=p(J.sampleTimingEntries,V,(D)=>D.startIndex),R=J.sampleTimingEntries[N],z=p(J.sampleTimingEntries,_,(D)=>D.startIndex),H=J.sampleTimingEntries[z],A=R.startDecodeTimestamp+(V-R.startIndex)*R.delta,F=H.startDecodeTimestamp+(_-H.startIndex)*H.delta-A,O=K0(Z);if(O&&O.delta===F)O.count++;else Z.push({startIndex:W.startChunkIndex+q,startDecodeTimestamp:A,count:1,delta:F});let B=W.samplesPerChunk*Q.sampleSize*$.info.numberOfChannels;K.push(B)}W.startSampleIndex=W.startChunkIndex,W.samplesPerChunk=1}J.sampleTimingEntries=Z,J.sampleSizes=K}if(J.sampleCompositionTimeOffsets.length>0){J.presentationTimestamps=[];for(let Q of J.sampleTimingEntries)for(let Z=0;Z<Q.count;Z++)J.presentationTimestamps.push({presentationTimestamp:Q.startDecodeTimestamp+Z*Q.delta,sampleIndex:Q.startIndex+Z});for(let Q of J.sampleCompositionTimeOffsets)for(let Z=0;Z<Q.count;Z++){let K=Q.startIndex+Z,G=J.presentationTimestamps[K];if(!G)continue;G.presentationTimestamp+=Q.offset}J.presentationTimestamps.sort((Q,Z)=>Q.presentationTimestamp-Z.presentationTimestamp),J.presentationTimestampIndexMap=Array(J.presentationTimestamps.length).fill(-1);for(let Q=0;Q<J.presentationTimestamps.length;Q++)J.presentationTimestampIndexMap[J.presentationTimestamps[Q].sampleIndex]=Q}return J}async readFragment($){if(this.lastReadFragment?.moofOffset===$)return this.lastReadFragment;let J=this.reader.requestSliceRange($,e1,v8);if(J instanceof Promise)J=await J;L(J);let Y=S1(J);L(Y?.name==="moof");let X=this.reader.requestSlice($,Y.totalSize);if(X instanceof Promise)X=await X;L(X),this.traverseBox(X);let Q=this.lastReadFragment;L(Q&&Q.moofOffset===$);for(let[,Z]of Q.trackData){let K=Z.track,{fragmentPositionCache:G}=K;if(!Z.startTimestampIsFinal){let j=K.fragmentLookupTable.find((U)=>U.moofOffset===Q.moofOffset);if(j)nJ(Z,j.timestamp);else{let U=p(G,Q.moofOffset-1,(q)=>q.moofOffset);if(U!==-1){let q=G[U];nJ(Z,q.endTimestamp)}}Z.startTimestampIsFinal=!0}let W=p(G,Z.startTimestamp,(j)=>j.startTimestamp);if(W===-1||G[W].moofOffset!==Q.moofOffset)G.splice(W+1,0,{moofOffset:Q.moofOffset,startTimestamp:Z.startTimestamp,endTimestamp:Z.endTimestamp});if(Z.encryptionAuxInfo&&K.encryptionInfo){let j=await GX(this.reader,K.encryptionInfo,Z.encryptionAuxInfo);for(let U=0;U<Math.min(Z.samples.length,j.length);U++){let q=j[U];Z.samples[U].encryption=q}}}return Q}readContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-e1)if(!this.traverseBox($))break}*iterateContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-e1){let Y=$.filePos,X=S1($);if(!X)break;yield{boxInfo:X,slice:$},$.filePos=Y+X.totalSize}}traverseBox($){let J=$.filePos,Y=S1($);if(!Y)return!1;let X=$.filePos,Q=J+Y.totalSize;switch(Y.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes($.slice(X,Y.contentSize));break;case"mvhd":{let Z=g($);if($.skip(3),Z===1)$.skip(16),this.movieTimescale=I($),this.movieDurationInTimescale=k0($);else $.skip(8),this.movieTimescale=I($),this.movieDurationInTimescale=I($)}break;case"trak":{let Z={id:-1,demuxer:this,trackBacking:null,disposition:{...M0,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Z0,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=Z,this.readContiguousBoxes($.slice(X,Y.contentSize)),Z.id!==-1&&Z.timescale!==-1&&Z.info!==null){if(Z.info.type==="video"&&Z.info.width!==-1){let K=Z;Z.trackBacking=new oJ(K),this.tracks.push(Z)}else if(Z.info.type==="audio"&&Z.info.numberOfChannels!==-1){let K=Z;Z.trackBacking=new sJ(K),this.tracks.push(Z)}}this.currentTrack=null}break;case"tkhd":{let Z=this.currentTrack;if(!Z)break;let K=g($),W=!!(Z1($)&1);if(Z.disposition.default=W,K===0)$.skip(8),Z.id=I($),$.skip(4),Z.durationInMovieTimescale=I($);else if(K===1)$.skip(16),Z.id=I($),$.skip(4),Z.durationInMovieTimescale=k0($);else throw Error(`Incorrect track header version ${K}.`);$.skip(16);let j=[$8($),$8($),I$($),$8($),$8($),I$($),$8($),$8($),I$($)],U=s1(S6(oZ(j),90));L(U===0||U===90||U===180||U===270),Z.rotation=U}break;case"elst":{let Z=this.currentTrack;if(!Z)break;let K=g($);$.skip(3);let G=!1,W=0,j=I($);for(let U=0;U<j;U++){let q=K===1?k0($):I($),V=K===1?WX($):h1($),_=$8($);if(q===0)continue;if(G){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(V===-1){W+=q;continue}if(_!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}Z.editListPreviousSegmentDurations=W,Z.editListOffset=V,G=!0}}break;case"mdhd":{let Z=this.currentTrack;if(!Z)break;let K=g($);if($.skip(3),K===0)$.skip(8),Z.timescale=I($),Z.durationInMediaTimescale=I($);else if(K===1)$.skip(16),Z.timescale=I($),Z.durationInMediaTimescale=k0($);let G=G0($);if(G>0){Z.languageCode="";for(let W=0;W<3;W++)Z.languageCode=String.fromCharCode(96+(G&31))+Z.languageCode,G>>=5;if(!c8(Z.languageCode))Z.languageCode=Z0}}break;case"hdlr":{let Z=this.currentTrack;if(!Z)break;$.skip(8);let K=J0($,4);if(K==="vide")Z.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null};else if(K==="soun")Z.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null}}break;case"stbl":{let Z=this.currentTrack;if(!Z)break;Z.sampleTableByteOffset=J,this.readContiguousBoxes($.slice(X,Y.contentSize))}break;case"stsd":{let Z=this.currentTrack;if(!Z)break;if(Z.info===null||Z.sampleTable)break;let K=g($);$.skip(3);let G=I($);for(let W=0;W<G;W++){let j=$.filePos,U=S1($);if(!U)break;Z.internalCodecId=U.name;let q=U.name.toLowerCase();if(Z.info.type==="video"){$.skip(24),Z.info.width=G0($),Z.info.height=G0($),Z.info.squarePixelWidth=Z.info.width,Z.info.squarePixelHeight=Z.info.height,$.skip(50),Z.frmaCodecString=null,this.readContiguousBoxes($.slice($.filePos,j+U.totalSize-$.filePos));let V=q==="encv"?Z.frmaCodecString:q;if(Z.frmaCodecString=null,V==="avc1"||V==="avc3")Z.info.codec="avc",Z.info.avcType=V==="avc1"?1:3;else if(V==="hvc1"||V==="hev1")Z.info.codec="hevc";else if(V==="vp08")Z.info.codec="vp8";else if(V==="vp09")Z.info.codec="vp9";else if(V==="av01")Z.info.codec="av1";else if(V===null)console.warn("Unknown encrypted video codec due to missing frma box.");else console.warn(`Unsupported video codec (sample entry type '${U.name}').`)}else{$.skip(8);let V=G0($);$.skip(6);let _=G0($),N=G0($);$.skip(4);let R=I($)/65536,z=null;if(K===0&&V>0){if(V===1)$.skip(4),N=8*I($),$.skip(8);else if(V===2)$.skip(4),R=f$($),_=I($),$.skip(4),N=I($),z=I($),$.skip(8)}Z.info.numberOfChannels=_,Z.info.sampleRate=R,Z.frmaCodecString=null,this.readContiguousBoxes($.slice($.filePos,j+U.totalSize-$.filePos));let H=q==="enca"?Z.frmaCodecString:q;if(Z.frmaCodecString=null,H==="mp4a");else if(H==="opus")Z.info.codec="opus",Z.info.sampleRate=x1;else if(H==="flac")Z.info.codec="flac";else if(H==="ulaw")Z.info.codec="ulaw";else if(H==="alaw")Z.info.codec="alaw";else if(H==="ac-3")Z.info.codec="ac3";else if(H==="ec-3")Z.info.codec="eac3";else if(H==="twos")if(N===8)Z.info.codec="pcm-s8";else if(N===16)Z.info.codec=Z.info.pcmLittleEndian?"pcm-s16":"pcm-s16be";else console.warn(`Unsupported sample size ${N} for codec 'twos'.`),Z.info.codec=null;else if(H==="sowt")if(N===8)Z.info.codec="pcm-s8";else if(N===16)Z.info.codec="pcm-s16";else console.warn(`Unsupported sample size ${N} for codec 'sowt'.`),Z.info.codec=null;else if(H==="raw ")Z.info.codec="pcm-u8";else if(H==="in24")Z.info.codec=Z.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(H==="in32")Z.info.codec=Z.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(H==="fl32")Z.info.codec=Z.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(H==="fl64")Z.info.codec=Z.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(H==="ipcm"){let A=Z.info.pcmSampleSize;if(Z.info.pcmLittleEndian)if(A===16)Z.info.codec="pcm-s16";else if(A===24)Z.info.codec="pcm-s24";else if(A===32)Z.info.codec="pcm-s32";else console.warn(`Invalid ipcm sample size ${A}.`),Z.info.codec=null;else if(A===16)Z.info.codec="pcm-s16be";else if(A===24)Z.info.codec="pcm-s24be";else if(A===32)Z.info.codec="pcm-s32be";else console.warn(`Invalid ipcm sample size ${A}.`),Z.info.codec=null}else if(H==="fpcm"){let A=Z.info.pcmSampleSize;if(Z.info.pcmLittleEndian)if(A===32)Z.info.codec="pcm-f32";else if(A===64)Z.info.codec="pcm-f64";else console.warn(`Invalid fpcm sample size ${A}.`),Z.info.codec=null;else if(A===32)Z.info.codec="pcm-f32be";else if(A===64)Z.info.codec="pcm-f64be";else console.warn(`Invalid fpcm sample size ${A}.`),Z.info.codec=null}else if(H==="lpcm"&&z!==null){let A=N+7>>3,M=Boolean(z&1),F=Boolean(z&2),O=z&4?-1:0;if(N>0&&N<=64){if(M){if(N===32)Z.info.codec=F?"pcm-f32be":"pcm-f32"}else if(O&1<<A-1){if(A===1)Z.info.codec="pcm-s8";else if(A===2)Z.info.codec=F?"pcm-s16be":"pcm-s16";else if(A===3)Z.info.codec=F?"pcm-s24be":"pcm-s24";else if(A===4)Z.info.codec=F?"pcm-s32be":"pcm-s32"}else if(A===1)Z.info.codec="pcm-u8"}if(Z.info.codec===null)console.warn("Unsupported PCM format.")}else if(H===null)console.warn("Unknown encrypted audio codec due to missing frma box.");else console.warn(`Unsupported audio codec (sample entry type '${U.name}').`)}$.filePos=j+U.totalSize}}break;case"frma":{let Z=this.currentTrack;if(!Z)break;let G=J0($,4).toLowerCase();Z.frmaCodecString=G}break;case"schm":{let Z=this.currentTrack;if(!Z)break;$.skip(4);let K=J0($,4);if(K==="cenc"||K==="cens"||K==="cbcs")Z.encryptionInfo={scheme:K,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null};else console.warn(`Unsupported encryption scheme '${K}'.`)}break;case"tenc":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;let K=g($);$.skip(3),$.skip(1);let G=g($);if(K>0)Z.encryptionInfo.defaultCryptByteBlock=G>>4,Z.encryptionInfo.defaultSkipByteBlock=G&15;else Z.encryptionInfo.defaultCryptByteBlock=0,Z.encryptionInfo.defaultSkipByteBlock=0;if(Z.encryptionInfo.defaultIsProtected=g($)!==0,Z.encryptionInfo.defaultPerSampleIvSize=g($),Z.encryptionInfo.defaultKid=r1(h($,16)),Z.encryptionInfo.defaultIsProtected&&Z.encryptionInfo.defaultPerSampleIvSize===0){let W=g($),j=new Uint8Array(16);j.set(h($,W),0),Z.encryptionInfo.defaultConstantIv=j}}break;case"avcC":{let Z=this.currentTrack;if(!Z)break;L(Z.info),Z.info.codecDescription=h($,Y.contentSize)}break;case"hvcC":{let Z=this.currentTrack;if(!Z)break;L(Z.info),Z.info.codecDescription=h($,Y.contentSize)}break;case"vpcC":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="video"),$.skip(4);let K=g($),G=g($),W=g($),j=W>>4,U=W>>1&7,q=W&1,V=g($),_=g($),N=g($);Z.info.vp9CodecInfo={profile:K,level:G,bitDepth:j,chromaSubsampling:U,videoFullRangeFlag:q,colourPrimaries:V,transferCharacteristics:_,matrixCoefficients:N}}break;case"av1C":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="video"),$.skip(1);let K=g($),G=K>>5,W=K&31,j=g($),U=j>>7,q=j>>6&1,V=j>>5&1,_=j>>4&1,N=j>>3&1,R=j>>2&1,z=j&3,H=G===2&&q?V?12:10:q?10:8;Z.info.av1CodecInfo={profile:G,level:W,tier:U,bitDepth:H,monochrome:_,chromaSubsamplingX:N,chromaSubsamplingY:R,chromaSamplePosition:z}}break;case"colr":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="video");let K=J0($,4);if(K!=="nclx"&&K!=="nclc")break;let G=G0($),W=G0($),j=G0($),U=void 0;if(K==="nclx")U=Boolean(g($)&128);Z.info.colorSpace={primaries:_8[G],transfer:z8[W],matrix:A8[j],fullRange:U}}break;case"pasp":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="video");let K=I($),G=I($);if(K>0&&G>0)if(K>G)Z.info.squarePixelWidth=Math.round(Z.info.width*K/G);else Z.info.squarePixelHeight=Math.round(Z.info.height*G/K)}break;case"wave":this.readContiguousBoxes($.slice(X,Y.contentSize));break;case"esds":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="audio"),$.skip(4);let K=g($);L(K===3),y$($),$.skip(2);let G=g($),W=(G&128)!==0,j=(G&64)!==0,U=(G&32)!==0;if(W)$.skip(2);if(j){let R=g($);$.skip(R)}if(U)$.skip(2);let q=g($);L(q===4);let V=y$($),_=$.filePos,N=g($);if(N===64||N===103)Z.info.codec="aac",Z.info.aacCodecInfo={isMpeg2:N===103,objectType:null};else if(N===105||N===107)Z.info.codec="mp3";else if(N===221)Z.info.codec="vorbis";else console.warn(`Unsupported audio codec (objectTypeIndication ${N}) - discarding track.`);if($.skip(12),V>$.filePos-_){let R=g($);L(R===5);let z=y$($);if(Z.info.codecDescription=h($,z),Z.info.codec==="aac"){let H=C8(Z.info.codecDescription);if(H.numberOfChannels!==null)Z.info.numberOfChannels=H.numberOfChannels;if(H.sampleRate!==null)Z.info.sampleRate=H.sampleRate}}}break;case"enda":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="audio"),Z.info.pcmLittleEndian=!!(G0($)&255)}break;case"pcmC":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="audio"),$.skip(4);let K=g($);Z.info.pcmLittleEndian=Boolean(K&1),Z.info.pcmSampleSize=g($)}break;case"dOps":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="audio"),$.skip(1);let K=g($),G=G0($),W=I($),j=r6($),U=g($),q;if(U!==0)q=h($,2+K);else q=new Uint8Array(0);let V=new Uint8Array(19+q.byteLength),_=new DataView(V.buffer);_.setUint32(0,1332770163,!1),_.setUint32(4,1214603620,!1),_.setUint8(8,1),_.setUint8(9,K),_.setUint16(10,G,!0),_.setUint32(12,W,!0),_.setInt16(16,j,!0),_.setUint8(18,U),V.set(q,19),Z.info.codecDescription=V,Z.info.numberOfChannels=K}break;case"dfLa":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="audio"),$.skip(4);let K=127,G=128,W=$.filePos;while($.filePos<Q){let _=g($),N=Z1($);if((_&K)===_1.STREAMINFO){$.skip(10);let z=I($),H=z>>>12,A=(z>>9&7)+1;Z.info.sampleRate=H,Z.info.numberOfChannels=A,$.skip(20)}else $.skip(N);if(_&G)break}let j=$.filePos;$.filePos=W;let U=h($,j-W),q=new Uint8Array(4+U.byteLength);new DataView(q.buffer).setUint32(0,1716281667,!1),q.set(U,4),Z.info.codecDescription=q}break;case"dac3":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="audio");let K=h($,3),G=new c(K),W=G.readBits(2);G.skipBits(8);let j=G.readBits(3),U=G.readBits(1);if(W<3)Z.info.sampleRate=P8[W];Z.info.numberOfChannels=s6[j]+U}break;case"dec3":{let Z=this.currentTrack;if(!Z)break;L(Z.info?.type==="audio");let K=h($,Y.contentSize),G=e7(K);if(!G){console.warn("Invalid dec3 box contents, ignoring.");break}let W=b$(G);if(W!==null)Z.info.sampleRate=W;Z.info.numberOfChannels=T$(G)}break;case"stts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=I($),G=0,W=0;for(let j=0;j<K;j++){let U=I($),q=I($);Z.sampleTable.sampleTimingEntries.push({startIndex:G,startDecodeTimestamp:W,count:U,delta:q}),G+=U,W+=U*q}}break;case"ctts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=I($),G=0;for(let W=0;W<K;W++){let j=I($),U=h1($);Z.sampleTable.sampleCompositionTimeOffsets.push({startIndex:G,count:j,offset:U}),G+=j}}break;case"stsz":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=I($),G=I($);if(K===0)for(let W=0;W<G;W++){let j=I($);Z.sampleTable.sampleSizes.push(j)}else Z.sampleTable.sampleSizes.push(K)}break;case"stz2":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),$.skip(3);let K=g($),G=I($),W=h($,Math.ceil(G*K/8)),j=new c(W);for(let U=0;U<G;U++){let q=j.readBits(K);Z.sampleTable.sampleSizes.push(q)}}break;case"stss":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),Z.sampleTable.keySampleIndices=[];let K=I($);for(let G=0;G<K;G++){let W=I($)-1;Z.sampleTable.keySampleIndices.push(W)}if(Z.sampleTable.keySampleIndices[0]!==0)Z.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=I($);for(let W=0;W<K;W++){let j=I($)-1,U=I($),q=I($);Z.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:j,samplesPerChunk:U,sampleDescriptionIndex:q})}let G=0;for(let W=0;W<Z.sampleTable.sampleToChunk.length;W++)if(Z.sampleTable.sampleToChunk[W].startSampleIndex=G,W<Z.sampleTable.sampleToChunk.length-1){let U=Z.sampleTable.sampleToChunk[W+1].startChunkIndex-Z.sampleTable.sampleToChunk[W].startChunkIndex;G+=U*Z.sampleTable.sampleToChunk[W].samplesPerChunk}}break;case"stco":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=I($);for(let G=0;G<K;G++){let W=I($);Z.sampleTable.chunkOffsets.push(W)}}break;case"co64":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=I($);for(let G=0;G<K;G++){let W=k0($);Z.sampleTable.chunkOffsets.push(W)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes($.slice(X,Y.contentSize));break;case"mehd":{let Z=g($);$.skip(3);let K=Z===1?k0($):I($);this.movieDurationInTimescale=K}break;case"trex":{$.skip(4);let Z=I($),K=I($),G=I($),W=I($),j=I($);this.fragmentTrackDefaults.push({trackId:Z,defaultSampleDescriptionIndex:K,defaultSampleDuration:G,defaultSampleSize:W,defaultSampleFlags:j})}break;case"tfra":{let Z=g($);$.skip(3);let K=I($),G=this.tracks.find((H)=>H.id===K);if(!G)break;let W=I($),j=(W&48)>>4,U=(W&12)>>2,q=W&3,V=[g,G0,Z1,I],_=V[j],N=V[U],R=V[q],z=I($);for(let H=0;H<z;H++){let A=Z===1?k0($):I($),M=Z===1?k0($):I($);_($),N($),R($),G.fragmentLookupTable.push({timestamp:A,moofOffset:M})}G.fragmentLookupTable.sort((H,A)=>H.timestamp-A.timestamp);for(let H=0;H<G.fragmentLookupTable.length-1;H++){let A=G.fragmentLookupTable[H],M=G.fragmentLookupTable[H+1];if(A.timestamp===M.timestamp)G.fragmentLookupTable.splice(H+1,1),H--}}break;case"moof":this.currentFragment={moofOffset:J,moofSize:Y.totalSize,implicitBaseDataOffset:J,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes($.slice(X,Y.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(L(this.currentFragment),this.readContiguousBoxes($.slice(X,Y.contentSize)),this.currentTrack){let Z=this.currentFragment.trackData.get(this.currentTrack.id);$:if(Z){if(Z.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break $}Z.presentationTimestamps=Z.samples.map((j,U)=>({presentationTimestamp:j.presentationTimestamp,sampleIndex:U})).sort((j,U)=>j.presentationTimestamp-U.presentationTimestamp);for(let j=0;j<Z.presentationTimestamps.length;j++){let U=Z.presentationTimestamps[j],q=Z.samples[U.sampleIndex];if(Z.firstKeyFrameTimestamp===null&&q.isKeyFrame)Z.firstKeyFrameTimestamp=q.presentationTimestamp;if(j<Z.presentationTimestamps.length-1){let _=Z.presentationTimestamps[j+1].presentationTimestamp-U.presentationTimestamp;q.duration=_}}let K=Z.samples[Z.presentationTimestamps[0].sampleIndex],G=Z.samples[K0(Z.presentationTimestamps).sampleIndex];Z.startTimestamp=K.presentationTimestamp,Z.endTimestamp=G.presentationTimestamp+G.duration;let{currentFragmentState:W}=this.currentTrack;if(L(W),W.startTimestamp!==null)nJ(Z,W.startTimestamp),Z.startTimestampIsFinal=!0;if(W.encryptionAuxInfo&&!Z.samples[0].encryption)Z.encryptionAuxInfo=W.encryptionAuxInfo}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let Z=v$(h($,Y.contentSize));if(this.currentFragment)this.currentFragment.psshBoxes.push(Z);else if(!this.currentTrack)this.psshBoxes.push(Z)}break;case"tfhd":{L(this.currentFragment),$.skip(1);let Z=Z1($),K=Boolean(Z&1),G=Boolean(Z&2),W=Boolean(Z&8),j=Boolean(Z&16),U=Boolean(Z&32),q=Boolean(Z&65536),V=Boolean(Z&131072),_=I($),N=this.tracks.find((z)=>z.id===_);if(!N)break;let R=this.fragmentTrackDefaults.find((z)=>z.trackId===_);if(this.currentTrack=N,N.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:R?.defaultSampleDescriptionIndex??null,defaultSampleDuration:R?.defaultSampleDuration??null,defaultSampleSize:R?.defaultSampleSize??null,defaultSampleFlags:R?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},K)N.currentFragmentState.baseDataOffset=k0($);else if(V)N.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset;if(G)N.currentFragmentState.sampleDescriptionIndex=I($);if(W)N.currentFragmentState.defaultSampleDuration=I($);if(j)N.currentFragmentState.defaultSampleSize=I($);if(U)N.currentFragmentState.defaultSampleFlags=I($);if(q)N.currentFragmentState.defaultSampleDuration=0}break;case"tfdt":{let Z=this.currentTrack;if(!Z)break;L(Z.currentFragmentState);let K=g($);$.skip(3);let G=K===0?I($):k0($);Z.currentFragmentState.startTimestamp=G}break;case"trun":{let Z=this.currentTrack;if(!Z)break;L(this.currentFragment),L(Z.currentFragmentState);let K=g($),G=Z1($),W=Boolean(G&1),j=Boolean(G&4),U=Boolean(G&256),q=Boolean(G&512),V=Boolean(G&1024),_=Boolean(G&2048),N=I($),R=null;if(W)R=h1($);let z=null;if(j)z=I($);let H;if(this.currentFragment.trackData.has(Z.id)){if(H=this.currentFragment.trackData.get(Z.id),R!==null)H.currentOffset=Z.currentFragmentState.baseDataOffset+R}else H={track:Z,currentTimestamp:0,currentOffset:Z.currentFragmentState.baseDataOffset+(R??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(Z.id,H);for(let A=0;A<N;A++){let M;if(U)M=I($);else L(Z.currentFragmentState.defaultSampleDuration!==null),M=Z.currentFragmentState.defaultSampleDuration;let F;if(q)F=I($);else L(Z.currentFragmentState.defaultSampleSize!==null),F=Z.currentFragmentState.defaultSampleSize;let O;if(V)O=I($);else L(Z.currentFragmentState.defaultSampleFlags!==null),O=Z.currentFragmentState.defaultSampleFlags;if(A===0&&z!==null)O=z;let B=0;if(_)if(K===0)B=I($);else B=h1($);let D=!(O&65536);H.samples.push({presentationTimestamp:H.currentTimestamp+B,duration:M,byteOffset:H.currentOffset,byteSize:F,isKeyFrame:D,encryption:null}),H.currentOffset+=F,H.currentTimestamp+=M}this.currentFragment.implicitBaseDataOffset=H.currentOffset}break;case"saiz":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;if($.skip(1),Z1($)&1){let q=J0($,4),V=I($);if(q!==Z.encryptionInfo.scheme||V!==0)break}let G=g($),W=I($),j=null;if(G===0&&W>0)j=h($,W);let U=QX(Z);U.defaultSampleInfoSize=G,U.sampleSizes=j,U.sampleCount=W}break;case"saio":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;let K=g($);if(Z1($)&1){let q=J0($,4),V=I($);if(q!==Z.encryptionInfo.scheme||V!==0)break}let W=I($);if(W===0)break;if(W>1)console.warn("Multiple saio entries are not supported; using the first offset only.");let j=K===0?I($):Number(k0($));if(this.currentFragment)j+=this.currentFragment.moofOffset;let U=QX(Z);U.offset=j}break;case"senc":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;L(this.currentFragment);let K=this.currentFragment.trackData.get(Z.id);if(!K)break;$.skip(1);let G=Z1($),W=Boolean(G&2),j=I($),U=Z.encryptionInfo.defaultPerSampleIvSize;L(U!==null);for(let q=0;q<Math.min(j,K.samples.length);q++){let V=new Uint8Array(16);if(U>0)V.set(h($,U),0);else V.set(Z.encryptionInfo.defaultConstantIv,0);let _=null;if(W){let R=G0($);_=[];for(let z=0;z<R;z++){let H=G0($),A=I($);_.push({clearLen:H,protectedLen:A})}}let N=K.samples[q];N.encryption={iv:V,subsamples:_}}}break;case"udta":{let Z=this.iterateContiguousBoxes($.slice(X,Y.contentSize));for(let{boxInfo:K,slice:G}of Z){if(K.name!=="meta"&&!this.currentTrack){let W=G.filePos;if(this.metadataTags.raw??={},K.name[0]==="©")this.metadataTags.raw[K.name]??=Y1(G);else this.metadataTags.raw[K.name]??=h(G,K.contentSize);G.filePos=W}switch(K.name){case"meta":G.skip(-K.headerSize),this.traverseBox(G);break;case"©nam":case"name":if(this.currentTrack)this.currentTrack.name=H0.decode(h(G,K.contentSize));else this.metadataTags.title??=Y1(G);break;case"©des":if(!this.currentTrack)this.metadataTags.description??=Y1(G);break;case"©ART":if(!this.currentTrack)this.metadataTags.artist??=Y1(G);break;case"©alb":if(!this.currentTrack)this.metadataTags.album??=Y1(G);break;case"albr":if(!this.currentTrack)this.metadataTags.albumArtist??=Y1(G);break;case"©gen":if(!this.currentTrack)this.metadataTags.genre??=Y1(G);break;case"©day":if(!this.currentTrack){let W=new Date(Y1(G));if(!Number.isNaN(W.getTime()))this.metadataTags.date??=W}break;case"©cmt":if(!this.currentTrack)this.metadataTags.comment??=Y1(G);break;case"©lyr":if(!this.currentTrack)this.metadataTags.lyrics??=Y1(G);break}}}break;case"meta":{if(this.currentTrack)break;let K=I($)!==0;if(this.currentMetadataKeys=new Map,K)this.readContiguousBoxes($.slice(X,Y.contentSize));else this.readContiguousBoxes($.slice(X+4,Y.contentSize-4));this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;$.skip(4);let Z=I($);for(let K=0;K<Z;K++){let G=I($);$.skip(4);let W=H0.decode(h($,G-8));this.currentMetadataKeys.set(K+1,W)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let Z=this.iterateContiguousBoxes($.slice(X,Y.contentSize));for(let{boxInfo:K,slice:G}of Z){let W=K.name,j=(W.charCodeAt(0)<<24)+(W.charCodeAt(1)<<16)+(W.charCodeAt(2)<<8)+W.charCodeAt(3);if(this.currentMetadataKeys.has(j))W=this.currentMetadataKeys.get(j);let U=$X(G);switch(this.metadataTags.raw??={},this.metadataTags.raw[W]??=U,W){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":if(typeof U==="string")this.metadataTags.title??=U;break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":if(typeof U==="string")this.metadataTags.description??=U;break;case"©ART":case"com.apple.quicktime.artist":case"artist":if(typeof U==="string")this.metadataTags.artist??=U;break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":if(typeof U==="string")this.metadataTags.album??=U;break;case"aART":case"album_artist":if(typeof U==="string")this.metadataTags.albumArtist??=U;break;case"©cmt":case"com.apple.quicktime.comment":case"comment":if(typeof U==="string")this.metadataTags.comment??=U;break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":if(typeof U==="string")this.metadataTags.genre??=U;break;case"©lyr":case"lyrics":if(typeof U==="string")this.metadataTags.lyrics??=U;break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof U==="string"){let q=new Date(U);if(!Number.isNaN(q.getTime()))this.metadataTags.date??=q}break;case"covr":case"com.apple.quicktime.artwork":if(U instanceof P1)this.metadataTags.images??=[],this.metadataTags.images.push({data:U.data,kind:"coverFront",mimeType:U.mimeType});else if(U instanceof Uint8Array)this.metadataTags.images??=[],this.metadataTags.images.push({data:U,kind:"coverFront",mimeType:"image/*"});break;case"track":if(typeof U==="string"){let q=U.split("/"),V=Number.parseInt(q[0],10),_=q[1]&&Number.parseInt(q[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(_&&Number.isInteger(_)&&_>0)this.metadataTags.tracksTotal??=_}break;case"trkn":if(U instanceof Uint8Array&&U.length>=6){let q=u(U),V=q.getUint16(2,!1),_=q.getUint16(4,!1);if(V>0)this.metadataTags.trackNumber??=V;if(_>0)this.metadataTags.tracksTotal??=_}break;case"disc":case"disk":if(U instanceof Uint8Array&&U.length>=6){let q=u(U),V=q.getUint16(2,!1),_=q.getUint16(4,!1);if(V>0)this.metadataTags.discNumber??=V;if(_>0)this.metadataTags.discsTotal??=_}break}}}break}return $.filePos=Q,!0}}class iJ{constructor($){this.internalTrack=$,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let $=this.internalTrack.demuxer,J=this.internalTrack.trackBacking.getType(),Y=0;for(let X of $.tracks){if(X.trackBacking.getType()===J)Y++;if(X===this.internalTrack)break}return Y}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}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let $=this.internalTrack;if($.durationInMediaTimescale<=0)return null;return L($.trackBacking),((await $.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+$.durationInMediaTimescale/$.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket($){let J=await this.fetchPacketForSampleIndex(0,$);if(J||!this.internalTrack.demuxer.isFragmented)return J;return this.performFragmentedLookup(null,(Y)=>{if(Y.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,$)}mapTimestampIntoTimescale($){return E1($*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket($,J){let Y=this.mapTimestampIntoTimescale($),X=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Q=rJ(X,Y),Z=await this.fetchPacketForSampleIndex(Q,J);if(!ZX(X)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(K)=>{let G=K.trackData.get(this.internalTrack.id);if(!G)return{sampleIndex:-1,correctSampleFound:!1};let W=p(G.presentationTimestamps,Y,(q)=>q.presentationTimestamp),j=W!==-1?G.presentationTimestamps[W].sampleIndex:-1,U=W!==-1&&Y<G.endTimestamp;return{sampleIndex:j,correctSampleFound:U}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0)return this.fetchPacketForSampleIndex(Y+1,J);let X=this.packetToFragmentLocation.get($);if(X===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(X.fragment,(Q)=>{if(Q===X.fragment){let Z=Q.trackData.get(this.internalTrack.id);if(X.sampleIndex+1<Z.samples.length)return{sampleIndex:X.sampleIndex+1,correctSampleFound:!0}}else if(Q.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let Y=this.mapTimestampIntoTimescale($),X=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Q=dZ(X,Y),Z=await this.fetchPacketForSampleIndex(Q,J);if(!ZX(X)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(K)=>{let G=K.trackData.get(this.internalTrack.id);if(!G)return{sampleIndex:-1,correctSampleFound:!1};let W=L8(G.presentationTimestamps,(q)=>{return G.samples[q.sampleIndex].isKeyFrame&&q.presentationTimestamp<=Y}),j=W!==-1?G.presentationTimestamps[W].sampleIndex:-1,U=W!==-1&&Y<G.endTimestamp;return{sampleIndex:j,correctSampleFound:U}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0){let Q=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Z=nZ(Q,Y);return this.fetchPacketForSampleIndex(Z,J)}let X=this.packetToFragmentLocation.get($);if(X===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(X.fragment,(Q)=>{if(Q===X.fragment){let K=Q.trackData.get(this.internalTrack.id).samples.findIndex((G,W)=>G.isKeyFrame&&W>X.sampleIndex);if(K!==-1)return{sampleIndex:K,correctSampleFound:!0}}else{let Z=Q.trackData.get(this.internalTrack.id);if(Z&&Z.firstKeyFrameTimestamp!==null){let K=Z.samples.findIndex((G)=>G.isKeyFrame);return L(K!==-1),{sampleIndex:K,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async fetchPacketForSampleIndex($,J){if($===-1)return null;let Y=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=cZ(Y,$);if(!X)return null;let Q;if(J.metadataOnly)Q=V0;else{let W=this.internalTrack.demuxer.reader.requestSlice(X.sampleOffset,X.sampleSize);if(W instanceof Promise)W=await W;if(!W)return null;if(Q=h(W,X.sampleSize),this.internalTrack.encryptionAuxInfo){L(this.internalTrack.encryptionInfo);let j=await GX(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);if($<j.length)Q=await KX(this.internalTrack,j[$],Q,null)}}let Z=(X.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,K=X.duration/this.internalTrack.timescale,G=new i(Q,X.isKeyFrame?"key":"delta",Z,K,$,X.sampleSize);return this.packetToSampleIndex.set(G,$),G}async fetchPacketInFragment($,J,Y){if(J===-1)return null;let Q=$.trackData.get(this.internalTrack.id).samples[J];L(Q);let Z;if(Y.metadataOnly)Z=V0;else{let j=this.internalTrack.demuxer.reader.requestSlice(Q.byteOffset,Q.byteSize);if(j instanceof Promise)j=await j;if(!j)return null;if(Z=h(j,Q.byteSize),Q.encryption)Z=await KX(this.internalTrack,Q.encryption,Z,$)}let K=(Q.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,G=Q.duration/this.internalTrack.timescale,W=new i(Z,Q.isKeyFrame?"key":"delta",K,G,$.moofOffset+J,Q.byteSize);return this.packetToFragmentLocation.set(W,{fragment:$,sampleIndex:J}),W}async performFragmentedLookup($,J,Y,X,Q){let Z=this.internalTrack.demuxer,K=null,G=null,W=-1;if($){let{sampleIndex:R,correctSampleFound:z}=J($);if(z)return this.fetchPacketInFragment($,R,Q);if(R!==-1)G=$,W=R}let j=p(this.internalTrack.fragmentLookupTable,Y,(R)=>R.timestamp),U=j!==-1?this.internalTrack.fragmentLookupTable[j]:null,q=p(this.internalTrack.fragmentPositionCache,Y,(R)=>R.startTimestamp),V=q!==-1?this.internalTrack.fragmentPositionCache[q]:null,_=Math.max(U?.moofOffset??0,V?.moofOffset??0)||null,N;if(!$)N=_??0;else if(_===null||$.moofOffset>=_)N=$.moofOffset+$.moofSize,K=$;else N=_;while(!0){if(K){let A=K.trackData.get(this.internalTrack.id);if(A&&A.startTimestamp>X)break}let R=Z.reader.requestSliceRange(N,e1,v8);if(R instanceof Promise)R=await R;if(!R)break;let z=N,H=S1(R);if(!H)break;if(H.name==="moof"){K=await Z.readFragment(z);let{sampleIndex:A,correctSampleFound:M}=J(K);if(M)return this.fetchPacketInFragment(K,A,Q);if(A!==-1)G=K,W=A}N=z+H.totalSize}if(U&&(!G||G.moofOffset<U.moofOffset)){let R=this.internalTrack.fragmentLookupTable[j-1];L(!R||R.timestamp<U.timestamp);let z=R?.timestamp??-1/0;return this.performFragmentedLookup(null,J,z,X,Q)}if(G)return this.fetchPacketInFragment(G,W,Q);return null}}class oJ extends iJ{constructor($){super($);this.decoderConfigPromise=null,this.internalTrack=$}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let J=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=J&&E$(J.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let J=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=J&&P$(J.data)}let $={codec:i8(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};if(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)$.displayAspectWidth=this.internalTrack.info.squarePixelWidth,$.displayAspectHeight=this.internalTrack.info.squarePixelHeight;return $})()}}class sJ extends iJ{constructor($){super($);this.decoderConfig=null,this.internalTrack=$}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:a8(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}var rJ=($,J)=>{if($.presentationTimestamps){let Y=p($.presentationTimestamps,J,(X)=>X.presentationTimestamp);if(Y===-1)return-1;return $.presentationTimestamps[Y].sampleIndex}else{let Y=p($.sampleTimingEntries,J,(Q)=>Q.startDecodeTimestamp);if(Y===-1)return-1;let X=$.sampleTimingEntries[Y];return X.startIndex+Math.min(Math.floor((J-X.startDecodeTimestamp)/X.delta),X.count-1)}},dZ=($,J)=>{if(!$.keySampleIndices)return rJ($,J);if($.presentationTimestamps){let Y=p($.presentationTimestamps,J,(X)=>X.presentationTimestamp);if(Y===-1)return-1;for(let X=Y;X>=0;X--){let Q=$.presentationTimestamps[X].sampleIndex;if(C1($.keySampleIndices,Q,(K)=>K)!==-1)return Q}return-1}else{let Y=rJ($,J),X=p($.keySampleIndices,Y,(Q)=>Q);return $.keySampleIndices[X]??-1}},cZ=($,J)=>{let Y=p($.sampleTimingEntries,J,(H)=>H.startIndex),X=$.sampleTimingEntries[Y];if(!X||X.startIndex+X.count<=J)return null;let Z=X.startDecodeTimestamp+(J-X.startIndex)*X.delta,K=p($.sampleCompositionTimeOffsets,J,(H)=>H.startIndex),G=$.sampleCompositionTimeOffsets[K];if(G&&J-G.startIndex<G.count)Z+=G.offset;let W=$.sampleSizes[Math.min(J,$.sampleSizes.length-1)],j=p($.sampleToChunk,J,(H)=>H.startSampleIndex),U=$.sampleToChunk[j];L(U);let q=U.startChunkIndex+Math.floor((J-U.startSampleIndex)/U.samplesPerChunk),V=$.chunkOffsets[q],_=U.startSampleIndex+(q-U.startChunkIndex)*U.samplesPerChunk,N=0,R=V;if($.sampleSizes.length===1)R+=W*(J-_),N+=W*U.samplesPerChunk;else for(let H=_;H<_+U.samplesPerChunk;H++){let A=$.sampleSizes[H];if(H<J)R+=A;N+=A}let z=X.delta;if($.presentationTimestamps){let H=$.presentationTimestampIndexMap[J];if(L(H!==void 0),H<$.presentationTimestamps.length-1)z=$.presentationTimestamps[H+1].presentationTimestamp-Z}return{presentationTimestamp:Z,duration:z,sampleOffset:R,sampleSize:W,chunkOffset:V,chunkSize:N,isKeyFrame:$.keySampleIndices?C1($.keySampleIndices,J,(H)=>H)!==-1:!0}},nZ=($,J)=>{if(!$.keySampleIndices)return J+1;let Y=p($.keySampleIndices,J,(X)=>X);return $.keySampleIndices[Y+1]??-1},nJ=($,J)=>{$.startTimestamp+=J,$.endTimestamp+=J;for(let Y of $.samples)Y.presentationTimestamp+=J;for(let Y of $.presentationTimestamps)Y.presentationTimestamp+=J},oZ=($)=>{let[J,Y]=$,X=Math.atan2(Y,J);if(!Number.isFinite(X))return 0;return X*(180/Math.PI)},ZX=($)=>{return $.sampleSizes.length===0},QX=($)=>{if($.currentFragmentState)return $.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null};else return $.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}},GX=async($,J,Y)=>{if(Y.resolved)return Y.resolved;if(Y.offset===null||Y.sampleCount===0)throw Error("Incomplete saiz/saio info; cannot resolve encryption data.");let X=0;if(Y.defaultSampleInfoSize>0)X=Y.defaultSampleInfoSize*Y.sampleCount;else{L(Y.sampleSizes);for(let G=0;G<Y.sampleCount;G++)X+=Y.sampleSizes[G]}let Q=$.requestSlice(Y.offset,X);if(Q instanceof Promise)Q=await Q;if(!Q)throw Error("Failed to read auxiliary encryption info.");let Z=J.defaultPerSampleIvSize;L(Z!==null);let K=[];for(let G=0;G<Y.sampleCount;G++){let W=Y.defaultSampleInfoSize>0?Y.defaultSampleInfoSize:Y.sampleSizes[G],j=new Uint8Array(16);if(Z>0)j.set(h(Q,Z),0);else j.set(J.defaultConstantIv,0);let U=null;if(W>Z){let q=G0(Q);U=[];for(let V=0;V<q;V++){let _=G0(Q),N=I(Q);U.push({clearLen:_,protectedLen:N})}}K.push({iv:j,subsamples:U})}return Y.resolved=K,K},KX=async($,J,Y,X)=>{L($.encryptionInfo);let Q=$.encryptionInfo;L(Q.defaultKid!==null);let Z=Q.defaultKid,K,G=$.demuxer.decryptionKeyCache.get(Z);if(G)K=await G;else{if(!$.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let W=(async()=>{let j=$.demuxer.psshBoxes;if(X){j=[...j,...X.psshBoxes].filter((q)=>q.keyIds===null||q.keyIds.includes(Z));for(let q=0;q<j.length-1;q++)for(let V=q+1;V<j.length;V++)if(x$(j[q],j[V]))j.splice(V,1),V--}let U=await $.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:Z,psshBoxes:j});if(!(typeof U==="string"&&U.length===32&&P7.test(U)||U instanceof Uint8Array&&U.byteLength===16))throw TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return U instanceof Uint8Array?U:b7(U)})();$.demuxer.decryptionKeyCache.set(Z,W),K=await W}if(Q.scheme==="cenc"||Q.scheme==="cens")return sZ(K,Q,J,Y);else return rZ(K,Q,J,Y)},sZ=async($,J,Y,X)=>{let Q=new Uint8Array(16);Q.set(Y.iv,0);let Z=await crypto.subtle.importKey("raw",$,{name:"AES-CTR"},!1,["decrypt"]),K=async(N)=>{let R=await crypto.subtle.decrypt({name:"AES-CTR",counter:Q,length:64},Z,N);return new Uint8Array(R)};if(!Y.subsamples)return K(X);L(J.defaultCryptByteBlock!==null&&J.defaultSkipByteBlock!==null);let G=UX(Y.subsamples,J.defaultCryptByteBlock,J.defaultSkipByteBlock),W=0;for(let N of G)for(let R of N.perSubsample)W+=R.length;let j=new Uint8Array(W),U=0;for(let N of G)for(let R of N.perSubsample)j.set(X.subarray(R.offset,R.offset+R.length),U),U+=R.length;let q=await K(j),V=new Uint8Array(X),_=0;for(let N of G)for(let R of N.perSubsample)V.set(q.subarray(_,_+R.length),R.offset),_+=R.length;return V},rZ=($,J,Y,X)=>{let Q=new S$;Q.init({key:$,iv:Y.iv});let{defaultCryptByteBlock:Z,defaultSkipByteBlock:K}=J;if(L(Z!==null&&K!==null),!Y.subsamples){let U=new Uint8Array(X),q=Math.floor(X.length/16);for(let V=0;V<q;V++){let _=V*16;Q.in.set(X.subarray(_,_+16)),Q.decrypt(),U.set(Q.out,_)}return U}if(Z===0&&K===0)throw Error("cbcs with subsamples requires pattern encryption.");let G=new Uint8Array(X),W=UX(Y.subsamples,Z,K),j=new DataView(Y.iv.buffer,Y.iv.byteOffset,16);for(let U of W){Q.iv[0]=j.getUint32(0,!1),Q.iv[1]=j.getUint32(4,!1),Q.iv[2]=j.getUint32(8,!1),Q.iv[3]=j.getUint32(12,!1);for(let q of U.perSubsample){let V=q.length/16;for(let _=0;_<V;_++){let N=q.offset+_*16;Q.in.set(X.subarray(N,N+16)),Q.decrypt(),G.set(Q.out,N)}}}return G},UX=($,J,Y)=>{let X=[],Q=J!==0||Y!==0,Z=0;for(let K of $){Z+=K.clearLen;let G=[];if(!Q){if(K.protectedLen>0)G.push({offset:Z,length:K.protectedLen});Z+=K.protectedLen}else{let W=K.protectedLen,j=Z;while(W>0){if(W<16*J)break;let U=16*J;G.push({offset:j,length:U}),j+=U,W-=U;let q=Math.min(16*Y,W);j+=q,W-=q}Z+=K.protectedLen}X.push({perSubsample:G})}return X};/*!
|
|
85
|
+
*/var N1=16,d1=new Uint32Array(256),q6=new Uint32Array(256),N6=new Uint32Array(256),V6=new Uint32Array(256),_6=new Uint32Array(256),h0=new Uint32Array(256),YX=new Uint32Array(10),XX=!1,iZ=()=>{let $=new Uint8Array(256),J=new Uint8Array(256),Y=new Uint8Array(256);for(let Z=0,K=1;Z<256;Z++)Y[Z]=K,J[K]=Z,K=K^K<<1^(K&128?283:0);let X=(Z,K)=>Z&&K?Y[(J[Z]+J[K])%255]:0;$[0]=99;for(let Z=1;Z<256;Z++){let K=Y[255-J[Z]],G=K^K<<1^K<<2^K<<3^K<<4;G=G>>>8^G&255^99,$[Z]=G}for(let Z=0;Z<256;Z++){let K=$[Z],G=$.indexOf(Z);d1[Z]=K<<24|K<<16|K<<8|K,h0[Z]=G<<24|G<<16|G<<8|G;let W=X(G,14),j=X(G,9),U=X(G,13),q=X(G,11),N=W<<24|j<<16|U<<8|q;q6[Z]=N,N6[Z]=N>>>8|N<<24,V6[Z]=N>>>16|N<<16,_6[Z]=N>>>24|N<<8}let Q=1;for(let Z=0;Z<10;Z++)YX[Z]=Q<<24,Q=Q<<1^(Q&128?283:0);XX=!0};class m${constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(N1/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(N1),this.out=new Uint8Array(N1),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:$,iv:J}){if(F($.byteLength===16),F(J.byteLength===16),!XX)iZ();let Y=new DataView($.buffer,$.byteOffset,$.byteLength),X=new DataView(J.buffer,J.byteOffset,J.byteLength);this.roundkey[0]=Y.getUint32(0,!1),this.roundkey[1]=Y.getUint32(4,!1),this.roundkey[2]=Y.getUint32(8,!1),this.roundkey[3]=Y.getUint32(12,!1),this.iv[0]=X.getUint32(0,!1),this.iv[1]=X.getUint32(4,!1),this.iv[2]=X.getUint32(8,!1),this.iv[3]=X.getUint32(12,!1);for(let Q=4;Q<44;Q+=4){let Z=this.roundkey[Q-1];this.roundkey[Q]=this.roundkey[Q-4]^d1[Z>>>16&255]&4278190080^d1[Z>>>8&255]&16711680^d1[Z>>>0&255]&65280^d1[Z>>>24&255]&255^YX[Q/4-1],this.roundkey[Q+1]=this.roundkey[Q-3]^this.roundkey[Q],this.roundkey[Q+2]=this.roundkey[Q-2]^this.roundkey[Q+1],this.roundkey[Q+3]=this.roundkey[Q-1]^this.roundkey[Q+2]}for(let Q=0,Z=40;Q<Z;Q+=4,Z-=4)for(let K=0;K<4;K++){let G=this.roundkey[Q+K];this.roundkey[Q+K]=this.roundkey[Z+K],this.roundkey[Z+K]=G}for(let Q=4;Q<40;Q+=4)for(let Z=0;Z<4;Z++){let K=this.roundkey[Q+Z];this.roundkey[Q+Z]=q6[d1[K>>>24&255]&255]^N6[d1[K>>>16&255]&255]^V6[d1[K>>>8&255]&255]^_6[d1[K>>>0&255]&255]}}decrypt(){let $=this.inView.getUint32(0,!1)^this.roundkey[0],J=this.inView.getUint32(4,!1)^this.roundkey[1],Y=this.inView.getUint32(8,!1)^this.roundkey[2],X=this.inView.getUint32(12,!1)^this.roundkey[3],Q=this.inView.getUint32(0,!1),Z=this.inView.getUint32(4,!1),K=this.inView.getUint32(8,!1),G=this.inView.getUint32(12,!1),W,j,U,q;for(let R=1;R<10;R++){let H=R*4;W=q6[$>>>24]^N6[X>>>16&255]^V6[Y>>>8&255]^_6[J&255]^this.roundkey[H],j=q6[J>>>24]^N6[$>>>16&255]^V6[X>>>8&255]^_6[Y&255]^this.roundkey[H+1],U=q6[Y>>>24]^N6[J>>>16&255]^V6[$>>>8&255]^_6[X&255]^this.roundkey[H+2],q=q6[X>>>24]^N6[Y>>>16&255]^V6[J>>>8&255]^_6[$&255]^this.roundkey[H+3],$=W,J=j,Y=U,X=q}let N=h0[$>>>24&255]&4278190080^h0[X>>>16&255]&16711680^h0[Y>>>8&255]&65280^h0[J>>>0&255]&255^this.roundkey[40],_=h0[J>>>24&255]&4278190080^h0[$>>>16&255]&16711680^h0[X>>>8&255]&65280^h0[Y>>>0&255]&255^this.roundkey[41],V=h0[Y>>>24&255]&4278190080^h0[J>>>16&255]&16711680^h0[$>>>8&255]&65280^h0[X>>>0&255]&255^this.roundkey[42],z=h0[X>>>24&255]&4278190080^h0[Y>>>16&255]&16711680^h0[J>>>8&255]&65280^h0[$>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,N^this.iv[0],!1),this.outView.setUint32(4,_^this.iv[1],!1),this.outView.setUint32(8,V^this.iv[2],!1),this.outView.setUint32(12,z^this.iv[3],!1),this.iv[0]=Q,this.iv[1]=Z,this.iv[2]=K,this.iv[3]=G}}var ZX=($,J,Y)=>{let X=!1,Q=0,Z=65536,K=16,G=new m$;return new ReadableStream({pull:async(W)=>{if(!X)G.init(await J()),X=!0;let j=Z+K,U=$.requestSliceRange(Q,0,j);if(U instanceof Promise)U=await U;if(!U||U.length===0)throw Error("Invalid ciphertext.");let q=U.length;if(q%16!==0)throw Error("Invalid ciphertext.");let N=q===j?q-K:q,_=f(U,N),V=new Uint8Array(N);for(let z=0;z<N;z+=16)G.in.set(_.subarray(z,z+16)),G.decrypt(),V.set(G.out,z);if(N<q)W.enqueue(V),Q+=N;else{let z=V[N-1];if(z===0||z>16)throw Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let R=V.subarray(0,N-z);W.enqueue(R),W.close(),Y()}},cancel:()=>{Y()}})};/*!
|
|
86
86
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
87
87
|
*
|
|
88
88
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
89
89
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
90
90
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
91
|
-
*/var b;(function($){$[$.EBML=440786851]="EBML",$[$.EBMLVersion=17030]="EBMLVersion",$[$.EBMLReadVersion=17143]="EBMLReadVersion",$[$.EBMLMaxIDLength=17138]="EBMLMaxIDLength",$[$.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",$[$.DocType=17026]="DocType",$[$.DocTypeVersion=17031]="DocTypeVersion",$[$.DocTypeReadVersion=17029]="DocTypeReadVersion",$[$.Void=236]="Void",$[$.Segment=408125543]="Segment",$[$.SeekHead=290298740]="SeekHead",$[$.Seek=19899]="Seek",$[$.SeekID=21419]="SeekID",$[$.SeekPosition=21420]="SeekPosition",$[$.Duration=17545]="Duration",$[$.Info=357149030]="Info",$[$.TimestampScale=2807729]="TimestampScale",$[$.MuxingApp=19840]="MuxingApp",$[$.WritingApp=22337]="WritingApp",$[$.Tracks=374648427]="Tracks",$[$.TrackEntry=174]="TrackEntry",$[$.TrackNumber=215]="TrackNumber",$[$.TrackUID=29637]="TrackUID",$[$.TrackType=131]="TrackType",$[$.FlagEnabled=185]="FlagEnabled",$[$.FlagDefault=136]="FlagDefault",$[$.FlagForced=21930]="FlagForced",$[$.FlagOriginal=21934]="FlagOriginal",$[$.FlagHearingImpaired=21931]="FlagHearingImpaired",$[$.FlagVisualImpaired=21932]="FlagVisualImpaired",$[$.FlagCommentary=21935]="FlagCommentary",$[$.FlagLacing=156]="FlagLacing",$[$.Name=21358]="Name",$[$.Language=2274716]="Language",$[$.LanguageBCP47=2274717]="LanguageBCP47",$[$.CodecID=134]="CodecID",$[$.CodecPrivate=25506]="CodecPrivate",$[$.CodecDelay=22186]="CodecDelay",$[$.SeekPreRoll=22203]="SeekPreRoll",$[$.DefaultDuration=2352003]="DefaultDuration",$[$.Video=224]="Video",$[$.PixelWidth=176]="PixelWidth",$[$.PixelHeight=186]="PixelHeight",$[$.DisplayWidth=21680]="DisplayWidth",$[$.DisplayHeight=21690]="DisplayHeight",$[$.DisplayUnit=21682]="DisplayUnit",$[$.AlphaMode=21440]="AlphaMode",$[$.Audio=225]="Audio",$[$.SamplingFrequency=181]="SamplingFrequency",$[$.Channels=159]="Channels",$[$.BitDepth=25188]="BitDepth",$[$.SimpleBlock=163]="SimpleBlock",$[$.BlockGroup=160]="BlockGroup",$[$.Block=161]="Block",$[$.BlockAdditions=30113]="BlockAdditions",$[$.BlockMore=166]="BlockMore",$[$.BlockAdditional=165]="BlockAdditional",$[$.BlockAddID=238]="BlockAddID",$[$.BlockDuration=155]="BlockDuration",$[$.ReferenceBlock=251]="ReferenceBlock",$[$.Cluster=524531317]="Cluster",$[$.Timestamp=231]="Timestamp",$[$.Cues=475249515]="Cues",$[$.CuePoint=187]="CuePoint",$[$.CueTime=179]="CueTime",$[$.CueTrackPositions=183]="CueTrackPositions",$[$.CueTrack=247]="CueTrack",$[$.CueClusterPosition=241]="CueClusterPosition",$[$.Colour=21936]="Colour",$[$.MatrixCoefficients=21937]="MatrixCoefficients",$[$.TransferCharacteristics=21946]="TransferCharacteristics",$[$.Primaries=21947]="Primaries",$[$.Range=21945]="Range",$[$.Projection=30320]="Projection",$[$.ProjectionType=30321]="ProjectionType",$[$.ProjectionPoseRoll=30325]="ProjectionPoseRoll",$[$.Attachments=423732329]="Attachments",$[$.AttachedFile=24999]="AttachedFile",$[$.FileDescription=18046]="FileDescription",$[$.FileName=18030]="FileName",$[$.FileMediaType=18016]="FileMediaType",$[$.FileData=18012]="FileData",$[$.FileUID=18094]="FileUID",$[$.Chapters=272869232]="Chapters",$[$.Tags=307544935]="Tags",$[$.Tag=29555]="Tag",$[$.Targets=25536]="Targets",$[$.TargetTypeValue=26826]="TargetTypeValue",$[$.TargetType=25546]="TargetType",$[$.TagTrackUID=25541]="TagTrackUID",$[$.TagEditionUID=25545]="TagEditionUID",$[$.TagChapterUID=25540]="TagChapterUID",$[$.TagAttachmentUID=25542]="TagAttachmentUID",$[$.SimpleTag=26568]="SimpleTag",$[$.TagName=17827]="TagName",$[$.TagLanguage=17530]="TagLanguage",$[$.TagString=17543]="TagString",$[$.TagBinary=17541]="TagBinary",$[$.ContentEncodings=28032]="ContentEncodings",$[$.ContentEncoding=25152]="ContentEncoding",$[$.ContentEncodingOrder=20529]="ContentEncodingOrder",$[$.ContentEncodingScope=20530]="ContentEncodingScope",$[$.ContentCompression=20532]="ContentCompression",$[$.ContentCompAlgo=16980]="ContentCompAlgo",$[$.ContentCompSettings=16981]="ContentCompSettings",$[$.ContentEncryption=20533]="ContentEncryption"})(b||(b={}));var iZ=[b.EBML,b.Segment],U6=[b.SeekHead,b.Info,b.Cluster,b.Tracks,b.Cues,b.Attachments,b.Chapters,b.Tags],i6=[...iZ,...U6];var aJ=8,u0=2,Q1=2*aJ,tJ=($)=>{if($.remainingLength<1)return null;let J=g($);if($.skip(-1),J===0)return null;let Y=1,X=128;while((J&X)===0)Y++,X>>=1;if($.remainingLength<Y)return null;return Y},W6=($)=>{if($.remainingLength<1)return null;let J=g($);if(J===0)return null;let Y=1,X=128;while((J&X)===0)Y++,X>>=1;if($.remainingLength<Y-1)return null;let Q=J&X-1;for(let Z=1;Z<Y;Z++)Q*=256,Q+=g($);return Q},d=($,J)=>{if(J<1||J>8)throw Error("Bad unsigned int size "+J);let Y=0;for(let X=0;X<J;X++)Y*=256,Y+=g($);return Y},jX=($,J)=>{if(J<1)throw Error("Bad unsigned int size "+J);let Y=0n;for(let X=0;X<J;X++)Y<<=8n,Y+=BigInt(g($));return Y};var g$=($)=>{let J=tJ($);if(J===null)return null;if($.remainingLength<J)return null;return d($,J)},eJ=($)=>{if($.remainingLength<1)return null;if(g($)===255)return;$.skip(-1);let Y=W6($);if(Y===null)return null;if(Y===72057594037927940)return;return Y},K1=($)=>{L($.remainingLength>=u0);let J=g$($);if(J===null)return null;let Y=eJ($);if(Y===null)return null;return{id:J,size:Y}},J8=($,J)=>{let Y=h($,J),X=0;while(X<J&&Y[X]!==0)X+=1;return String.fromCharCode(...Y.subarray(0,X))},j6=($,J)=>{let Y=h($,J),X=0;while(X<J&&Y[X]!==0)X+=1;return H0.decode(Y.subarray(0,X))},k$=($,J)=>{if(J===0)return 0;if(J!==4&&J!==8)throw Error("Bad float size "+J);return J===4?qX($):f$($)},u$=async($,J,Y,X)=>{let Q=new Set(Y),Z=J;while(X===null||Z<X){let K=$.requestSliceRange(Z,u0,Q1);if(K instanceof Promise)K=await K;if(!K)break;let G=K1(K);if(!G)break;if(Q.has(G.id))return{pos:Z,found:!0};g1(G.size),Z=K.filePos+G.size}return{pos:X!==null&&X>Z?X:Z,found:!1}},$Y=async($,J,Y,X)=>{let Z=new Set(Y),K=J;while(K<X){let G=$.requestSliceRange(K,0,Math.min(65536,X-K));if(G instanceof Promise)G=await G;if(!G)break;if(G.length<aJ)break;for(let W=0;W<G.length-aJ;W++){G.filePos=K;let j=g$(G);if(j!==null&&Z.has(j))return K;K++}}return null},m0={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function g1($){if($===void 0)throw Error("Undefined element size is used in a place where it is not supported.")}/*!
|
|
91
|
+
*/class l$ extends P0{constructor($){super($);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.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=$._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(($)=>$.trackBacking)}async getMimeType(){await this.readMetadata();let $=await this.getTrackBackings(),J=await Promise.all($.map((Y)=>Y.getDecoderConfig().then((X)=>X?.codec??null)));return eJ({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some((Y)=>Y.info?.type==="video"),hasAudio:this.tracks.some((Y)=>Y.info?.type==="audio"),codecStrings:J.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let $=0,J=!1;while(!0){let Y=this.reader.requestSliceRange($,Q8,h8);if(Y instanceof Promise)Y=await Y;if(!Y)break;let X=$,Q=l1(Y);if(!Q)break;if(Q.name==="ftyp"||Q.name==="styp"){let Z=Z0(Y,4);this.isQuickTime=Z==="qt "}else if(Q.name==="moov"){let Z=this.reader.requestSlice(Y.filePos,Q.contentSize);if(Z instanceof Promise)Z=await Z;if(!Z)break;this.moovSlice=Z,this.readContiguousBoxes(this.moovSlice);for(let K of this.tracks){let G=K.editListPreviousSegmentDurations/this.movieTimescale;K.editListOffset-=Math.round(G*K.timescale)}J=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>X+Q.totalSize;break}else if(Q.name==="moof"){if(!this.input._initInput)throw Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');let Z=await this.input._initInput._getDemuxer();if(Z.constructor!==l$)throw Error("Init input must match the input's format.");await Z.readMetadata(),this.movieTimescale=Z.movieTimescale,this.movieDurationInTimescale=Z.movieDurationInTimescale,this.metadataTags=Z.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=Z.fragmentTrackDefaults,this.psshBoxes=Z.psshBoxes;for(let K of Z.tracks){let G={id:K.id,demuxer:this,trackBacking:null,disposition:K.disposition,timescale:K.timescale,durationInMediaTimescale:K.durationInMediaTimescale,durationInMovieTimescale:K.durationInMovieTimescale,rotation:K.rotation,internalCodecId:K.internalCodecId,name:K.name,languageCode:K.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:K.editListPreviousSegmentDurations,editListOffset:K.editListOffset,encryptionInfo:K.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:K.info};if(K.trackBacking){if(F(G.info),G.info.type==="video"&&G.info.width!==-1){let W=G;G.trackBacking=new JY(W),this.tracks.push(G)}else if(G.info.type==="audio"&&G.info.numberOfChannels!==-1){let W=G;G.trackBacking=new YY(W),this.tracks.push(G)}}}J=!1;break}$=X+Q.totalSize}if(J){F(this.reader.fileSize!==null);let Y=this.reader.requestSlice(this.reader.fileSize-4,4);if(Y instanceof Promise)Y=await Y;F(Y);let X=y(Y),Q=this.reader.fileSize-X;if(Q>=0&&Q<=this.reader.fileSize-h8){let Z=this.reader.requestSliceRange(Q,Q8,h8);if(Z instanceof Promise)Z=await Z;if(Z){let K=l1(Z);if(K&&K.name==="mfra"){let G=this.reader.requestSlice(Z.filePos,K.contentSize);if(G instanceof Promise)G=await G;if(G)this.readContiguousBoxes(G)}}}}})()}getSampleTableForTrack($){if($.sampleTable)return $.sampleTable;let J={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if($.sampleTable=J,$.sampleTableByteOffset===null)return J;F(this.moovSlice);let Y=this.moovSlice.slice($.sampleTableByteOffset);if(this.currentTrack=$,this.traverseBox(Y),this.currentTrack=null,$.info?.type==="audio"&&$.info.codec&&S0.includes($.info.codec)&&J.sampleCompositionTimeOffsets.length===0){F($.info?.type==="audio");let Q=u1($.info.codec),Z=[],K=[];for(let G=0;G<J.sampleToChunk.length;G++){let W=J.sampleToChunk[G],j=J.sampleToChunk[G+1],U=(j?j.startChunkIndex:J.chunkOffsets.length)-W.startChunkIndex;for(let q=0;q<U;q++){let N=W.startSampleIndex+q*W.samplesPerChunk,_=N+W.samplesPerChunk,V=p(J.sampleTimingEntries,N,(D)=>D.startIndex),z=J.sampleTimingEntries[V],R=p(J.sampleTimingEntries,_,(D)=>D.startIndex),H=J.sampleTimingEntries[R],A=z.startDecodeTimestamp+(N-z.startIndex)*z.delta,L=H.startDecodeTimestamp+(_-H.startIndex)*H.delta-A,w=W0(Z);if(w&&w.delta===L)w.count++;else Z.push({startIndex:W.startChunkIndex+q,startDecodeTimestamp:A,count:1,delta:L});let O=W.samplesPerChunk*Q.sampleSize*$.info.numberOfChannels;K.push(O)}W.startSampleIndex=W.startChunkIndex,W.samplesPerChunk=1}J.sampleTimingEntries=Z,J.sampleSizes=K}if(J.sampleCompositionTimeOffsets.length>0){J.presentationTimestamps=[];for(let Q of J.sampleTimingEntries)for(let Z=0;Z<Q.count;Z++)J.presentationTimestamps.push({presentationTimestamp:Q.startDecodeTimestamp+Z*Q.delta,sampleIndex:Q.startIndex+Z});for(let Q of J.sampleCompositionTimeOffsets)for(let Z=0;Z<Q.count;Z++){let K=Q.startIndex+Z,G=J.presentationTimestamps[K];if(!G)continue;G.presentationTimestamp+=Q.offset}J.presentationTimestamps.sort((Q,Z)=>Q.presentationTimestamp-Z.presentationTimestamp),J.presentationTimestampIndexMap=Array(J.presentationTimestamps.length).fill(-1);for(let Q=0;Q<J.presentationTimestamps.length;Q++)J.presentationTimestampIndexMap[J.presentationTimestamps[Q].sampleIndex]=Q}return J}async readFragment($){if(this.lastReadFragment?.moofOffset===$)return this.lastReadFragment;let J=this.reader.requestSliceRange($,Q8,h8);if(J instanceof Promise)J=await J;F(J);let Y=l1(J);F(Y?.name==="moof");let X=this.reader.requestSlice($,Y.totalSize);if(X instanceof Promise)X=await X;F(X),this.traverseBox(X);let Q=this.lastReadFragment;F(Q&&Q.moofOffset===$);for(let[,Z]of Q.trackData){let K=Z.track,{fragmentPositionCache:G}=K;if(!Z.startTimestampIsFinal){let j=K.fragmentLookupTable.find((U)=>U.moofOffset===Q.moofOffset);if(j)$Y(Z,j.timestamp);else{let U=p(G,Q.moofOffset-1,(q)=>q.moofOffset);if(U!==-1){let q=G[U];$Y(Z,q.endTimestamp)}}Z.startTimestampIsFinal=!0}let W=p(G,Z.startTimestamp,(j)=>j.startTimestamp);if(W===-1||G[W].moofOffset!==Q.moofOffset)G.splice(W+1,0,{moofOffset:Q.moofOffset,startTimestamp:Z.startTimestamp,endTimestamp:Z.endTimestamp});if(Z.encryptionAuxInfo&&K.encryptionInfo){let j=await WX(this.reader,K.encryptionInfo,Z.encryptionAuxInfo);for(let U=0;U<Math.min(Z.samples.length,j.length);U++){let q=j[U];Z.samples[U].encryption=q}}}return Q}readContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-Q8)if(!this.traverseBox($))break}*iterateContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-Q8){let Y=$.filePos,X=l1($);if(!X)break;yield{boxInfo:X,slice:$},$.filePos=Y+X.totalSize}}traverseBox($){let J=$.filePos,Y=l1($);if(!Y)return!1;let X=$.filePos,Q=J+Y.totalSize;switch(Y.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes($.slice(X,Y.contentSize));break;case"mvhd":{let Z=g($);if($.skip(3),Z===1)$.skip(16),this.movieTimescale=y($),this.movieDurationInTimescale=i0($);else $.skip(8),this.movieTimescale=y($),this.movieDurationInTimescale=y($)}break;case"trak":{let Z={id:-1,demuxer:this,trackBacking:null,disposition:{...x0,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:K0,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=Z,this.readContiguousBoxes($.slice(X,Y.contentSize)),Z.id!==-1&&Z.timescale!==-1&&Z.info!==null){if(Z.info.type==="video"&&Z.info.width!==-1){let K=Z;Z.trackBacking=new JY(K),this.tracks.push(Z)}else if(Z.info.type==="audio"&&Z.info.numberOfChannels!==-1){let K=Z;Z.trackBacking=new YY(K),this.tracks.push(Z)}}this.currentTrack=null}break;case"tkhd":{let Z=this.currentTrack;if(!Z)break;let K=g($),W=!!(V1($)&1);if(Z.disposition.default=W,K===0)$.skip(8),Z.id=y($),$.skip(4),Z.durationInMovieTimescale=y($);else if(K===1)$.skip(16),Z.id=y($),$.skip(4),Z.durationInMovieTimescale=i0($);else throw Error(`Incorrect track header version ${K}.`);$.skip(16);let j=[K8($),K8($),k$($),K8($),K8($),k$($),K8($),K8($),k$($)],U=J8(l6($2(j),90));F(U===0||U===90||U===180||U===270),Z.rotation=U}break;case"elst":{let Z=this.currentTrack;if(!Z)break;let K=g($);$.skip(3);let G=!1,W=0,j=y($);for(let U=0;U<j;U++){let q=K===1?i0($):y($),N=K===1?jX($):p1($),_=K8($);if(q===0)continue;if(G){k._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(N===-1){W+=q;continue}if(_!==1){k._warn("Unsupported edit list entry: media rate must be 1.");break}Z.editListPreviousSegmentDurations=W,Z.editListOffset=N,G=!0}}break;case"mdhd":{let Z=this.currentTrack;if(!Z)break;let K=g($);if($.skip(3),K===0)$.skip(8),Z.timescale=y($),Z.durationInMediaTimescale=y($);else if(K===1)$.skip(16),Z.timescale=y($),Z.durationInMediaTimescale=i0($);let G=U0($);if(G>0){Z.languageCode="";for(let W=0;W<3;W++)Z.languageCode=String.fromCharCode(96+(G&31))+Z.languageCode,G>>=5;if(!a8(Z.languageCode))Z.languageCode=K0}}break;case"hdlr":{let Z=this.currentTrack;if(!Z)break;$.skip(8);let K=Z0($,4);if(K==="vide")Z.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null};else if(K==="soun")Z.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null}}break;case"stbl":{let Z=this.currentTrack;if(!Z)break;Z.sampleTableByteOffset=J,this.readContiguousBoxes($.slice(X,Y.contentSize))}break;case"stsd":{let Z=this.currentTrack;if(!Z)break;if(Z.info===null||Z.sampleTable)break;let K=g($);$.skip(3);let G=y($);for(let W=0;W<G;W++){let j=$.filePos,U=l1($);if(!U)break;Z.internalCodecId=U.name;let q=U.name.toLowerCase();if(Z.info.type==="video"){$.skip(24),Z.info.width=U0($),Z.info.height=U0($),Z.info.squarePixelWidth=Z.info.width,Z.info.squarePixelHeight=Z.info.height,$.skip(50),Z.frmaCodecString=null,this.readContiguousBoxes($.slice($.filePos,j+U.totalSize-$.filePos));let N=q==="encv"?Z.frmaCodecString:q;if(Z.frmaCodecString=null,N==="avc1"||N==="avc3")Z.info.codec="avc",Z.info.avcType=N==="avc1"?1:3;else if(N==="hvc1"||N==="hev1")Z.info.codec="hevc";else if(N==="vp08")Z.info.codec="vp8";else if(N==="vp09")Z.info.codec="vp9";else if(N==="av01")Z.info.codec="av1";else if(Y6.includes(q))Z.info.codec="prores",Z.info.proresFormat=q;else if(N===null)k._warn("Unknown encrypted video codec due to missing frma box.");else k._warn(`Unsupported video codec (sample entry type '${U.name}').`)}else{$.skip(8);let N=U0($);$.skip(6);let _=U0($),V=U0($);$.skip(4);let z=y($)/65536,R=null;if(K===0&&N>0){if(N===1)$.skip(4),V=8*y($),$.skip(8);else if(N===2)$.skip(4),z=p$($),_=y($),$.skip(4),V=y($),R=y($),$.skip(8)}Z.info.numberOfChannels=_,Z.info.sampleRate=z,Z.frmaCodecString=null,this.readContiguousBoxes($.slice($.filePos,j+U.totalSize-$.filePos));let H=q==="enca"?Z.frmaCodecString:q;if(Z.frmaCodecString=null,H==="mp4a");else if(H==="opus")Z.info.codec="opus",Z.info.sampleRate=k1;else if(H==="flac")Z.info.codec="flac";else if(H==="ulaw")Z.info.codec="ulaw";else if(H==="alaw")Z.info.codec="alaw";else if(H==="ac-3")Z.info.codec="ac3";else if(H==="ec-3")Z.info.codec="eac3";else if(H==="twos")if(V===8)Z.info.codec="pcm-s8";else if(V===16)Z.info.codec=Z.info.pcmLittleEndian?"pcm-s16":"pcm-s16be";else k._warn(`Unsupported sample size ${V} for codec 'twos'.`),Z.info.codec=null;else if(H==="sowt")if(V===8)Z.info.codec="pcm-s8";else if(V===16)Z.info.codec="pcm-s16";else k._warn(`Unsupported sample size ${V} for codec 'sowt'.`),Z.info.codec=null;else if(H==="raw ")Z.info.codec="pcm-u8";else if(H==="in24")Z.info.codec=Z.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(H==="in32")Z.info.codec=Z.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(H==="fl32")Z.info.codec=Z.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(H==="fl64")Z.info.codec=Z.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(H==="ipcm"){let A=Z.info.pcmSampleSize;if(Z.info.pcmLittleEndian)if(A===16)Z.info.codec="pcm-s16";else if(A===24)Z.info.codec="pcm-s24";else if(A===32)Z.info.codec="pcm-s32";else k._warn(`Invalid ipcm sample size ${A}.`),Z.info.codec=null;else if(A===16)Z.info.codec="pcm-s16be";else if(A===24)Z.info.codec="pcm-s24be";else if(A===32)Z.info.codec="pcm-s32be";else k._warn(`Invalid ipcm sample size ${A}.`),Z.info.codec=null}else if(H==="fpcm"){let A=Z.info.pcmSampleSize;if(Z.info.pcmLittleEndian)if(A===32)Z.info.codec="pcm-f32";else if(A===64)Z.info.codec="pcm-f64";else k._warn(`Invalid fpcm sample size ${A}.`),Z.info.codec=null;else if(A===32)Z.info.codec="pcm-f32be";else if(A===64)Z.info.codec="pcm-f64be";else k._warn(`Invalid fpcm sample size ${A}.`),Z.info.codec=null}else if(H==="lpcm"&&R!==null){let A=V+7>>3,M=Boolean(R&1),L=Boolean(R&2),w=R&4?-1:0;if(V>0&&V<=64){if(M){if(V===32)Z.info.codec=L?"pcm-f32be":"pcm-f32"}else if(w&1<<A-1){if(A===1)Z.info.codec="pcm-s8";else if(A===2)Z.info.codec=L?"pcm-s16be":"pcm-s16";else if(A===3)Z.info.codec=L?"pcm-s24be":"pcm-s24";else if(A===4)Z.info.codec=L?"pcm-s32be":"pcm-s32"}else if(A===1)Z.info.codec="pcm-u8"}if(Z.info.codec===null)k._warn("Unsupported PCM format.")}else if(H===null)k._warn("Unknown encrypted audio codec due to missing frma box.");else k._warn(`Unsupported audio codec (sample entry type '${U.name}').`)}$.filePos=j+U.totalSize}}break;case"frma":{let Z=this.currentTrack;if(!Z)break;let G=Z0($,4).toLowerCase();Z.frmaCodecString=G}break;case"schm":{let Z=this.currentTrack;if(!Z)break;$.skip(4);let K=Z0($,4);if(K==="cenc"||K==="cens"||K==="cbcs")Z.encryptionInfo={scheme:K,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null};else k._warn(`Unsupported encryption scheme '${K}'.`)}break;case"tenc":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;let K=g($);$.skip(3),$.skip(1);let G=g($);if(K>0)Z.encryptionInfo.defaultCryptByteBlock=G>>4,Z.encryptionInfo.defaultSkipByteBlock=G&15;else Z.encryptionInfo.defaultCryptByteBlock=0,Z.encryptionInfo.defaultSkipByteBlock=0;if(Z.encryptionInfo.defaultIsProtected=g($)!==0,Z.encryptionInfo.defaultPerSampleIvSize=g($),Z.encryptionInfo.defaultKid=Y8(f($,16)),Z.encryptionInfo.defaultIsProtected&&Z.encryptionInfo.defaultPerSampleIvSize===0){let W=g($),j=new Uint8Array(16);j.set(f($,W),0),Z.encryptionInfo.defaultConstantIv=j}}break;case"avcC":{let Z=this.currentTrack;if(!Z)break;F(Z.info),Z.info.codecDescription=f($,Y.contentSize)}break;case"hvcC":{let Z=this.currentTrack;if(!Z)break;F(Z.info),Z.info.codecDescription=f($,Y.contentSize)}break;case"vpcC":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="video"),$.skip(4);let K=g($),G=g($),W=g($),j=W>>4,U=W>>1&7,q=W&1,N=g($),_=g($),V=g($);Z.info.vp9CodecInfo={profile:K,level:G,bitDepth:j,chromaSubsampling:U,videoFullRangeFlag:q,colourPrimaries:N,transferCharacteristics:_,matrixCoefficients:V}}break;case"av1C":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="video"),$.skip(1);let K=g($),G=K>>5,W=K&31,j=g($),U=j>>7,q=j>>6&1,N=j>>5&1,_=j>>4&1,V=j>>3&1,z=j>>2&1,R=j&3,H=G===2&&q?N?12:10:q?10:8;Z.info.av1CodecInfo={profile:G,level:W,tier:U,bitDepth:H,monochrome:_,chromaSubsamplingX:V,chromaSubsamplingY:z,chromaSamplePosition:R}}break;case"colr":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="video");let K=Z0($,4);if(K!=="nclx"&&K!=="nclc")break;let G=U0($),W=U0($),j=U0($),U=void 0;if(K==="nclx")U=Boolean(g($)&128);Z.info.colorSpace={primaries:M8[G],transfer:L8[W],matrix:O8[j],fullRange:U}}break;case"pasp":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="video");let K=y($),G=y($);if(K>0&&G>0)if(K>G)Z.info.squarePixelWidth=Math.round(Z.info.width*K/G);else Z.info.squarePixelHeight=Math.round(Z.info.height*G/K)}break;case"wave":this.readContiguousBoxes($.slice(X,Y.contentSize));break;case"esds":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="audio"),$.skip(4);let K=g($);F(K===3),u$($),$.skip(2);let G=g($),W=(G&128)!==0,j=(G&64)!==0,U=(G&32)!==0;if(W)$.skip(2);if(j){let z=g($);$.skip(z)}if(U)$.skip(2);let q=g($);F(q===4);let N=u$($),_=$.filePos,V=g($);if(V===64||V===103)Z.info.codec="aac",Z.info.aacCodecInfo={isMpeg2:V===103,objectType:null};else if(V===105||V===107)Z.info.codec="mp3";else if(V===221)Z.info.codec="vorbis";else k._warn(`Unsupported audio codec (objectTypeIndication ${V}) - discarding track.`);if($.skip(12),N>$.filePos-_){let z=g($);F(z===5);let R=u$($);if(Z.info.codecDescription=f($,R),Z.info.codec==="aac"){let H=v8(Z.info.codecDescription);if(H.numberOfChannels!==null)Z.info.numberOfChannels=H.numberOfChannels;if(H.sampleRate!==null)Z.info.sampleRate=H.sampleRate}}}break;case"enda":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="audio"),Z.info.pcmLittleEndian=!!(U0($)&255)}break;case"pcmC":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="audio"),$.skip(4);let K=g($);Z.info.pcmLittleEndian=Boolean(K&1),Z.info.pcmSampleSize=g($)}break;case"dOps":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="audio"),$.skip(1);let K=g($),G=U0($),W=y($),j=Y$($),U=g($),q;if(U!==0)q=f($,2+K);else q=new Uint8Array(0);let N=new Uint8Array(19+q.byteLength),_=new DataView(N.buffer);_.setUint32(0,1332770163,!1),_.setUint32(4,1214603620,!1),_.setUint8(8,1),_.setUint8(9,K),_.setUint16(10,G,!0),_.setUint32(12,W,!0),_.setInt16(16,j,!0),_.setUint8(18,U),N.set(q,19),Z.info.codecDescription=N,Z.info.numberOfChannels=K}break;case"dfLa":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="audio"),$.skip(4);let K=127,G=128,W=$.filePos;while($.filePos<Q){let _=g($),V=V1($);if((_&K)===O1.STREAMINFO){$.skip(10);let R=y($),H=R>>>12,A=(R>>9&7)+1;Z.info.sampleRate=H,Z.info.numberOfChannels=A,$.skip(20)}else $.skip(V);if(_&G)break}let j=$.filePos;$.filePos=W;let U=f($,j-W),q=new Uint8Array(4+U.byteLength);new DataView(q.buffer).setUint32(0,1716281667,!1),q.set(U,4),Z.info.codecDescription=q}break;case"dac3":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="audio");let K=f($,3),G=new n(K),W=G.readBits(2);G.skipBits(8);let j=G.readBits(3),U=G.readBits(1);if(W<3)Z.info.sampleRate=I8[W];Z.info.numberOfChannels=J$[j]+U}break;case"dec3":{let Z=this.currentTrack;if(!Z)break;F(Z.info?.type==="audio");let K=f($,Y.contentSize),G=$X(K);if(!G){k._warn("Invalid dec3 box contents, ignoring.");break}let W=S$(G);if(W!==null)Z.info.sampleRate=W;Z.info.numberOfChannels=h$(G)}break;case"stts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=y($),G=0,W=0;for(let j=0;j<K;j++){let U=y($),q=y($);Z.sampleTable.sampleTimingEntries.push({startIndex:G,startDecodeTimestamp:W,count:U,delta:q}),G+=U,W+=U*q}}break;case"ctts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=y($),G=0;for(let W=0;W<K;W++){let j=y($),U=p1($);Z.sampleTable.sampleCompositionTimeOffsets.push({startIndex:G,count:j,offset:U}),G+=j}}break;case"stsz":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=y($),G=y($);if(K===0)for(let W=0;W<G;W++){let j=y($);Z.sampleTable.sampleSizes.push(j)}else Z.sampleTable.sampleSizes.push(K)}break;case"stz2":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),$.skip(3);let K=g($),G=y($),W=f($,Math.ceil(G*K/8)),j=new n(W);for(let U=0;U<G;U++){let q=j.readBits(K);Z.sampleTable.sampleSizes.push(q)}}break;case"stss":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),Z.sampleTable.keySampleIndices=[];let K=y($);for(let G=0;G<K;G++){let W=y($)-1;Z.sampleTable.keySampleIndices.push(W)}if(Z.sampleTable.keySampleIndices[0]!==0)Z.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=y($);for(let W=0;W<K;W++){let j=y($)-1,U=y($),q=y($);Z.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:j,samplesPerChunk:U,sampleDescriptionIndex:q})}let G=0;for(let W=0;W<Z.sampleTable.sampleToChunk.length;W++)if(Z.sampleTable.sampleToChunk[W].startSampleIndex=G,W<Z.sampleTable.sampleToChunk.length-1){let U=Z.sampleTable.sampleToChunk[W+1].startChunkIndex-Z.sampleTable.sampleToChunk[W].startChunkIndex;G+=U*Z.sampleTable.sampleToChunk[W].samplesPerChunk}}break;case"stco":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=y($);for(let G=0;G<K;G++){let W=y($);Z.sampleTable.chunkOffsets.push(W)}}break;case"co64":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let K=y($);for(let G=0;G<K;G++){let W=i0($);Z.sampleTable.chunkOffsets.push(W)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes($.slice(X,Y.contentSize));break;case"mehd":{let Z=g($);$.skip(3);let K=Z===1?i0($):y($);this.movieDurationInTimescale=K}break;case"trex":{$.skip(4);let Z=y($),K=y($),G=y($),W=y($),j=y($);this.fragmentTrackDefaults.push({trackId:Z,defaultSampleDescriptionIndex:K,defaultSampleDuration:G,defaultSampleSize:W,defaultSampleFlags:j})}break;case"tfra":{let Z=g($);$.skip(3);let K=y($),G=this.tracks.find((H)=>H.id===K);if(!G)break;let W=y($),j=(W&48)>>4,U=(W&12)>>2,q=W&3,N=[g,U0,V1,y],_=N[j],V=N[U],z=N[q],R=y($);for(let H=0;H<R;H++){let A=Z===1?i0($):y($),M=Z===1?i0($):y($);_($),V($),z($),G.fragmentLookupTable.push({timestamp:A,moofOffset:M})}G.fragmentLookupTable.sort((H,A)=>H.timestamp-A.timestamp);for(let H=0;H<G.fragmentLookupTable.length-1;H++){let A=G.fragmentLookupTable[H],M=G.fragmentLookupTable[H+1];if(A.timestamp===M.timestamp)G.fragmentLookupTable.splice(H+1,1),H--}}break;case"moof":this.currentFragment={moofOffset:J,moofSize:Y.totalSize,implicitBaseDataOffset:J,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes($.slice(X,Y.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(F(this.currentFragment),this.readContiguousBoxes($.slice(X,Y.contentSize)),this.currentTrack){let Z=this.currentFragment.trackData.get(this.currentTrack.id);$:if(Z){if(Z.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break $}Z.presentationTimestamps=Z.samples.map((j,U)=>({presentationTimestamp:j.presentationTimestamp,sampleIndex:U})).sort((j,U)=>j.presentationTimestamp-U.presentationTimestamp);for(let j=0;j<Z.presentationTimestamps.length;j++){let U=Z.presentationTimestamps[j],q=Z.samples[U.sampleIndex];if(Z.firstKeyFrameTimestamp===null&&q.isKeyFrame)Z.firstKeyFrameTimestamp=q.presentationTimestamp;if(j<Z.presentationTimestamps.length-1){let _=Z.presentationTimestamps[j+1].presentationTimestamp-U.presentationTimestamp;q.duration=_}}let K=Z.samples[Z.presentationTimestamps[0].sampleIndex],G=Z.samples[W0(Z.presentationTimestamps).sampleIndex];Z.startTimestamp=K.presentationTimestamp,Z.endTimestamp=G.presentationTimestamp+G.duration;let{currentFragmentState:W}=this.currentTrack;if(F(W),W.startTimestamp!==null)$Y(Z,W.startTimestamp),Z.startTimestampIsFinal=!0;if(W.encryptionAuxInfo&&!Z.samples[0].encryption)Z.encryptionAuxInfo=W.encryptionAuxInfo}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let Z=f$(f($,Y.contentSize));if(this.currentFragment)this.currentFragment.psshBoxes.push(Z);else if(!this.currentTrack)this.psshBoxes.push(Z)}break;case"tfhd":{F(this.currentFragment),$.skip(1);let Z=V1($),K=Boolean(Z&1),G=Boolean(Z&2),W=Boolean(Z&8),j=Boolean(Z&16),U=Boolean(Z&32),q=Boolean(Z&65536),N=Boolean(Z&131072),_=y($),V=this.tracks.find((R)=>R.id===_);if(!V)break;let z=this.fragmentTrackDefaults.find((R)=>R.trackId===_);if(this.currentTrack=V,V.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:z?.defaultSampleDescriptionIndex??null,defaultSampleDuration:z?.defaultSampleDuration??null,defaultSampleSize:z?.defaultSampleSize??null,defaultSampleFlags:z?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},K)V.currentFragmentState.baseDataOffset=i0($);else if(N)V.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset;if(G)V.currentFragmentState.sampleDescriptionIndex=y($);if(W)V.currentFragmentState.defaultSampleDuration=y($);if(j)V.currentFragmentState.defaultSampleSize=y($);if(U)V.currentFragmentState.defaultSampleFlags=y($);if(q)V.currentFragmentState.defaultSampleDuration=0}break;case"tfdt":{let Z=this.currentTrack;if(!Z)break;F(Z.currentFragmentState);let K=g($);$.skip(3);let G=K===0?y($):i0($);Z.currentFragmentState.startTimestamp=G}break;case"trun":{let Z=this.currentTrack;if(!Z)break;F(this.currentFragment),F(Z.currentFragmentState);let K=g($),G=V1($),W=Boolean(G&1),j=Boolean(G&4),U=Boolean(G&256),q=Boolean(G&512),N=Boolean(G&1024),_=Boolean(G&2048),V=y($),z=null;if(W)z=p1($);let R=null;if(j)R=y($);let H;if(this.currentFragment.trackData.has(Z.id)){if(H=this.currentFragment.trackData.get(Z.id),z!==null)H.currentOffset=Z.currentFragmentState.baseDataOffset+z}else H={track:Z,currentTimestamp:0,currentOffset:Z.currentFragmentState.baseDataOffset+(z??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(Z.id,H);for(let A=0;A<V;A++){let M;if(U)M=y($);else F(Z.currentFragmentState.defaultSampleDuration!==null),M=Z.currentFragmentState.defaultSampleDuration;let L;if(q)L=y($);else F(Z.currentFragmentState.defaultSampleSize!==null),L=Z.currentFragmentState.defaultSampleSize;let w;if(N)w=y($);else F(Z.currentFragmentState.defaultSampleFlags!==null),w=Z.currentFragmentState.defaultSampleFlags;if(A===0&&R!==null)w=R;let O=0;if(_)if(K===0)O=y($);else O=p1($);let D=!(w&65536);H.samples.push({presentationTimestamp:H.currentTimestamp+O,duration:M,byteOffset:H.currentOffset,byteSize:L,isKeyFrame:D,encryption:null}),H.currentOffset+=L,H.currentTimestamp+=M}this.currentFragment.implicitBaseDataOffset=H.currentOffset}break;case"saiz":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;if($.skip(1),V1($)&1){let q=Z0($,4),N=y($);if(q!==Z.encryptionInfo.scheme||N!==0)break}let G=g($),W=y($),j=null;if(G===0&&W>0)j=f($,W);let U=KX(Z);U.defaultSampleInfoSize=G,U.sampleSizes=j,U.sampleCount=W}break;case"saio":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;let K=g($);if(V1($)&1){let q=Z0($,4),N=y($);if(q!==Z.encryptionInfo.scheme||N!==0)break}let W=y($);if(W===0)break;if(W>1)k._warn("Multiple saio entries are not supported; using the first offset only.");let j=K===0?y($):Number(i0($));if(this.currentFragment)j+=this.currentFragment.moofOffset;let U=KX(Z);U.offset=j}break;case"senc":{let Z=this.currentTrack;if(!Z||!Z.encryptionInfo)break;F(this.currentFragment);let K=this.currentFragment.trackData.get(Z.id);if(!K)break;$.skip(1);let G=V1($),W=Boolean(G&2),j=y($),U=Z.encryptionInfo.defaultPerSampleIvSize;F(U!==null);for(let q=0;q<Math.min(j,K.samples.length);q++){let N=new Uint8Array(16);if(U>0)N.set(f($,U),0);else N.set(Z.encryptionInfo.defaultConstantIv,0);let _=null;if(W){let z=U0($);_=[];for(let R=0;R<z;R++){let H=U0($),A=y($);_.push({clearLen:H,protectedLen:A})}}let V=K.samples[q];V.encryption={iv:N,subsamples:_}}}break;case"udta":{let Z=this.iterateContiguousBoxes($.slice(X,Y.contentSize));for(let{boxInfo:K,slice:G}of Z){if(K.name!=="meta"&&!this.currentTrack){let W=G.filePos;if(this.metadataTags.raw??={},K.name[0]==="©")this.metadataTags.raw[K.name]??=q1(G);else this.metadataTags.raw[K.name]??=f(G,K.contentSize);G.filePos=W}switch(K.name){case"meta":G.skip(-K.headerSize),this.traverseBox(G);break;case"©nam":case"name":if(this.currentTrack)this.currentTrack.name=A0.decode(f(G,K.contentSize));else this.metadataTags.title??=q1(G);break;case"©des":if(!this.currentTrack)this.metadataTags.description??=q1(G);break;case"©ART":if(!this.currentTrack)this.metadataTags.artist??=q1(G);break;case"©alb":if(!this.currentTrack)this.metadataTags.album??=q1(G);break;case"albr":if(!this.currentTrack)this.metadataTags.albumArtist??=q1(G);break;case"©gen":if(!this.currentTrack)this.metadataTags.genre??=q1(G);break;case"©day":if(!this.currentTrack){let W=new Date(q1(G));if(!Number.isNaN(W.getTime()))this.metadataTags.date??=W}break;case"©cmt":if(!this.currentTrack)this.metadataTags.comment??=q1(G);break;case"©lyr":if(!this.currentTrack)this.metadataTags.lyrics??=q1(G);break}}}break;case"meta":{if(this.currentTrack)break;let K=y($)!==0;if(this.currentMetadataKeys=new Map,K)this.readContiguousBoxes($.slice(X,Y.contentSize));else this.readContiguousBoxes($.slice(X+4,Y.contentSize-4));this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;$.skip(4);let Z=y($);for(let K=0;K<Z;K++){let G=y($);$.skip(4);let W=A0.decode(f($,G-8));this.currentMetadataKeys.set(K+1,W)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let Z=this.iterateContiguousBoxes($.slice(X,Y.contentSize));for(let{boxInfo:K,slice:G}of Z){let W=K.name,j=(W.charCodeAt(0)<<24)+(W.charCodeAt(1)<<16)+(W.charCodeAt(2)<<8)+W.charCodeAt(3);if(this.currentMetadataKeys.has(j))W=this.currentMetadataKeys.get(j);let U=JX(G);switch(this.metadataTags.raw??={},this.metadataTags.raw[W]??=U,W){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":if(typeof U==="string")this.metadataTags.title??=U;break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":if(typeof U==="string")this.metadataTags.description??=U;break;case"©ART":case"com.apple.quicktime.artist":case"artist":if(typeof U==="string")this.metadataTags.artist??=U;break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":if(typeof U==="string")this.metadataTags.album??=U;break;case"aART":case"album_artist":if(typeof U==="string")this.metadataTags.albumArtist??=U;break;case"©cmt":case"com.apple.quicktime.comment":case"comment":if(typeof U==="string")this.metadataTags.comment??=U;break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":if(typeof U==="string")this.metadataTags.genre??=U;break;case"©lyr":case"lyrics":if(typeof U==="string")this.metadataTags.lyrics??=U;break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof U==="string"){let q=new Date(U);if(!Number.isNaN(q.getTime()))this.metadataTags.date??=q}break;case"covr":case"com.apple.quicktime.artwork":if(U instanceof S1)this.metadataTags.images??=[],this.metadataTags.images.push({data:U.data,kind:"coverFront",mimeType:U.mimeType});else if(U instanceof Uint8Array)this.metadataTags.images??=[],this.metadataTags.images.push({data:U,kind:"coverFront",mimeType:"image/*"});break;case"track":if(typeof U==="string"){let q=U.split("/"),N=Number.parseInt(q[0],10),_=q[1]&&Number.parseInt(q[1],10);if(Number.isInteger(N)&&N>0)this.metadataTags.trackNumber??=N;if(_&&Number.isInteger(_)&&_>0)this.metadataTags.tracksTotal??=_}break;case"trkn":if(U instanceof Uint8Array&&U.length>=6){let q=l(U),N=q.getUint16(2,!1),_=q.getUint16(4,!1);if(N>0)this.metadataTags.trackNumber??=N;if(_>0)this.metadataTags.tracksTotal??=_}break;case"disc":case"disk":if(U instanceof Uint8Array&&U.length>=6){let q=l(U),N=q.getUint16(2,!1),_=q.getUint16(4,!1);if(N>0)this.metadataTags.discNumber??=N;if(_>0)this.metadataTags.discsTotal??=_}break}}}break}return $.filePos=Q,!0}}class ZY{constructor($){this.internalTrack=$,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let $=this.internalTrack.demuxer,J=this.internalTrack.trackBacking.getType(),Y=0;for(let X of $.tracks){if(X.trackBacking.getType()===J)Y++;if(X===this.internalTrack)break}return Y}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}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let $=this.internalTrack;if($.durationInMediaTimescale<=0)return null;return F($.trackBacking),((await $.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+$.durationInMediaTimescale/$.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket($){let J=await this.fetchPacketForSampleIndex(0,$);if(J||!this.internalTrack.demuxer.isFragmented)return J;return this.performFragmentedLookup(null,(Y)=>{if(Y.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,$)}mapTimestampIntoTimescale($){return y1($*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket($,J){let Y=this.mapTimestampIntoTimescale($),X=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Q=XY(X,Y),Z=await this.fetchPacketForSampleIndex(Q,J);if(!QX(X)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(K)=>{let G=K.trackData.get(this.internalTrack.id);if(!G)return{sampleIndex:-1,correctSampleFound:!1};let W=p(G.presentationTimestamps,Y,(q)=>q.presentationTimestamp),j=W!==-1?G.presentationTimestamps[W].sampleIndex:-1,U=W!==-1&&Y<G.endTimestamp;return{sampleIndex:j,correctSampleFound:U}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0)return this.fetchPacketForSampleIndex(Y+1,J);let X=this.packetToFragmentLocation.get($);if(X===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(X.fragment,(Q)=>{if(Q===X.fragment){let Z=Q.trackData.get(this.internalTrack.id);if(X.sampleIndex+1<Z.samples.length)return{sampleIndex:X.sampleIndex+1,correctSampleFound:!0}}else if(Q.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let Y=this.mapTimestampIntoTimescale($),X=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Q=aZ(X,Y),Z=await this.fetchPacketForSampleIndex(Q,J);if(!QX(X)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(K)=>{let G=K.trackData.get(this.internalTrack.id);if(!G)return{sampleIndex:-1,correctSampleFound:!1};let W=B8(G.presentationTimestamps,(q)=>{return G.samples[q.sampleIndex].isKeyFrame&&q.presentationTimestamp<=Y}),j=W!==-1?G.presentationTimestamps[W].sampleIndex:-1,U=W!==-1&&Y<G.endTimestamp;return{sampleIndex:j,correctSampleFound:U}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0){let Q=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Z=eZ(Q,Y);return this.fetchPacketForSampleIndex(Z,J)}let X=this.packetToFragmentLocation.get($);if(X===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(X.fragment,(Q)=>{if(Q===X.fragment){let K=Q.trackData.get(this.internalTrack.id).samples.findIndex((G,W)=>G.isKeyFrame&&W>X.sampleIndex);if(K!==-1)return{sampleIndex:K,correctSampleFound:!0}}else{let Z=Q.trackData.get(this.internalTrack.id);if(Z&&Z.firstKeyFrameTimestamp!==null){let K=Z.samples.findIndex((G)=>G.isKeyFrame);return F(K!==-1),{sampleIndex:K,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async fetchPacketForSampleIndex($,J){if($===-1)return null;let Y=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=tZ(Y,$);if(!X)return null;let Q;if(J.metadataOnly)Q=w0;else{let W=this.internalTrack.demuxer.reader.requestSlice(X.sampleOffset,X.sampleSize);if(W instanceof Promise)W=await W;if(!W)return null;if(Q=f(W,X.sampleSize),this.internalTrack.encryptionAuxInfo){F(this.internalTrack.encryptionInfo);let j=await WX(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);if($<j.length)Q=await GX(this.internalTrack,j[$],Q,null)}}let Z=(X.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,K=X.duration/this.internalTrack.timescale,G=new t(Q,X.isKeyFrame?"key":"delta",Z,K,$,X.sampleSize);return this.packetToSampleIndex.set(G,$),G}async fetchPacketInFragment($,J,Y){if(J===-1)return null;let Q=$.trackData.get(this.internalTrack.id).samples[J];F(Q);let Z;if(Y.metadataOnly)Z=w0;else{let j=this.internalTrack.demuxer.reader.requestSlice(Q.byteOffset,Q.byteSize);if(j instanceof Promise)j=await j;if(!j)return null;if(Z=f(j,Q.byteSize),Q.encryption)Z=await GX(this.internalTrack,Q.encryption,Z,$)}let K=(Q.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,G=Q.duration/this.internalTrack.timescale,W=new t(Z,Q.isKeyFrame?"key":"delta",K,G,$.moofOffset+J,Q.byteSize);return this.packetToFragmentLocation.set(W,{fragment:$,sampleIndex:J}),W}async performFragmentedLookup($,J,Y,X,Q){let Z=this.internalTrack.demuxer,K=null,G=null,W=-1;if($){let{sampleIndex:z,correctSampleFound:R}=J($);if(R)return this.fetchPacketInFragment($,z,Q);if(z!==-1)G=$,W=z}let j=p(this.internalTrack.fragmentLookupTable,Y,(z)=>z.timestamp),U=j!==-1?this.internalTrack.fragmentLookupTable[j]:null,q=p(this.internalTrack.fragmentPositionCache,Y,(z)=>z.startTimestamp),N=q!==-1?this.internalTrack.fragmentPositionCache[q]:null,_=Math.max(U?.moofOffset??0,N?.moofOffset??0)||null,V;if(!$)V=_??0;else if(_===null||$.moofOffset>=_)V=$.moofOffset+$.moofSize,K=$;else V=_;while(!0){if(K){let A=K.trackData.get(this.internalTrack.id);if(A&&A.startTimestamp>X)break}let z=Z.reader.requestSliceRange(V,Q8,h8);if(z instanceof Promise)z=await z;if(!z)break;let R=V,H=l1(z);if(!H)break;if(H.name==="moof"){K=await Z.readFragment(R);let{sampleIndex:A,correctSampleFound:M}=J(K);if(M)return this.fetchPacketInFragment(K,A,Q);if(A!==-1)G=K,W=A}V=R+H.totalSize}if(U&&(!G||G.moofOffset<U.moofOffset)){let z=this.internalTrack.fragmentLookupTable[j-1];F(!z||z.timestamp<U.timestamp);let R=z?.timestamp??-1/0;return this.performFragmentedLookup(null,J,R,X,Q)}if(G)return this.fetchPacketInFragment(G,W,Q);return null}}class JY extends ZY{constructor($){super($);this.decoderConfigPromise=null,this.internalTrack=$}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}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 this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let J=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=J&&I$(J.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let J=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=J&&y$(J.data)}let $={codec:X6(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};if(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)$.displayAspectWidth=this.internalTrack.info.squarePixelWidth,$.displayAspectHeight=this.internalTrack.info.squarePixelHeight;return $})()}}class YY extends ZY{constructor($){super($);this.decoderConfig=null,this.internalTrack=$}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:Z6(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}var XY=($,J)=>{if($.presentationTimestamps){let Y=p($.presentationTimestamps,J,(X)=>X.presentationTimestamp);if(Y===-1)return-1;return $.presentationTimestamps[Y].sampleIndex}else{let Y=p($.sampleTimingEntries,J,(Q)=>Q.startDecodeTimestamp);if(Y===-1)return-1;let X=$.sampleTimingEntries[Y];return X.startIndex+Math.min(Math.floor((J-X.startDecodeTimestamp)/X.delta),X.count-1)}},aZ=($,J)=>{if(!$.keySampleIndices)return XY($,J);if($.presentationTimestamps){let Y=p($.presentationTimestamps,J,(X)=>X.presentationTimestamp);if(Y===-1)return-1;for(let X=Y;X>=0;X--){let Q=$.presentationTimestamps[X].sampleIndex;if(I1($.keySampleIndices,Q,(K)=>K)!==-1)return Q}return-1}else{let Y=XY($,J),X=p($.keySampleIndices,Y,(Q)=>Q);return $.keySampleIndices[X]??-1}},tZ=($,J)=>{let Y=p($.sampleTimingEntries,J,(H)=>H.startIndex),X=$.sampleTimingEntries[Y];if(!X||X.startIndex+X.count<=J)return null;let Z=X.startDecodeTimestamp+(J-X.startIndex)*X.delta,K=p($.sampleCompositionTimeOffsets,J,(H)=>H.startIndex),G=$.sampleCompositionTimeOffsets[K];if(G&&J-G.startIndex<G.count)Z+=G.offset;let W=$.sampleSizes[Math.min(J,$.sampleSizes.length-1)],j=p($.sampleToChunk,J,(H)=>H.startSampleIndex),U=$.sampleToChunk[j];F(U);let q=U.startChunkIndex+Math.floor((J-U.startSampleIndex)/U.samplesPerChunk),N=$.chunkOffsets[q],_=U.startSampleIndex+(q-U.startChunkIndex)*U.samplesPerChunk,V=0,z=N;if($.sampleSizes.length===1)z+=W*(J-_),V+=W*U.samplesPerChunk;else for(let H=_;H<_+U.samplesPerChunk;H++){let A=$.sampleSizes[H];if(H<J)z+=A;V+=A}let R=X.delta;if($.presentationTimestamps){let H=$.presentationTimestampIndexMap[J];if(F(H!==void 0),H<$.presentationTimestamps.length-1)R=$.presentationTimestamps[H+1].presentationTimestamp-Z}return{presentationTimestamp:Z,duration:R,sampleOffset:z,sampleSize:W,chunkOffset:N,chunkSize:V,isKeyFrame:$.keySampleIndices?I1($.keySampleIndices,J,(H)=>H)!==-1:!0}},eZ=($,J)=>{if(!$.keySampleIndices)return J+1;let Y=p($.keySampleIndices,J,(X)=>X);return $.keySampleIndices[Y+1]??-1},$Y=($,J)=>{$.startTimestamp+=J,$.endTimestamp+=J;for(let Y of $.samples)Y.presentationTimestamp+=J;for(let Y of $.presentationTimestamps)Y.presentationTimestamp+=J},$2=($)=>{let[J,Y]=$,X=Math.atan2(Y,J);if(!Number.isFinite(X))return 0;return X*(180/Math.PI)},QX=($)=>{return $.sampleSizes.length===0},KX=($)=>{if($.currentFragmentState)return $.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null};else return $.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}},WX=async($,J,Y)=>{if(Y.resolved)return Y.resolved;if(Y.offset===null||Y.sampleCount===0)throw Error("Incomplete saiz/saio info; cannot resolve encryption data.");let X=0;if(Y.defaultSampleInfoSize>0)X=Y.defaultSampleInfoSize*Y.sampleCount;else{F(Y.sampleSizes);for(let G=0;G<Y.sampleCount;G++)X+=Y.sampleSizes[G]}let Q=$.requestSlice(Y.offset,X);if(Q instanceof Promise)Q=await Q;if(!Q)throw Error("Failed to read auxiliary encryption info.");let Z=J.defaultPerSampleIvSize;F(Z!==null);let K=[];for(let G=0;G<Y.sampleCount;G++){let W=Y.defaultSampleInfoSize>0?Y.defaultSampleInfoSize:Y.sampleSizes[G],j=new Uint8Array(16);if(Z>0)j.set(f(Q,Z),0);else j.set(J.defaultConstantIv,0);let U=null;if(W>Z){let q=U0(Q);U=[];for(let N=0;N<q;N++){let _=U0(Q),V=y(Q);U.push({clearLen:_,protectedLen:V})}}K.push({iv:j,subsamples:U})}return Y.resolved=K,K},GX=async($,J,Y,X)=>{F($.encryptionInfo);let Q=$.encryptionInfo;F(Q.defaultKid!==null);let Z=Q.defaultKid,K,G=$.demuxer.decryptionKeyCache.get(Z);if(G)K=await G;else{if(!$.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let W=(async()=>{let j=$.demuxer.psshBoxes;if(X){j=[...j,...X.psshBoxes].filter((q)=>q.keyIds===null||q.keyIds.includes(Z));for(let q=0;q<j.length-1;q++)for(let N=q+1;N<j.length;N++)if(g$(j[q],j[N]))j.splice(N,1),N--}let U=await $.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:Z,psshBoxes:j});if(!(typeof U==="string"&&U.length===32&&T7.test(U)||U instanceof Uint8Array&&U.byteLength===16))throw TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return U instanceof Uint8Array?U:v7(U)})();$.demuxer.decryptionKeyCache.set(Z,W),K=await W}if(Q.scheme==="cenc"||Q.scheme==="cens")return J2(K,Q,J,Y);else return Y2(K,Q,J,Y)},J2=async($,J,Y,X)=>{let Q=new Uint8Array(16);Q.set(Y.iv,0);let Z=await crypto.subtle.importKey("raw",$,{name:"AES-CTR"},!1,["decrypt"]),K=async(V)=>{let z=await crypto.subtle.decrypt({name:"AES-CTR",counter:Q,length:64},Z,V);return new Uint8Array(z)};if(!Y.subsamples)return K(X);F(J.defaultCryptByteBlock!==null&&J.defaultSkipByteBlock!==null);let G=UX(Y.subsamples,J.defaultCryptByteBlock,J.defaultSkipByteBlock),W=0;for(let V of G)for(let z of V.perSubsample)W+=z.length;let j=new Uint8Array(W),U=0;for(let V of G)for(let z of V.perSubsample)j.set(X.subarray(z.offset,z.offset+z.length),U),U+=z.length;let q=await K(j),N=new Uint8Array(X),_=0;for(let V of G)for(let z of V.perSubsample)N.set(q.subarray(_,_+z.length),z.offset),_+=z.length;return N},Y2=($,J,Y,X)=>{let Q=new m$;Q.init({key:$,iv:Y.iv});let{defaultCryptByteBlock:Z,defaultSkipByteBlock:K}=J;if(F(Z!==null&&K!==null),!Y.subsamples){let U=new Uint8Array(X),q=Math.floor(X.length/16);for(let N=0;N<q;N++){let _=N*16;Q.in.set(X.subarray(_,_+16)),Q.decrypt(),U.set(Q.out,_)}return U}if(Z===0&&K===0)throw Error("cbcs with subsamples requires pattern encryption.");let G=new Uint8Array(X),W=UX(Y.subsamples,Z,K),j=new DataView(Y.iv.buffer,Y.iv.byteOffset,16);for(let U of W){Q.iv[0]=j.getUint32(0,!1),Q.iv[1]=j.getUint32(4,!1),Q.iv[2]=j.getUint32(8,!1),Q.iv[3]=j.getUint32(12,!1);for(let q of U.perSubsample){let N=q.length/16;for(let _=0;_<N;_++){let V=q.offset+_*16;Q.in.set(X.subarray(V,V+16)),Q.decrypt(),G.set(Q.out,V)}}}return G},UX=($,J,Y)=>{let X=[],Q=J!==0||Y!==0,Z=0;for(let K of $){Z+=K.clearLen;let G=[];if(!Q){if(K.protectedLen>0)G.push({offset:Z,length:K.protectedLen});Z+=K.protectedLen}else{let W=K.protectedLen,j=Z;while(W>0){if(W<16*J)break;let U=16*J;G.push({offset:j,length:U}),j+=U,W-=U;let q=Math.min(16*Y,W);j+=q,W-=q}Z+=K.protectedLen}X.push({perSubsample:G})}return X};/*!
|
|
92
92
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
93
93
|
*
|
|
94
94
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
95
95
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
96
96
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
97
|
-
*/var
|
|
97
|
+
*/var b;(function($){$[$.EBML=440786851]="EBML",$[$.EBMLVersion=17030]="EBMLVersion",$[$.EBMLReadVersion=17143]="EBMLReadVersion",$[$.EBMLMaxIDLength=17138]="EBMLMaxIDLength",$[$.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",$[$.DocType=17026]="DocType",$[$.DocTypeVersion=17031]="DocTypeVersion",$[$.DocTypeReadVersion=17029]="DocTypeReadVersion",$[$.Void=236]="Void",$[$.Segment=408125543]="Segment",$[$.SeekHead=290298740]="SeekHead",$[$.Seek=19899]="Seek",$[$.SeekID=21419]="SeekID",$[$.SeekPosition=21420]="SeekPosition",$[$.Duration=17545]="Duration",$[$.Info=357149030]="Info",$[$.TimestampScale=2807729]="TimestampScale",$[$.MuxingApp=19840]="MuxingApp",$[$.WritingApp=22337]="WritingApp",$[$.Tracks=374648427]="Tracks",$[$.TrackEntry=174]="TrackEntry",$[$.TrackNumber=215]="TrackNumber",$[$.TrackUID=29637]="TrackUID",$[$.TrackType=131]="TrackType",$[$.FlagEnabled=185]="FlagEnabled",$[$.FlagDefault=136]="FlagDefault",$[$.FlagForced=21930]="FlagForced",$[$.FlagOriginal=21934]="FlagOriginal",$[$.FlagHearingImpaired=21931]="FlagHearingImpaired",$[$.FlagVisualImpaired=21932]="FlagVisualImpaired",$[$.FlagCommentary=21935]="FlagCommentary",$[$.FlagLacing=156]="FlagLacing",$[$.Name=21358]="Name",$[$.Language=2274716]="Language",$[$.LanguageBCP47=2274717]="LanguageBCP47",$[$.CodecID=134]="CodecID",$[$.CodecPrivate=25506]="CodecPrivate",$[$.CodecDelay=22186]="CodecDelay",$[$.SeekPreRoll=22203]="SeekPreRoll",$[$.DefaultDuration=2352003]="DefaultDuration",$[$.Video=224]="Video",$[$.PixelWidth=176]="PixelWidth",$[$.PixelHeight=186]="PixelHeight",$[$.DisplayWidth=21680]="DisplayWidth",$[$.DisplayHeight=21690]="DisplayHeight",$[$.DisplayUnit=21682]="DisplayUnit",$[$.AlphaMode=21440]="AlphaMode",$[$.Audio=225]="Audio",$[$.SamplingFrequency=181]="SamplingFrequency",$[$.Channels=159]="Channels",$[$.BitDepth=25188]="BitDepth",$[$.SimpleBlock=163]="SimpleBlock",$[$.BlockGroup=160]="BlockGroup",$[$.Block=161]="Block",$[$.BlockAdditions=30113]="BlockAdditions",$[$.BlockMore=166]="BlockMore",$[$.BlockAdditional=165]="BlockAdditional",$[$.BlockAddID=238]="BlockAddID",$[$.BlockDuration=155]="BlockDuration",$[$.ReferenceBlock=251]="ReferenceBlock",$[$.Cluster=524531317]="Cluster",$[$.Timestamp=231]="Timestamp",$[$.Cues=475249515]="Cues",$[$.CuePoint=187]="CuePoint",$[$.CueTime=179]="CueTime",$[$.CueTrackPositions=183]="CueTrackPositions",$[$.CueTrack=247]="CueTrack",$[$.CueClusterPosition=241]="CueClusterPosition",$[$.Colour=21936]="Colour",$[$.MatrixCoefficients=21937]="MatrixCoefficients",$[$.TransferCharacteristics=21946]="TransferCharacteristics",$[$.Primaries=21947]="Primaries",$[$.Range=21945]="Range",$[$.Projection=30320]="Projection",$[$.ProjectionType=30321]="ProjectionType",$[$.ProjectionPoseRoll=30325]="ProjectionPoseRoll",$[$.Attachments=423732329]="Attachments",$[$.AttachedFile=24999]="AttachedFile",$[$.FileDescription=18046]="FileDescription",$[$.FileName=18030]="FileName",$[$.FileMediaType=18016]="FileMediaType",$[$.FileData=18012]="FileData",$[$.FileUID=18094]="FileUID",$[$.Chapters=272869232]="Chapters",$[$.Tags=307544935]="Tags",$[$.Tag=29555]="Tag",$[$.Targets=25536]="Targets",$[$.TargetTypeValue=26826]="TargetTypeValue",$[$.TargetType=25546]="TargetType",$[$.TagTrackUID=25541]="TagTrackUID",$[$.TagEditionUID=25545]="TagEditionUID",$[$.TagChapterUID=25540]="TagChapterUID",$[$.TagAttachmentUID=25542]="TagAttachmentUID",$[$.SimpleTag=26568]="SimpleTag",$[$.TagName=17827]="TagName",$[$.TagLanguage=17530]="TagLanguage",$[$.TagString=17543]="TagString",$[$.TagBinary=17541]="TagBinary",$[$.ContentEncodings=28032]="ContentEncodings",$[$.ContentEncoding=25152]="ContentEncoding",$[$.ContentEncodingOrder=20529]="ContentEncodingOrder",$[$.ContentEncodingScope=20530]="ContentEncodingScope",$[$.ContentCompression=20532]="ContentCompression",$[$.ContentCompAlgo=16980]="ContentCompAlgo",$[$.ContentCompSettings=16981]="ContentCompSettings",$[$.ContentEncryption=20533]="ContentEncryption"})(b||(b={}));var X2=[b.EBML,b.Segment],H6=[b.SeekHead,b.Info,b.Cluster,b.Tracks,b.Cues,b.Attachments,b.Chapters,b.Tags],X$=[...X2,...H6];var QY=8,a0=2,_1=2*QY,KY=($)=>{if($.remainingLength<1)return null;let J=g($);if($.skip(-1),J===0)return null;let Y=1,X=128;while((J&X)===0)Y++,X>>=1;if($.remainingLength<Y)return null;return Y},z6=($)=>{if($.remainingLength<1)return null;let J=g($);if(J===0)return null;let Y=1,X=128;while((J&X)===0)Y++,X>>=1;if($.remainingLength<Y-1)return null;let Q=J&X-1;for(let Z=1;Z<Y;Z++)Q*=256,Q+=g($);return Q},d=($,J)=>{if(J<1||J>8)throw Error("Bad unsigned int size "+J);let Y=0;for(let X=0;X<J;X++)Y*=256,Y+=g($);return Y},qX=($,J)=>{if(J<1)throw Error("Bad unsigned int size "+J);let Y=0n;for(let X=0;X<J;X++)Y<<=8n,Y+=BigInt(g($));return Y};var d$=($)=>{let J=KY($);if(J===null)return null;if($.remainingLength<J)return null;return d($,J)},GY=($)=>{if($.remainingLength<1)return null;if(g($)===255)return;$.skip(-1);let Y=z6($);if(Y===null)return null;if(Y===72057594037927940)return;return Y},H1=($)=>{F($.remainingLength>=a0);let J=d$($);if(J===null)return null;let Y=GY($);if(Y===null)return null;return{id:J,size:Y}},G8=($,J)=>{let Y=f($,J),X=0;while(X<J&&Y[X]!==0)X+=1;return String.fromCharCode(...Y.subarray(0,X))},R6=($,J)=>{let Y=f($,J),X=0;while(X<J&&Y[X]!==0)X+=1;return A0.decode(Y.subarray(0,X))},c$=($,J)=>{if(J===0)return 0;if(J!==4&&J!==8)throw Error("Bad float size "+J);return J===4?NX($):p$($)},n$=async($,J,Y,X)=>{let Q=new Set(Y),Z=J;while(X===null||Z<X){let K=$.requestSliceRange(Z,a0,_1);if(K instanceof Promise)K=await K;if(!K)break;let G=H1(K);if(!G)break;if(Q.has(G.id))return{pos:Z,found:!0};c1(G.size),Z=K.filePos+G.size}return{pos:X!==null&&X>Z?X:Z,found:!1}},WY=async($,J,Y,X)=>{let Z=new Set(Y),K=J;while(K<X){let G=$.requestSliceRange(K,0,Math.min(65536,X-K));if(G instanceof Promise)G=await G;if(!G)break;if(G.length<QY)break;for(let W=0;W<G.length-QY;W++){G.filePos=K;let j=d$(G);if(j!==null&&Z.has(j))return K;K++}}return null},d0={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function c1($){if($===void 0)throw Error("Undefined element size is used in a place where it is not supported.")}/*!
|
|
98
98
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
99
99
|
*
|
|
100
100
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
101
101
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
102
102
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
103
|
-
*/var k1;(function($){$[$.None=0]="None",$[$.Xiph=1]="Xiph",$[$.FixedSize=2]="FixedSize",$[$.Ebml=3]="Ebml"})(k1||(k1={}));var m$;(function($){$[$.Block=1]="Block",$[$.Private=2]="Private",$[$.Next=4]="Next"})(m$||(m$={}));var a6;(function($){$[$.Zlib=0]="Zlib",$[$.Bzlib=1]="Bzlib",$[$.lzo1x=2]="lzo1x",$[$.HeaderStripping=3]="HeaderStripping"})(a6||(a6={}));var YY=[{id:b.SeekHead,flag:"seekHeadSeen"},{id:b.Info,flag:"infoSeen"},{id:b.Tracks,flag:"tracksSeen"},{id:b.Cues,flag:"cuesSeen"}],NX=10485760;class XY extends L0{constructor($){super($);this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=$._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(($)=>$.tracks.map((J)=>J.trackBacking))}async getMimeType(){await this.readMetadata();let $=await this.getTrackBackings(),J=await Promise.all($.map((Y)=>Y.getDecoderConfig().then((X)=>X?.codec??null)));return JY({isWebM:this.isWebM,hasVideo:this.segments.some((Y)=>Y.tracks.some((X)=>X.info?.type==="video")),hasAudio:this.segments.some((Y)=>Y.tracks.some((X)=>X.info?.type==="audio")),codecStrings:J.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let J of this.segments)if(!J.metadataTagsCollected){if(this.reader.fileSize!==null)await this.loadSegmentMetadata(J);J.metadataTagsCollected=!0}let $={};for(let J of this.segments)$={...$,...J.metadataTags};return $}readMetadata(){return this.readMetadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,u0,Q1);if(J instanceof Promise)J=await J;if(!J)break;let Y=K1(J);if(!Y)break;let{id:X,size:Q}=Y,Z=J.filePos;if(X===b.EBML){g1(Q);let K=this.reader.requestSlice(Z,Q);if(K instanceof Promise)K=await K;if(!K)break;this.readContiguousElements(K)}else if(X===b.Segment){if(await this.readSegment(Z,Q),Q===void 0)break;if(this.reader.fileSize===null)break}else if(X===b.Cluster){if(this.reader.fileSize===null)break;if(Q===void 0)Q=(await u$(this.reader,Z,i6,this.reader.fileSize)).pos-Z;let K=K0(this.segments);if(K)K.elementEndPos=Z+Q}g1(Q),$=Z+Q}})()}async readSegment($,J){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:$,elementEndPos:J===void 0?null:$+J,clusterSeekStartPos:$,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let Y=$;while(this.currentSegment.elementEndPos===null||Y<this.currentSegment.elementEndPos){let K=this.reader.requestSliceRange(Y,u0,Q1);if(K instanceof Promise)K=await K;if(!K)break;let G=Y,W=K1(K);if(!W||!U6.includes(W.id)&&W.id!==b.Void){let _=await $Y(this.reader,G,U6,Math.min(this.currentSegment.elementEndPos??1/0,G+NX));if(_){Y=_;continue}else break}let{id:j,size:U}=W,q=K.filePos,V=YY.findIndex((_)=>_.id===j);if(V!==-1){let _=YY[V].flag;this.currentSegment[_]=!0,g1(U);let N=this.reader.requestSlice(q,U);if(N instanceof Promise)N=await N;if(N)this.readContiguousElements(N)}else if(j===b.Tags||j===b.Attachments){if(j===b.Tags)this.currentSegment.tagsSeen=!0;else this.currentSegment.attachmentsSeen=!0;g1(U);let _=this.reader.requestSlice(q,U);if(_ instanceof Promise)_=await _;if(_)this.readContiguousElements(_)}else if(j===b.Cluster){this.currentSegment.clusterSeekStartPos=G;break}if(U===void 0)break;else Y=q+U}if(this.currentSegment.seekEntries.sort((K,G)=>K.segmentPosition-G.segmentPosition),this.reader.fileSize!==null)for(let K of this.currentSegment.seekEntries){let G=YY.find((_)=>_.id===K.id);if(!G)continue;if(this.currentSegment[G.flag])continue;let W=this.reader.requestSliceRange($+K.segmentPosition,u0,Q1);if(W instanceof Promise)W=await W;if(!W)continue;let j=K1(W);if(!j)continue;let{id:U,size:q}=j;if(U!==G.id)continue;g1(q),this.currentSegment[G.flag]=!0;let V=this.reader.requestSlice(W.filePos,q);if(V instanceof Promise)V=await V;if(!V)continue;this.readContiguousElements(V)}if(this.currentSegment.timestampScale===-1)this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1000;for(let K of this.currentSegment.tracks)if(K.defaultDurationNs!==null)K.defaultDuration=this.currentSegment.timestampFactor*K.defaultDurationNs/1e9;let X=new Map(this.currentSegment.tracks.map((K)=>[K.id,K]));for(let K of this.currentSegment.cuePoints){let G=X.get(K.trackId);if(G)G.cuePoints.push(K)}for(let K of this.currentSegment.tracks){K.cuePoints.sort((G,W)=>G.time-W.time);for(let G=0;G<K.cuePoints.length-1;G++){let W=K.cuePoints[G],j=K.cuePoints[G+1];if(W.time===j.time)K.cuePoints.splice(G+1,1),G--}}let Q=null,Z=-1/0;for(let K of this.currentSegment.tracks)if(K.cuePoints.length>Z)Z=K.cuePoints.length,Q=K;for(let K of this.currentSegment.tracks)if(K.cuePoints.length===0)K.cuePoints=Q.cuePoints;this.currentSegment=null}async readCluster($,J){if(J.lastReadCluster?.elementStartPos===$)return J.lastReadCluster;let Y=this.reader.requestSliceRange($,u0,Q1);if(Y instanceof Promise)Y=await Y;L(Y);let X=$,Q=K1(Y);L(Q);let Z=Q.id;L(Z===b.Cluster);let K=Q.size,G=Y.filePos;if(K===void 0)K=(await u$(this.reader,G,i6,J.elementEndPos)).pos-G;let W=this.reader.requestSlice(G,K);if(W instanceof Promise)W=await W;let j={segment:J,elementStartPos:X,elementEndPos:G+K,dataStartPos:G,timestamp:-1,trackData:new Map};if(this.currentCluster=j,W){let U=this.readContiguousElements(W,i6);j.elementEndPos=U}for(let[,U]of j.trackData){let q=U.track;L(U.blocks.length>0);let V=!1;for(let z=0;z<U.blocks.length;z++){let H=U.blocks[z];H.timestamp+=j.timestamp,V||=H.lacing!==k1.None}U.presentationTimestamps=U.blocks.map((z,H)=>({timestamp:z.timestamp,blockIndex:H})).sort((z,H)=>z.timestamp-H.timestamp);for(let z=0;z<U.presentationTimestamps.length;z++){let H=U.presentationTimestamps[z],A=U.blocks[H.blockIndex];if(U.firstKeyFrameTimestamp===null&&A.isKeyFrame)U.firstKeyFrameTimestamp=A.timestamp;if(z<U.presentationTimestamps.length-1){let M=U.presentationTimestamps[z+1];A.duration=M.timestamp-A.timestamp}else if(A.duration===0){if(q.defaultDuration!=null){if(A.lacing===k1.None)A.duration=q.defaultDuration}}}if(V)this.expandLacedBlocks(U.blocks,q),U.presentationTimestamps=U.blocks.map((z,H)=>({timestamp:z.timestamp,blockIndex:H})).sort((z,H)=>z.timestamp-H.timestamp);let _=U.blocks[U.presentationTimestamps[0].blockIndex],N=U.blocks[K0(U.presentationTimestamps).blockIndex];U.startTimestamp=_.timestamp,U.endTimestamp=N.timestamp+N.duration;let R=p(q.clusterPositionCache,U.startTimestamp,(z)=>z.startTimestamp);if(R===-1||q.clusterPositionCache[R].elementStartPos!==X)q.clusterPositionCache.splice(R+1,0,{elementStartPos:j.elementStartPos,startTimestamp:U.startTimestamp})}return J.lastReadCluster=j,j}getTrackDataInCluster($,J){let Y=$.trackData.get(J);if(!Y){let X=$.segment.tracks.find((Q)=>Q.id===J);if(!X)return null;Y={track:X,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},$.trackData.set(J,Y)}return Y}expandLacedBlocks($,J){for(let Y=0;Y<$.length;Y++){let X=$[Y];if(X.lacing===k1.None)continue;if(!X.decoded)X.data=this.decodeBlockData(J,X.data),X.decoded=!0;let Q=x0.tempFromBytes(X.data),Z=[],K=g(Q)+1;switch(X.lacing){case k1.Xiph:{let W=0;for(let j=0;j<K-1;j++){let U=0;while(Q.bufferPos<Q.length){let q=g(Q);if(U+=q,q<255){Z.push(U),W+=U;break}}}Z.push(Q.length-(Q.bufferPos+W))}break;case k1.FixedSize:{let W=Q.length-1,j=Math.floor(W/K);for(let U=0;U<K;U++)Z.push(j)}break;case k1.Ebml:{let W=W6(Q);L(W!==null);let j=W;Z.push(j);let U=j;for(let q=1;q<K-1;q++){let V=Q.bufferPos,_=W6(Q);L(_!==null);let N=_,z=(1<<(Q.bufferPos-V)*7-1)-1,H=N-z;j+=H,Z.push(j),U+=j}Z.push(Q.length-(Q.bufferPos+U))}break;default:L(!1)}L(Z.length===K),$.splice(Y,1);let G=X.duration||K*(J.defaultDuration??0);for(let W=0;W<K;W++){let j=Z[W],U=h(Q,j),q=X.timestamp+G*W/K,V=G/K;$.splice(Y+W,0,{timestamp:q,duration:V,isKeyFrame:X.isKeyFrame,data:U,lacing:k1.None,decoded:!0,mainAdditional:X.mainAdditional})}Y+=K,Y--}}async loadSegmentMetadata($){for(let J of $.seekEntries){if(J.id===b.Tags&&!$.tagsSeen);else if(J.id===b.Attachments&&!$.attachmentsSeen);else continue;let Y=this.reader.requestSliceRange($.dataStartPos+J.segmentPosition,u0,Q1);if(Y instanceof Promise)Y=await Y;if(!Y)continue;let X=K1(Y);if(!X||X.id!==J.id)continue;let{size:Q}=X;g1(Q),L(!this.currentSegment),this.currentSegment=$;let Z=this.reader.requestSlice(Y.filePos,Q);if(Z instanceof Promise)Z=await Z;if(Z)this.readContiguousElements(Z);if(this.currentSegment=null,J.id===b.Tags)$.tagsSeen=!0;else if(J.id===b.Attachments)$.attachmentsSeen=!0}}readContiguousElements($,J){while($.remainingLength>=u0){let Y=$.filePos;if(!this.traverseElement($,J))return Y}return $.filePos}traverseElement($,J){let Y=K1($);if(!Y)return!1;if(J&&J.includes(Y.id))return!1;let{id:X,size:Q}=Y,Z=$.filePos;switch(g1(Q),X){case b.DocType:this.isWebM=J8($,Q)==="webm";break;case b.Seek:{if(!this.currentSegment)break;let K={id:-1,segmentPosition:-1};if(this.currentSegment.seekEntries.push(K),this.readContiguousElements($.slice(Z,Q)),K.id===-1||K.segmentPosition===-1)this.currentSegment.seekEntries.pop()}break;case b.SeekID:{let K=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!K)break;K.id=d($,Q)}break;case b.SeekPosition:{let K=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!K)break;K.segmentPosition=d($,Q)}break;case b.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=d($,Q),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case b.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=k$($,Q)}break;case b.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...M0,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements($.slice(Z,Q)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some((K)=>{return K.data?.type!=="decompress"||K.scope!==m$.Block||K.data.algorithm!==a6.HeaderStripping}))console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null;if(this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let K=this.currentTrack.codecId.indexOf("/"),G=K===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,K);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let j=this.currentTrack.info.displayWidth*this.currentTrack.info.height,U=this.currentTrack.info.displayHeight*this.currentTrack.info.width;if(j>0&&U>0)if(j>U)this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*j/U);else this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*U/j)}if(this.currentTrack.codecId===m0.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===m0.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===m0.vp8)this.currentTrack.info.codec="vp8";else if(G===m0.vp9)this.currentTrack.info.codec="vp9";else if(G===m0.av1)this.currentTrack.info.codec="av1";let W=this.currentTrack;this.currentTrack.trackBacking=new VX(W),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){if(G===m0.aac)this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===m0.mp3)this.currentTrack.info.codec="mp3";else if(G===m0.opus)this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=x1;else if(G===m0.vorbis)this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===m0.flac)this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===m0.ac3)this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===m0.eac3)this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId==="A_PCM/INT/LIT"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32"}else if(this.currentTrack.codecId==="A_PCM/INT/BIG"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16be";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24be";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32be"}else if(this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"){if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-f32";else if(this.currentTrack.info.bitDepth===64)this.currentTrack.info.codec="pcm-f64"}let W=this.currentTrack;this.currentTrack.trackBacking=new _X(W),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case b.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=d($,Q)}break;case b.TrackType:{if(!this.currentTrack)break;let K=d($,Q);if(K===1)this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1};else if(K===2)this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8000,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null}}break;case b.FlagEnabled:{if(!this.currentTrack)break;if(!d($,Q))this.currentTrack=null}break;case b.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!d($,Q)}break;case b.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!d($,Q)}break;case b.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!d($,Q)}break;case b.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!d($,Q)}break;case b.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!d($,Q)}break;case b.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!d($,Q)}break;case b.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=J8($,Q)}break;case b.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=h($,Q)}break;case b.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=d($,Q)}break;case b.Name:{if(!this.currentTrack)break;this.currentTrack.name=j6($,Q)}break;case b.Language:{if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;if(this.currentTrack.languageCode=J8($,Q),!c8(this.currentTrack.languageCode))this.currentTrack.languageCode=Z0}break;case b.LanguageBCP47:{if(!this.currentTrack)break;let G=J8($,Q).split("-")[0];if(G)this.currentTrack.languageCode=G;else this.currentTrack.languageCode=Z0;this.currentTrack.hasLanguageBcp47=!0}break;case b.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,Q))}break;case b.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=d($,Q)}break;case b.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=d($,Q)}break;case b.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=d($,Q)}break;case b.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=d($,Q)}break;case b.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=d($,Q)}break;case b.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=d($,Q)===1}break;case b.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements($.slice(Z,Q))}break;case b.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let K=d($,Q),G=A8[K]??null;this.currentTrack.info.colorSpace.matrix=G}break;case b.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=d($,Q)===2}break;case b.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let K=d($,Q),G=z8[K]??null;this.currentTrack.info.colorSpace.transfer=G}break;case b.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let K=d($,Q),G=_8[K]??null;this.currentTrack.info.colorSpace.primaries=G}break;case b.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,Q))}break;case b.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let G=-k$($,Q);try{this.currentTrack.info.rotation=s1(G)}catch{}}break;case b.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements($.slice(Z,Q))}break;case b.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=k$($,Q)}break;case b.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=d($,Q)}break;case b.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=d($,Q)}break;case b.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements($.slice(Z,Q)),this.currentCueTime=null}break;case b.CueTime:this.currentCueTime=d($,Q);break;case b.CueTrackPositions:{if(this.currentCueTime===null)break;L(this.currentSegment);let K={time:this.currentCueTime,trackId:-1,clusterPosition:-1};if(this.currentSegment.cuePoints.push(K),this.readContiguousElements($.slice(Z,Q)),K.trackId===-1||K.clusterPosition===-1)this.currentSegment.cuePoints.pop()}break;case b.CueTrack:{let K=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!K)break;K.trackId=d($,Q)}break;case b.CueClusterPosition:{let K=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!K)break;L(this.currentSegment),K.clusterPosition=this.currentSegment.dataStartPos+d($,Q)}break;case b.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=d($,Q)}break;case b.SimpleBlock:{if(!this.currentCluster)break;let K=W6($);if(K===null)break;let G=this.getTrackDataInCluster(this.currentCluster,K);if(!G)break;let W=r6($),j=g($),U=j>>1&3,q=!!(j&128);if(G.track.info?.type==="audio"&&G.track.info.codec)q=!0;let V=h($,Q-($.filePos-Z)),_=G.track.decodingInstructions.length>0;G.blocks.push({timestamp:W,duration:0,isKeyFrame:q,data:V,lacing:U,decoded:!_,mainAdditional:null})}break;case b.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements($.slice(Z,Q)),this.currentBlock=null}break;case b.Block:{if(!this.currentCluster)break;let K=W6($);if(K===null)break;let G=this.getTrackDataInCluster(this.currentCluster,K);if(!G)break;let W=r6($),U=g($)>>1&3,q=h($,Q-($.filePos-Z)),V=G.track.decodingInstructions.length>0;this.currentBlock={timestamp:W,duration:0,isKeyFrame:!0,data:q,lacing:U,decoded:!V,mainAdditional:null},G.blocks.push(this.currentBlock)}break;case b.BlockAdditions:this.readContiguousElements($.slice(Z,Q));break;case b.BlockMore:{if(!this.currentBlock)break;if(this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements($.slice(Z,Q)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1)this.currentBlock.mainAdditional=this.currentBlockAdditional.data;this.currentBlockAdditional=null}break;case b.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=h($,Q)}break;case b.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=d($,Q)}break;case b.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=d($,Q)}break;case b.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case b.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements($.slice(Z,Q));break;case b.Targets:this.readContiguousElements($.slice(Z,Q));break;case b.TargetTypeValue:if(d($,Q)!==50)this.currentTagTargetIsMovie=!1;break;case b.TagTrackUID:case b.TagEditionUID:case b.TagChapterUID:case b.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case b.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements($.slice(Z,Q))}break;case b.TagName:this.currentSimpleTagName=j6($,Q);break;case b.TagString:{if(!this.currentSimpleTagName)break;let K=j6($,Q);this.processTagValue(this.currentSimpleTagName,K)}break;case b.TagBinary:{if(!this.currentSimpleTagName)break;let K=h($,Q);this.processTagValue(this.currentSimpleTagName,K)}break;case b.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements($.slice(Z,Q));let K=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData)K.raw??={},K.raw[this.currentAttachedFile.fileUid.toString()]=new u6(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0);if(this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let G=this.currentAttachedFile.fileName,W="unknown";if(G){let j=G.toLowerCase();if(j.startsWith("cover."))W="coverFront";else if(j.startsWith("back."))W="coverBack"}K.images??=[],K.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:W,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case b.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=jX($,Q)}break;case b.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=j6($,Q)}break;case b.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=J8($,Q)}break;case b.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=h($,Q)}break;case b.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=j6($,Q)}break;case b.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements($.slice(Z,Q)),this.currentTrack.decodingInstructions.sort((K,G)=>G.order-K.order)}break;case b.ContentEncoding:{if(this.currentDecodingInstruction={order:0,scope:m$.Block,data:null},this.readContiguousElements($.slice(Z,Q)),this.currentDecodingInstruction.data)this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction);this.currentDecodingInstruction=null}break;case b.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=d($,Q)}break;case b.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=d($,Q)}break;case b.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:a6.Zlib,settings:null},this.readContiguousElements($.slice(Z,Q))}break;case b.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=d($,Q)}break;case b.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=h($,Q)}break;case b.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return $.filePos=Z+Q,!0}decodeBlockData($,J){L($.decodingInstructions.length>0);let Y=J;for(let X of $.decodingInstructions)switch(L(X.data),X.data.type){case"decompress":switch(X.data.algorithm){case a6.HeaderStripping:if(X.data.settings&&X.data.settings.length>0){let Q=X.data.settings,Z=new Uint8Array(Q.length+Y.length);Z.set(Q,0),Z.set(Y,Q.length),Y=Z}break;default:}break;default:}return Y}processTagValue($,J){if(!this.currentSegment?.metadataTags)return;let Y=this.currentSegment.metadataTags;if(Y.raw??={},Y.raw[$]??=J,typeof J==="string")switch($.toLowerCase()){case"title":Y.title??=J;break;case"description":Y.description??=J;break;case"artist":Y.artist??=J;break;case"album":Y.album??=J;break;case"album_artist":Y.albumArtist??=J;break;case"genre":Y.genre??=J;break;case"comment":Y.comment??=J;break;case"lyrics":Y.lyrics??=J;break;case"date":{let X=new Date(J);if(!Number.isNaN(X.getTime()))Y.date??=X}break;case"track_number":case"part_number":{let X=J.split("/"),Q=Number.parseInt(X[0],10),Z=X[1]&&Number.parseInt(X[1],10);if(Number.isInteger(Q)&&Q>0)Y.trackNumber??=Q;if(Z&&Number.isInteger(Z)&&Z>0)Y.tracksTotal??=Z}break;case"disc_number":case"disc":{let X=J.split("/"),Q=Number.parseInt(X[0],10),Z=X[1]&&Number.parseInt(X[1],10);if(Number.isInteger(Q)&&Q>0)Y.discNumber??=Q;if(Z&&Number.isInteger(Z)&&Z>0)Y.discsTotal??=Z}break}}}class ZY{constructor($){this.internalTrack=$,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let $=this.internalTrack.demuxer,J=this.internalTrack.trackBacking.getType(),Y=0;for(let X of $.segments)for(let Q of X.tracks){if(Q.trackBacking.getType()===J)Y++;if(Q===this.internalTrack)break}return Y}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let $=this.internalTrack.segment;if($.duration<=0)return null;let J=$.duration/$.timestampFactor,Y=await this.getFirstPacket({metadataOnly:!0});return J+=Y?.timestamp??0,J}async getLiveRefreshInterval(){return null}async getFirstPacket($){return this.performClusterLookup(null,(J)=>{if(J.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,$)}intoTimescale($){return E1($*this.internalTrack.segment.timestampFactor)}async getPacket($,J){let Y=this.intoTimescale($);return this.performClusterLookup(null,(X)=>{let Q=X.trackData.get(this.internalTrack.id);if(!Q)return{blockIndex:-1,correctBlockFound:!1};let Z=p(Q.presentationTimestamps,Y,(W)=>W.timestamp),K=Z!==-1?Q.presentationTimestamps[Z].blockIndex:-1,G=Z!==-1&&Y<Q.endTimestamp;return{blockIndex:K,correctBlockFound:G}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToClusterLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(Y.cluster,(X)=>{if(X===Y.cluster){let Q=X.trackData.get(this.internalTrack.id);if(Y.blockIndex+1<Q.blocks.length)return{blockIndex:Y.blockIndex+1,correctBlockFound:!0}}else if(X.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let Y=this.intoTimescale($);return this.performClusterLookup(null,(X)=>{let Q=X.trackData.get(this.internalTrack.id);if(!Q)return{blockIndex:-1,correctBlockFound:!1};let Z=L8(Q.presentationTimestamps,(W)=>{return Q.blocks[W.blockIndex].isKeyFrame&&W.timestamp<=Y}),K=Z!==-1?Q.presentationTimestamps[Z].blockIndex:-1,G=Z!==-1&&Y<Q.endTimestamp;return{blockIndex:K,correctBlockFound:G}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToClusterLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(Y.cluster,(X)=>{if(X===Y.cluster){let Z=X.trackData.get(this.internalTrack.id).blocks.findIndex((K,G)=>K.isKeyFrame&&G>Y.blockIndex);if(Z!==-1)return{blockIndex:Z,correctBlockFound:!0}}else{let Q=X.trackData.get(this.internalTrack.id);if(Q&&Q.firstKeyFrameTimestamp!==null){let Z=Q.blocks.findIndex((K)=>K.isKeyFrame);return L(Z!==-1),{blockIndex:Z,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,J)}async fetchPacketInCluster($,J,Y){if(J===-1)return null;let Q=$.trackData.get(this.internalTrack.id).blocks[J];if(L(Q),!Q.decoded)Q.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,Q.data),Q.decoded=!0;let Z=Y.metadataOnly?V0:Q.data,K=Q.timestamp/this.internalTrack.segment.timestampFactor,G=Q.duration/this.internalTrack.segment.timestampFactor,W={};if(Q.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode)W.alpha=Y.metadataOnly?V0:Q.mainAdditional,W.alphaByteLength=Q.mainAdditional.byteLength;let j=new i(Z,Q.isKeyFrame?"key":"delta",K,G,$.dataStartPos+J,Q.data.byteLength,W);return this.packetToClusterLocation.set(j,{cluster:$,blockIndex:J}),j}async performClusterLookup($,J,Y,X,Q){let{demuxer:Z,segment:K}=this.internalTrack,G=null,W=null,j=-1;if($){let{blockIndex:z,correctBlockFound:H}=J($);if(H)return this.fetchPacketInCluster($,z,Q);if(z!==-1)W=$,j=z}let U=p(this.internalTrack.cuePoints,Y,(z)=>z.time),q=U!==-1?this.internalTrack.cuePoints[U]:null,V=p(this.internalTrack.clusterPositionCache,Y,(z)=>z.startTimestamp),_=V!==-1?this.internalTrack.clusterPositionCache[V]:null,N=Math.max(q?.clusterPosition??0,_?.elementStartPos??0)||null,R;if(!$)R=N??K.clusterSeekStartPos;else if(N===null||$.elementStartPos>=N)R=$.elementEndPos,G=$;else R=N;while(K.elementEndPos===null||R<=K.elementEndPos-u0){if(G){let D=G.trackData.get(this.internalTrack.id);if(D&&D.startTimestamp>X)break}let z=Z.reader.requestSliceRange(R,u0,Q1);if(z instanceof Promise)z=await z;if(!z)break;let H=R,A=K1(z);if(!A||!U6.includes(A.id)&&A.id!==b.Void){let D=await $Y(Z.reader,H,U6,Math.min(K.elementEndPos??1/0,H+NX));if(D){R=D;continue}else break}let{id:M,size:F}=A,O=z.filePos;if(M===b.Cluster){G=await Z.readCluster(H,K),F=G.elementEndPos-O;let{blockIndex:D,correctBlockFound:w}=J(G);if(w)return this.fetchPacketInCluster(G,D,Q);if(D!==-1)W=G,j=D}if(F===void 0)L(M!==b.Cluster),F=(await u$(Z.reader,O,i6,K.elementEndPos)).pos-O;let B=O+F;if(K.elementEndPos===null){let D=Z.reader.requestSliceRange(B,u0,Q1);if(D instanceof Promise)D=await D;if(!D)break;if(g$(D)===b.Segment){K.elementEndPos=B;break}}R=B}if(q&&(!W||W.elementStartPos<q.clusterPosition)){let z=this.internalTrack.cuePoints[U-1];L(!z||z.time<q.time);let H=z?.time??-1/0;return this.performClusterLookup(null,J,H,X,Q)}if(W)return this.fetchPacketInCluster(W,j,Q);return null}}class VX extends ZY{constructor($){super($);this.decoderConfigPromise=null,this.internalTrack=$}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.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 this.internalTrack.info.alphaMode}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{let $=null;if(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)$=await this.getFirstPacket({});let Y={codec:i8({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&$?p6($.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&$?c6($.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&$?E$($.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&$?P$($.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};if(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)Y.displayAspectWidth=this.internalTrack.info.squarePixelWidth,Y.displayAspectHeight=this.internalTrack.info.squarePixelHeight;return Y})()}}class _X extends ZY{constructor($){super($);this.decoderConfig=null,this.internalTrack=$}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:a8({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}/*!
|
|
103
|
+
*/var UY=($)=>{let Y=($.hasVideo?"video/":$.hasAudio?"audio/":"application/")+($.isWebM?"webm":"x-matroska");if($.codecStrings.length>0){let X=[...new Set($.codecStrings.filter(Boolean))];Y+=`; codecs="${X.join(", ")}"`}return Y};/*!
|
|
104
104
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
105
105
|
*
|
|
106
106
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
107
107
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
108
108
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
109
|
-
*/var t6=async($,J,Y,X=null)=>{let Z=J;while(Y===null||Z<Y){let K=Y!==null?Math.min(65536,Y-Z):65536,G=$.requestSliceRange(Z,V1,K);if(G instanceof Promise)G=await G;if(!G||G.length<V1)break;while(G.remainingLength>=V1){let W=G.filePos,j=I(G),U=$.fileSize!==null?$.fileSize-Z:null,q=J6(j,U);if(q.header&&(!X||q.header.sampleRate===X.sampleRate&&q.header.mpegVersionId===X.mpegVersionId&&q.header.layer===X.layer&&t1(q.header.channel)===t1(X.channel)))return{header:q.header,startPos:Z};G.filePos=W+q.bytesAdvanced,Z=G.filePos}}return null};/*!
|
|
109
|
+
*/var n1;(function($){$[$.None=0]="None",$[$.Xiph=1]="Xiph",$[$.FixedSize=2]="FixedSize",$[$.Ebml=3]="Ebml"})(n1||(n1={}));var s$;(function($){$[$.Block=1]="Block",$[$.Private=2]="Private",$[$.Next=4]="Next"})(s$||(s$={}));var Z$;(function($){$[$.Zlib=0]="Zlib",$[$.Bzlib=1]="Bzlib",$[$.lzo1x=2]="lzo1x",$[$.HeaderStripping=3]="HeaderStripping"})(Z$||(Z$={}));var jY=[{id:b.SeekHead,flag:"seekHeadSeen"},{id:b.Info,flag:"infoSeen"},{id:b.Tracks,flag:"tracksSeen"},{id:b.Cues,flag:"cuesSeen"}],VX=10485760;class qY extends P0{constructor($){super($);this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=$._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(($)=>$.tracks.map((J)=>J.trackBacking))}async getMimeType(){await this.readMetadata();let $=await this.getTrackBackings(),J=await Promise.all($.map((Y)=>Y.getDecoderConfig().then((X)=>X?.codec??null)));return UY({isWebM:this.isWebM,hasVideo:this.segments.some((Y)=>Y.tracks.some((X)=>X.info?.type==="video")),hasAudio:this.segments.some((Y)=>Y.tracks.some((X)=>X.info?.type==="audio")),codecStrings:J.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let J of this.segments)if(!J.metadataTagsCollected){if(this.reader.fileSize!==null)await this.loadSegmentMetadata(J);J.metadataTagsCollected=!0}let $={};for(let J of this.segments)$={...$,...J.metadataTags};return $}readMetadata(){return this.readMetadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,a0,_1);if(J instanceof Promise)J=await J;if(!J)break;let Y=H1(J);if(!Y)break;let{id:X,size:Q}=Y,Z=J.filePos;if(X===b.EBML){c1(Q);let K=this.reader.requestSlice(Z,Q);if(K instanceof Promise)K=await K;if(!K)break;this.readContiguousElements(K)}else if(X===b.Segment){if(await this.readSegment(Z,Q),Q===void 0)break;if(this.reader.fileSize===null)break}else if(X===b.Cluster){if(this.reader.fileSize===null)break;if(Q===void 0)Q=(await n$(this.reader,Z,X$,this.reader.fileSize)).pos-Z;let K=W0(this.segments);if(K)K.elementEndPos=Z+Q}c1(Q),$=Z+Q}})()}async readSegment($,J){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:$,elementEndPos:J===void 0?null:$+J,clusterSeekStartPos:$,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let Y=$;while(this.currentSegment.elementEndPos===null||Y<this.currentSegment.elementEndPos){let K=this.reader.requestSliceRange(Y,a0,_1);if(K instanceof Promise)K=await K;if(!K)break;let G=Y,W=H1(K);if(!W||!H6.includes(W.id)&&W.id!==b.Void){let _=await WY(this.reader,G,H6,Math.min(this.currentSegment.elementEndPos??1/0,G+VX));if(_){Y=_;continue}else break}let{id:j,size:U}=W,q=K.filePos,N=jY.findIndex((_)=>_.id===j);if(N!==-1){let _=jY[N].flag;this.currentSegment[_]=!0,c1(U);let V=this.reader.requestSlice(q,U);if(V instanceof Promise)V=await V;if(V)this.readContiguousElements(V)}else if(j===b.Tags||j===b.Attachments){if(j===b.Tags)this.currentSegment.tagsSeen=!0;else this.currentSegment.attachmentsSeen=!0;c1(U);let _=this.reader.requestSlice(q,U);if(_ instanceof Promise)_=await _;if(_)this.readContiguousElements(_)}else if(j===b.Cluster){this.currentSegment.clusterSeekStartPos=G;break}if(U===void 0)break;else Y=q+U}if(this.currentSegment.seekEntries.sort((K,G)=>K.segmentPosition-G.segmentPosition),this.reader.fileSize!==null)for(let K of this.currentSegment.seekEntries){let G=jY.find((_)=>_.id===K.id);if(!G)continue;if(this.currentSegment[G.flag])continue;let W=this.reader.requestSliceRange($+K.segmentPosition,a0,_1);if(W instanceof Promise)W=await W;if(!W)continue;let j=H1(W);if(!j)continue;let{id:U,size:q}=j;if(U!==G.id)continue;c1(q),this.currentSegment[G.flag]=!0;let N=this.reader.requestSlice(W.filePos,q);if(N instanceof Promise)N=await N;if(!N)continue;this.readContiguousElements(N)}if(this.currentSegment.timestampScale===-1)this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1000;for(let K of this.currentSegment.tracks)if(K.defaultDurationNs!==null)K.defaultDuration=this.currentSegment.timestampFactor*K.defaultDurationNs/1e9;let X=new Map(this.currentSegment.tracks.map((K)=>[K.id,K]));for(let K of this.currentSegment.cuePoints){let G=X.get(K.trackId);if(G)G.cuePoints.push(K)}for(let K of this.currentSegment.tracks){K.cuePoints.sort((G,W)=>G.time-W.time);for(let G=0;G<K.cuePoints.length-1;G++){let W=K.cuePoints[G],j=K.cuePoints[G+1];if(W.time===j.time)K.cuePoints.splice(G+1,1),G--}}let Q=null,Z=-1/0;for(let K of this.currentSegment.tracks)if(K.cuePoints.length>Z)Z=K.cuePoints.length,Q=K;for(let K of this.currentSegment.tracks)if(K.cuePoints.length===0)K.cuePoints=Q.cuePoints;this.currentSegment=null}async readCluster($,J){if(J.lastReadCluster?.elementStartPos===$)return J.lastReadCluster;let Y=this.reader.requestSliceRange($,a0,_1);if(Y instanceof Promise)Y=await Y;F(Y);let X=$,Q=H1(Y);F(Q);let Z=Q.id;F(Z===b.Cluster);let K=Q.size,G=Y.filePos;if(K===void 0)K=(await n$(this.reader,G,X$,J.elementEndPos)).pos-G;let W=this.reader.requestSlice(G,K);if(W instanceof Promise)W=await W;let j={segment:J,elementStartPos:X,elementEndPos:G+K,dataStartPos:G,timestamp:-1,trackData:new Map};if(this.currentCluster=j,W){let U=this.readContiguousElements(W,X$);j.elementEndPos=U}for(let[,U]of j.trackData){let q=U.track;F(U.blocks.length>0);let N=!1;for(let R=0;R<U.blocks.length;R++){let H=U.blocks[R];H.timestamp+=j.timestamp,N||=H.lacing!==n1.None}U.presentationTimestamps=U.blocks.map((R,H)=>({timestamp:R.timestamp,blockIndex:H})).sort((R,H)=>R.timestamp-H.timestamp);for(let R=0;R<U.presentationTimestamps.length;R++){let H=U.presentationTimestamps[R],A=U.blocks[H.blockIndex];if(U.firstKeyFrameTimestamp===null&&A.isKeyFrame)U.firstKeyFrameTimestamp=A.timestamp;if(R<U.presentationTimestamps.length-1){let M=U.presentationTimestamps[R+1];A.duration=M.timestamp-A.timestamp}else if(A.duration===0){if(q.defaultDuration!=null){if(A.lacing===n1.None)A.duration=q.defaultDuration}}}if(N)this.expandLacedBlocks(U.blocks,q),U.presentationTimestamps=U.blocks.map((R,H)=>({timestamp:R.timestamp,blockIndex:H})).sort((R,H)=>R.timestamp-H.timestamp);let _=U.blocks[U.presentationTimestamps[0].blockIndex],V=U.blocks[W0(U.presentationTimestamps).blockIndex];U.startTimestamp=_.timestamp,U.endTimestamp=V.timestamp+V.duration;let z=p(q.clusterPositionCache,U.startTimestamp,(R)=>R.startTimestamp);if(z===-1||q.clusterPositionCache[z].elementStartPos!==X)q.clusterPositionCache.splice(z+1,0,{elementStartPos:j.elementStartPos,startTimestamp:U.startTimestamp})}return J.lastReadCluster=j,j}getTrackDataInCluster($,J){let Y=$.trackData.get(J);if(!Y){let X=$.segment.tracks.find((Q)=>Q.id===J);if(!X)return null;Y={track:X,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},$.trackData.set(J,Y)}return Y}expandLacedBlocks($,J){for(let Y=0;Y<$.length;Y++){let X=$[Y];if(X.lacing===n1.None)continue;if(!X.decoded)X.data=this.decodeBlockData(J,X.data),X.decoded=!0;let Q=u0.tempFromBytes(X.data),Z=[],K=g(Q)+1;switch(X.lacing){case n1.Xiph:{let W=0;for(let j=0;j<K-1;j++){let U=0;while(Q.bufferPos<Q.length){let q=g(Q);if(U+=q,q<255){Z.push(U),W+=U;break}}}Z.push(Q.length-(Q.bufferPos+W))}break;case n1.FixedSize:{let W=Q.length-1,j=Math.floor(W/K);for(let U=0;U<K;U++)Z.push(j)}break;case n1.Ebml:{let W=z6(Q);F(W!==null);let j=W;Z.push(j);let U=j;for(let q=1;q<K-1;q++){let N=Q.bufferPos,_=z6(Q);F(_!==null);let V=_,R=(1<<(Q.bufferPos-N)*7-1)-1,H=V-R;j+=H,Z.push(j),U+=j}Z.push(Q.length-(Q.bufferPos+U))}break;default:F(!1)}F(Z.length===K),$.splice(Y,1);let G=X.duration||K*(J.defaultDuration??0);for(let W=0;W<K;W++){let j=Z[W],U=f(Q,j),q=X.timestamp+G*W/K,N=G/K;$.splice(Y+W,0,{timestamp:q,duration:N,isKeyFrame:X.isKeyFrame,data:U,lacing:n1.None,decoded:!0,postProcessed:!1,mainAdditional:X.mainAdditional})}Y+=K,Y--}}async loadSegmentMetadata($){for(let J of $.seekEntries){if(J.id===b.Tags&&!$.tagsSeen);else if(J.id===b.Attachments&&!$.attachmentsSeen);else continue;let Y=this.reader.requestSliceRange($.dataStartPos+J.segmentPosition,a0,_1);if(Y instanceof Promise)Y=await Y;if(!Y)continue;let X=H1(Y);if(!X||X.id!==J.id)continue;let{size:Q}=X;c1(Q),F(!this.currentSegment),this.currentSegment=$;let Z=this.reader.requestSlice(Y.filePos,Q);if(Z instanceof Promise)Z=await Z;if(Z)this.readContiguousElements(Z);if(this.currentSegment=null,J.id===b.Tags)$.tagsSeen=!0;else if(J.id===b.Attachments)$.attachmentsSeen=!0}}readContiguousElements($,J){while($.remainingLength>=a0){let Y=$.filePos;if(!this.traverseElement($,J))return Y}return $.filePos}traverseElement($,J){let Y=H1($);if(!Y)return!1;if(J&&J.includes(Y.id))return!1;let{id:X,size:Q}=Y,Z=$.filePos;switch(c1(Q),X){case b.DocType:this.isWebM=G8($,Q)==="webm";break;case b.Seek:{if(!this.currentSegment)break;let K={id:-1,segmentPosition:-1};if(this.currentSegment.seekEntries.push(K),this.readContiguousElements($.slice(Z,Q)),K.id===-1||K.segmentPosition===-1)this.currentSegment.seekEntries.pop()}break;case b.SeekID:{let K=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!K)break;K.id=d($,Q)}break;case b.SeekPosition:{let K=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!K)break;K.segmentPosition=d($,Q)}break;case b.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=d($,Q),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case b.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=c$($,Q)}break;case b.TrackEntry:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...x0,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements($.slice(Z,Q)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some((K)=>{return K.data?.type!=="decompress"||K.scope!==s$.Block||K.data.algorithm!==Z$.HeaderStripping}))k._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null;if(this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let K=this.currentTrack.codecId.indexOf("/"),G=K===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,K);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let j=this.currentTrack.info.displayWidth*this.currentTrack.info.height,U=this.currentTrack.info.displayHeight*this.currentTrack.info.width;if(j>0&&U>0)if(j>U)this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*j/U);else this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*U/j)}if(this.currentTrack.codecId===d0.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===d0.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===d0.vp8)this.currentTrack.info.codec="vp8";else if(G===d0.vp9)this.currentTrack.info.codec="vp9";else if(G===d0.av1)this.currentTrack.info.codec="av1";else if(G===d0.prores){let j=this.currentTrack.codecPrivate?A0.decode(this.currentTrack.codecPrivate):"";if(Y6.includes(j))this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=j}let W=this.currentTrack;this.currentTrack.trackBacking=new _X(W),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){if(G===d0.aac)this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===d0.mp3)this.currentTrack.info.codec="mp3";else if(G===d0.opus)this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=k1;else if(G===d0.vorbis)this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===d0.flac)this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===d0.ac3)this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(G===d0.eac3)this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId==="A_PCM/INT/LIT"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32"}else if(this.currentTrack.codecId==="A_PCM/INT/BIG"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16be";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24be";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32be"}else if(this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"){if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-f32";else if(this.currentTrack.info.bitDepth===64)this.currentTrack.info.codec="pcm-f64"}let W=this.currentTrack;this.currentTrack.trackBacking=new HX(W),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case b.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=d($,Q)}break;case b.TrackType:{if(!this.currentTrack)break;let K=d($,Q);if(K===1)this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1,proresFormat:null};else if(K===2)this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8000,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null}}break;case b.FlagEnabled:{if(!this.currentTrack)break;if(!d($,Q))this.currentTrack=null}break;case b.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!d($,Q)}break;case b.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!d($,Q)}break;case b.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!d($,Q)}break;case b.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!d($,Q)}break;case b.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!d($,Q)}break;case b.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!d($,Q)}break;case b.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=G8($,Q)}break;case b.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=f($,Q)}break;case b.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=d($,Q)}break;case b.Name:{if(!this.currentTrack)break;this.currentTrack.name=R6($,Q)}break;case b.Language:{if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;if(this.currentTrack.languageCode=G8($,Q),!a8(this.currentTrack.languageCode))this.currentTrack.languageCode=K0}break;case b.LanguageBCP47:{if(!this.currentTrack)break;let G=G8($,Q).split("-")[0];if(G)this.currentTrack.languageCode=G;else this.currentTrack.languageCode=K0;this.currentTrack.hasLanguageBcp47=!0}break;case b.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,Q))}break;case b.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=d($,Q)}break;case b.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=d($,Q)}break;case b.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=d($,Q)}break;case b.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=d($,Q)}break;case b.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=d($,Q)}break;case b.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=d($,Q)===1}break;case b.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements($.slice(Z,Q))}break;case b.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let K=d($,Q),G=O8[K]??null;this.currentTrack.info.colorSpace.matrix=G}break;case b.Range:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=d($,Q)===2}break;case b.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let K=d($,Q),G=L8[K]??null;this.currentTrack.info.colorSpace.transfer=G}break;case b.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let K=d($,Q),G=M8[K]??null;this.currentTrack.info.colorSpace.primaries=G}break;case b.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,Q))}break;case b.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let G=-c$($,Q);try{this.currentTrack.info.rotation=J8(G)}catch{}}break;case b.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements($.slice(Z,Q))}break;case b.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=c$($,Q)}break;case b.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=d($,Q)}break;case b.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=d($,Q)}break;case b.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements($.slice(Z,Q)),this.currentCueTime=null}break;case b.CueTime:this.currentCueTime=d($,Q);break;case b.CueTrackPositions:{if(this.currentCueTime===null)break;F(this.currentSegment);let K={time:this.currentCueTime,trackId:-1,clusterPosition:-1};if(this.currentSegment.cuePoints.push(K),this.readContiguousElements($.slice(Z,Q)),K.trackId===-1||K.clusterPosition===-1)this.currentSegment.cuePoints.pop()}break;case b.CueTrack:{let K=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!K)break;K.trackId=d($,Q)}break;case b.CueClusterPosition:{let K=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!K)break;F(this.currentSegment),K.clusterPosition=this.currentSegment.dataStartPos+d($,Q)}break;case b.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=d($,Q)}break;case b.SimpleBlock:{if(!this.currentCluster)break;let K=z6($);if(K===null)break;let G=this.getTrackDataInCluster(this.currentCluster,K);if(!G)break;let W=Y$($),j=g($),U=j>>1&3,q=!!(j&128);if(G.track.info?.type==="audio"&&G.track.info.codec)q=!0;let N=f($,Q-($.filePos-Z)),_=G.track.decodingInstructions.length>0;G.blocks.push({timestamp:W,duration:0,isKeyFrame:q,data:N,lacing:U,decoded:!_,postProcessed:!1,mainAdditional:null})}break;case b.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements($.slice(Z,Q)),this.currentBlock=null}break;case b.Block:{if(!this.currentCluster)break;let K=z6($);if(K===null)break;let G=this.getTrackDataInCluster(this.currentCluster,K);if(!G)break;let W=Y$($),U=g($)>>1&3,q=f($,Q-($.filePos-Z)),N=G.track.decodingInstructions.length>0;this.currentBlock={timestamp:W,duration:0,isKeyFrame:!0,data:q,lacing:U,decoded:!N,postProcessed:!1,mainAdditional:null},G.blocks.push(this.currentBlock)}break;case b.BlockAdditions:this.readContiguousElements($.slice(Z,Q));break;case b.BlockMore:{if(!this.currentBlock)break;if(this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements($.slice(Z,Q)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1)this.currentBlock.mainAdditional=this.currentBlockAdditional.data;this.currentBlockAdditional=null}break;case b.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=f($,Q)}break;case b.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=d($,Q)}break;case b.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=d($,Q)}break;case b.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case b.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements($.slice(Z,Q));break;case b.Targets:this.readContiguousElements($.slice(Z,Q));break;case b.TargetTypeValue:if(d($,Q)!==50)this.currentTagTargetIsMovie=!1;break;case b.TagTrackUID:case b.TagEditionUID:case b.TagChapterUID:case b.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case b.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements($.slice(Z,Q))}break;case b.TagName:this.currentSimpleTagName=R6($,Q);break;case b.TagString:{if(!this.currentSimpleTagName)break;let K=R6($,Q);this.processTagValue(this.currentSimpleTagName,K)}break;case b.TagBinary:{if(!this.currentSimpleTagName)break;let K=f($,Q);this.processTagValue(this.currentSimpleTagName,K)}break;case b.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements($.slice(Z,Q));let K=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData)K.raw??={},K.raw[this.currentAttachedFile.fileUid.toString()]=new s6(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0);if(this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let G=this.currentAttachedFile.fileName,W="unknown";if(G){let j=G.toLowerCase();if(j.startsWith("cover."))W="coverFront";else if(j.startsWith("back."))W="coverBack"}K.images??=[],K.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:W,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case b.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=qX($,Q)}break;case b.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=R6($,Q)}break;case b.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=G8($,Q)}break;case b.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=f($,Q)}break;case b.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=R6($,Q)}break;case b.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements($.slice(Z,Q)),this.currentTrack.decodingInstructions.sort((K,G)=>G.order-K.order)}break;case b.ContentEncoding:{if(this.currentDecodingInstruction={order:0,scope:s$.Block,data:null},this.readContiguousElements($.slice(Z,Q)),this.currentDecodingInstruction.data)this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction);this.currentDecodingInstruction=null}break;case b.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=d($,Q)}break;case b.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=d($,Q)}break;case b.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Z$.Zlib,settings:null},this.readContiguousElements($.slice(Z,Q))}break;case b.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=d($,Q)}break;case b.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=f($,Q)}break;case b.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return $.filePos=Z+Q,!0}decodeBlockData($,J){F($.decodingInstructions.length>0);let Y=J;for(let X of $.decodingInstructions)switch(F(X.data),X.data.type){case"decompress":switch(X.data.algorithm){case Z$.HeaderStripping:if(X.data.settings&&X.data.settings.length>0){let Q=X.data.settings,Z=new Uint8Array(Q.length+Y.length);Z.set(Q,0),Z.set(Y,Q.length),Y=Z}break;default:}break;default:}return Y}processTagValue($,J){if(!this.currentSegment?.metadataTags)return;let Y=this.currentSegment.metadataTags;if(Y.raw??={},Y.raw[$]??=J,typeof J==="string")switch($.toLowerCase()){case"title":Y.title??=J;break;case"description":Y.description??=J;break;case"artist":Y.artist??=J;break;case"album":Y.album??=J;break;case"album_artist":Y.albumArtist??=J;break;case"genre":Y.genre??=J;break;case"comment":Y.comment??=J;break;case"lyrics":Y.lyrics??=J;break;case"date":{let X=new Date(J);if(!Number.isNaN(X.getTime()))Y.date??=X}break;case"track_number":case"part_number":{let X=J.split("/"),Q=Number.parseInt(X[0],10),Z=X[1]&&Number.parseInt(X[1],10);if(Number.isInteger(Q)&&Q>0)Y.trackNumber??=Q;if(Z&&Number.isInteger(Z)&&Z>0)Y.tracksTotal??=Z}break;case"disc_number":case"disc":{let X=J.split("/"),Q=Number.parseInt(X[0],10),Z=X[1]&&Number.parseInt(X[1],10);if(Number.isInteger(Q)&&Q>0)Y.discNumber??=Q;if(Z&&Number.isInteger(Z)&&Z>0)Y.discsTotal??=Z}break}}}class NY{constructor($){this.internalTrack=$,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let $=this.internalTrack.demuxer,J=this.internalTrack.trackBacking.getType(),Y=0;for(let X of $.segments)for(let Q of X.tracks){if(Q.trackBacking.getType()===J)Y++;if(Q===this.internalTrack)break}return Y}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let $=this.internalTrack.segment;if($.duration<=0)return null;let J=$.duration/$.timestampFactor,Y=await this.getFirstPacket({metadataOnly:!0});return J+=Y?.timestamp??0,J}async getLiveRefreshInterval(){return null}async getFirstPacket($){return this.performClusterLookup(null,(J)=>{if(J.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,$)}intoTimescale($){return y1($*this.internalTrack.segment.timestampFactor)}async getPacket($,J){let Y=this.intoTimescale($);return this.performClusterLookup(null,(X)=>{let Q=X.trackData.get(this.internalTrack.id);if(!Q)return{blockIndex:-1,correctBlockFound:!1};let Z=p(Q.presentationTimestamps,Y,(W)=>W.timestamp),K=Z!==-1?Q.presentationTimestamps[Z].blockIndex:-1,G=Z!==-1&&Y<Q.endTimestamp;return{blockIndex:K,correctBlockFound:G}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToClusterLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(Y.cluster,(X)=>{if(X===Y.cluster){let Q=X.trackData.get(this.internalTrack.id);if(Y.blockIndex+1<Q.blocks.length)return{blockIndex:Y.blockIndex+1,correctBlockFound:!0}}else if(X.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let Y=this.intoTimescale($);return this.performClusterLookup(null,(X)=>{let Q=X.trackData.get(this.internalTrack.id);if(!Q)return{blockIndex:-1,correctBlockFound:!1};let Z=B8(Q.presentationTimestamps,(W)=>{return Q.blocks[W.blockIndex].isKeyFrame&&W.timestamp<=Y}),K=Z!==-1?Q.presentationTimestamps[Z].blockIndex:-1,G=Z!==-1&&Y<Q.endTimestamp;return{blockIndex:K,correctBlockFound:G}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToClusterLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(Y.cluster,(X)=>{if(X===Y.cluster){let Z=X.trackData.get(this.internalTrack.id).blocks.findIndex((K,G)=>K.isKeyFrame&&G>Y.blockIndex);if(Z!==-1)return{blockIndex:Z,correctBlockFound:!0}}else{let Q=X.trackData.get(this.internalTrack.id);if(Q&&Q.firstKeyFrameTimestamp!==null){let Z=Q.blocks.findIndex((K)=>K.isKeyFrame);return F(Z!==-1),{blockIndex:Z,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,J)}async fetchPacketInCluster($,J,Y){if(J===-1)return null;let Q=$.trackData.get(this.internalTrack.id).blocks[J];if(F(Q),!Q.decoded)Q.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,Q.data),Q.decoded=!0;if(!Q.postProcessed){if(this.internalTrack.info?.codec==="prores"){if(!(Q.data.length>=8&&Q.data[4]===105&&Q.data[5]===99&&Q.data[6]===112&&Q.data[7]===102)){let q=new Uint8Array(Q.data.length+8);l(q).setUint32(0,q.length,!1),q[4]=105,q[5]=99,q[6]=112,q[7]=102,q.set(Q.data,8),Q.data=q}}Q.postProcessed=!0}let Z=Y.metadataOnly?w0:Q.data,K=Q.timestamp/this.internalTrack.segment.timestampFactor,G=Q.duration/this.internalTrack.segment.timestampFactor,W={};if(Q.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode)W.alpha=Y.metadataOnly?w0:Q.mainAdditional,W.alphaByteLength=Q.mainAdditional.byteLength;let j=new t(Z,Q.isKeyFrame?"key":"delta",K,G,$.dataStartPos+J,Q.data.byteLength,W);return this.packetToClusterLocation.set(j,{cluster:$,blockIndex:J}),j}async performClusterLookup($,J,Y,X,Q){let{demuxer:Z,segment:K}=this.internalTrack,G=null,W=null,j=-1;if($){let{blockIndex:R,correctBlockFound:H}=J($);if(H)return this.fetchPacketInCluster($,R,Q);if(R!==-1)W=$,j=R}let U=p(this.internalTrack.cuePoints,Y,(R)=>R.time),q=U!==-1?this.internalTrack.cuePoints[U]:null,N=p(this.internalTrack.clusterPositionCache,Y,(R)=>R.startTimestamp),_=N!==-1?this.internalTrack.clusterPositionCache[N]:null,V=Math.max(q?.clusterPosition??0,_?.elementStartPos??0)||null,z;if(!$)z=V??K.clusterSeekStartPos;else if(V===null||$.elementStartPos>=V)z=$.elementEndPos,G=$;else z=V;while(K.elementEndPos===null||z<=K.elementEndPos-a0){if(G){let D=G.trackData.get(this.internalTrack.id);if(D&&D.startTimestamp>X)break}let R=Z.reader.requestSliceRange(z,a0,_1);if(R instanceof Promise)R=await R;if(!R)break;let H=z,A=H1(R);if(!A||!H6.includes(A.id)&&A.id!==b.Void){let D=await WY(Z.reader,H,H6,Math.min(K.elementEndPos??1/0,H+VX));if(D){z=D;continue}else break}let{id:M,size:L}=A,w=R.filePos;if(M===b.Cluster){G=await Z.readCluster(H,K),L=G.elementEndPos-w;let{blockIndex:D,correctBlockFound:B}=J(G);if(B)return this.fetchPacketInCluster(G,D,Q);if(D!==-1)W=G,j=D}if(L===void 0)F(M!==b.Cluster),L=(await n$(Z.reader,w,X$,K.elementEndPos)).pos-w;let O=w+L;if(K.elementEndPos===null){let D=Z.reader.requestSliceRange(O,a0,_1);if(D instanceof Promise)D=await D;if(!D)break;if(d$(D)===b.Segment){K.elementEndPos=O;break}}z=O}if(q&&(!W||W.elementStartPos<q.clusterPosition)){let R=this.internalTrack.cuePoints[U-1];F(!R||R.time<q.time);let H=R?.time??-1/0;return this.performClusterLookup(null,J,H,X,Q)}if(W)return this.fetchPacketInCluster(W,j,Q);return null}}class _X extends NY{constructor($){super($);this.decoderConfigPromise=null,this.internalTrack=$}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.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 this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{let $=null;if(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)$=await this.getFirstPacket({});let Y={codec:X6({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&$?i6($.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&$?t6($.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&$?I$($.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&$?y$($.data):null,proresFormat:this.internalTrack.info.proresFormat}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};if(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)Y.displayAspectWidth=this.internalTrack.info.squarePixelWidth,Y.displayAspectHeight=this.internalTrack.info.squarePixelHeight;return Y})()}}class HX extends NY{constructor($){super($);this.decoderConfig=null,this.internalTrack=$}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:Z6({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}/*!
|
|
110
110
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
111
111
|
*
|
|
112
112
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
113
113
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
114
114
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
115
|
-
*/
|
|
115
|
+
*/var Q$=async($,J,Y,X=null)=>{let Z=J;while(Y===null||Z<Y){let K=Y!==null?Math.min(65536,Y-Z):65536,G=$.requestSliceRange(Z,w1,K);if(G instanceof Promise)G=await G;if(!G||G.length<w1)break;while(G.remainingLength>=w1){let W=G.filePos,j=y(G),U=$.fileSize!==null?$.fileSize-Z:null,q=W6(j,U);if(q.header&&(!X||q.header.sampleRate===X.sampleRate&&q.header.mpegVersionId===X.mpegVersionId&&q.header.layer===X.layer&&Z8(q.header.channel)===Z8(X.channel)))return{header:q.header,startPos:Z};G.filePos=W+q.bytesAdvanced,Z=G.filePos}}return null};/*!
|
|
116
116
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
117
117
|
*
|
|
118
118
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
119
119
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
120
120
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
121
|
-
*/
|
|
121
|
+
*/class VY extends P0{constructor($){super($);this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new X1,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{while(!this.firstFrameHeader&&!this.lastSampleLoaded)await this.advanceReader();if(!this.firstFrameHeader)throw Error("No valid MP3 frame found.");this.trackBackings=[new zX(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)while(!0){let K=this.reader.requestSlice(this.lastLoadedPos,f0);if(K instanceof Promise)K=await K;if(!K){this.lastSampleLoaded=!0;return}let G=t0(K);if(!G)break;this.lastLoadedPos=K.filePos+G.size}let $=await Q$(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!$){this.lastSampleLoaded=!0;return}let J=$.header;this.lastLoadedPos=$.startPos+J.totalSize-1;let Y=G6(J.mpegVersionId,J.channel),X=this.reader.requestSlice($.startPos+Y,4);if(X instanceof Promise)X=await X;if(X){let K=y(X);if(K===K6||K===o6){if(!this.xingData){let W=this.reader.requestSlice($.startPos+Y+4,12);if(W instanceof Promise)W=await W;if(W){let j=f(W,12),U=l(j),q=U.getUint32(0,!1);this.xingData={frameCount:q&Q6.FrameCount?U.getUint32(4,!1):null,fileSize:q&Q6.FileSize?U.getUint32(8,!1):null}}}return}}if(!this.firstFrameHeader)this.firstFrameHeader=J,this.firstFrameHeaderPos=$.startPos;let Q=J.audioSamplesInFrame/this.firstFrameHeader.sampleRate,Z={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:Q,dataStart:$.startPos,dataSize:J.totalSize};this.loadedSamples.push(Z),this.nextTimestampInSamples+=J.audioSamplesInFrame;return}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let $=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let J=0,Y=!1;while(!0){let X=this.reader.requestSlice(J,f0);if(X instanceof Promise)X=await X;if(!X)break;let Q=t0(X);if(!Q)break;Y=!0;let Z=this.reader.requestSlice(X.filePos,Q.size);if(Z instanceof Promise)Z=await Z;if(!Z)break;W8(Z,Q,this.metadataTags),J=X.filePos+Q.size}if(!Y&&this.reader.fileSize!==null&&this.reader.fileSize>=K$){let X=this.reader.requestSlice(this.reader.fileSize-K$,K$);if(X instanceof Promise)X=await X;if(F(X),Z0(X,3)==="TAG")RX(X,this.metadataTags)}return this.metadataTags}finally{$()}}}class zX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return F(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let $=this.demuxer;if(F($.firstFrameHeader!==null),F($.firstFrameHeaderPos!==null),$.xingData){if($.xingData.frameCount!==null)return $.xingData.frameCount*$.firstFrameHeader.audioSamplesInFrame/$.firstFrameHeader.sampleRate}else if($.reader.fileSize!==null){let J=d7($.firstFrameHeader.lowSamplingFrequency,$.firstFrameHeader.layer,$.firstFrameHeader.bitrate,$.firstFrameHeader.sampleRate),Y=($.reader.fileSize-$.firstFrameHeaderPos)/J;return Math.round(Y)*$.firstFrameHeader.audioSamplesInFrame/$.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return K0}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return F(this.demuxer.firstFrameHeader),Z8(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return F(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...x0}}async getDecoderConfig(){return F(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Z8(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex($,J){if($===-1)return null;let Y=this.demuxer.loadedSamples[$];if(!Y)return null;let X;if(J.metadataOnly)X=w0;else{let Q=this.demuxer.reader.requestSlice(Y.dataStart,Y.dataSize);if(Q instanceof Promise)Q=await Q;if(!Q)return null;X=f(Q,Y.dataSize)}return new t(X,"key",Y.timestamp,Y.duration,$,Y.dataSize)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getNextPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{let X=I1(this.demuxer.loadedSamples,$.timestamp,(Z)=>Z.timestamp);if(X===-1)throw Error("Packet was not created from this track.");let Q=X+1;while(Q>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(Q,J)}finally{Y()}}async getPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{while(!0){let X=p(this.demuxer.loadedSamples,$,(Q)=>Q.timestamp);if(X===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(X,J);if(X>=0&&X+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(X,J);await this.demuxer.advanceReader()}}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
|
|
122
122
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
123
123
|
*
|
|
124
124
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
125
125
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
126
126
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
127
|
-
*/var
|
|
127
|
+
*/var o$=1399285583,Z2=79764919,AX=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let Y=0;Y<8;Y++)J=J&2147483648?J<<1^Z2:J<<1;AX[$]=J>>>0&4294967295}var _Y=($)=>{let J=l($),Y=J.getUint32(22,!0);J.setUint32(22,0,!0);let X=0;for(let Q=0;Q<$.length;Q++){let Z=$[Q];X=(X<<8^AX[X>>>24^Z])>>>0}return J.setUint32(22,Y,!0),X},HY=($,J,Y)=>{let X=0,Q=null;if($.length>0){if(J.codec==="vorbis"){F(J.vorbisInfo);let Z=J.vorbisInfo.modeBlockflags.length,G=(1<<S7(Z-1))-1<<1,W=($[0]&G)>>1;if(W>=J.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let j=Y,U=J.vorbisInfo.modeBlockflags[W];if(Q=J.vorbisInfo.blocksizes[U],U===1){let q=(G|1)+1,N=$[0]&q?1:0;j=J.vorbisInfo.blocksizes[N]}X=j!==null?j+Q>>2:0}else if(J.codec==="opus")X=a7($).durationInSamples}return{durationInSamples:X,vorbisBlockSize:Q}},zY=($)=>{let J="audio/ogg";if($.codecStrings){let Y=[...new Set($.codecStrings)];J+=`; codecs="${Y.join(", ")}"`}return J};/*!
|
|
128
128
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
129
129
|
*
|
|
130
130
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
131
131
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
132
132
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
133
|
-
*/class jY extends L0{constructor($){super($);this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,Y8,I8);if(J instanceof Promise)J=await J;if(!J)break;let Y=N6(J);if(!Y)break;if(!(Y.headerType&2))break;this.bitstreams.push({serialNumber:Y.serialNumber,bosPage:Y,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),$=Y.headerStartPos+Y.totalSize}for(let J of this.bitstreams){let Y=await this.readPacket(J.bosPage,0);if(!Y)continue;if(Y.data.byteLength>=7&&Y.data[0]===1&&Y.data[1]===118&&Y.data[2]===111&&Y.data[3]===114&&Y.data[4]===98&&Y.data[5]===105&&Y.data[6]===115)await this.readVorbisMetadata(Y,J);else if(Y.data.byteLength>=8&&Y.data[0]===79&&Y.data[1]===112&&Y.data[2]===117&&Y.data[3]===115&&Y.data[4]===72&&Y.data[5]===101&&Y.data[6]===97&&Y.data[7]===100)await this.readOpusMetadata(Y,J);if(J.codecInfo.codec!==null)this.trackBackings.push(new wX(J,this))}})()}async readVorbisMetadata($,J){let Y=await this.findNextPacketStart($);if(!Y)return;let X=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!X)return;if(Y=await this.findNextPacketStart(X),!Y)return;let Q=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!Q)return;if(X.data[0]!==3||Q.data[0]!==5)return;let Z=[],K=(U)=>{while(!0){if(Z.push(Math.min(255,U)),U<255)break;U-=255}};K($.data.length),K(X.data.length);let G=new Uint8Array(1+Z.length+$.data.length+X.data.length+Q.data.length);G[0]=2,G.set(Z,1),G.set($.data,1+Z.length),G.set(X.data,1+Z.length+$.data.length),G.set(Q.data,1+Z.length+$.data.length+X.data.length),J.codecInfo.codec="vorbis",J.description=G,J.lastMetadataPacket=Q;let W=u($.data);J.numberOfChannels=W.getUint8(11),J.sampleRate=W.getUint32(12,!0);let j=W.getUint8(28);J.codecInfo.vorbisInfo={blocksizes:[1<<(j&15),1<<(j>>4)],modeBlockflags:mJ(Q.data).modeBlockflags},o6(X.data.subarray(7),this.metadataTags)}async readOpusMetadata($,J){let Y=await this.findNextPacketStart($);if(!Y)return;let X=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!X)return;J.codecInfo.codec="opus",J.description=$.data,J.lastMetadataPacket=X;let Q=n6($.data);J.numberOfChannels=Q.outputChannelCount,J.sampleRate=x1,J.codecInfo.opusInfo={preSkip:Q.preSkip},o6(X.data.subarray(8),this.metadataTags)}async readPacket($,J){L(J<$.lacingValues.length);let Y=0;for(let U=0;U<J;U++)Y+=$.lacingValues[U];let X=$,Q=Y,Z=J,K=[];$:while(!0){let U=this.reader.requestSlice(X.dataStartPos,X.dataSize);if(U instanceof Promise)U=await U;L(U);let q=h(U,X.dataSize);while(!0){if(Z===X.lacingValues.length){K.push(q.subarray(Y,Q));break}let _=X.lacingValues[Z];if(Q+=_,_<255){K.push(q.subarray(Y,Q));break $}Z++}let V=X.headerStartPos+X.totalSize;while(!0){let _=this.reader.requestSliceRange(V,Y8,I8);if(_ instanceof Promise)_=await _;if(!_)return null;let N=N6(_);if(!N)return null;if(X=N,X.serialNumber===$.serialNumber)break;V=X.headerStartPos+X.totalSize}Y=0,Q=0,Z=0}let G=K.reduce((U,q)=>U+q.length,0);if(G===0)return null;let W=new Uint8Array(G),j=0;for(let U=0;U<K.length;U++){let q=K[U];W.set(q,j),j+=q.length}return{data:W,endPage:X,endSegmentIndex:Z}}async findNextPacketStart($){if($.endSegmentIndex<$.endPage.lacingValues.length-1)return{startPage:$.endPage,startSegmentIndex:$.endSegmentIndex+1};if(!!($.endPage.headerType&4))return null;let Y=$.endPage.headerStartPos+$.endPage.totalSize;while(!0){let X=this.reader.requestSliceRange(Y,Y8,I8);if(X instanceof Promise)X=await X;if(!X)return null;let Q=N6(X);if(!Q)return null;if(Q.serialNumber===$.endPage.serialNumber)return{startPage:Q,startSegmentIndex:0};Y=Q.headerStartPos+Q.totalSize}}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.trackBackings.map((J)=>J.getDecoderConfig().then((Y)=>Y?.codec??null)));return UY({codecStrings:$.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class wX{constructor($,J){this.bitstream=$,this.demuxer=J,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new o0,this.internalSampleRate=$.codecInfo.codec==="opus"?x1:$.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let $=this.demuxer.trackBackings.findIndex((J)=>J.bitstream===this.bitstream);return L($!==-1),$+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return L(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Z0}getDisposition(){return{...M0,primary:!1}}granulePositionToTimestampInSamples($){if(this.bitstream.codecInfo.codec==="opus")return L(this.bitstream.codecInfo.opusInfo),$-this.bitstream.codecInfo.opusInfo.preSkip;return $}createEncodedPacketFromOggPacket($,J,Y){if(!$)return null;let{durationInSamples:X,vorbisBlockSize:Q}=GY($.data,this.bitstream.codecInfo,J.vorbisLastBlocksize),Z=new i(Y.metadataOnly?V0:$.data,"key",Math.max(0,J.timestampInSamples)/this.internalSampleRate,X/this.internalSampleRate,$.endPage.headerStartPos+$.endSegmentIndex,$.data.byteLength);return this.encodedPacketToMetadata.set(Z,{packet:$,timestampInSamples:J.timestampInSamples,durationInSamples:X,vorbisLastBlockSize:J.vorbisLastBlocksize,vorbisBlockSize:Q}),Z}async getFirstPacket($){L(this.bitstream.lastMetadataPacket);let J=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!J)return null;let Y=0;if(this.bitstream.codecInfo.codec==="opus")L(this.bitstream.codecInfo.opusInfo),Y-=this.bitstream.codecInfo.opusInfo.preSkip;let X=await this.demuxer.readPacket(J.startPage,J.startSegmentIndex);return this.createEncodedPacketFromOggPacket(X,{timestampInSamples:Y,vorbisLastBlocksize:null},$)}async getNextPacket($,J){let Y=this.encodedPacketToMetadata.get($);if(!Y)throw Error("Packet was not created from this track.");let X=await this.demuxer.findNextPacketStart(Y.packet);if(!X)return null;let Q=Y.timestampInSamples+Y.durationInSamples,Z=await this.demuxer.readPacket(X.startPage,X.startSegmentIndex);return this.createEncodedPacketFromOggPacket(Z,{timestampInSamples:Q,vorbisLastBlocksize:Y.vorbisBlockSize},J)}async getPacket($,J){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential($,J);let Y=E1($*this.internalSampleRate);if(Y===0)return this.getFirstPacket(J);if(Y<0)return null;L(this.bitstream.lastMetadataPacket);let X=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!X)return null;let Q=X.startPage,Z=this.demuxer.reader.fileSize,K=[Q];$:while(Q.headerStartPos+Q.totalSize<Z){let H=Q.headerStartPos,A=Math.floor((H+Z)/2),M=A;while(!0){let F=Math.min(M+WY,Z-Y8),O=this.demuxer.reader.requestSlice(M,F-M);if(O instanceof Promise)O=await O;if(L(O),!AX(O,F)){Z=A+Y8;continue $}let D=this.demuxer.reader.requestSliceRange(O.filePos,Y8,I8);if(D instanceof Promise)D=await D;L(D);let w=N6(D);L(w);let P=!1;if(w.serialNumber===this.bitstream.serialNumber)P=!0;else{let C=this.demuxer.reader.requestSlice(w.headerStartPos,w.totalSize);if(C instanceof Promise)C=await C;L(C);let E=h(C,w.totalSize);P=KY(E)===w.checksum}if(!P){M=w.headerStartPos+4;continue}if(P&&w.serialNumber!==this.bitstream.serialNumber){M=w.headerStartPos+w.totalSize;continue}if(w.granulePosition===-1){M=w.headerStartPos+w.totalSize;continue}if(this.granulePositionToTimestampInSamples(w.granulePosition)>Y)Z=w.headerStartPos;else Q=w,K.push(w);continue $}}let G=X.startPage;for(let H of K){if(H.granulePosition===Q.granulePosition)break;if(!G||H.headerStartPos>G.headerStartPos)G=H}let W=G,j=[W];while(!0){if(W.serialNumber===this.bitstream.serialNumber&&W.granulePosition===Q.granulePosition)break;let H=W.headerStartPos+W.totalSize,A=this.demuxer.reader.requestSliceRange(H,Y8,I8);if(A instanceof Promise)A=await A;L(A);let M=N6(A);if(L(M),W=M,W.serialNumber===this.bitstream.serialNumber)j.push(W)}L(W.granulePosition!==-1);let U=null,q,V,_=W,N=0;if(W.headerStartPos===X.startPage.headerStartPos)q=this.granulePositionToTimestampInSamples(0),V=!0,U=0;else{q=0,V=!1;for(let M=W.lacingValues.length-1;M>=0;M--)if(W.lacingValues[M]<255){U=M+1;break}if(U===null)throw Error("Invalid page with granule position: no packets end on this page.");N=U-1;let H={data:V0,endPage:_,endSegmentIndex:N};if(await this.demuxer.findNextPacketStart(H)){let M=FX(j,W,U);L(M);let F=MX(j,M.page,M.segmentIndex);if(F)W=F.page,U=F.segmentIndex}else while(!0){let M=FX(j,W,U);if(!M)break;let F=MX(j,M.page,M.segmentIndex);if(!F)break;if(W=F.page,U=F.segmentIndex,M.page.headerStartPos!==_.headerStartPos){_=M.page,N=M.segmentIndex;break}}}let R=null,z=null;while(W!==null){L(U!==null);let H=await this.demuxer.readPacket(W,U);if(!H)break;if(!(W.headerStartPos===X.startPage.headerStartPos&&U<X.startSegmentIndex)){let F=this.createEncodedPacketFromOggPacket(H,{timestampInSamples:q,vorbisLastBlocksize:z?.vorbisBlockSize??null},J);L(F);let O=this.encodedPacketToMetadata.get(F);if(L(O),!V&&H.endPage.headerStartPos===_.headerStartPos&&H.endSegmentIndex===N)q=this.granulePositionToTimestampInSamples(W.granulePosition),V=!0,F=this.createEncodedPacketFromOggPacket(H,{timestampInSamples:q-O.durationInSamples,vorbisLastBlocksize:z?.vorbisBlockSize??null},J),L(F),O=this.encodedPacketToMetadata.get(F),L(O);else q+=O.durationInSamples;if(R=F,z=O,V&&(Math.max(q,0)>Y||Math.max(O.timestampInSamples,0)===Y))break}let M=await this.demuxer.findNextPacketStart(H);if(!M)break;W=M.startPage,U=M.startSegmentIndex}return R}async getPacketSequential($,J){let Y=await this.sequentialScanMutex.acquire();try{let X=E1($*this.internalSampleRate);$=X/this.internalSampleRate;let Q=p(this.sequentialScanCache,X,(G)=>G.timestampInSamples),Z;if(Q!==-1){let G=this.sequentialScanCache[Q];Z=this.createEncodedPacketFromOggPacket(G.packet,{timestampInSamples:G.timestampInSamples,vorbisLastBlocksize:G.vorbisLastBlockSize},J)}else Z=await this.getFirstPacket(J);let K=0;while(Z&&Z.timestamp<$){let G=await this.getNextPacket(Z,J);if(!G||G.timestamp>$)break;if(Z=G,K++,K===100){K=0;let W=this.encodedPacketToMetadata.get(Z);if(L(W),this.sequentialScanCache.length>0)L(K0(this.sequentialScanCache).timestampInSamples<=W.timestampInSamples);this.sequentialScanCache.push(W)}}return Z}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}var MX=($,J,Y)=>{let X=J,Q=Y;$:while(!0){Q--;for(Q;Q>=0;Q--)if(X.lacingValues[Q]<255){Q++;break $}if(L(Q===-1),!(X.headerType&1)){Q=0;break}let K=bJ($,(G)=>G.headerStartPos<X.headerStartPos);if(!K)return null;X=K,Q=X.lacingValues.length}if(L(Q!==-1),Q===X.lacingValues.length){let Z=$[$.indexOf(X)+1];L(Z),X=Z,Q=0}return{page:X,segmentIndex:Q}},FX=($,J,Y)=>{if(Y>0)return{page:J,segmentIndex:Y-1};let X=bJ($,(Q)=>Q.headerStartPos<J.headerStartPos);if(!X)return null;return{page:X,segmentIndex:X.lacingValues.length-1}};/*!
|
|
133
|
+
*/var U8=27,g8=282,RY=g8+65025,A6=($)=>{let J=$.filePos;if(f8($)!==o$)return null;$.skip(1);let X=g($),Q=FX($),Z=f8($),K=f8($),G=f8($),W=g($),j=new Uint8Array(W);for(let _=0;_<W;_++)j[_]=g($);let U=27+W,q=j.reduce((_,V)=>_+V,0),N=U+q;return{headerStartPos:J,totalSize:N,dataStartPos:J+U,dataSize:q,headerType:X,granulePosition:Q,serialNumber:Z,sequenceNumber:K,checksum:G,lacingValues:j}},MX=($,J)=>{while($.filePos<J-3){let Y=f8($),X=Y&255,Q=Y>>>8&255,Z=Y>>>16&255,K=Y>>>24&255,G=79;if(X!==79&&Q!==79&&Z!==79&&K!==79)continue;if($.skip(-4),Y===o$)return!0;$.skip(1)}return!1};/*!
|
|
134
134
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
135
135
|
*
|
|
136
136
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
137
137
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
138
138
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
139
|
-
*/var H1;(function($){$[$.PCM=1]="PCM",$[$.IEEE_FLOAT=3]="IEEE_FLOAT",$[$.ALAW=6]="ALAW",$[$.MULAW=7]="MULAW",$[$.EXTENSIBLE=65534]="EXTENSIBLE"})(H1||(H1={}));class NY extends L0{constructor($){super($);this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=this.reader.requestSlice(0,12);if($ instanceof Promise)$=await $;L($);let J=J0($,4),Y=J!=="RIFX",X=J==="RF64",Q=u1($,Y),Z=X?this.reader.fileSize:Math.min(Q+8,this.reader.fileSize??1/0);if(J0($,4)!=="WAVE")throw Error("Invalid WAVE file - wrong format");let G=0,W=null,j=$.filePos;while(Z===null||j<Z){let q=this.reader.requestSlice(j,8);if(q instanceof Promise)q=await q;if(!q)break;let V=J0(q,4),_=u1(q,Y),N=q.filePos;if(X&&G===0&&V!=="ds64")throw Error('Invalid RF64 file: First chunk must be "ds64".');if(V==="fmt ")await this.parseFmtChunk(N,_,Y);else if(V==="data"){if(W??=_,this.dataStart=q.filePos,this.dataSize=Math.min(W,(Z??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(V==="ds64"){let R=this.reader.requestSlice(N,_);if(R instanceof Promise)R=await R;if(!R)break;let z=qY(R,Y);W=qY(R,Y),Z=Math.min(z+8,this.reader.fileSize??1/0)}else if(V==="LIST")await this.parseListChunk(N,_,Y);else if(V==="ID3 "||V==="id3 ")await this.parseId3Chunk(N,_);j=N+_+(_&1),G++}if(!this.audioInfo)throw Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw Error('Invalid WAVE file - missing "data" chunk');let U=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/U)*U,this.trackBackings.push(new OX(this))})()}async parseFmtChunk($,J,Y){let X=this.reader.requestSlice($,J);if(X instanceof Promise)X=await X;if(!X)return;let Q=_6(X,Y),Z=_6(X,Y),K=u1(X,Y);X.skip(4);let G=_6(X,Y),W;if(J===14)W=8;else W=_6(X,Y);if(J>=18&&Q!==357){let j=_6(X,Y),U=J-18;if(Math.min(U,j)>=22&&Q===H1.EXTENSIBLE){X.skip(6);let V=h(X,16);Q=V[0]|V[1]<<8}}if(Q===H1.MULAW||Q===H1.ALAW)W=8;this.audioInfo={format:Q,numberOfChannels:Z,sampleRate:K,sampleSizeInBytes:Math.ceil(W/8),blockSizeInBytes:G}}async parseListChunk($,J,Y){let X=this.reader.requestSlice($,J);if(X instanceof Promise)X=await X;if(!X)return;let Q=J0(X,4);if(Q!=="INFO"&&Q!=="INF0")return;let Z=X.filePos;while(Z<=$+J-8){X.filePos=Z;let K=J0(X,4),G=u1(X,Y),W=h(X,G),j=0;for(let q=0;q<W.length;q++){if(W[q]===0)break;j++}let U=String.fromCharCode(...W.subarray(0,j));switch(this.metadataTags.raw??={},this.metadataTags.raw[K]=U,K){case"INAM":case"TITL":this.metadataTags.title??=U;break;case"TIT3":this.metadataTags.description??=U;break;case"IART":this.metadataTags.artist??=U;break;case"IPRD":this.metadataTags.album??=U;break;case"IPRT":case"ITRK":case"TRCK":{let q=U.split("/"),V=Number.parseInt(q[0],10),_=q[1]&&Number.parseInt(q[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(_&&Number.isInteger(_)&&_>0)this.metadataTags.tracksTotal??=_}break;case"ICRD":case"IDIT":{let q=new Date(U);if(!Number.isNaN(q.getTime()))this.metadataTags.date??=q}break;case"YEAR":{let q=Number.parseInt(U,10);if(Number.isInteger(q)&&q>0)this.metadataTags.date??=new Date(q,0,1)}break;case"IGNR":case"GENR":this.metadataTags.genre??=U;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=U;break}Z+=8+G+(G&1)}}async parseId3Chunk($,J){let Y=this.reader.requestSlice($,J);if(Y instanceof Promise)Y=await Y;if(!Y)return;let X=G1(Y);if(X){let Q=J-d0;if(X.size=Math.min(X.size,Q),X.size>0){let Z=Y.slice($+d0,X.size);q6(Z,X,this.metadataTags)}}}getCodec(){if(L(this.audioInfo),this.audioInfo.format===H1.MULAW)return"ulaw";if(this.audioInfo.format===H1.ALAW)return"alaw";if(this.audioInfo.format===H1.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";else if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";else if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";else if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===H1.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32"}return null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}var V6=2048;class OX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return L(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let $=this.demuxer.getCodec();if(!$)return null;return L(this.demuxer.audioInfo),{codec:$,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}}getNumberOfChannels(){return L(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return L(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return L(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return L(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Z0}getDisposition(){return{...M0}}async getPacketAtIndex($,J){L($>=0),L(this.demuxer.audioInfo);let Y=$*V6*this.demuxer.audioInfo.blockSizeInBytes;if(Y>=this.demuxer.dataSize)return null;let X=Math.min(V6*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-Y);if(this.demuxer.reader.fileSize===null){let G=this.demuxer.reader.requestSlice(this.demuxer.dataStart+Y,X);if(G instanceof Promise)G=await G;if(!G)return null}let Q;if(J.metadataOnly)Q=V0;else{let G=this.demuxer.reader.requestSlice(this.demuxer.dataStart+Y,X);if(G instanceof Promise)G=await G;L(G),Q=h(G,X)}let Z=$*V6/this.demuxer.audioInfo.sampleRate,K=X/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max($,this.demuxer.lastKnownPacketIndex),new i(Q,"key",Z,K,$,X)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getPacket($,J){L(this.demuxer.audioInfo);let Y=Math.floor(Math.min($*this.demuxer.audioInfo.sampleRate/V6,(this.demuxer.dataSize-1)/(V6*this.demuxer.audioInfo.blockSizeInBytes)));if(Y<0)return null;let X=await this.getPacketAtIndex(Y,J);if(X)return X;if(Y===0)return null;L(this.demuxer.reader.fileSize===null);let Q=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,J);while(Q){let Z=await this.getNextPacket(Q,J);if(!Z)break;Q=Z}return Q}getNextPacket($,J){L(this.demuxer.audioInfo);let Y=Math.round($.timestamp*this.demuxer.audioInfo.sampleRate/V6);return this.getPacketAtIndex(Y+1,J)}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
|
|
139
|
+
*/class AY extends P0{constructor($){super($);this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,U8,g8);if(J instanceof Promise)J=await J;if(!J)break;let Y=A6(J);if(!Y)break;if(!(Y.headerType&2))break;this.bitstreams.push({serialNumber:Y.serialNumber,bosPage:Y,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),$=Y.headerStartPos+Y.totalSize}for(let J of this.bitstreams){let Y=await this.readPacket(J.bosPage,0);if(!Y)continue;if(Y.data.byteLength>=7&&Y.data[0]===1&&Y.data[1]===118&&Y.data[2]===111&&Y.data[3]===114&&Y.data[4]===98&&Y.data[5]===105&&Y.data[6]===115)await this.readVorbisMetadata(Y,J);else if(Y.data.byteLength>=8&&Y.data[0]===79&&Y.data[1]===112&&Y.data[2]===117&&Y.data[3]===115&&Y.data[4]===72&&Y.data[5]===101&&Y.data[6]===97&&Y.data[7]===100)await this.readOpusMetadata(Y,J);if(J.codecInfo.codec!==null)this.trackBackings.push(new OX(J,this))}})()}async readVorbisMetadata($,J){let Y=await this.findNextPacketStart($);if(!Y)return;let X=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!X)return;if(Y=await this.findNextPacketStart(X),!Y)return;let Q=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!Q)return;if(X.data[0]!==3||Q.data[0]!==5)return;let Z=[],K=(U)=>{while(!0){if(Z.push(Math.min(255,U)),U<255)break;U-=255}};K($.data.length),K(X.data.length);let G=new Uint8Array(1+Z.length+$.data.length+X.data.length+Q.data.length);G[0]=2,G.set(Z,1),G.set($.data,1+Z.length),G.set(X.data,1+Z.length+$.data.length),G.set(Q.data,1+Z.length+$.data.length+X.data.length),J.codecInfo.codec="vorbis",J.description=G,J.lastMetadataPacket=Q;let W=l($.data);J.numberOfChannels=W.getUint8(11),J.sampleRate=W.getUint32(12,!0);let j=W.getUint8(28);J.codecInfo.vorbisInfo={blocksizes:[1<<(j&15),1<<(j>>4)],modeBlockflags:rJ(Q.data).modeBlockflags},$$(X.data.subarray(7),this.metadataTags)}async readOpusMetadata($,J){let Y=await this.findNextPacketStart($);if(!Y)return;let X=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!X)return;J.codecInfo.codec="opus",J.description=$.data,J.lastMetadataPacket=X;let Q=e6($.data);J.numberOfChannels=Q.outputChannelCount,J.sampleRate=k1,J.codecInfo.opusInfo={preSkip:Q.preSkip},$$(X.data.subarray(8),this.metadataTags)}async readPacket($,J){F(J<$.lacingValues.length);let Y=0;for(let U=0;U<J;U++)Y+=$.lacingValues[U];let X=$,Q=Y,Z=J,K=[];$:while(!0){let U=this.reader.requestSlice(X.dataStartPos,X.dataSize);if(U instanceof Promise)U=await U;F(U);let q=f(U,X.dataSize);while(!0){if(Z===X.lacingValues.length){K.push(q.subarray(Y,Q));break}let _=X.lacingValues[Z];if(Q+=_,_<255){K.push(q.subarray(Y,Q));break $}Z++}let N=X.headerStartPos+X.totalSize;while(!0){let _=this.reader.requestSliceRange(N,U8,g8);if(_ instanceof Promise)_=await _;if(!_)return null;let V=A6(_);if(!V)return null;if(X=V,X.serialNumber===$.serialNumber)break;N=X.headerStartPos+X.totalSize}Y=0,Q=0,Z=0}let G=K.reduce((U,q)=>U+q.length,0);if(G===0)return null;let W=new Uint8Array(G),j=0;for(let U=0;U<K.length;U++){let q=K[U];W.set(q,j),j+=q.length}return{data:W,endPage:X,endSegmentIndex:Z}}async findNextPacketStart($){if($.endSegmentIndex<$.endPage.lacingValues.length-1)return{startPage:$.endPage,startSegmentIndex:$.endSegmentIndex+1};if(!!($.endPage.headerType&4))return null;let Y=$.endPage.headerStartPos+$.endPage.totalSize;while(!0){let X=this.reader.requestSliceRange(Y,U8,g8);if(X instanceof Promise)X=await X;if(!X)return null;let Q=A6(X);if(!Q)return null;if(Q.serialNumber===$.endPage.serialNumber)return{startPage:Q,startSegmentIndex:0};Y=Q.headerStartPos+Q.totalSize}}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.trackBackings.map((J)=>J.getDecoderConfig().then((Y)=>Y?.codec??null)));return zY({codecStrings:$.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class OX{constructor($,J){this.bitstream=$,this.demuxer=J,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new X1,this.internalSampleRate=$.codecInfo.codec==="opus"?k1:$.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let $=this.demuxer.trackBackings.findIndex((J)=>J.bitstream===this.bitstream);return F($!==-1),$+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return F(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return K0}getDisposition(){return{...x0,primary:!1}}granulePositionToTimestampInSamples($){if(this.bitstream.codecInfo.codec==="opus")return F(this.bitstream.codecInfo.opusInfo),$-this.bitstream.codecInfo.opusInfo.preSkip;return $}createEncodedPacketFromOggPacket($,J,Y){if(!$)return null;let{durationInSamples:X,vorbisBlockSize:Q}=HY($.data,this.bitstream.codecInfo,J.vorbisLastBlocksize),Z=new t(Y.metadataOnly?w0:$.data,"key",Math.max(0,J.timestampInSamples)/this.internalSampleRate,X/this.internalSampleRate,$.endPage.headerStartPos+$.endSegmentIndex,$.data.byteLength);return this.encodedPacketToMetadata.set(Z,{packet:$,timestampInSamples:J.timestampInSamples,durationInSamples:X,vorbisLastBlockSize:J.vorbisLastBlocksize,vorbisBlockSize:Q}),Z}async getFirstPacket($){F(this.bitstream.lastMetadataPacket);let J=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!J)return null;let Y=0;if(this.bitstream.codecInfo.codec==="opus")F(this.bitstream.codecInfo.opusInfo),Y-=this.bitstream.codecInfo.opusInfo.preSkip;let X=await this.demuxer.readPacket(J.startPage,J.startSegmentIndex);return this.createEncodedPacketFromOggPacket(X,{timestampInSamples:Y,vorbisLastBlocksize:null},$)}async getNextPacket($,J){let Y=this.encodedPacketToMetadata.get($);if(!Y)throw Error("Packet was not created from this track.");let X=await this.demuxer.findNextPacketStart(Y.packet);if(!X)return null;let Q=Y.timestampInSamples+Y.durationInSamples,Z=await this.demuxer.readPacket(X.startPage,X.startSegmentIndex);return this.createEncodedPacketFromOggPacket(Z,{timestampInSamples:Q,vorbisLastBlocksize:Y.vorbisBlockSize},J)}async getPacket($,J){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential($,J);let Y=y1($*this.internalSampleRate);if(Y===0)return this.getFirstPacket(J);if(Y<0)return null;F(this.bitstream.lastMetadataPacket);let X=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!X)return null;let Q=X.startPage,Z=this.demuxer.reader.fileSize,K=[Q];$:while(Q.headerStartPos+Q.totalSize<Z){let H=Q.headerStartPos,A=Math.floor((H+Z)/2),M=A;while(!0){let L=Math.min(M+RY,Z-U8),w=this.demuxer.reader.requestSlice(M,L-M);if(w instanceof Promise)w=await w;if(F(w),!MX(w,L)){Z=A+U8;continue $}let D=this.demuxer.reader.requestSliceRange(w.filePos,U8,g8);if(D instanceof Promise)D=await D;F(D);let B=A6(D);F(B);let C=!1;if(B.serialNumber===this.bitstream.serialNumber)C=!0;else{let P=this.demuxer.reader.requestSlice(B.headerStartPos,B.totalSize);if(P instanceof Promise)P=await P;F(P);let v=f(P,B.totalSize);C=_Y(v)===B.checksum}if(!C){M=B.headerStartPos+4;continue}if(C&&B.serialNumber!==this.bitstream.serialNumber){M=B.headerStartPos+B.totalSize;continue}if(B.granulePosition===-1){M=B.headerStartPos+B.totalSize;continue}if(this.granulePositionToTimestampInSamples(B.granulePosition)>Y)Z=B.headerStartPos;else Q=B,K.push(B);continue $}}let G=X.startPage;for(let H of K){if(H.granulePosition===Q.granulePosition)break;if(!G||H.headerStartPos>G.headerStartPos)G=H}let W=G,j=[W];while(!0){if(W.serialNumber===this.bitstream.serialNumber&&W.granulePosition===Q.granulePosition)break;let H=W.headerStartPos+W.totalSize,A=this.demuxer.reader.requestSliceRange(H,U8,g8);if(A instanceof Promise)A=await A;F(A);let M=A6(A);if(F(M),W=M,W.serialNumber===this.bitstream.serialNumber)j.push(W)}F(W.granulePosition!==-1);let U=null,q,N,_=W,V=0;if(W.headerStartPos===X.startPage.headerStartPos)q=this.granulePositionToTimestampInSamples(0),N=!0,U=0;else{q=0,N=!1;for(let M=W.lacingValues.length-1;M>=0;M--)if(W.lacingValues[M]<255){U=M+1;break}if(U===null)throw Error("Invalid page with granule position: no packets end on this page.");V=U-1;let H={data:w0,endPage:_,endSegmentIndex:V};if(await this.demuxer.findNextPacketStart(H)){let M=wX(j,W,U);F(M);let L=LX(j,M.page,M.segmentIndex);if(L)W=L.page,U=L.segmentIndex}else while(!0){let M=wX(j,W,U);if(!M)break;let L=LX(j,M.page,M.segmentIndex);if(!L)break;if(W=L.page,U=L.segmentIndex,M.page.headerStartPos!==_.headerStartPos){_=M.page,V=M.segmentIndex;break}}}let z=null,R=null;while(W!==null){F(U!==null);let H=await this.demuxer.readPacket(W,U);if(!H)break;if(!(W.headerStartPos===X.startPage.headerStartPos&&U<X.startSegmentIndex)){let L=this.createEncodedPacketFromOggPacket(H,{timestampInSamples:q,vorbisLastBlocksize:R?.vorbisBlockSize??null},J);F(L);let w=this.encodedPacketToMetadata.get(L);if(F(w),!N&&H.endPage.headerStartPos===_.headerStartPos&&H.endSegmentIndex===V)q=this.granulePositionToTimestampInSamples(W.granulePosition),N=!0,L=this.createEncodedPacketFromOggPacket(H,{timestampInSamples:q-w.durationInSamples,vorbisLastBlocksize:R?.vorbisBlockSize??null},J),F(L),w=this.encodedPacketToMetadata.get(L),F(w);else q+=w.durationInSamples;if(z=L,R=w,N&&(Math.max(q,0)>Y||Math.max(w.timestampInSamples,0)===Y))break}let M=await this.demuxer.findNextPacketStart(H);if(!M)break;W=M.startPage,U=M.startSegmentIndex}return z}async getPacketSequential($,J){let Y=await this.sequentialScanMutex.acquire();try{let X=y1($*this.internalSampleRate);$=X/this.internalSampleRate;let Q=p(this.sequentialScanCache,X,(G)=>G.timestampInSamples),Z;if(Q!==-1){let G=this.sequentialScanCache[Q];Z=this.createEncodedPacketFromOggPacket(G.packet,{timestampInSamples:G.timestampInSamples,vorbisLastBlocksize:G.vorbisLastBlockSize},J)}else Z=await this.getFirstPacket(J);let K=0;while(Z&&Z.timestamp<$){let G=await this.getNextPacket(Z,J);if(!G||G.timestamp>$)break;if(Z=G,K++,K===100){K=0;let W=this.encodedPacketToMetadata.get(Z);if(F(W),this.sequentialScanCache.length>0)F(W0(this.sequentialScanCache).timestampInSamples<=W.timestampInSamples);this.sequentialScanCache.push(W)}}return Z}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}var LX=($,J,Y)=>{let X=J,Q=Y;$:while(!0){Q--;for(Q;Q>=0;Q--)if(X.lacingValues[Q]<255){Q++;break $}if(F(Q===-1),!(X.headerType&1)){Q=0;break}let K=fJ($,(G)=>G.headerStartPos<X.headerStartPos);if(!K)return null;X=K,Q=X.lacingValues.length}if(F(Q!==-1),Q===X.lacingValues.length){let Z=$[$.indexOf(X)+1];F(Z),X=Z,Q=0}return{page:X,segmentIndex:Q}},wX=($,J,Y)=>{if(Y>0)return{page:J,segmentIndex:Y-1};let X=fJ($,(Q)=>Q.headerStartPos<J.headerStartPos);if(!X)return null;return{page:X,segmentIndex:X.lacingValues.length-1}};/*!
|
|
140
140
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
141
141
|
*
|
|
142
142
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
143
143
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
144
144
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
145
|
-
*/var
|
|
145
|
+
*/var B1;(function($){$[$.PCM=1]="PCM",$[$.IEEE_FLOAT=3]="IEEE_FLOAT",$[$.ALAW=6]="ALAW",$[$.MULAW=7]="MULAW",$[$.EXTENSIBLE=65534]="EXTENSIBLE"})(B1||(B1={}));class FY extends P0{constructor($){super($);this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=this.reader.requestSlice(0,12);if($ instanceof Promise)$=await $;F($);let J=Z0($,4),Y=J!=="RIFX",X=J==="RF64",Q=s1($,Y),Z=X?this.reader.fileSize:Math.min(Q+8,this.reader.fileSize??1/0);if(Z0($,4)!=="WAVE")throw Error("Invalid WAVE file - wrong format");let G=0,W=null,j=$.filePos;while(Z===null||j<Z){let q=this.reader.requestSlice(j,8);if(q instanceof Promise)q=await q;if(!q)break;let N=Z0(q,4),_=s1(q,Y),V=q.filePos;if(X&&G===0&&N!=="ds64")throw Error('Invalid RF64 file: First chunk must be "ds64".');if(N==="fmt ")await this.parseFmtChunk(V,_,Y);else if(N==="data"){if(W??=_,this.dataStart=q.filePos,this.dataSize=Math.min(W,(Z??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(N==="ds64"){let z=this.reader.requestSlice(V,_);if(z instanceof Promise)z=await z;if(!z)break;let R=MY(z,Y);W=MY(z,Y),Z=Math.min(R+8,this.reader.fileSize??1/0)}else if(N==="LIST")await this.parseListChunk(V,_,Y);else if(N==="ID3 "||N==="id3 ")await this.parseId3Chunk(V,_);j=V+_+(_&1),G++}if(!this.audioInfo)throw Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw Error('Invalid WAVE file - missing "data" chunk');let U=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/U)*U,this.trackBackings.push(new BX(this))})()}async parseFmtChunk($,J,Y){let X=this.reader.requestSlice($,J);if(X instanceof Promise)X=await X;if(!X)return;let Q=F6(X,Y),Z=F6(X,Y),K=s1(X,Y);X.skip(4);let G=F6(X,Y),W;if(J===14)W=8;else W=F6(X,Y);if(J>=18&&Q!==357){let j=F6(X,Y),U=J-18;if(Math.min(U,j)>=22&&Q===B1.EXTENSIBLE){X.skip(6);let N=f(X,16);Q=N[0]|N[1]<<8}}if(Q===B1.MULAW||Q===B1.ALAW)W=8;this.audioInfo={format:Q,numberOfChannels:Z,sampleRate:K,sampleSizeInBytes:Math.ceil(W/8),blockSizeInBytes:G}}async parseListChunk($,J,Y){let X=this.reader.requestSlice($,J);if(X instanceof Promise)X=await X;if(!X)return;let Q=Z0(X,4);if(Q!=="INFO"&&Q!=="INF0")return;let Z=X.filePos;while(Z<=$+J-8){X.filePos=Z;let K=Z0(X,4),G=s1(X,Y),W=f(X,G),j=0;for(let q=0;q<W.length;q++){if(W[q]===0)break;j++}let U=String.fromCharCode(...W.subarray(0,j));switch(this.metadataTags.raw??={},this.metadataTags.raw[K]=U,K){case"INAM":case"TITL":this.metadataTags.title??=U;break;case"TIT3":this.metadataTags.description??=U;break;case"IART":this.metadataTags.artist??=U;break;case"IPRD":this.metadataTags.album??=U;break;case"IPRT":case"ITRK":case"TRCK":{let q=U.split("/"),N=Number.parseInt(q[0],10),_=q[1]&&Number.parseInt(q[1],10);if(Number.isInteger(N)&&N>0)this.metadataTags.trackNumber??=N;if(_&&Number.isInteger(_)&&_>0)this.metadataTags.tracksTotal??=_}break;case"ICRD":case"IDIT":{let q=new Date(U);if(!Number.isNaN(q.getTime()))this.metadataTags.date??=q}break;case"YEAR":{let q=Number.parseInt(U,10);if(Number.isInteger(q)&&q>0)this.metadataTags.date??=new Date(q,0,1)}break;case"IGNR":case"GENR":this.metadataTags.genre??=U;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=U;break}Z+=8+G+(G&1)}}async parseId3Chunk($,J){let Y=this.reader.requestSlice($,J);if(Y instanceof Promise)Y=await Y;if(!Y)return;let X=t0(Y);if(X){let Q=J-f0;if(X.size=Math.min(X.size,Q),X.size>0){let Z=Y.slice($+f0,X.size);W8(Z,X,this.metadataTags)}}}getCodec(){if(F(this.audioInfo),this.audioInfo.format===B1.MULAW)return"ulaw";if(this.audioInfo.format===B1.ALAW)return"alaw";if(this.audioInfo.format===B1.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";else if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";else if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";else if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===B1.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32"}return null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}var M6=2048;class BX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return F(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let $=this.demuxer.getCodec();if(!$)return null;return F(this.demuxer.audioInfo),{codec:$,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}}getNumberOfChannels(){return F(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return F(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return F(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return F(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return K0}getDisposition(){return{...x0}}async getPacketAtIndex($,J){F($>=0),F(this.demuxer.audioInfo);let Y=$*M6*this.demuxer.audioInfo.blockSizeInBytes;if(Y>=this.demuxer.dataSize)return null;let X=Math.min(M6*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-Y);if(this.demuxer.reader.fileSize===null){let G=this.demuxer.reader.requestSlice(this.demuxer.dataStart+Y,X);if(G instanceof Promise)G=await G;if(!G)return null}let Q;if(J.metadataOnly)Q=w0;else{let G=this.demuxer.reader.requestSlice(this.demuxer.dataStart+Y,X);if(G instanceof Promise)G=await G;F(G),Q=f(G,X)}let Z=$*M6/this.demuxer.audioInfo.sampleRate,K=X/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max($,this.demuxer.lastKnownPacketIndex),new t(Q,"key",Z,K,$,X)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getPacket($,J){F(this.demuxer.audioInfo);let Y=Math.floor(Math.min($*this.demuxer.audioInfo.sampleRate/M6,(this.demuxer.dataSize-1)/(M6*this.demuxer.audioInfo.blockSizeInBytes)));if(Y<0)return null;let X=await this.getPacketAtIndex(Y,J);if(X)return X;if(Y===0)return null;F(this.demuxer.reader.fileSize===null);let Q=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,J);while(Q){let Z=await this.getNextPacket(Q,J);if(!Z)break;Q=Z}return Q}getNextPacket($,J){F(this.demuxer.audioInfo);let Y=Math.round($.timestamp*this.demuxer.audioInfo.sampleRate/M6);return this.getPacketAtIndex(Y+1,J)}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
|
|
146
146
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
147
147
|
*
|
|
148
148
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
149
149
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
150
150
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
151
|
-
*/var
|
|
151
|
+
*/var k8=7,z1=9,D1=($)=>{let J=$.filePos,Y=f($,9),X=new n(Y);if(X.readBits(12)!==4095)return null;if(X.skipBits(1),X.readBits(2)!==0)return null;let K=X.readBits(1),G=X.readBits(2)+1,W=X.readBits(4);if(W===15)return null;X.skipBits(1);let j=X.readBits(3);if(j===0)throw Error("ADTS frames with channel configuration 0 are not supported.");X.skipBits(1),X.skipBits(1),X.skipBits(1),X.skipBits(1);let U=X.readBits(13);X.skipBits(11);let q=X.readBits(2)+1;if(q!==1)throw Error("ADTS frames with more than one AAC frame are not supported.");let N=null;if(K===1)$.filePos-=2;else N=X.readBits(16);return{objectType:G,samplingFrequencyIndex:W,channelConfiguration:j,frameLength:U,numberOfAacFrames:q,crcCheck:N,startPos:J}};/*!
|
|
152
152
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
153
153
|
*
|
|
154
154
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
155
155
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
156
156
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
157
|
-
*/var
|
|
157
|
+
*/var G$=1024;class LY extends P0{constructor($){super($);this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new X1,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{while(!this.firstFrameHeader&&!this.lastSampleLoaded)await this.advanceReader();F(this.firstFrameHeader),this.trackBackings=[new DX(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)while(!0){let Z=this.reader.requestSlice(this.lastLoadedPos,f0);if(Z instanceof Promise)Z=await Z;if(!Z){this.lastSampleLoaded=!0;return}let K=t0(Z);if(!K)break;this.lastLoadedPos=Z.filePos+K.size}let $=this.reader.requestSliceRange(this.lastLoadedPos,k8,z1);if($ instanceof Promise)$=await $;if(!$){this.lastSampleLoaded=!0;return}let J=D1($);if(!J){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&J.startPos+J.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}if(!this.firstFrameHeader)this.firstFrameHeader=J;let Y=h1[J.samplingFrequencyIndex];F(Y!==void 0);let X=G$/Y,Q={timestamp:this.nextTimestampInSamples/Y,duration:X,dataStart:J.startPos,dataSize:J.frameLength};this.loadedSamples.push(Q),this.nextTimestampInSamples+=G$,this.lastLoadedPos=J.startPos+J.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let $=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let J=0;while(!0){let Y=this.reader.requestSlice(J,f0);if(Y instanceof Promise)Y=await Y;if(!Y)break;let X=t0(Y);if(!X)break;let Q=this.reader.requestSlice(Y.filePos,X.size);if(Q instanceof Promise)Q=await Q;if(!Q)break;W8(Q,X,this.metadataTags),J=Y.filePos+X.size}return this.metadataTags}finally{$()}}}class DX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/G$}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return K0}getCodec(){return"aac"}getInternalCodecId(){return F(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){F(this.demuxer.firstFrameHeader);let $=T8[this.demuxer.firstFrameHeader.channelConfiguration];return F($!==void 0),$}getSampleRate(){F(this.demuxer.firstFrameHeader);let $=h1[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return F($!==void 0),$}getDisposition(){return{...x0}}async getDecoderConfig(){return F(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex($,J){if($===-1)return null;let Y=this.demuxer.loadedSamples[$];if(!Y)return null;let X;if(J.metadataOnly)X=w0;else{let Q=this.demuxer.reader.requestSlice(Y.dataStart,Y.dataSize);if(Q instanceof Promise)Q=await Q;if(!Q)return null;X=f(Q,Y.dataSize)}return new t(X,"key",Y.timestamp,Y.duration,$,Y.dataSize)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getNextPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{let X=I1(this.demuxer.loadedSamples,$.timestamp,(Z)=>Z.timestamp);if(X===-1)throw Error("Packet was not created from this track.");let Q=X+1;while(Q>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(Q,J)}finally{Y()}}async getPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{while(!0){let X=p(this.demuxer.loadedSamples,$,(Q)=>Q.timestamp);if(X===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(X,J);if(X>=0&&X+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(X,J);await this.demuxer.advanceReader()}}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
|
|
158
158
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
159
159
|
*
|
|
160
160
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
161
161
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
162
162
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
163
|
-
*/
|
|
163
|
+
*/var wY=($)=>{if($===0)return null;else if($===1)return 192;else if($>=2&&$<=5)return 144*2**$;else if($===6)return"uncommon-u8";else if($===7)return"uncommon-u16";else if($>=8&&$<=15)return 2**$;else return null},CX=($,J)=>{switch($){case 0:return J;case 1:return 88200;case 2:return 176400;case 3:return 192000;case 4:return 8000;case 5:return 16000;case 6:return 22050;case 7:return 24000;case 8:return 32000;case 9:return 44100;case 10:return 48000;case 11:return 96000;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},OY=($)=>{let J=0,Y=new n(f($,1));while(Y.readBits(1)===1)J++;if(J===0)return Y.readBits(7);let X=[],Q=J-1,Z=new n(f($,Q)),K=8-J-1;for(let W=0;W<K;W++)X.unshift(Y.readBits(1));for(let W=0;W<Q;W++)for(let j=0;j<8;j++){let U=Z.readBits(1);if(j<2)continue;X.unshift(U)}return X.reduce((W,j,U)=>{return W|j<<U},0)},BY=($,J)=>{if(J==="uncommon-u16")return U0($)+1;else if(J==="uncommon-u8")return g($)+1;else if(typeof J==="number")return J;else v0(J),F(!1)},EX=($,J)=>{if(J==="uncommon-u16")return U0($);if(J==="uncommon-u16-10")return U0($)*10;if(J==="uncommon-u8")return g($);if(typeof J==="number")return J;return null},PX=($)=>{let Y=0;for(let X of $){Y^=X;for(let Q=0;Q<8;Q++){if((Y&128)!==0)Y=Y<<1^7;else Y<<=1;Y&=255}}return Y};/*!
|
|
164
164
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
165
165
|
*
|
|
166
166
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
167
167
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
168
168
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
169
|
-
*/
|
|
169
|
+
*/class DY extends P0{constructor($){super($);this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new X1,this.lastSampleLoaded=!1,this.reader=$._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),F(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSlice($,f0);if(J instanceof Promise)J=await J;if(!J){this.lastSampleLoaded=!0;return}let Y=t0(J);if(!Y)break;let X=this.reader.requestSlice(J.filePos,Y.size);if(X instanceof Promise)X=await X;F(X),W8(X,Y,this.metadataTags),$=J.filePos+Y.size}$+=4;while(this.reader.fileSize===null||$<this.reader.fileSize){let J=this.reader.requestSlice($,4);if(J instanceof Promise)J=await J;if($+=4,J===null)throw Error(`Metadata block at position ${$} is too small! Corrupted file.`);F(J);let Y=g(J),X=V1(J),Q=(Y&128)!==0;switch(Y&127){case O1.STREAMINFO:{let K=this.reader.requestSlice($,X);if(K instanceof Promise)K=await K;if(F(K),K===null)throw Error(`StreamInfo block at position ${$} is too small! Corrupted file.`);let G=f(K,34),W=new n(G),j=W.readBits(16),U=W.readBits(16),q=W.readBits(24),N=W.readBits(24),_=W.readBits(20),V=W.readBits(3)+1;W.readBits(5);let z=W.readBits(36);W.skipBits(128);let R=new Uint8Array(42);R.set(new Uint8Array([102,76,97,67]),0),R.set(new Uint8Array([128,0,0,34]),4),R.set(G,8),this.audioInfo={numberOfChannels:V,sampleRate:_,totalSamples:z,minimumBlockSize:j,maximumBlockSize:U,minimumFrameSize:q,maximumFrameSize:N,description:R},this.trackBacking=new bX(this);break}case O1.VORBIS_COMMENT:{let K=this.reader.requestSlice($,X);if(K instanceof Promise)K=await K;F(K),$$(f(K,X),this.metadataTags);break}case O1.PICTURE:{let K=this.reader.requestSlice($,X);if(K instanceof Promise)K=await K;F(K);let G=y(K),W=y(K),j=A0.decode(f(K,W)),U=y(K),q=A0.decode(f(K,U));K.skip(16);let N=y(K),_=f(K,N);this.metadataTags.images??=[],this.metadataTags.images.push({data:_,mimeType:j,kind:G===3?"coverFront":G===4?"coverBack":"unknown",description:q});break}default:break}if($+=X,Q){this.lastLoadedPos=$;break}}if(!this.audioInfo)throw Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:$,isFirstPacket:J}){F(this.audioInfo);let Y=6,X=16,Q=10,Z=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+X+2,K=this.audioInfo.minimumFrameSize||Q,W=(this.audioInfo.maximumFrameSize||Z)+X,j=await this.reader.requestSliceRange($,X,W);if(!j)return null;let U=this.readFlacFrameHeader({slice:j,isFirstPacket:J});if(!U)return null;j.filePos=$+K;while(!0){if(j.filePos>j.end-Y)return{num:U.num,blockSize:U.blockSize,sampleRate:U.sampleRate,size:j.end-$,isLastFrame:!0};if(g(j)===255){let N=j.filePos,_=g(j),V=this.blockingBit===1?249:248;if(_!==V){j.filePos=N;continue}j.skip(-2);let z=j.filePos-$,R=this.readFlacFrameHeader({slice:j,isFirstPacket:!1});if(!R){j.filePos=N;continue}if(this.blockingBit===0){if(R.num-U.num!==1){j.filePos=N;continue}}else if(R.num-U.num!==U.blockSize){j.filePos=N;continue}return{num:U.num,blockSize:U.blockSize,sampleRate:U.sampleRate,size:z,isLastFrame:!1}}}}readFlacFrameHeader({slice:$,isFirstPacket:J}){let Y=$.filePos,X=f($,4),Q=new n(X);if(Q.readBits(15)!==32764)return null;if(this.blockingBit===null){F(J);let z=Q.readBits(1);this.blockingBit=z}else if(this.blockingBit===1){if(F(!J),Q.readBits(1)!==1)return null}else if(this.blockingBit===0){if(F(!J),Q.readBits(1)!==0)return null}else throw Error("Invalid blocking bit");let K=wY(Q.readBits(4));if(!K)return null;F(this.audioInfo);let G=CX(Q.readBits(4),this.audioInfo.sampleRate);if(!G)return null;if(Q.readBits(4),Q.readBits(3),Q.readBits(1)!==0)return null;let j=OY($),U=BY($,K),q=EX($,G);if(q===null)return null;if(q!==this.audioInfo.sampleRate)return null;let N=$.filePos-Y,_=g($);$.skip(-N),$.skip(-1);let V=PX(f($,N));if(_!==V)return null;return{num:j,blockSize:U,sampleRate:q}}async advanceReader(){await this.readMetadata(),F(this.lastLoadedPos!==null),F(this.audioInfo);let $=this.lastLoadedPos,J=await this.readNextFlacFrame({startPos:$,isFirstPacket:this.loadedSamples.length===0});if(!J){this.lastSampleLoaded=!0;return}let Y=this.loadedSamples[this.loadedSamples.length-1],Q={blockOffset:Y?Y.blockOffset+Y.blockSize:0,blockSize:J.blockSize,byteOffset:$,byteSize:J.size};if(this.lastLoadedPos=this.lastLoadedPos+J.size,this.loadedSamples.push(Q),J.isLastFrame){this.lastSampleLoaded=!0;return}}}class bX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return F(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return F(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return K0}getTimeResolution(){return F(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){if(F(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0)return null;return this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...x0}}async getDecoderConfig(){return F(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket($,J){if(F(this.demuxer.audioInfo),$<0)return null;let Y=await this.demuxer.readingMutex.acquire();try{while(!0){let X=p(this.demuxer.loadedSamples,$,(G)=>G.blockOffset/this.demuxer.audioInfo.sampleRate);if(X===-1){await this.demuxer.advanceReader();continue}let Q=this.demuxer.loadedSamples[X],Z=Q.blockOffset/this.demuxer.audioInfo.sampleRate,K=Q.blockSize/this.demuxer.audioInfo.sampleRate;if(Z+K<=$){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,J);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(X,J)}}finally{Y()}}async getNextPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{let X=$.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&X>=this.demuxer.loadedSamples.length)return null;while(X>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(X,J)}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}async getPacketAtIndex($,J){let Y=this.demuxer.loadedSamples[$];if(!Y)return null;let X;if(J.metadataOnly)X=w0;else{let K=this.demuxer.reader.requestSlice(Y.byteOffset,Y.byteSize);if(K instanceof Promise)K=await K;if(!K)return null;X=f(K,Y.byteSize)}F(this.demuxer.audioInfo);let Q=Y.blockOffset/this.demuxer.audioInfo.sampleRate,Z=Y.blockSize/this.demuxer.audioInfo.sampleRate;return new t(X,"key",Q,Z,$,Y.byteSize)}async getFirstPacket($){while(this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,$)}}/*!
|
|
170
170
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
171
171
|
*
|
|
172
172
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
173
173
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
174
174
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
175
|
-
*/var TX="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",bX=new Set;class MY extends L0{constructor($){super($);this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=I0+16+1,J=this.reader.requestSlice(0,$);if(J instanceof Promise)J=await J;L(J);let Y=h(J,$);if(Y[0]===71&&Y[I0]===71)this.packetOffset=0,this.packetStride=I0;else if(Y[0]===71&&Y[I0+16]===71)this.packetOffset=0,this.packetStride=I0+16;else if(Y[4]===71&&Y[4+I0+4]===71)this.packetOffset=4,this.packetStride=I0+4;else throw Error("Unreachable.");let X=256;this.minReferencePointByteDistance=X*this.packetStride;let Q=this.packetOffset,Z=null,K=!1,G=!1;while(!0){let W=await this.readPacketHeader(Q);if(!W)break;if(W.payloadUnitStartIndicator===0){Q+=this.packetStride;continue}let j=await this.readSection(Q,!0,!G);if(!j)break;let U=3,q=32,V=!1;if(!G&&j.pid!==0){if(!(j.payload[0]===0&&j.payload[1]===0&&j.payload[2]===1)){let R=new c(j.payload),z=R.readAlignedByte();R.skipBits(8*z),V=R.readBits(8)===2}}if(j.pid===0&&!K){let N=new c(j.payload),R=N.readAlignedByte();N.skipBits(8*R),N.skipBits(14);let z=N.readBits(10);N.skipBits(40);while(8*(z+U)-N.pos>q){let H=N.readBits(16);N.skipBits(3);let A=N.readBits(13);if(H!==0)if(Z!==null)throw Error("Only files with a single program are supported.");else Z=A}if(Z===null)throw Error("Program Association Table must link to a Program Map Table.");K=!0}else if((j.pid===Z||V)&&!G){let N=new c(j.payload),R=N.readAlignedByte();N.skipBits(8*R),N.skipBits(12);let z=N.readBits(12);N.skipBits(43);let H=N.readBits(13);N.skipBits(6);let A=N.readBits(10);N.skipBits(8*A);while(8*(z+U)-N.pos>q){let M=N.readBits(8);N.skipBits(3);let F=N.readBits(13);N.skipBits(6);let O=N.readBits(10),B=N.pos+8*O,D=!1,w=!1;while(N.pos<B){let T=N.readBits(8),C=N.readBits(8);if(T===106)D=!0;else if(T===122||T===204)w=!0;N.skipBits(8*C)}let P=null;switch(M){case 27:case 36:P={type:"video",codec:M===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let T;if(M===3||M===4)T="mp3";else if(M===15)T="aac";else if(M===129)T="ac3";else if(M===135)T="eac3";else throw Error("Unreachable.");P={type:"audio",codec:T,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:if(w)P={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};else if(D)P={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;default:if(!bX.has(M))console.warn(`Note: MPEG-TS streams with stream_type 0x${M.toString(16)} are not currently supported.`),bX.add(M)}if(P)this.elementaryStreams.push({demuxer:this,pid:F,streamType:M,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:P,referencePesPackets:[]})}G=!0}else{let N=this.elementaryStreams.find((R)=>R.pid===j.pid);$:if(N&&!N.initialized){let R=H6(j,!0);if(!R)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${N.pid}`);if(N.firstSection=j,N.canBeTrustedWithKeyPackets=j.randomAccessIndicator===1,this.input._initInput){let A=(await this.input._initInput._getDemuxer()).elementaryStreams.find((M)=>M.pid===j.pid&&M.info.codec===N.info.codec);if(A){N.info=A.info,N.initialized=!0;break $}}let z=new z6(N,R);if(N.info.type==="video"){while(!0){let H=z;if(H.suppliedPacket=null,await z.markNextPacket(),N.info.codec==="avc"){if(!z.suppliedPacket)throw Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(N.info.avcCodecInfo=p6(z.suppliedPacket.data),!N.info.avcCodecInfo)continue;let A=N.info.avcCodecInfo.sequenceParameterSets[0];L(A);let M=d6(A);N.info.width=M.displayWidth,N.info.height=M.displayHeight;let F=M.pixelAspectRatio.num,O=M.pixelAspectRatio.den;if(F>0&&O>0)if(F>O)N.info.squarePixelWidth=Math.round(N.info.width*F/O),N.info.squarePixelHeight=N.info.height;else N.info.squarePixelWidth=N.info.width,N.info.squarePixelHeight=Math.round(N.info.height*O/F);N.info.colorSpace={primaries:_8[M.colourPrimaries],transfer:z8[M.transferCharacteristics],matrix:A8[M.matrixCoefficients],fullRange:!!M.fullRangeFlag},N.info.reorderSize=M.maxDecFrameBuffering;break}else if(N.info.codec==="hevc"){if(!z.suppliedPacket)throw Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(N.info.hevcCodecInfo=c6(z.suppliedPacket.data),!N.info.hevcCodecInfo)continue;let M=N.info.hevcCodecInfo.arrays.find((O)=>O.nalUnitType===z0.SPS_NUT).nalUnits[0];L(M);let F=uJ(M);if(N.info.width=F.displayWidth,N.info.height=F.displayHeight,F.pixelAspectRatio.num>F.pixelAspectRatio.den)N.info.squarePixelWidth=Math.round(N.info.width*F.pixelAspectRatio.num/F.pixelAspectRatio.den),N.info.squarePixelHeight=N.info.height;else N.info.squarePixelWidth=N.info.width,N.info.squarePixelHeight=Math.round(N.info.height*F.pixelAspectRatio.den/F.pixelAspectRatio.num);N.info.colorSpace={primaries:_8[F.colourPrimaries],transfer:z8[F.transferCharacteristics],matrix:A8[F.matrixCoefficients],fullRange:!!F.fullRangeFlag},N.info.reorderSize=F.maxDecFrameBuffering;break}else throw Error("Unhandled.")}if(N.info.decoderConfig={codec:i8({width:N.info.width,height:N.info.height,codec:N.info.codec,codecDescription:null,colorSpace:N.info.colorSpace,avcType:1,avcCodecInfo:N.info.avcCodecInfo,hevcCodecInfo:N.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:N.info.width,codedHeight:N.info.height,colorSpace:N.info.colorSpace},N.info.width!==N.info.squarePixelWidth||N.info.height!==N.info.squarePixelHeight)N.info.decoderConfig.displayAspectWidth=N.info.squarePixelWidth,N.info.decoderConfig.displayAspectHeight=N.info.squarePixelHeight;N.initialized=!0}else{if(await z.markNextPacket(),!z.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${N.pid}`);if(N.info.codec==="aac"){let H=x0.tempFromBytes(z.suppliedPacket.data),A=z1(H);if(!A)throw Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");N.info.aacCodecInfo={isMpeg2:!1,objectType:A.objectType},N.info.numberOfChannels=D8[A.channelConfiguration],N.info.sampleRate=b1[A.samplingFrequencyIndex]}else if(N.info.codec==="mp3"){let H=I(x0.tempFromBytes(z.suppliedPacket.data)),A=J6(H,z.suppliedPacket.data.byteLength);if(!A.header)throw Error("Invalid MP3 audio stream; could not read frame header from first packet.");N.info.numberOfChannels=t1(A.header.channel),N.info.sampleRate=A.header.sampleRate}else if(N.info.codec==="ac3"){let H=lJ(z.suppliedPacket.data);if(!H)throw Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(H.fscod===3)throw Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");N.info.numberOfChannels=s6[H.acmod]+H.lfeon,N.info.sampleRate=P8[H.fscod]}else if(N.info.codec==="eac3"){let H=dJ(z.suppliedPacket.data);if(!H)throw Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let A=b$(H);if(A===null)throw Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");N.info.numberOfChannels=T$(H),N.info.sampleRate=A}else throw Error("Unhandled.");N.info.decoderConfig={codec:a8({codec:N.info.codec,codecDescription:null,aacCodecInfo:N.info.aacCodecInfo}),numberOfChannels:N.info.numberOfChannels,sampleRate:N.info.sampleRate},N.initialized=!0}}}if(G&&this.elementaryStreams.every((N)=>N.initialized))break;Q+=this.packetStride}if(!G){if(!K)throw Error("No Program Association Table found in the file.");throw Error("No Program Map Table found in the file.")}for(let W of this.elementaryStreams)if(W.info.type==="video")this.trackBackingEntries.push(new vX(W));else this.trackBackingEntries.push(new xX(W))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.trackBackingEntries.map((J)=>J.getDecoderConfig().then((Y)=>Y?.codec??null)));return AY($)}async readSection($,J,Y=!1){let X=$,Q=$,Z=[],K=0,G=null,W=!0,j=0;while(!0){let q=await this.readPacket(Q);if(Q+=this.packetStride,!q)break;if(!G){if(q.payloadUnitStartIndicator===0)break;G=q}else{if(q.pid!==G.pid)if(Y)break;else continue;if(q.payloadUnitStartIndicator===1)break}let V=!!(q.adaptationFieldControl&2),_=!!(q.adaptationFieldControl&1),N=0;if(V){if(N=1+q.body[0],q===G&&N>1)j=q.body[1]>>6&1}if(_)if(N===0)Z.push(q.body),K+=q.body.byteLength;else Z.push(q.body.subarray(N)),K+=q.body.byteLength-N;if(X=Q,!J&&K>=64){W=!1;break}if(C1(this.sectionEndPositions,X,(z)=>z)!==-1){W=!1;break}}if(W){let q=p(this.sectionEndPositions,X,(V)=>V);this.sectionEndPositions.splice(q+1,0,X)}if(!G)return null;let U;if(Z.length===1)U=Z[0];else{let q=Z.reduce((_,N)=>_+N.length,0);U=new Uint8Array(q);let V=0;for(let _ of Z)U.set(_,V),V+=_.length}return{startPos:$,endPos:J?X:null,pid:G.pid,payload:U,randomAccessIndicator:j}}async readPacketHeader($){let J=this.reader.requestSlice($,4);if(J instanceof Promise)J=await J;if(!J)return null;if(g(J)!==71)throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let X=G0(J),Q=X>>15,Z=X>>14&1,K=X>>13&1,G=X&8191,W=g(J),j=W>>6,U=W>>4&3,q=W&15;return{payloadUnitStartIndicator:Z,pid:G,adaptationFieldControl:U}}async readPacket($){let J=this.reader.requestSlice($,I0);if(J instanceof Promise)J=await J;if(!J)return null;let Y=h(J,I0);if(Y[0]!==71)throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let Q=(Y[1]<<8)+Y[2],Z=Q>>15,K=Q>>14&1,G=Q>>13&1,W=Q&8191,j=Y[3],U=j>>6,q=j>>4&3,V=j&15;return{payloadUnitStartIndicator:K,pid:W,adaptationFieldControl:q,body:Y.subarray(4)}}}var S8=($,J)=>{if($.payload.byteLength<3)return null;let Y=new c($.payload);if(Y.readBits(24)!==1)return null;let Q=Y.readBits(8);if(Y.skipBits(16),Q===188||Q===190||Q===191||Q===240||Q===241||Q===255||Q===242||Q===248)return null;Y.skipBits(8);let Z=Y.readBits(2);Y.skipBits(14);let K=null;if(Z===2||Z===3)K=0,Y.skipBits(4),K+=Y.readBits(3)*1073741824,Y.skipBits(1),K+=Y.readBits(15)*32768,Y.skipBits(1),K+=Y.readBits(15);else if(J)throw Error(TX);return{sectionStartPos:$.startPos,sectionEndPos:$.endPos,pts:K,randomAccessIndicator:$.randomAccessIndicator}},H6=($,J)=>{L($.endPos!==null);let Y=S8($,J);if(!Y)return null;let X=new c($.payload);X.skipBits(32);let Q=X.readBits(16),Z=6;X.skipBits(16);let K=X.readBits(8),G=X.pos+8*K;X.pos=G;let W=G/8;L(Number.isInteger(W));let j=$.payload.subarray(W,Q>0?Z+Q:$.payload.byteLength);return{...Y,data:j}};class d${constructor($){this.elementaryStream=$,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let $=this.elementaryStream.demuxer,J=this.elementaryStream.info.type,Y=0;for(let X of $.trackBackingEntries){if(X.getType()===J)Y++;if(L(X instanceof d$),X.elementaryStream===this.elementaryStream)break}return Y}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return Z0}getDisposition(){return{...M0,primary:!1}}getTimeResolution(){return W1}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket($,J,Y){let X;if(this.allPacketsAreKeyPackets())X="key";else X=$.randomAccessIndicator===1?"key":"delta";return new i(Y.metadataOnly?V0:$.data,X,$.pts/W1,Math.max(J/W1,0),$.sequenceNumber,$.data.byteLength)}async getFirstPacket($){let J=this.elementaryStream.firstSection;L(J);let Y=H6(J,!0);L(Y);let X=new z6(this.elementaryStream,Y),Q=new p$(this,X),Z=await Q.readNext();if(!Z)return null;let K=this.createEncodedPacket(Z.packet,Z.duration,$);return this.packetBuffers.set(K,Q),this.packetSectionStarts.set(K,Z.packet.sectionStartPos),K}async getNextPacket($,J){let Y=this.packetBuffers.get($);if(Y){let j=await Y.readNext();if(!j)return null;this.packetBuffers.delete($);let U=this.createEncodedPacket(j.packet,j.duration,J);return this.packetBuffers.set(U,Y),this.packetSectionStarts.set(U,j.packet.sectionStartPos),U}let X=this.packetSectionStarts.get($);if(X===void 0)throw Error("Packet was not created from this track.");let Z=await this.elementaryStream.demuxer.readSection(X,!0);L(Z);let K=H6(Z,!0);L(K);let G=new z6(this.elementaryStream,K);Y=new p$(this,G);let W=$.sequenceNumber;while(!0){let j=await Y.readNext();if(!j)return null;if(j.packet.sequenceNumber>W){let U=this.createEncodedPacket(j.packet,j.duration,J);return this.packetBuffers.set(U,Y),this.packetSectionStarts.set(U,j.packet.sectionStartPos),U}}}async getNextKeyPacket($,J){let Y=$;while(!0){if(Y=await this.getNextPacket(Y,J),!Y)return null;if(Y.type==="key")return Y}}getPacket($,J){return this.doPacketLookup($,!1,J)}getKeyPacket($,J){return this.doPacketLookup($,!0,J)}async doPacketLookup($,J,Y){let X=E1($*W1),Q=this.elementaryStream.demuxer,{reader:Z,seekChunkSize:K}=Q,G=this.elementaryStream.pid,W=async(M,F,O)=>{let B=M;while(B<F){let D=await Q.readPacketHeader(B);if(!D)return null;if(D.pid===G&&D.payloadUnitStartIndicator===1){let w=await Q.readSection(B,O);if(!w)return null;let P=S8(w,!1);if(P&&P.pts!==null)return{pesPacketHeader:P,section:w}}B+=Q.packetStride}return null},j=this.elementaryStream.firstSection;L(j);let U=S8(j,!0);if(L(U),X<U.pts)return null;let q,V=this.elementaryStream.referencePesPackets,_=p(V,X,(M)=>M.pts),N=_!==-1?V[_]:null;if(N&&X-N.pts<W1/2)q=N.sectionStartPos;else{let M=0;if(Z.fileSize!==null){let F=Math.ceil(Z.fileSize/K);if(F>1){let O=0,B=F-1;M=O;while(O<=B){let D=Math.floor((O+B)/2),w=F$(D*K,Q.packetStride)+U.sectionStartPos,P=w+K,T=await W(w,P,!1);if(!T){B=D-1;continue}if(T.pesPacketHeader.pts<=X)M=D,O=D+1;else B=D-1}}}q=F$(M*K,Q.packetStride)+U.sectionStartPos}let z=(await W(q,Z.fileSize??1/0,!1))?.pesPacketHeader??null;if(!z)z=U;let H=this.getReorderSize(),A=async(M,F)=>{let O=await Q.readSection(M,!0);L(O);let B=H6(O,!0);L(B);let D=new z6(this.elementaryStream,B),w=new p$(this,D);while(!0){if((K0(w.presentationOrderPackets)?.pts??-1/0)>=X)break;if(!await w.readNextPacket())break}let P=L8(w.presentationOrderPackets,F);if(P===-1)return null;let T=w.presentationOrderPackets[P],C=P===0?0:T.pts-w.presentationOrderPackets[P-1].pts;while(w.decodeOrderPackets[0]!==T)w.decodeOrderPackets.shift();w.lastDuration=C;let E=await w.readNext();L(E);let v=this.createEncodedPacket(E.packet,E.duration,Y);return this.packetBuffers.set(v,w),this.packetSectionStarts.set(v,E.packet.sectionStartPos),v};if(!J||this.allPacketsAreKeyPackets()){$:while(!0){let M=z.sectionStartPos+Q.packetStride;while(!0){let F=await Q.readPacketHeader(M);if(!F)break $;if(F.pid===G&&F.payloadUnitStartIndicator===1){let O=await Q.readSection(M,!1);if(O){let B=S8(O,!1);if(B&&B.pts!==null){if(B.pts>X)break $;z=B,LY(this.elementaryStream,z);break}}}M+=Q.packetStride}}$:for(let M=0;M<H+1;M++){let F=z.sectionStartPos-Q.packetStride;while(F>=Q.packetOffset){let O=await Q.readPacketHeader(F);if(!O)break $;if(O.pid===G&&O.payloadUnitStartIndicator===1){let B=await Q.readSection(F,!1);if(B){let D=S8(B,!1);if(D&&D.pts!==null){z=D;break}}}F-=Q.packetStride}}return A(z.sectionStartPos,(M)=>M.pts<=X)}else{let M=q,F=null,O=!this.elementaryStream.canBeTrustedWithKeyPackets;while(!0){let B=null,D=M<=U.sectionStartPos,w,P=null;if(D)w=U,P=j;else{let E=await W(M,Z.fileSize??1/0,O);w=E?.pesPacketHeader??null,P=E?.section??null}let T=!1,C=0;$:while(w){if(F!==null&&w.sectionStartPos>=F)break;if(w.pts<=X){let v;if(this.elementaryStream.canBeTrustedWithKeyPackets)v=w.randomAccessIndicator===1;else{L(P);let x=H6(P,!0);L(x);let S=new z6(this.elementaryStream,x);await S.markNextPacket(),v=S.suppliedPacket?.randomAccessIndicator===1}if(v)B=w}if(w.pts>X)T=!0;if(T){if(C++,C>H)break}let E=w.sectionStartPos+Q.packetStride;while(!0){let v=await Q.readPacketHeader(E);if(!v)break $;if(v.pid===G&&v.payloadUnitStartIndicator===1){let x=await Q.readSection(E,O);if(x){let S=S8(x,!1);if(S&&S.pts!==null){w=S,P=x,LY(this.elementaryStream,w);break}}}E+=Q.packetStride}}if(B){let E=B;if(C===0)$:for(let x=0;x<H;x++){let S=E.sectionStartPos-Q.packetStride;while(S>=Q.packetOffset){let k=await Q.readPacketHeader(S);if(!k)break $;if(k.pid===G&&k.payloadUnitStartIndicator===1){let m=await Q.readSection(S,O);if(m){let f=S8(m,!1);if(f&&f.pts!==null){E=f;break}}}S-=Q.packetStride}}let v=await A(E.sectionStartPos,(x)=>x.pts<=X&&x.randomAccessIndicator===1);return L(v),v}if(D)return null;F=M,M=Math.max(F$(M-U.sectionStartPos-K,Q.packetStride)+U.sectionStartPos,U.sectionStartPos)}}}}class vX extends d${getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return L(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class xX extends d${getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return L(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}var LY=($,J)=>{let Y=$.referencePesPackets,X=p(Y,J.sectionStartPos,(Q)=>Q.sectionStartPos);if(X>=0){let Q=Y[X];if(J.pts<=Q.pts)return!1;let Z=$.demuxer.minReferencePointByteDistance;if(J.sectionStartPos-Q.sectionStartPos<Z)return!1;if(X<Y.length-1){let K=Y[X+1];if(K.pts<J.pts)return!1;if(K.sectionStartPos-J.sectionStartPos<Z)return!1}}return Y.splice(X+1,0,J),!0};class z6{constructor($,J){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=$,this.pid=$.pid,this.demuxer=$.demuxer,this.startingPesPacket=J}ensureBuffered($){let J=this.endPos-this.currentPos;if(J>=$)return $;return this.bufferData($-J).then(()=>Math.min(this.endPos-this.currentPos,$))}getCurrentPesPacket(){let $=this.pesPackets[this.currentPesPacketIndex];return L($),$}async bufferData($){let J=this.endPos+$;while(this.endPos<J){let Y;if(this.pesPackets.length===0)Y=this.startingPesPacket;else{let X=K0(this.pesPackets).sectionEndPos;L(X!==null);while(!0){let Q=await this.demuxer.readPacketHeader(X);if(!Q)return;if(Q.pid===this.pid){let Z=await this.demuxer.readSection(X,!0);if(!Z)return;let K=H6(Z,!1);if(K){Y=K;break}}X+=this.demuxer.packetStride}}this.pesPackets.push(Y),this.endPos+=Y.data.byteLength}}readBytes($){let J=this.getCurrentPesPacket(),Y=this.currentPos-this.currentPesPacketPos,X=Y+$;if(this.currentPos+=$,X<=J.data.byteLength)return J.data.subarray(Y,X);let Q=new Uint8Array($);Q.set(J.data.subarray(Y));let Z=J.data.byteLength-Y;while(!0){this.advanceCurrentPacket();let K=this.getCurrentPesPacket(),G=$-Z;if(G<=K.data.byteLength){Q.set(K.data.subarray(0,G),Z);break}Q.set(K.data,Z),Z+=K.data.byteLength}return Q}readU8(){let $=this.getCurrentPesPacket(),J=this.currentPos-this.currentPesPacketPos;if(this.currentPos++,J<$.data.byteLength)return $.data[J];return this.advanceCurrentPacket(),$=this.getCurrentPesPacket(),$.data[0]}seekTo($){if($===this.currentPos)return;if($<this.currentPos)while($<this.currentPesPacketPos){this.currentPesPacketIndex--;let J=this.getCurrentPesPacket();this.currentPesPacketPos-=J.data.byteLength}else while(!0){let J=this.getCurrentPesPacket(),Y=this.currentPesPacketPos+J.data.byteLength;if($<Y)break;this.currentPesPacketPos+=J.data.byteLength,this.currentPesPacketIndex++}this.currentPos=$}skip($){this.seekTo(this.currentPos+$)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){L(!this.suppliedPacket);let $=this.elementaryStream;if($.info.type==="video"){let J=$.info.codec,Y=1024;if(J!=="avc"&&J!=="hevc")throw Error("Unhandled.");let X=null;while(!0){let Q=this.ensureBuffered(1024);if(Q instanceof Promise)Q=await Q;if(Q===0)break;let Z=this.currentPos,K=this.readBytes(Q),G=K.byteLength,W=0;while(W<G){let j=K.indexOf(0,W);if(j===-1||j>=G)break;W=j;let U=Z+W;if(W+4>=G){this.seekTo(U);break}let q=K[W+1],V=K[W+2],_=K[W+3],N=0,R=null;if(q===0&&V===0&&_===1)N=4,R=K[W+4];else if(q===0&&V===1)N=3,R=_;if(N===0){W++;continue}let z=U;if(X===null){X=z,W+=N;continue}if(R!==null){let H=J==="avc"?b8(R):y1(R);if(J==="avc"?H===S0.AUD:H===z0.AUD_NUT){let M=z-X;return this.seekTo(X),this.supplyPacket(M,0)}}W+=N}if(Q<1024)break}if(X!==null){let Q=this.endPos-X;return this.seekTo(X),this.supplyPacket(Q,0)}}else{let J=$.info.codec,Y=128;while(!0){let X=this.ensureBuffered(128);if(X instanceof Promise)X=await X;let Q=this.currentPos;while(this.currentPos-Q<X){let Z=this.readU8();if(J==="aac"){if(Z!==255)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(U1);if(G instanceof Promise)G=await G;if(G<U1)return;let W=this.readBytes(U1),j=z1(x0.tempFromBytes(W));if(j){this.seekTo(K);let U=this.ensureBuffered(j.frameLength);if(U instanceof Promise)U=await U;return this.supplyPacket(U,Math.round($$*W1/$.info.sampleRate))}else this.seekTo(K+1)}else if(J==="mp3"){if(Z!==255)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(V1);if(G instanceof Promise)G=await G;if(G<V1)return;let W=this.readBytes(V1),j=u(W).getUint32(0),U=J6(j,null);if(U.header){this.seekTo(K);let q=this.ensureBuffered(U.header.totalSize);if(q instanceof Promise)q=await q;let V=U.header.audioSamplesInFrame*W1/$.info.sampleRate;return this.supplyPacket(q,Math.round(V))}else this.seekTo(K+1)}else if(J==="ac3"){if(Z!==11)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(5);if(G instanceof Promise)G=await G;if(G<5)return;let W=this.readBytes(5);if(W[0]!==11||W[1]!==119){this.seekTo(K+1);continue}let j=W[4]>>6,U=W[4]&63;if(j===3||U>37){this.seekTo(K+1);continue}let q=a7[3*U+j];if(L(q!==void 0),this.seekTo(K),G=this.ensureBuffered(q),G instanceof Promise)G=await G;let V=Math.round(t7*W1/$.info.sampleRate);return this.supplyPacket(G,V)}else if(J==="eac3"){if(Z!==11)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(5);if(G instanceof Promise)G=await G;if(G<5)return;let W=this.readBytes(5);if(W[0]!==11||W[1]!==119){this.seekTo(K+1);continue}let U=(((W[2]&7)<<8|W[3])+1)*2,V=W[4]>>6===3?3:W[4]>>4&3,_=pJ[V];if(this.seekTo(K),G=this.ensureBuffered(U),G instanceof Promise)G=await G;let N=_*256,R=Math.round(N*W1/$.info.sampleRate);return this.supplyPacket(G,R)}else throw Error("Unhandled.")}if(X<128)break}}}supplyPacket($,J){let Y=this.getCurrentPesPacket(),X;if(this.lastSuppliedPesPacket===Y)L(this.nextPts!==null),X=this.nextPts;else{if(Y.pts===null)throw Error(TX);X=Y.pts,LY(this.elementaryStream,Y)}this.lastSuppliedPesPacket=Y,this.nextPts=X+J;let Q=Y.sectionStartPos,Z=Q+(this.currentPos-this.currentPesPacketPos),K=this.readBytes($),G=Y.randomAccessIndicator;if(G===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")G=1;else if(this.elementaryStream.info.decoderConfig){let W=T8(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,K)==="key";G=Number(W)}}this.suppliedPacket={pts:X,data:K,sequenceNumber:Z,sectionStartPos:Q,randomAccessIndicator:G},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class p${constructor($,J){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=$,this.context=J,this.reorderSize=$.getReorderSize(),L(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0){if(!await this.readNextPacket())return null}await this.ensureCurrentPacketHasNext();let $=this.decodeOrderPackets[0],J=this.presentationOrderPackets.indexOf($);L(J!==-1);let Y;if(J===this.presentationOrderPackets.length-1)Y=this.lastDuration;else Y=this.presentationOrderPackets[J+1].pts-$.pts,this.lastDuration=Y;this.decodeOrderPackets.shift();while(this.presentationOrderPackets.length>0){let X=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(X))break;this.presentationOrderPackets.shift()}return{packet:$,duration:Y}}async readNextPacket(){if(this.reachedEnd)return!1;let $;if(this.context.suppliedPacket)$=this.context.suppliedPacket;else await this.context.markNextPacket(),$=this.context.suppliedPacket;if(this.context.suppliedPacket=null,!$)return this.reachedEnd=!0,this.flushReorderBuffer(),!1;return this.decodeOrderPackets.push($),this.processPacketThroughReorderBuffer($),!0}async ensureCurrentPacketHasNext(){let $=this.decodeOrderPackets[0];L($);while(!0){let J=this.presentationOrderPackets.indexOf($);if(J!==-1&&J<=this.presentationOrderPackets.length-2)break;if(!await this.readNextPacket())break}}processPacketThroughReorderBuffer($){if(this.reorderBuffer.push($),this.reorderBuffer.length>this.reorderSize){let J=0;for(let X=1;X<this.reorderBuffer.length;X++)if(this.reorderBuffer[X].pts<this.reorderBuffer[J].pts)J=X;let Y=this.reorderBuffer[J];this.presentationOrderPackets.push(Y),this.reorderBuffer.splice(J,1)}}flushReorderBuffer(){this.reorderBuffer.sort(($,J)=>$.pts-J.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}/*!
|
|
175
|
+
*/var R1=90000,m0=188,CY=($)=>{let J="video/MP2T",Y=[...new Set($.filter(Boolean))];if(Y.length>0)J+=`; codecs="${Y.join(", ")}"`;return J};/*!
|
|
176
176
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
177
177
|
*
|
|
178
178
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
179
179
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
180
180
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
181
|
-
*/var R6="application/vnd.apple.mpegurl",FY="#EXT-X-STREAM-INF:",wY="#EXT-X-I-FRAME-STREAM-INF:",OY="#EXT-X-MEDIA:",J$="#EXTINF:",BY="#EXT-X-MAP:",DY="#EXT-X-KEY:",CY="#EXT-X-MEDIA-SEQUENCE:",EY="#EXT-X-BYTERANGE:",PY="#EXT-X-PROGRAM-DATE-TIME:",IX="#EXT-X-DISCONTINUITY",bY="#EXT-X-TARGETDURATION:",yX="#EXT-X-ENDLIST",TY="#EXT-X-PLAYLIST-TYPE:",SX="#EXT-X-I-FRAMES-ONLY",c$=($)=>$.length===0||$.startsWith("#")&&!$.startsWith("#EXT");class X8{constructor($){this._attributes={};let J="",Y="",X=!1,Q=!1;for(let Z=0;Z<$.length;Z++){let K=$[Z];if(K==='"')Q=!Q;else if(K==="="&&!X&&!Q)X=!0;else if(K===","&&!Q){if(J)this._attributes[J.trim().toLowerCase()]=Y;J="",Y="",X=!1}else if(X)Y+=K;else J+=K}if(J)this._attributes[J.trim().toLowerCase()]=Y}get($){return this._attributes[$.toLowerCase()]??null}getAsNumber($){let J=this.get($);if(J===null)return null;let Y=Number(J);return Number.isFinite(Y)?Y:null}merge($){Object.assign(this._attributes,$._attributes)}}/*!
|
|
181
|
+
*/var vX="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",TX=new Set;class PY extends P0{constructor($){super($);this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=m0+16+1,J=this.reader.requestSlice(0,$);if(J instanceof Promise)J=await J;F(J);let Y=f(J,$);if(Y[0]===71&&Y[m0]===71)this.packetOffset=0,this.packetStride=m0;else if(Y[0]===71&&Y[m0+16]===71)this.packetOffset=0,this.packetStride=m0+16;else if(Y[4]===71&&Y[4+m0+4]===71)this.packetOffset=4,this.packetStride=m0+4;else throw Error("Unreachable.");let X=256;this.minReferencePointByteDistance=X*this.packetStride;let Q=this.packetOffset,Z=null,K=!1,G=!1;while(!0){let W=await this.readPacketHeader(Q);if(!W)break;if(W.payloadUnitStartIndicator===0){Q+=this.packetStride;continue}if(G&&!this.elementaryStreams.some((V)=>V.pid===W.pid)){Q+=this.packetStride;continue}let j=await this.readSection(Q,!0,!G);if(!j)break;let U=3,q=32,N=!1;if(!G&&j.pid!==0){if(!(j.payload[0]===0&&j.payload[1]===0&&j.payload[2]===1)){let z=new n(j.payload),R=z.readAlignedByte();z.skipBits(8*R),N=z.readBits(8)===2}}if(j.pid===0&&!K){let V=new n(j.payload),z=V.readAlignedByte();V.skipBits(8*z),V.skipBits(14);let R=V.readBits(10);V.skipBits(40);while(8*(R+U)-V.pos>q){let H=V.readBits(16);V.skipBits(3);let A=V.readBits(13);if(H!==0)if(Z!==null)throw Error("Only files with a single program are supported.");else Z=A}if(Z===null)throw Error("Program Association Table must link to a Program Map Table.");K=!0}else if((j.pid===Z||N)&&!G){let V=new n(j.payload),z=V.readAlignedByte();V.skipBits(8*z),V.skipBits(12);let R=V.readBits(12);V.skipBits(43);let H=V.readBits(13);V.skipBits(6);let A=V.readBits(10);V.skipBits(8*A);while(8*(R+U)-V.pos>q){let M=V.readBits(8);V.skipBits(3);let L=V.readBits(13);V.skipBits(6);let w=V.readBits(10),O=V.pos+8*w,D=!1,B=!1;while(V.pos<O){let E=V.readBits(8),P=V.readBits(8);if(E===106)D=!0;else if(E===122||E===204)B=!0;V.skipBits(8*P)}let C=null;switch(M){case 27:case 36:C={type:"video",codec:M===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let E;if(M===3||M===4)E="mp3";else if(M===15)E="aac";else if(M===129)E="ac3";else if(M===135)E="eac3";else throw Error("Unreachable.");C={type:"audio",codec:E,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:if(B)C={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};else if(D)C={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;default:if(!TX.has(M))k._warn(`Note: MPEG-TS streams with stream_type 0x${M.toString(16)} are not currently supported.`),TX.add(M)}if(C)this.elementaryStreams.push({demuxer:this,pid:L,streamType:M,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:C,referencePesPackets:[]})}G=!0}else{let V=this.elementaryStreams.find((z)=>z.pid===j.pid);$:if(V&&!V.initialized){let z=L6(j,!0);if(!z)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${V.pid}`);if(V.firstSection=j,V.canBeTrustedWithKeyPackets=j.randomAccessIndicator===1,this.input._initInput){let A=(await this.input._initInput._getDemuxer()).elementaryStreams.find((M)=>M.pid===j.pid&&M.info.codec===V.info.codec);if(A){V.info=A.info,V.initialized=!0;break $}}let R=new w6(V,z);if(V.info.type==="video"){while(!0){let H=R;if(H.suppliedPacket=null,await R.markNextPacket(),V.info.codec==="avc"){if(!R.suppliedPacket)throw Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(V.info.avcCodecInfo=i6(R.suppliedPacket.data),!V.info.avcCodecInfo)continue;let A=V.info.avcCodecInfo.sequenceParameterSets[0];F(A);let M=a6(A);V.info.width=M.displayWidth,V.info.height=M.displayHeight;let L=M.pixelAspectRatio.num,w=M.pixelAspectRatio.den;if(L>0&&w>0)if(L>w)V.info.squarePixelWidth=Math.round(V.info.width*L/w),V.info.squarePixelHeight=V.info.height;else V.info.squarePixelWidth=V.info.width,V.info.squarePixelHeight=Math.round(V.info.height*w/L);V.info.colorSpace={primaries:M8[M.colourPrimaries],transfer:L8[M.transferCharacteristics],matrix:O8[M.matrixCoefficients],fullRange:!!M.fullRangeFlag},V.info.reorderSize=M.maxDecFrameBuffering;break}else if(V.info.codec==="hevc"){if(!R.suppliedPacket)throw Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(V.info.hevcCodecInfo=t6(R.suppliedPacket.data),!V.info.hevcCodecInfo)continue;let M=V.info.hevcCodecInfo.arrays.find((w)=>w.nalUnitType===M0.SPS_NUT).nalUnits[0];F(M);let L=oJ(M);if(V.info.width=L.displayWidth,V.info.height=L.displayHeight,L.pixelAspectRatio.num>L.pixelAspectRatio.den)V.info.squarePixelWidth=Math.round(V.info.width*L.pixelAspectRatio.num/L.pixelAspectRatio.den),V.info.squarePixelHeight=V.info.height;else V.info.squarePixelWidth=V.info.width,V.info.squarePixelHeight=Math.round(V.info.height*L.pixelAspectRatio.den/L.pixelAspectRatio.num);V.info.colorSpace={primaries:M8[L.colourPrimaries],transfer:L8[L.transferCharacteristics],matrix:O8[L.matrixCoefficients],fullRange:!!L.fullRangeFlag},V.info.reorderSize=L.maxDecFrameBuffering;break}else throw Error("Unhandled.")}if(V.info.decoderConfig={codec:X6({width:V.info.width,height:V.info.height,codec:V.info.codec,codecDescription:null,colorSpace:V.info.colorSpace,avcType:1,avcCodecInfo:V.info.avcCodecInfo,hevcCodecInfo:V.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:V.info.width,codedHeight:V.info.height,colorSpace:V.info.colorSpace},V.info.width!==V.info.squarePixelWidth||V.info.height!==V.info.squarePixelHeight)V.info.decoderConfig.displayAspectWidth=V.info.squarePixelWidth,V.info.decoderConfig.displayAspectHeight=V.info.squarePixelHeight;V.initialized=!0}else{if(await R.markNextPacket(),!R.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${V.pid}`);if(V.info.codec==="aac"){let H=u0.tempFromBytes(R.suppliedPacket.data),A=D1(H);if(!A)throw Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");V.info.aacCodecInfo={isMpeg2:!1,objectType:A.objectType},V.info.numberOfChannels=T8[A.channelConfiguration],V.info.sampleRate=h1[A.samplingFrequencyIndex]}else if(V.info.codec==="mp3"){let H=y(u0.tempFromBytes(R.suppliedPacket.data)),A=W6(H,R.suppliedPacket.data.byteLength);if(!A.header)throw Error("Invalid MP3 audio stream; could not read frame header from first packet.");V.info.numberOfChannels=Z8(A.header.channel),V.info.sampleRate=A.header.sampleRate}else if(V.info.codec==="ac3"){let H=iJ(R.suppliedPacket.data);if(!H)throw Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(H.fscod===3)throw Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");V.info.numberOfChannels=J$[H.acmod]+H.lfeon,V.info.sampleRate=I8[H.fscod]}else if(V.info.codec==="eac3"){let H=tJ(R.suppliedPacket.data);if(!H)throw Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let A=S$(H);if(A===null)throw Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");V.info.numberOfChannels=h$(H),V.info.sampleRate=A}else throw Error("Unhandled.");V.info.decoderConfig={codec:Z6({codec:V.info.codec,codecDescription:null,aacCodecInfo:V.info.aacCodecInfo}),numberOfChannels:V.info.numberOfChannels,sampleRate:V.info.sampleRate},V.initialized=!0}}}if(G&&this.elementaryStreams.every((V)=>V.initialized))break;Q+=this.packetStride}if(!G){if(!K)throw Error("No Program Association Table found in the file.");throw Error("No Program Map Table found in the file.")}for(let W of this.elementaryStreams)if(W.info.type==="video")this.trackBackingEntries.push(new xX(W));else this.trackBackingEntries.push(new IX(W))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.trackBackingEntries.map((J)=>J.getDecoderConfig().then((Y)=>Y?.codec??null)));return CY($)}async readSection($,J,Y=!1){let X=$,Q=$,Z=[],K=0,G=null,W=!0,j=0;while(!0){let q=await this.readPacket(Q);if(Q+=this.packetStride,!q)break;if(!G){if(q.payloadUnitStartIndicator===0)break;G=q}else{if(q.pid!==G.pid)if(Y)break;else continue;if(q.payloadUnitStartIndicator===1)break}let N=!!(q.adaptationFieldControl&2),_=!!(q.adaptationFieldControl&1),V=0;if(N){if(V=1+q.body[0],q===G&&V>1)j=q.body[1]>>6&1}if(_)if(V===0)Z.push(q.body),K+=q.body.byteLength;else Z.push(q.body.subarray(V)),K+=q.body.byteLength-V;if(X=Q,!J&&K>=64){W=!1;break}if(I1(this.sectionEndPositions,X,(R)=>R)!==-1){W=!1;break}}if(W){let q=p(this.sectionEndPositions,X,(N)=>N);this.sectionEndPositions.splice(q+1,0,X)}if(!G)return null;let U;if(Z.length===1)U=Z[0];else{let q=Z.reduce((_,V)=>_+V.length,0);U=new Uint8Array(q);let N=0;for(let _ of Z)U.set(_,N),N+=_.length}return{startPos:$,endPos:J?X:null,pid:G.pid,payload:U,randomAccessIndicator:j}}async readPacketHeader($){let J=this.reader.requestSlice($,4);if(J instanceof Promise)J=await J;if(!J)return null;if(g(J)!==71)throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let X=U0(J),Q=X>>15,Z=X>>14&1,K=X>>13&1,G=X&8191,W=g(J),j=W>>6,U=W>>4&3,q=W&15;return{payloadUnitStartIndicator:Z,pid:G,adaptationFieldControl:U}}async readPacket($){let J=this.reader.requestSlice($,m0);if(J instanceof Promise)J=await J;if(!J)return null;let Y=f(J,m0);if(Y[0]!==71)throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let Q=(Y[1]<<8)+Y[2],Z=Q>>15,K=Q>>14&1,G=Q>>13&1,W=Q&8191,j=Y[3],U=j>>6,q=j>>4&3,N=j&15;return{payloadUnitStartIndicator:K,pid:W,adaptationFieldControl:q,body:Y.subarray(4)}}}var u8=($,J)=>{if($.payload.byteLength<3)return null;let Y=new n($.payload);if(Y.readBits(24)!==1)return null;let Q=Y.readBits(8);if(Y.skipBits(16),Q===188||Q===190||Q===191||Q===240||Q===241||Q===255||Q===242||Q===248)return null;Y.skipBits(8);let Z=Y.readBits(2);Y.skipBits(14);let K=null;if(Z===2||Z===3)K=0,Y.skipBits(4),K+=Y.readBits(3)*1073741824,Y.skipBits(1),K+=Y.readBits(15)*32768,Y.skipBits(1),K+=Y.readBits(15);else if(J)throw Error(vX);return{sectionStartPos:$.startPos,sectionEndPos:$.endPos,pts:K,randomAccessIndicator:$.randomAccessIndicator}},L6=($,J)=>{F($.endPos!==null);let Y=u8($,J);if(!Y)return null;let X=new n($.payload);X.skipBits(32);let Q=X.readBits(16),Z=6;X.skipBits(16);let K=X.readBits(8),G=X.pos+8*K;X.pos=G;let W=G/8;F(Number.isInteger(W));let j=$.payload.subarray(W,Q>0?Z+Q:$.payload.byteLength);return{...Y,data:j}};class i${constructor($){this.elementaryStream=$,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let $=this.elementaryStream.demuxer,J=this.elementaryStream.info.type,Y=0;for(let X of $.trackBackingEntries){if(X.getType()===J)Y++;if(F(X instanceof i$),X.elementaryStream===this.elementaryStream)break}return Y}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return K0}getDisposition(){return{...x0,primary:!1}}getTimeResolution(){return R1}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket($,J,Y){let X;if(this.allPacketsAreKeyPackets())X="key";else X=$.randomAccessIndicator===1?"key":"delta";return new t(Y.metadataOnly?w0:$.data,X,$.pts/R1,Math.max(J/R1,0),$.sequenceNumber,$.data.byteLength)}async getFirstPacket($){let J=this.elementaryStream.firstSection;F(J);let Y=L6(J,!0);F(Y);let X=new w6(this.elementaryStream,Y),Q=new r$(this,X),Z=await Q.readNext();if(!Z)return null;let K=this.createEncodedPacket(Z.packet,Z.duration,$);return this.packetBuffers.set(K,Q),this.packetSectionStarts.set(K,Z.packet.sectionStartPos),K}async getNextPacket($,J){let Y=this.packetBuffers.get($);if(Y){let j=await Y.readNext();if(!j)return null;this.packetBuffers.delete($);let U=this.createEncodedPacket(j.packet,j.duration,J);return this.packetBuffers.set(U,Y),this.packetSectionStarts.set(U,j.packet.sectionStartPos),U}let X=this.packetSectionStarts.get($);if(X===void 0)throw Error("Packet was not created from this track.");let Z=await this.elementaryStream.demuxer.readSection(X,!0);F(Z);let K=L6(Z,!0);F(K);let G=new w6(this.elementaryStream,K);Y=new r$(this,G);let W=$.sequenceNumber;while(!0){let j=await Y.readNext();if(!j)return null;if(j.packet.sequenceNumber>W){let U=this.createEncodedPacket(j.packet,j.duration,J);return this.packetBuffers.set(U,Y),this.packetSectionStarts.set(U,j.packet.sectionStartPos),U}}}async getNextKeyPacket($,J){let Y=$;while(!0){if(Y=await this.getNextPacket(Y,J),!Y)return null;if(Y.type==="key")return Y}}getPacket($,J){return this.doPacketLookup($,!1,J)}getKeyPacket($,J){return this.doPacketLookup($,!0,J)}async doPacketLookup($,J,Y){let X=y1($*R1),Q=this.elementaryStream.demuxer,{reader:Z,seekChunkSize:K}=Q,G=this.elementaryStream.pid,W=async(M,L,w)=>{let O=M;while(O<L){let D=await Q.readPacketHeader(O);if(!D)return null;if(D.pid===G&&D.payloadUnitStartIndicator===1){let B=await Q.readSection(O,w);if(!B)return null;let C=u8(B,!1);if(C&&C.pts!==null)return{pesPacketHeader:C,section:B}}O+=Q.packetStride}return null},j=this.elementaryStream.firstSection;F(j);let U=u8(j,!0);if(F(U),X<U.pts)return null;let q,N=this.elementaryStream.referencePesPackets,_=p(N,X,(M)=>M.pts),V=_!==-1?N[_]:null;if(V&&X-V.pts<R1/2)q=V.sectionStartPos;else{let M=0;if(Z.fileSize!==null){let L=Math.ceil(Z.fileSize/K);if(L>1){let w=0,O=L-1;M=w;while(w<=O){let D=Math.floor((w+O)/2),B=E$(D*K,Q.packetStride)+U.sectionStartPos,C=B+K,E=await W(B,C,!1);if(!E){O=D-1;continue}if(E.pesPacketHeader.pts<=X)M=D,w=D+1;else O=D-1}}}q=E$(M*K,Q.packetStride)+U.sectionStartPos}let R=(await W(q,Z.fileSize??1/0,!1))?.pesPacketHeader??null;if(!R)R=U;let H=this.getReorderSize(),A=async(M,L)=>{let w=await Q.readSection(M,!0);F(w);let O=L6(w,!0);F(O);let D=new w6(this.elementaryStream,O),B=new r$(this,D);while(!0){if((W0(B.presentationOrderPackets)?.pts??-1/0)>=X)break;if(!await B.readNextPacket())break}let C=B8(B.presentationOrderPackets,L);if(C===-1)return null;let E=B.presentationOrderPackets[C],P=C===0?0:E.pts-B.presentationOrderPackets[C-1].pts;while(B.decodeOrderPackets[0]!==E)B.decodeOrderPackets.shift();B.lastDuration=P;let v=await B.readNext();F(v);let T=this.createEncodedPacket(v.packet,v.duration,Y);return this.packetBuffers.set(T,B),this.packetSectionStarts.set(T,v.packet.sectionStartPos),T};if(!J||this.allPacketsAreKeyPackets()){$:while(!0){let M=R.sectionStartPos+Q.packetStride;while(!0){let L=await Q.readPacketHeader(M);if(!L)break $;if(L.pid===G&&L.payloadUnitStartIndicator===1){let w=await Q.readSection(M,!1);if(w){let O=u8(w,!1);if(O&&O.pts!==null){if(O.pts>X)break $;R=O,EY(this.elementaryStream,R);break}}}M+=Q.packetStride}}$:for(let M=0;M<H+1;M++){let L=R.sectionStartPos-Q.packetStride;while(L>=Q.packetOffset){let w=await Q.readPacketHeader(L);if(!w)break $;if(w.pid===G&&w.payloadUnitStartIndicator===1){let O=await Q.readSection(L,!1);if(O){let D=u8(O,!1);if(D&&D.pts!==null){R=D;break}}}L-=Q.packetStride}}return A(R.sectionStartPos,(M)=>M.pts<=X)}else{let M=q,L=null,w=!this.elementaryStream.canBeTrustedWithKeyPackets;while(!0){let O=null,D=M<=U.sectionStartPos,B,C=null;if(D)B=U,C=j;else{let v=await W(M,Z.fileSize??1/0,w);B=v?.pesPacketHeader??null,C=v?.section??null}let E=!1,P=0;$:while(B){if(L!==null&&B.sectionStartPos>=L)break;if(B.pts<=X){let T;if(this.elementaryStream.canBeTrustedWithKeyPackets)T=B.randomAccessIndicator===1;else{F(C);let x=L6(C,!0);F(x);let I=new w6(this.elementaryStream,x);await I.markNextPacket(),T=I.suppliedPacket?.randomAccessIndicator===1}if(T)O=B}if(B.pts>X)E=!0;if(E){if(P++,P>H)break}let v=B.sectionStartPos+Q.packetStride;while(!0){let T=await Q.readPacketHeader(v);if(!T)break $;if(T.pid===G&&T.payloadUnitStartIndicator===1){let x=await Q.readSection(v,w);if(x){let I=u8(x,!1);if(I&&I.pts!==null){B=I,C=x,EY(this.elementaryStream,B);break}}}v+=Q.packetStride}}if(O){let v=O;if(P===0)$:for(let x=0;x<H;x++){let I=v.sectionStartPos-Q.packetStride;while(I>=Q.packetOffset){let S=await Q.readPacketHeader(I);if(!S)break $;if(S.pid===G&&S.payloadUnitStartIndicator===1){let u=await Q.readSection(I,w);if(u){let r=u8(u,!1);if(r&&r.pts!==null){v=r;break}}}I-=Q.packetStride}}let T=await A(v.sectionStartPos,(x)=>x.pts<=X&&x.randomAccessIndicator===1);return F(T),T}if(D)return null;L=M,M=Math.max(E$(M-U.sectionStartPos-K,Q.packetStride)+U.sectionStartPos,U.sectionStartPos)}}}}class xX extends i${getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return F(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class IX extends i${getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return F(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}var EY=($,J)=>{let Y=$.referencePesPackets,X=p(Y,J.sectionStartPos,(Q)=>Q.sectionStartPos);if(X>=0){let Q=Y[X];if(J.pts<=Q.pts)return!1;let Z=$.demuxer.minReferencePointByteDistance;if(J.sectionStartPos-Q.sectionStartPos<Z)return!1;if(X<Y.length-1){let K=Y[X+1];if(K.pts<J.pts)return!1;if(K.sectionStartPos-J.sectionStartPos<Z)return!1}}return Y.splice(X+1,0,J),!0};class w6{constructor($,J){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=$,this.pid=$.pid,this.demuxer=$.demuxer,this.startingPesPacket=J}ensureBuffered($){let J=this.endPos-this.currentPos;if(J>=$)return $;return this.bufferData($-J).then(()=>Math.min(this.endPos-this.currentPos,$))}getCurrentPesPacket(){let $=this.pesPackets[this.currentPesPacketIndex];return F($),$}async bufferData($){let J=this.endPos+$;while(this.endPos<J){let Y;if(this.pesPackets.length===0)Y=this.startingPesPacket;else{let X=W0(this.pesPackets).sectionEndPos;F(X!==null);while(!0){let Q=await this.demuxer.readPacketHeader(X);if(!Q)return;if(Q.pid===this.pid){let Z=await this.demuxer.readSection(X,!0);if(!Z)return;let K=L6(Z,!1);if(K){Y=K;break}}X+=this.demuxer.packetStride}}this.pesPackets.push(Y),this.endPos+=Y.data.byteLength}}readBytes($){let J=this.getCurrentPesPacket(),Y=this.currentPos-this.currentPesPacketPos,X=Y+$;if(this.currentPos+=$,X<=J.data.byteLength)return J.data.subarray(Y,X);let Q=new Uint8Array($);Q.set(J.data.subarray(Y));let Z=J.data.byteLength-Y;while(!0){this.advanceCurrentPacket();let K=this.getCurrentPesPacket(),G=$-Z;if(G<=K.data.byteLength){Q.set(K.data.subarray(0,G),Z);break}Q.set(K.data,Z),Z+=K.data.byteLength}return Q}readU8(){let $=this.getCurrentPesPacket(),J=this.currentPos-this.currentPesPacketPos;if(this.currentPos++,J<$.data.byteLength)return $.data[J];return this.advanceCurrentPacket(),$=this.getCurrentPesPacket(),$.data[0]}seekTo($){if($===this.currentPos)return;if($<this.currentPos)while($<this.currentPesPacketPos){this.currentPesPacketIndex--;let J=this.getCurrentPesPacket();this.currentPesPacketPos-=J.data.byteLength}else while(!0){let J=this.getCurrentPesPacket(),Y=this.currentPesPacketPos+J.data.byteLength;if($<Y)break;this.currentPesPacketPos+=J.data.byteLength,this.currentPesPacketIndex++}this.currentPos=$}skip($){this.seekTo(this.currentPos+$)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){F(!this.suppliedPacket);let $=this.elementaryStream;if($.info.type==="video"){let J=$.info.codec,Y=1024;if(J!=="avc"&&J!=="hevc")throw Error("Unhandled.");let X=J==="avc"?1:2,Q=null,Z=!1,K=0;while(!0){let G=this.ensureBuffered(1024);if(G instanceof Promise)G=await G;if(G===0)break;let W=this.currentPos,j=this.readBytes(G),U=j.byteLength,q=0;while(q<U){let N=j.indexOf(0,q);if(N===-1||N>=U)break;q=N;let _=W+q;if(q+3>=U){this.seekTo(_);break}let V=j[q+1],z=j[q+2],R=j[q+3],H=0;if(V===0&&z===0&&R===1)H=4;else if(V===0&&z===1)H=3;if(H===0){q++;continue}let A=_;Q??=A;let M=q+H,L=M+X,w=6;if(L+(J==="avc"?w:1)>U){this.seekTo(_);break}let D=j[M],B,C,E;if(J==="avc")B=y8(D),C=B===B0.NON_IDR_SLICE||B===B0.SLICE_DPA||B===B0.IDR,E=B===B0.SEI||B===B0.SPS||B===B0.PPS||B===B0.AUD;else{if(B=m1(D),((D&1)<<5|j[M+1]>>3)>0){q+=H;continue}C=B<=M0.RASL_R||B>=M0.BLA_W_LP&&B<=21,E=B>=M0.VPS_NUT&&B<=37||B===M0.PREFIX_SEI_NUT||B>=41&&B<=44||B>=48&&B<=55}let P=!1;if(C){let v;if(J==="avc"){let T=j.subarray(L,L+w),x=h(new n(T));v=!Z||x<=K,K=x}else v=j[L]>>7===1;if(v)if(Z)P=!0;else Z=!0}else if(E&&Z)P=!0;if(P){let v=A-Q;return this.seekTo(Q),this.supplyPacket(v,0)}q+=H}if(G<1024)break}if(Q!==null&&this.endPos>Q){let G=this.endPos-Q;return this.seekTo(Q),this.supplyPacket(G,0)}}else{let J=$.info.codec,Y=128;while(!0){let X=this.ensureBuffered(128);if(X instanceof Promise)X=await X;let Q=this.currentPos;while(this.currentPos-Q<X){let Z=this.readU8();if(J==="aac"){if(Z!==255)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(z1);if(G instanceof Promise)G=await G;if(G<z1)return;let W=this.readBytes(z1),j=D1(u0.tempFromBytes(W));if(j){this.seekTo(K);let U=this.ensureBuffered(j.frameLength);if(U instanceof Promise)U=await U;return this.supplyPacket(U,Math.round(G$*R1/$.info.sampleRate))}else this.seekTo(K+1)}else if(J==="mp3"){if(Z!==255)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(w1);if(G instanceof Promise)G=await G;if(G<w1)return;let W=this.readBytes(w1),j=l(W).getUint32(0),U=W6(j,null);if(U.header){this.seekTo(K);let q=this.ensureBuffered(U.header.totalSize);if(q instanceof Promise)q=await q;let N=U.header.audioSamplesInFrame*R1/$.info.sampleRate;return this.supplyPacket(q,Math.round(N))}else this.seekTo(K+1)}else if(J==="ac3"){if(Z!==11)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(5);if(G instanceof Promise)G=await G;if(G<5)return;let W=this.readBytes(5);if(W[0]!==11||W[1]!==119){this.seekTo(K+1);continue}let j=W[4]>>6,U=W[4]&63;if(j===3||U>37){this.seekTo(K+1);continue}let q=t7[3*U+j];if(F(q!==void 0),this.seekTo(K),G=this.ensureBuffered(q),G instanceof Promise)G=await G;let N=Math.round(e7*R1/$.info.sampleRate);return this.supplyPacket(G,N)}else if(J==="eac3"){if(Z!==11)continue;this.skip(-1);let K=this.currentPos,G=this.ensureBuffered(5);if(G instanceof Promise)G=await G;if(G<5)return;let W=this.readBytes(5);if(W[0]!==11||W[1]!==119){this.seekTo(K+1);continue}let U=(((W[2]&7)<<8|W[3])+1)*2,N=W[4]>>6===3?3:W[4]>>4&3,_=aJ[N];if(this.seekTo(K),G=this.ensureBuffered(U),G instanceof Promise)G=await G;let V=_*256,z=Math.round(V*R1/$.info.sampleRate);return this.supplyPacket(G,z)}else throw Error("Unhandled.")}if(X<128)break}}}supplyPacket($,J){let Y=this.getCurrentPesPacket(),X;if(this.lastSuppliedPesPacket===Y)F(this.nextPts!==null),X=this.nextPts;else{if(Y.pts===null)throw Error(vX);X=Y.pts,EY(this.elementaryStream,Y)}this.lastSuppliedPesPacket=Y,this.nextPts=X+J;let Q=Y.sectionStartPos,Z=Q+(this.currentPos-this.currentPesPacketPos),K=this.readBytes($),G=Y.randomAccessIndicator;if(G===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")G=1;else if(this.elementaryStream.info.decoderConfig){let W=S8(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,K)==="key";G=Number(W)}}this.suppliedPacket={pts:X,data:K,sequenceNumber:Z,sectionStartPos:Q,randomAccessIndicator:G},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class r${constructor($,J){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=$,this.context=J,this.reorderSize=$.getReorderSize(),F(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0){if(!await this.readNextPacket())return null}await this.ensureCurrentPacketHasNext();let $=this.decodeOrderPackets[0],J=this.presentationOrderPackets.indexOf($);F(J!==-1);let Y;if(J===this.presentationOrderPackets.length-1)Y=this.lastDuration;else Y=this.presentationOrderPackets[J+1].pts-$.pts,this.lastDuration=Y;this.decodeOrderPackets.shift();while(this.presentationOrderPackets.length>0){let X=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(X))break;this.presentationOrderPackets.shift()}return{packet:$,duration:Y}}async readNextPacket(){if(this.reachedEnd)return!1;let $;if(this.context.suppliedPacket)$=this.context.suppliedPacket;else await this.context.markNextPacket(),$=this.context.suppliedPacket;if(this.context.suppliedPacket=null,!$)return this.reachedEnd=!0,this.flushReorderBuffer(),!1;return this.decodeOrderPackets.push($),this.processPacketThroughReorderBuffer($),!0}async ensureCurrentPacketHasNext(){let $=this.decodeOrderPackets[0];F($);while(!0){let J=this.presentationOrderPackets.indexOf($);if(J!==-1&&J<=this.presentationOrderPackets.length-2)break;if(!await this.readNextPacket())break}}processPacketThroughReorderBuffer($){if(this.reorderBuffer.push($),this.reorderBuffer.length>this.reorderSize){let J=0;for(let X=1;X<this.reorderBuffer.length;X++)if(this.reorderBuffer[X].pts<this.reorderBuffer[J].pts)J=X;let Y=this.reorderBuffer[J];this.presentationOrderPackets.push(Y),this.reorderBuffer.splice(J,1)}}flushReorderBuffer(){this.reorderBuffer.sort(($,J)=>$.pts-J.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}/*!
|
|
182
182
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
183
183
|
*
|
|
184
184
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
185
185
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
186
186
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
187
|
-
*/
|
|
187
|
+
*/var O6="application/vnd.apple.mpegurl",bY="#EXT-X-STREAM-INF:",TY="#EXT-X-I-FRAME-STREAM-INF:",vY="#EXT-X-MEDIA:",W$="#EXTINF:",xY="#EXT-X-MAP:",IY="#EXT-X-KEY:",yY="#EXT-X-MEDIA-SEQUENCE:",SY="#EXT-X-BYTERANGE:",hY="#EXT-X-PROGRAM-DATE-TIME:",yX="#EXT-X-DISCONTINUITY",fY="#EXT-X-TARGETDURATION:",SX="#EXT-X-ENDLIST",gY="#EXT-X-PLAYLIST-TYPE:",hX="#EXT-X-I-FRAMES-ONLY",a$=($)=>$.length===0||$.startsWith("#")&&!$.startsWith("#EXT");class j8{constructor($){this._attributes={};let J="",Y="",X=!1,Q=!1;for(let Z=0;Z<$.length;Z++){let K=$[Z];if(K==='"')Q=!Q;else if(K==="="&&!X&&!Q)X=!0;else if(K===","&&!Q){if(J)this._attributes[J.trim().toLowerCase()]=Y;J="",Y="",X=!1}else if(X)Y+=K;else J+=K}if(J)this._attributes[J.trim().toLowerCase()]=Y}get($){return this._attributes[$.toLowerCase()]??null}getAsNumber($){let J=this.get($);if(J===null)return null;let Y=Number(J);return Number.isFinite(Y)?Y:null}merge($){Object.assign(this._attributes,$._attributes)}}/*!
|
|
188
188
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
189
189
|
*
|
|
190
190
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
191
191
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
192
192
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
193
|
-
*/s8();var SY=0,hY=1/0,tZ=null;if(typeof FinalizationRegistry<"u")tZ=new FinalizationRegistry(($)=>{$()});class r0 extends i1{constructor(){super();if(this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u")this._refFinalizationRegistry=new FinalizationRegistry(($)=>{$._decrementRefCount()})}async getSizeOrNull(){if(this._disposed)throw new R0;return this._sizePromise??=(async()=>{let $=this._getFileSize();if($!==void 0)return $;return await this._read(0,1,SY,hY),$=this._getFileSize(),L($!==void 0),$})()}async getSize(){if(this._disposed)throw new R0;let $=await this.getSizeOrNull();if($===null)throw Error("Cannot determine the size of an unsized source.");return $}slice($,J){if(!Number.isInteger($)||$<0)throw TypeError("offset must be a non-negative integer.");if(J!==void 0&&(!Number.isInteger(J)||J<0))throw TypeError("length, when provided, must be a non-negative integer.");return new gY(this,$,J)}_dispatchRead($,J){this.onread?.($,J),this._emit("read",{start:$,end:J})}ref(){return new A6(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){if(this._refCount--,this._refCount===0)this._dispose(),this._disposed=!0}}class A6{constructor($){if(this._freed=!1,$._disposed)throw Error("Cannot ref a disposed source.");$._incrementRefCount(),$._refFinalizationRegistry?.register(this,$,this),this._source=$}get source(){if(!this._source)throw Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error("Illegal operation: double free on SourceRef.");let $=this.source;L($._refCount>0),$._decrementRefCount(),$._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){if(!this.freed)this.free()}}class R1 extends r0{constructor($,J){if(typeof $!=="string")throw TypeError("rootPath must be a string.");if(typeof J!=="function")throw TypeError("requestHandler must be a function.");super();this.rootPath=$,this.requestHandler=J}_resolveRequest($){let J=this.requestHandler($),Y=(X)=>{if(!(X instanceof r0||X instanceof A6))throw TypeError("requestHandler must return or resolve to a Source or SourceRef.");let Q=X instanceof r0?X.ref():X;return Q.source._usedForHls||=this._usedForHls,Q};if(J instanceof Promise)return J.then(Y);else return Y(J)}}var fY=($,J)=>{return $.path===J.path};class n$ extends R1{constructor(){super(...arguments);this._root=null,this._rootRequest=null}_read($,J,Y,X){if(!this._root){if(!this._rootRequest){let Q=this._resolveRequest({path:this.rootPath,isRoot:!0}),Z=(K)=>{let G=K instanceof r0?K.ref():K;return this._root=G,this._rootRequest=null,G};if(Q instanceof Promise)this._rootRequest=Q.then(Z);else Z(Q),L(this._root)}if(this._rootRequest)return this._rootRequest.then((Q)=>Q.source._read($,J,Y,X))}return this._root.source._read($,J,Y,X)}_getFileSize(){if(this._root)return this._root.source._getFileSize();return}_dispose(){if(this._root)this._root.free();else if(this._rootRequest)this._rootRequest.then(($)=>$.free())}}var eZ=524288,$2=($,J,Y)=>{if(J instanceof Error&&(J.message.includes("Failed to fetch")||J.message.includes("Load failed")||J.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let Q=null;try{if(typeof window<"u"&&typeof window.location<"u")Q=new URL(Y instanceof Request?Y.url:Y,window.location.href).origin}catch{}if((typeof navigator<"u"&&typeof navigator.onLine==="boolean"?navigator.onLine:!0)&&Q!==null&&Q!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**($-2),16)},hX=new Set;class h8 extends R1{constructor($,J={}){if(typeof $!=="string"&&!($ instanceof URL)&&!(typeof Request<"u"&&$ instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.requestInit!==void 0&&(!J.requestInit||typeof J.requestInit!=="object"))throw TypeError("options.requestInit, when provided, must be an object.");if(J.getRetryDelay!==void 0&&typeof J.getRetryDelay!=="function")throw TypeError("options.getRetryDelay, when provided, must be a function.");if(J.maxCacheSize!==void 0&&(!g6(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(J.parallelism!==void 0&&(!Number.isInteger(J.parallelism)||J.parallelism<1))throw TypeError("options.parallelism, when provided, must be a positive number.");if(J.fetchFn!==void 0&&typeof J.fetchFn!=="function")throw TypeError("options.fetchFn, when provided, must be a function.");let Y=$ instanceof Request?$.url:$ instanceof URL?$.href:$;super(Y,(Z)=>new h8(Z.path,this._options));this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._url=$,this._options=J,this._getRetryDelay=J.getRetryDelay??$2,this._requestInit={...J.requestInit};let X=null;if(J.requestInit?.headers){let Z={...L$(J.requestInit.headers)},K=Object.keys(Z).find((G)=>G.toLowerCase()==="range");if(K!==void 0)X=Z[K],delete Z[K],this._requestInit.headers=Z}if($ instanceof Request){let Z=$.headers.get("Range");if(Z!==null){X??=Z;let K=new Request($);K.headers.delete("Range"),this._url=K}}if(X!==null){let Z=Y2(X);if(Z)this._offset=Z.offset,this._length=Z.length}let Q=2;this._orchestrator=new fX({maxCacheSize:J.maxCacheSize??67108864,maxWorkerCount:J.parallelism??Q,runWorker:this._runWorker.bind(this),prefetchProfile:X2.network})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let $=this._orchestrator.fileSize;if($===null)return this._length!==null?this._length:null;return s0($-this._offset,0,this._length??1/0)}_read($,J,Y,X){if(this._length!==null&&J>this._length)return null;let Q=this._offset,Z=this._orchestrator.read(Q+$,Q+J,Math.max(Q+Y,Q),Q+Math.min(X,this._length??1/0)),K=(G)=>{if(!G)return null;return G.offset-=this._offset,G};if(Z instanceof Promise)return Z.then(K);else return K(Z)}async _runWorker($){while(!0){let J=new AbortController,Y=await h7(this._options.fetchFn??fetch,this._url,S7(this._requestInit,{headers:{Range:`bytes=${$.currentPos}-`},signal:J.signal}),this._getRetryDelay,()=>this._disposed);if(!Y.ok)throw Error(`Error fetching ${String(this._url)}: ${Y.status} ${Y.statusText}`);$:if(this._orchestrator.fileSize===null){let Q=Y.headers.get("Content-Range");if(Q){let K=/\/(\d+)/.exec(Q);if(K){this._orchestrator.supplyFileSize(Number(K[1]));break $}}let Z=Y.headers.get("Content-Length");if(Z)this._orchestrator.supplyFileSize($.currentPos+Number(Z))}if(this._fileSizeDetermined=!0,Y.status!==206){if(!this._usedForHls){let Q=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);if(Q.origin!=="null"&&!(Q.pathname.endsWith(".m3u8")||Q.pathname.endsWith(".m3u"))){if(!hX.has(Q.origin))console.log(this._usedForHls,this._url,Q.pathname),console.warn(`HTTP server (origin ${Q.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),hX.add(Q.origin)}}if($.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null)$.targetPos=this._orchestrator.fileSize;else $.targetPos=1/0,$.strictTarget=!1;this._orchestrator.consolidateEverythingIntoOneWorker($)}if(!Y.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let X=Y.body.getReader();while(!0){if($.currentPos>=$.targetPos||$.aborted){J.abort(),this._orchestrator.signalWorkerStoppedRunning($);return}let Q;try{Q=await X.read()}catch(G){if(this._disposed)throw G;let W=this._getRetryDelay(1,G,this._url);if(W!==null){console.error("Error while reading response stream. Attempting to resume.",G),await k6(1000*W);break}else throw G}if($.aborted)continue;let{done:Z,value:K}=Q;if(Z){if($.currentPos>=$.targetPos){this._orchestrator.onWorkerFinished($);return}if($.strictTarget)break;else{this._orchestrator.onWorkerFinished($);return}}this._dispatchRead($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}}}_dispose(){this._orchestrator.dispose()}}var J2=/^bytes=(\d+)-(\d*)$/,Y2=($)=>{let J=J2.exec($.trim());if(!J)return null;let Y=Number(J[1]),X=J[2]===""?null:Number(J[2]);if(X!==null&&X<Y)return null;return{offset:Y,length:X!==null?X-Y+1:null}};class o$ extends r0{constructor($,J={}){if(!($ instanceof ReadableStream))throw TypeError("stream must be a ReadableStream.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!g6(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=$,this._maxCacheSize=J.maxCacheSize??33554432}_getFileSize(){return this._endIndex}_read($,J){if(this._endIndex!==null&&J>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,J);let Y=p(this._cache,$,(j)=>j.start),X=Y!==-1?this._cache[Y]:null;if(X&&X.start<=$&&J<=X.end)return{bytes:X.bytes,view:X.view,offset:X.start};let Q=$,Z=new Uint8Array(J-$);if(Y!==-1)for(let j=Y;j<this._cache.length;j++){let U=this._cache[j];if(U.start>=J)break;let q=Math.max($,U.start);if(q>Q)this._throwDueToCacheMiss();let V=Math.min(J,U.end);if(q<V)Z.set(U.bytes.subarray(q-U.start,V-U.start),q-$),Q=V}if(Q===J)return{bytes:Z,view:u(Z),offset:$};if(this._currentIndex>Q)this._throwDueToCacheMiss();let{promise:K,resolve:G,reject:W}=U0();if(this._pendingSlices.push({start:$,end:J,bytes:Z,resolve:G,reject:W}),this._targetIndex=Math.max(this._targetIndex,J),!this._pulling)this._pulling=!0,this._pull().catch((j)=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach((U)=>U.reject(j)),this._pendingSlices.length=0;else throw j});return K}_throwDueToCacheMiss(){throw Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){this._reader??=this._stream.getReader();while(this._currentIndex<this._targetIndex&&!this._disposed){let{done:$,value:J}=await this._reader.read();if($){for(let Q of this._pendingSlices)Q.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let Y=this._currentIndex,X=this._currentIndex+J.byteLength;this._dispatchRead(Y,X);for(let Q=0;Q<this._pendingSlices.length;Q++){let Z=this._pendingSlices[Q],K=Math.max(Y,Z.start),G=Math.min(X,Z.end);if(K<G){if(Z.bytes.set(J.subarray(K-Y,G-Y),K-Z.start),G===Z.end)Z.resolve({bytes:Z.bytes,view:u(Z.bytes),offset:Z.start}),this._pendingSlices.splice(Q,1),Q--}}this._cache.push({start:Y,end:X,bytes:J,view:u(J),age:0});while(this._cache.length>0){let Q=this._cache[0];if(this._maxRequestedIndex-Q.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=J.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}var X2={none:($,J)=>({start:$,end:J}),fileSystem:($,J)=>{return $=Math.floor(($-65536)/65536)*65536,J=Math.ceil((J+65536)/65536)*65536,{start:$,end:J}},network:($,J,Y)=>{$=Math.max(0,Math.floor(($-65536)/65536)*65536);for(let Q of Y){let K=Math.max((Q.startPos+Q.targetPos)/2,Q.targetPos-8388608);if(w$($,J,K,Q.targetPos)){let G=Q.targetPos-Q.startPos,W=Math.ceil((G+1)/8388608)*8388608,j=2**Math.ceil(Math.log2(G+1)),U=Math.min(j,W);J=Math.max(J,Q.startPos+U)}}return J=Math.max(J,$+eZ),{start:$,end:J}}};class fX{constructor($){this.options=$,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read($,J,Y,X){L(!this.disposed);let Q=this.options.prefetchProfile($,J,this.workers),Z=Math.max(Q.start,Y),K=Math.min(Q.end,this.fileSize??1/0,X);L(Z<=$&&J<=K);let G=null,W=p(this.cache,$,(F)=>F.start),j=W!==-1?this.cache[W]:null;if(j&&j.start<=$&&J<=j.end)j.age=this.nextAge++,G={bytes:j.bytes,view:j.view,offset:j.start};let U=p(this.cache,Z,(F)=>F.start),q=G?null:new Uint8Array(J-$),V=0,_=Z,N=[];if(U!==-1){for(let F=U;F<this.cache.length;F++){let O=this.cache[F];if(O.start>=K)break;if(O.end<=Z)continue;let B=Math.max(Z,O.start),D=Math.min(K,O.end);if(L(B<=D),_<B)N.push({start:_,end:B});if(_=D,q){let w=Math.max($,O.start),P=Math.min(J,O.end);if(w<P){let T=w-$;if(q.set(O.bytes.subarray(w-O.start,P-O.start),T),T===V)V=P-$}}O.age=this.nextAge++}if(_<K)N.push({start:_,end:K})}else N.push({start:Z,end:K});if(q&&V>=q.length)G={bytes:q,view:u(q),offset:$};if(N.length===0)return L(G),G;let{promise:R,resolve:z,reject:H}=U0(),A=[];for(let F of N){let O=Math.max($,F.start),B=Math.min(J,F.end);if(O===F.start&&B===F.end)A.push(F);else if(O<B)A.push({start:O,end:B})}let M=q&&{start:$,bytes:q,holes:A,resolve:z,reject:H};$:for(let F of N){for(let D of this.workers)if(this.checkHoleAgainstWorker(D,F,M?[M]:[])){this.checkQueuedReadsAgainstWorker(D);continue $}let O=F.end<K||this.fileSize!==null,B=this.createWorker(F.start,F.end,O);if(B){if(M)B.pendingSlices=[M];this.runWorker(B)}else{let D=p(this.queuedReads,F.start,(P)=>P.hole.start),w=D!==-1?this.queuedReads[D]:null;if(w&&F.start<=w.hole.end){if(w.hole.end=Math.max(w.hole.end,F.end),w.strictTarget&&=O,M)w.pendingSlices.push(M)}else D++,w={hole:{start:F.start,end:F.end},strictTarget:O,pendingSlices:M?[M]:[],age:this.nextAge++},this.queuedReads.splice(D,0,w);while(D+1<this.queuedReads.length){let P=this.queuedReads[D+1];if(P.hole.start>w.hole.end)break;w.hole.end=Math.max(w.hole.end,P.hole.end),w.pendingSlices.push(...P.pendingSlices),w.strictTarget&&=P.strictTarget,w.age=Math.min(w.age,P.age),this.queuedReads.splice(D+1,1)}}}if(!G)L(q),G=R.then((F)=>F&&{bytes:F,view:u(F),offset:$});return G}checkHoleAgainstWorker($,J,Y){if(w$(J.start-131072,J.start,$.currentPos,$.targetPos)){$.targetPos=Math.max($.targetPos,J.end);for(let Q=0;Q<Y.length;Q++){let Z=Y[Q];if(!$.pendingSlices.includes(Z))$.pendingSlices.push(Z)}if(!$.running)this.runWorker($);return!0}return!1}checkQueuedReadsAgainstWorker($){let J=!1;for(let Y=0;Y<this.queuedReads.length;Y++){let X=this.queuedReads[Y];if(this.checkHoleAgainstWorker($,X.hole,X.pendingSlices))this.queuedReads.splice(Y,1),Y--,J=!0;else if(J)break}}createWorker($,J,Y){if(this.workers.length>=this.options.maxWorkerCount){let Q=null,Z=null;for(let K=0;K<this.workers.length;K++){let G=this.workers[K];if(!G.running&&G.pendingSlices.length===0&&(!Q||G.age<Q.age))Z=K,Q=G}if(Q)L(Z!==null),L(Q.pendingSlices.length===0),this.workers.splice(Z,1);else return null}let X={startPos:$,currentPos:$,targetPos:J,strictTarget:Y,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(X),X}runWorker($){L(!$.running),L($.currentPos<$.targetPos),$.running=!0,$.age=this.nextAge++,this.options.runWorker($).catch((J)=>{if($.running=!1,$.pendingSlices.length>0)$.pendingSlices.forEach((Y)=>Y.reject(J)),$.pendingSlices.length=0;else throw J}).finally(()=>{if($.running)return;if(this.queuedReads.length>0){let J=0;for(let Q=1;Q<this.queuedReads.length;Q++)if(this.queuedReads[Q].age<this.queuedReads[J].age)J=Q;let Y=this.queuedReads[J];this.queuedReads.splice(J,1);let X=this.createWorker(Y.hole.start,Y.hole.end,Y.strictTarget);L(X),X.pendingSlices=Y.pendingSlices,this.runWorker(X)}})}consolidateEverythingIntoOneWorker($){let J=new Set($.pendingSlices);for(let Y=0;Y<this.workers.length;Y++){let X=this.workers[Y];if(X===$)continue;for(let Q of X.pendingSlices)J.add(Q);X.aborted=!0,X.pendingSlices.length=0,this.workers.splice(Y,1),Y--}for(let Y=0;Y<this.queuedReads.length;Y++){let X=this.queuedReads[Y];for(let Q of X.pendingSlices)J.add(Q)}$.pendingSlices=[...J],this.queuedReads.length=0}supplyWorkerData($,J){L(!$.aborted);let Y=$.currentPos,X=Y+J.length;if(this.insertIntoCache({start:Y,end:X,bytes:J,view:u(J),age:this.nextAge++}),$.currentPos+=J.length,$.currentPos>$.targetPos)$.targetPos=$.currentPos,this.checkQueuedReadsAgainstWorker($);for(let Q=0;Q<$.pendingSlices.length;Q++){let Z=$.pendingSlices[Q],K=Math.max(Y,Z.start),G=Math.min(X,Z.start+Z.bytes.length);if(K<G)Z.bytes.set(J.subarray(K-Y,G-Y),K-Z.start);for(let W=0;W<Z.holes.length;W++){let j=Z.holes[W];if(Y<=j.start&&X>j.start)j.start=X;if(j.end<=j.start)Z.holes.splice(W,1),W--}if(Z.holes.length===0)Z.resolve(Z.bytes),$.pendingSlices.splice(Q,1),Q--}for(let Q=0;Q<this.workers.length;Q++){let Z=this.workers[Q];if($===Z||Z.running)continue;if(w$(Y,X,Z.currentPos,Z.targetPos))this.workers.splice(Q,1),Q--}}supplyFileSize($){L(this.fileSize===null),this.fileSize=$;for(let J of this.workers){J.targetPos=Math.min(J.targetPos,$),J.strictTarget=!0;for(let Y=0;Y<J.pendingSlices.length;Y++){let X=J.pendingSlices[Y];for(let Q of X.holes)if(Q.end>$){X.resolve(null),J.pendingSlices.splice(Y,1),Y--;break}}}for(let J=0;J<this.queuedReads.length;J++){let Y=this.queuedReads[J];if(Y.hole.start>=$){for(let X of Y.pendingSlices)X.resolve(null);this.queuedReads.splice(J,1),J--}else if(Y.hole.end>$){Y.hole.end=$,Y.strictTarget=!0;for(let X=0;X<Y.pendingSlices.length;X++){let Q=Y.pendingSlices[X];if(Q.start>=$)Q.resolve(null),Y.pendingSlices.splice(X,1),X--}}}}signalWorkerStoppedRunning($){$.running=!1,$.pendingSlices.length=0}onWorkerFinished($){let J=this.workers.indexOf($);if(L(J!==-1),$.running=!1,this.workers.splice(J,1),this.fileSize===null)this.supplyFileSize($.currentPos);for(let Y of $.pendingSlices)Y.resolve(null)}insertIntoCache($){if(this.options.maxCacheSize===0)return;let J=p(this.cache,$.start,(Y)=>Y.start)+1;if(J>0){let Y=this.cache[J-1];if(Y.end>=$.end)return;if(Y.end>$.start){let X=new Uint8Array($.end-Y.start);X.set(Y.bytes,0),X.set($.bytes,$.start-Y.start),this.currentCacheSize+=$.end-Y.end,Y.bytes=X,Y.view=u(X),Y.end=$.end,J--,$=Y}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length;for(let Y=J+1;Y<this.cache.length;Y++){let X=this.cache[Y];if($.end<=X.start)break;if($.end>=X.end){this.cache.splice(Y,1),this.currentCacheSize-=X.bytes.length,Y--;continue}let Q=new Uint8Array(X.end-$.start);Q.set($.bytes,0),Q.set(X.bytes,X.start-$.start),this.currentCacheSize-=$.end-X.start,$.bytes=Q,$.view=u(Q),$.end=X.end,this.cache.splice(Y,1);break}while(this.currentCacheSize>this.options.maxCacheSize){let Y=0,X=this.cache[0];for(let Q=1;Q<this.cache.length;Q++){let Z=this.cache[Q];if(Z.age<X.age)Y=Q,X=Z}if(this.currentCacheSize-X.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(Y,1),this.currentCacheSize-=X.bytes.length}}dispose(){for(let $ of this.workers)$.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}class gY extends r0{constructor($,J,Y){super();if(this._ref=null,$._disposed)throw Error("Cannot create a slice of a disposed source.");this._baseSource=$,this._offset=J,this._length=Y??null}_getFileSize(){let $=this._baseSource._getFileSize();if($===void 0)return this._length!==null?this._length:void 0;if($===null)if(this._length!==null)return this._length;else return null;return s0($-this._offset,0,this._length??1/0)}_read($,J,Y,X){if(this._length!==null&&J>this._length)return null;let Q=this._baseSource._read(this._offset+$,this._offset+J,this._offset+Y,this._offset+X),Z=(K)=>{if(!K)return null;return K.offset-=this._offset,K};if(Q instanceof Promise)return Q.then(Z);else return Z(Q)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}/*!
|
|
193
|
+
*/class mY{constructor($,J,Y){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=$,this.path=J,this.trackDeclarations=Y}async getDurationFromMetadata($){let J=await this.getSegmentAt(1/0,{skipLiveWait:$.skipLiveWait});if(!J)return null;return J.timestamp+J.duration}async getUnixTimeForTimestamp($){let J=await this.getSegmentAt($,{});if(J??=await this.getFirstSegment({}),!J||J.unixEpochTimestamp===null)return null;let Y=$-J.timestamp;return J.unixEpochTimestamp+Y}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let $=[];if(this.trackDeclarations){for(let J of this.trackDeclarations)if(J.type==="video"){let Y=P8($,(X)=>X.getType()==="video")+1;$.push(new kY(this,J,Y))}else if(J.type==="audio"){let Y=P8($,(X)=>X.getType()==="audio")+1;$.push(new uY(this,J,Y))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let Y=await this.getInputForSegment(this.firstSegment).getTracks();for(let X of Y)if(X.type==="video"){let Q=P8($,(Z)=>Z.getType()==="video")+1;$.push(new kY(this,{id:$.length+1,type:"video"},Q))}else if(X.type==="audio"){let Q=P8($,(Z)=>Z.getType()==="audio")+1;$.push(new uY(this,{id:$.length+1,type:"audio"},Q))}}return $})()}async getFirstTimestampForInput($){let J=this.firstTimestampCache.get($);if(J!==void 0)return J;let Y=await $.getFirstTimestamp();return this.firstTimestampCache.set($,Y),Y}async getMediaOffset($,J){let Y=$.firstSegment??$,X;if(this.firstSegmentFirstTimestamps.has(Y))X=this.firstSegmentFirstTimestamps.get(Y);else{let W=this.getInputForSegment(Y);X=await this.getFirstTimestampForInput(W),this.firstSegmentFirstTimestamps.set(Y,X)}if(Y===$)return Y.timestamp-X;let Q=await this.getFirstTimestampForInput(J),Z=$.timestamp-Y.timestamp,G=Q-X-Z;if(Math.abs(G)<=Math.min(0.25,Z))return Y.timestamp-X;else return $.timestamp-Q}dispose(){for(let $ of this.inputCache)$.input.dispose();this.inputCache.length=0}}class lY{constructor($,J,Y){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=$,this.decl=J,this.number=Y}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error("Missing first segment, can't retrieve track.");let Y=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find((X)=>X.type===this.decl.type&&X.number===this.number);if(!Y)throw Error("No matching track found in underlying media data.");this.firstInputTrack=Y})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate($){if(this.firstInputTrack)return $();return this.hydrate().then($)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),F(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp($){return this.segmentedInput.getUnixTimeForTimestamp($)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata($){return this.segmentedInput.getDurationFromMetadata($)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket($,J,Y){F($.sequenceNumber>=0),F(this.segmentedInput.firstSegment);let X=await this.segmentedInput.getMediaOffset(J,Y.input),Q=J.timestamp-this.segmentedInput.firstSegment.timestamp,Z=$.clone({timestamp:i8($.timestamp+X,await Y.getTimeResolution()),sequenceNumber:Math.floor(1e8*Q)+$.sequenceNumber});return this.packetInfos.set(Z,{segment:J,track:Y,sourcePacket:$}),Z}async getFirstPacket($){await this.hydrate(),F(this.segmentedInput.firstSegment),F(this.firstInputTrack);let J=await this.firstInputTrack._backing.getFirstPacket($);if(!J)return null;return this.createAdjustedPacket(J,this.segmentedInput.firstSegment,this.firstInputTrack)}getNextPacket($,J){return this._getNextInternal($,J,!1)}getNextKeyPacket($,J){return this._getNextInternal($,J,!0)}async _getNextInternal($,J,Y){let X=this.packetInfos.get($);if(!X)throw Error("Packet was not created from this track.");let Q=Y?await X.track._backing.getNextKeyPacket(X.sourcePacket,J):await X.track._backing.getNextPacket(X.sourcePacket,J);if(Q)return this.createAdjustedPacket(Q,X.segment,X.track);let Z=X.segment;while(!0){let K=await this.segmentedInput.getNextSegment(Z,{skipLiveWait:J.skipLiveWait});if(!K)return null;let j=(await this.segmentedInput.getInputForSegment(K).getTracks()).find((q)=>q.type===X.track.type&&q.number===X.track.number);if(!j){Z=K;continue}let U=await j._backing.getFirstPacket(J);if(!U)return null;return this.createAdjustedPacket(U,K,j)}}getPacket($,J){return this._getPacketInternal($,J,!1)}getKeyPacket($,J){return this._getPacketInternal($,J,!0)}async _getPacketInternal($,J,Y){let X=await this.segmentedInput.getSegmentAt($,{skipLiveWait:J.skipLiveWait});if(!X)return null;await this.hydrate();while(X){let Q=this.segmentedInput.getInputForSegment(X),K=(await Q.getTracks()).find((U)=>U.type===this.firstInputTrack.type&&U.number===this.firstInputTrack.number);if(!K){X=await this.segmentedInput.getPreviousSegment(X,{skipLiveWait:J.skipLiveWait});continue}let G=await this.segmentedInput.getMediaOffset(X,Q),W=$-G,j=Y?await K._backing.getKeyPacket(W,J):await K._backing.getPacket(W,J);if(!j){X=await this.segmentedInput.getPreviousSegment(X,{skipLiveWait:J.skipLiveWait});continue}return this.createAdjustedPacket(j,X,K)}return null}}class kY extends lY{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class uY extends lY{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}var P4=(()=>({}));/*!
|
|
194
194
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
195
195
|
*
|
|
196
196
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
197
197
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
198
198
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
199
|
-
*/var gX=function($,J,Y){if(J!==null&&J!==void 0){if(typeof J!=="object"&&typeof J!=="function")throw TypeError("Object expected.");var X,Q;if(Y){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");X=J[Symbol.asyncDispose]}if(X===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(X=J[Symbol.dispose],Y)Q=X}if(typeof X!=="function")throw TypeError("Object not disposable.");if(Q)X=function(){try{Q.call(this)}catch(Z){return Promise.reject(Z)}};$.stack.push({value:J,dispose:X,async:Y})}else if(Y)$.stack.push({async:!0});return J},kX=function($){return function(J){function Y(K){J.error=J.hasError?new $(K,J.error,"An error was suppressed during disposal."):K,J.hasError=!0}var X,Q=0;function Z(){while(X=J.stack.pop())try{if(!X.async&&Q===1)return Q=0,J.stack.push(X),Promise.resolve().then(Z);if(X.dispose){var K=X.dispose.call(X.value);if(X.async)return Q|=2,Promise.resolve(K).then(Z,function(G){return Y(G),Z()})}else Q|=1}catch(G){Y(G)}if(Q===1)return J.hasError?Promise.reject(J.error):Promise.resolve();if(J.hasError)throw J.error}return Z()}}(typeof SuppressedError==="function"?SuppressedError:function($,J,Y){var X=Error(Y);return X.name="SuppressedError",X.error=$,X.suppressed=J,X}),Z2=/^0[xX][0-9a-fA-F]+$/,Q2=/^data:.*;base64,/i;class s$ extends IY{constructor($,J,Y,X){super($.input,J,Y);this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=$,this.nextLines=X}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let $=this.getRemainingWaitTimeMs();if($>0)await k6($);this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let $=performance.now()-this.lastSegmentUpdateTime,J=Math.max(0,1000*this.refreshInterval-$);if(J<=50)return 0;return J}async updateSegments(){let $=this.nextLines;if(this.nextLines=null,!$){let z={stack:[],error:void 0,hasError:!1};try{let H=gX(z,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),M=await new f8(H.source).requestEntireFile();L(M),$=r$(M,M.length,{ignore:c$})}catch(H){z.error=H,z.hasError=!0}finally{kX(z)}}let J=!1,Y=0,X=null,Q=null,Z=0,K=null,G=null,W=null,j=null,U=null,q=null,V=!1,_=K0(this.segments)??null,N=(z)=>{let H=z.indexOf("@"),A=Number(H===-1?z:z.slice(0,H));if(!Number.isInteger(A)||A<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${z}'.`);let M=null;if(H!==-1){if(M=Number(z.slice(H+1)),!Number.isInteger(M)||M<0)throw Error(`Invalid #EXT-X-BYTERANGE offset '${z}'.`)}return{length:A,offset:M}},R=(z)=>{if(Z=z,_){if(L(_.sequenceNumber!==null),_.sequenceNumber<z)Y=_.timestamp+_.duration,K=_.firstSegment,G=_.initSegment,U=_.lastProgramDateTimeSeconds,_=null}};for(let z=0;z<$.length;z++){let H=$[z];if(!J){if(H!=="#EXTM3U")throw Error("Invalid M3U8 file; expected first line to be #EXTM3U.");J=!0;continue}if(!H.startsWith("#")){if(!_){if(X===null)throw Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let A=Q;if(A&&A.method==="AES-128"&&!A.iv){let B=new Uint8Array(X1),D=u(B);D.setUint32(8,Math.floor(Z/4294967296)),D.setUint32(12,Z),A={...A,iv:B}}let F={path:J1(this.path,H),offset:j?.offset??0,length:j?.length??null},O={timestamp:Y,relativeToUnixEpoch:U!==null,firstSegment:K,sequenceNumber:Z,location:F,duration:X,encryption:A,initSegment:G,lastProgramDateTimeSeconds:U};K??=O,Y+=X,this.segments.push(O)}if(X=null,j===null)W=null;else j=null;R(Z+1)}if(H.startsWith(J$)){if(_){V=!0;continue}if(!V){if(U===null&&Z>0&&q!==null)Y=Z*q;V=!0}let A=H.slice(J$.length),M=A.indexOf(","),F=M===-1?A:A.slice(0,M),O=Number(F);if(!Number.isFinite(O)||O<0)throw Error(`Invalid #EXTINF tag duration '${F}'.`);X=O}else if(H.startsWith(BY)){let A=new X8(H.slice(BY.length)),M=A.get("uri");if(!M)throw Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let F=A.get("byterange"),O=null;if(F!==null)O=N(F);if(O&&O.offset===null)throw Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!_){let D={path:J1(this.path,M),offset:O?.offset??0,length:O?.length??null};if(Q?.method==="AES-128"&&!Q.iv)throw Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");G={timestamp:Y,relativeToUnixEpoch:U!==null,firstSegment:null,sequenceNumber:null,location:D,duration:0,encryption:Q,initSegment:null,lastProgramDateTimeSeconds:U}}if(X=null,j===null)W=null;else j=null}else if(H.startsWith(DY)){let A=new X8(H.slice(DY.length)),M=A.get("method");if(M==="NONE")Q=null;else if(M==="AES-128"){let F=A.get("uri");if(!F)throw Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let O=null,B=A.get("iv");if(B){if(!Z2.test(B))throw Error(`Unsupported IV format '${B}'.`);let w=B.slice(2);w=w.padStart(X1*2,"0"),O=new Uint8Array(X1);for(let P=0;P<X1;P++){let T=-X1*2+P;O[P]=parseInt(w.slice(T,T+2),16)}}let D=A.get("keyformat")??"identity";if(D!=="identity")throw Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");Q={method:"AES-128",keyUri:J1(this.path,F),iv:O,keyFormat:D}}else if(M==="SAMPLE-AES"||M==="SAMPLE-AES-CTR"){let F=A.get("uri");if(!F)throw Error(`Invalid #EXT-X-KEY: ${M} requires a URI attribute.`);if((A.get("keyformat")??"identity")==="identity")throw Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let B=null;if(Q2.test(F)){let D=F.indexOf(","),w=f6(F.slice(D+1));if(w.length>=8&&w[4]===112&&w[5]===115&&w[6]===115&&w[7]===104){let P=u(w).getUint32(0);B=v$(w.subarray(8,Math.min(P,w.length)))}}Q={method:M,psshBox:B}}else throw Error(`Unsupported encryption method '${M}'. If you think this method should be supported, please raise an issue.`)}else if(H.startsWith(CY)){let A=H.slice(CY.length),M=Number(A);if(!Number.isInteger(M)||M<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${A}'.`);R(M)}else if(H.startsWith(EY)){let A=N(H.slice(EY.length));if(A.offset===null){if(W===null)throw Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");A.offset=W}j=A,W=A.offset+A.length}else if(H.startsWith(PY)){if(_)continue;let A=H.slice(PY.length),M=Date.parse(A);if(!Number.isFinite(M))continue;let F=M/1000;if(U===F)continue;if(U===null&&this.segments.length>0){let O=K0(this.segments),B=O.timestamp+O.duration,D=F-B;for(let w of this.segments)w.timestamp+=D,w.relativeToUnixEpoch=!0;Y+=D}U=F,Y=F}else if(H===IX)K=null;else if(H.startsWith(bY)){let A=H.slice(bY.length),M=Number(A);if(!Number.isFinite(M)||M<0)throw Error(`Invalid EXT-X-TARGETDURATION value '${A}'.`);this.refreshInterval=M,q=M}else if(H===yX){this.streamHasEnded=!0;break}else if(H.startsWith(TY)){if(H.slice(TY.length).toLowerCase()==="vod")this.streamHasEnded=!0}}if(!J)throw Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){if(this.segments.length===0)await this.runUpdateSegments();return this.segments[0]??null}async getSegmentAt($,J){if(this.segments.length===0)await this.runUpdateSegments();let Y=!!J.skipLiveWait&&this.getRemainingWaitTimeMs()>0;while(!0){let X=p(this.segments,$,(Z)=>Z.timestamp);if(X===-1)return null;if(X<this.segments.length-1||this.streamHasEnded||Y)return this.segments[X];let Q=this.segments[X];if($<Q.timestamp+Q.duration)return Q;if(await this.runUpdateSegments(),J.skipLiveWait)Y=!0}}async getNextSegment($,J){let Y=this.segments.indexOf($);L(Y!==-1);let X=Y+1,Q=!!J.skipLiveWait&&this.getRemainingWaitTimeMs()>0;while(!0){if(X<this.segments.length)return this.segments[X];if(this.streamHasEnded||Q)return null;if(await this.runUpdateSegments(),J.skipLiveWait)Q=!0}}async getPreviousSegment($){let J=this.segments.indexOf($);return L(J!==-1),this.segments[J-1]??null}getInputForSegment($){let J=$,Y=this.inputCache.find((G)=>G.segment===J);if(Y)return Y.age=this.nextInputCacheAge++,Y.input;let X=null;if(J.initSegment||J.firstSegment)X=this.getInputForSegment(J.initSegment??J.firstSegment);let Q={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&((G)=>{if(!J.encryption||!(J.encryption.method==="SAMPLE-AES"||J.encryption.method==="SAMPLE-AES-CTR")||!J.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(G);let W=G.psshBoxes,{psshBox:j}=J.encryption;if((j.keyIds===null||j.keyIds.includes(G.keyId))&&!W.some((U)=>x$(U,j)))W=[...W,j];return this.input._formatOptions.isobmff.resolveKeyId({...G,psshBoxes:W})})}},Z=new A1({source:new n$(J.location.path,async(G)=>{L(G.isRoot);let W={...G,isRoot:!1},j,U=J.location.offset>0||J.location.length!==null;if(!J.encryption||J.encryption.method==="SAMPLE-AES"||J.encryption.method==="SAMPLE-AES-CTR"){if(j=await this.input._getSourceCached(W),U){let V=j.source.slice(J.location.offset,J.location.length??void 0).ref();j.free(),j=V}}else if(J.encryption.method==="AES-128"){let q=J.encryption;L(q.iv);let V=await this.input._getSourceCached(W);if(U){let z=V.source.slice(J.location.offset,J.location.length??void 0).ref();V.free(),V=z}let _=new f8(V.source),N=XX(_,async()=>{let R={stack:[],error:void 0,hasError:!1};try{let z=gX(R,await this.input._getSourceCached({path:q.keyUri,isRoot:!1},uX),!1),A=await new f8(z.source).requestSlice(0,X1);if(!A)throw Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:h(A,X1),iv:q.iv}}catch(z){R.error=z,R.hasError=!0}finally{kX(R)}},()=>{V.free()});j=new o$(N).ref()}else L(!1);return j}),formats:this.input._formats.filter((G)=>!(G instanceof Y$)),initInput:X??void 0,formatOptions:Q});Z._onFormatDetermined=(G)=>{if((J.encryption?.method==="SAMPLE-AES"||J.encryption?.method==="SAMPLE-AES-CTR")&&!G._isIsobmff)throw Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:J,input:Z,age:this.nextInputCacheAge++});let K=4;if(this.inputCache.length>K){let G=r8(this.inputCache,(W)=>W.age);L(G!==-1),this.inputCache.splice(G,1)}return Z}async getLiveRefreshInterval(){if(this.getRemainingWaitTimeMs()===0)await this.runUpdateSegments();return this.streamHasEnded?null:this.refreshInterval}}/*!
|
|
199
|
+
*/e8();var pY=0,dY=1/0,Q2=null;if(typeof FinalizationRegistry<"u")Q2=new FinalizationRegistry(($)=>{$()});class Z1 extends L1{constructor(){super();if(this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,typeof FinalizationRegistry<"u")this._refFinalizationRegistry=new FinalizationRegistry(($)=>{$._decrementRefCount()})}async getSizeOrNull(){if(this._disposed)throw new D0;return this._sizePromise??=(async()=>{let $=this._getFileSize();if($!==void 0)return $;return await this._read(0,1,pY,dY),$=this._getFileSize(),F($!==void 0),$})()}async getSize(){if(this._disposed)throw new D0;let $=await this.getSizeOrNull();if($===null)throw Error("Cannot determine the size of an unsized source.");return $}slice($,J){if(!Number.isInteger($)||$<0)throw TypeError("offset must be a non-negative integer.");if(J!==void 0&&(!Number.isInteger(J)||J<0))throw TypeError("length, when provided, must be a non-negative integer.");return new nY(this,$,J)}_dispatchRead($,J){this.onread?.($,J),this._emit("read",{start:$,end:J})}ref(){return new B6(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){if(this._refCount--,this._refCount===0)this._dispose(),this._disposed=!0}}class B6{constructor($){if(this._freed=!1,$._disposed)throw Error("Cannot ref a disposed source.");$._incrementRefCount(),$._refFinalizationRegistry?.register(this,$,this),this._source=$}get source(){if(!this._source)throw Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error("Illegal operation: double free on SourceRef.");let $=this.source;F($._refCount>0),$._decrementRefCount(),$._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){if(!this.freed)this.free()}}class Q1 extends Z1{constructor($,J){if(typeof $!=="string")throw TypeError("rootPath must be a string.");if(typeof J!=="function")throw TypeError("requestHandler must be a function.");super();this.rootPath=$,this.requestHandler=J}_resolveRequest($){let J=this.requestHandler($),Y=(X)=>{if(!(X instanceof Z1||X instanceof B6))throw TypeError("requestHandler must return or resolve to a Source or SourceRef.");let Q=X instanceof Z1?X.ref():X;return Q.source._usedForHls||=this._usedForHls,Q};if(J instanceof Promise)return J.then(Y);else return Y(J)}}var cY=($,J)=>{return $.path===J.path};class t$ extends Q1{constructor(){super(...arguments);this._root=null,this._rootRequest=null}_read($,J,Y,X){if(!this._root){if(!this._rootRequest){let Q=this._resolveRequest({path:this.rootPath,isRoot:!0}),Z=(K)=>{let G=K instanceof Z1?K.ref():K;return this._root=G,this._rootRequest=null,G};if(Q instanceof Promise)this._rootRequest=Q.then(Z);else Z(Q),F(this._root)}if(this._rootRequest)return this._rootRequest.then((Q)=>Q.source._read($,J,Y,X))}return this._root.source._read($,J,Y,X)}_getFileSize(){if(this._root)return this._root.source._getFileSize();return}_dispose(){if(this._root)this._root.free();else if(this._rootRequest)this._rootRequest.then(($)=>$.free())}}var K2=524288,G2=($,J,Y)=>{if(J instanceof Error&&(J.message.includes("Failed to fetch")||J.message.includes("Load failed")||J.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let Q=null;try{if(typeof window<"u"&&typeof window.location<"u")Q=new URL(Y instanceof Request?Y.url:Y,window.location.href).origin}catch{}if((typeof navigator<"u"&&typeof navigator.onLine==="boolean"?navigator.onLine:!0)&&Q!==null&&Q!==window.location.origin)return k._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**($-2),16)},fX=new Set;class m8 extends Q1{constructor($,J={}){if(typeof $!=="string"&&!($ instanceof URL)&&!(typeof Request<"u"&&$ instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.requestInit!==void 0&&(!J.requestInit||typeof J.requestInit!=="object"))throw TypeError("options.requestInit, when provided, must be an object.");if(J.getRetryDelay!==void 0&&typeof J.getRetryDelay!=="function")throw TypeError("options.getRetryDelay, when provided, must be a function.");if(J.maxCacheSize!==void 0&&(!n6(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(J.parallelism!==void 0&&(!Number.isInteger(J.parallelism)||J.parallelism<1))throw TypeError("options.parallelism, when provided, must be a positive number.");if(J.fetchFn!==void 0&&typeof J.fetchFn!=="function")throw TypeError("options.fetchFn, when provided, must be a function.");let Y=$ instanceof Request?$.url:$ instanceof URL?$.href:$;super(Y,(Z)=>new m8(Z.path,this._options));this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._url=$,this._options=J,this._getRetryDelay=J.getRetryDelay??G2,this._requestInit={...J.requestInit};let X=null;if(J.requestInit?.headers){let Z={...D$(J.requestInit.headers)},K=Object.keys(Z).find((G)=>G.toLowerCase()==="range");if(K!==void 0)X=Z[K],delete Z[K],this._requestInit.headers=Z}if($ instanceof Request){let Z=$.headers.get("Range");if(Z!==null){X??=Z;let K=new Request($);K.headers.delete("Range"),this._url=K}}if(X!==null){let Z=U2(X);if(Z)this._offset=Z.offset,this._length=Z.length}let Q=2;this._orchestrator=new gX({maxCacheSize:J.maxCacheSize??67108864,maxWorkerCount:J.parallelism??Q,runWorker:this._runWorker.bind(this),prefetchProfile:j2.network})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let $=this._orchestrator.fileSize;if($===null)return this._length!==null?this._length:null;return r0($-this._offset,0,this._length??1/0)}_read($,J,Y,X){if(this._length!==null&&J>this._length)return null;let Q=this._offset,Z=this._orchestrator.read(Q+$,Q+J,Math.max(Q+Y,Q),Q+Math.min(X,this._length??1/0)),K=(G)=>{if(!G)return null;return G.offset-=this._offset,G};if(Z instanceof Promise)return Z.then(K);else return K(Z)}async _runWorker($){while(!0){let J=new AbortController,Y=await f7(this._options.fetchFn??fetch,this._url,h7(this._requestInit,{headers:{Range:`bytes=${$.currentPos}-`},signal:J.signal}),this._getRetryDelay,()=>this._disposed);if(!Y.ok)throw Error(`Error fetching ${String(this._url)}: ${Y.status} ${Y.statusText}`);if(Y.redirected)this.rootPath=Y.url;$:if(this._orchestrator.fileSize===null){let Q=Y.headers.get("Content-Range");if(Q){let K=/\/(\d+)/.exec(Q);if(K){this._orchestrator.supplyFileSize(Number(K[1]));break $}}let Z=Y.headers.get("Content-Length");if(Z)this._orchestrator.supplyFileSize($.currentPos+Number(Z))}if(this._fileSizeDetermined=!0,Y.status!==206){if(!this._usedForHls){let Q=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);if(Q.origin!=="null"&&!(Q.pathname.endsWith(".m3u8")||Q.pathname.endsWith(".m3u"))){if(!fX.has(Q.origin))k._warn(`HTTP server (origin ${Q.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),fX.add(Q.origin)}}if($.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null)$.targetPos=this._orchestrator.fileSize;else $.targetPos=1/0,$.strictTarget=!1;this._orchestrator.consolidateEverythingIntoOneWorker($)}if(!Y.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let X=Y.body.getReader();while(!0){if($.currentPos>=$.targetPos||$.aborted){J.abort(),this._orchestrator.signalWorkerStoppedRunning($);return}let Q;try{Q=await X.read()}catch(G){if(this._disposed)throw G;let W=this._getRetryDelay(1,G,this._url);if(W!==null){k._error("Error while reading response stream. Attempting to resume.",G),await J6(1000*W);break}else throw G}if($.aborted)continue;let{done:Z,value:K}=Q;if(Z){if($.currentPos>=$.targetPos){this._orchestrator.onWorkerFinished($);return}if($.strictTarget)break;else{this._orchestrator.onWorkerFinished($);return}}this._dispatchRead($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}}}_dispose(){this._orchestrator.dispose()}}var W2=/^bytes=(\d+)-(\d*)$/,U2=($)=>{let J=W2.exec($.trim());if(!J)return null;let Y=Number(J[1]),X=J[2]===""?null:Number(J[2]);if(X!==null&&X<Y)return null;return{offset:Y,length:X!==null?X-Y+1:null}};class e$ extends Z1{constructor($,J={}){if(!($ instanceof ReadableStream))throw TypeError("stream must be a ReadableStream.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!n6(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=$,this._maxCacheSize=J.maxCacheSize??33554432}_getFileSize(){return this._endIndex}_read($,J){if(this._endIndex!==null&&J>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,J);let Y=p(this._cache,$,(j)=>j.start),X=Y!==-1?this._cache[Y]:null;if(X&&X.start<=$&&J<=X.end)return{bytes:X.bytes,view:X.view,offset:X.start};let Q=$,Z=new Uint8Array(J-$);if(Y!==-1)for(let j=Y;j<this._cache.length;j++){let U=this._cache[j];if(U.start>=J)break;let q=Math.max($,U.start);if(q>Q)this._throwDueToCacheMiss();let N=Math.min(J,U.end);if(q<N)Z.set(U.bytes.subarray(q-U.start,N-U.start),q-$),Q=N}if(Q===J)return{bytes:Z,view:l(Z),offset:$};if(this._currentIndex>Q)this._throwDueToCacheMiss();let{promise:K,resolve:G,reject:W}=q0();if(this._pendingSlices.push({start:$,end:J,bytes:Z,resolve:G,reject:W}),this._targetIndex=Math.max(this._targetIndex,J),!this._pulling)this._pulling=!0,this._pull().catch((j)=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach((U)=>U.reject(j)),this._pendingSlices.length=0;else throw j});return K}_throwDueToCacheMiss(){throw Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){this._reader??=this._stream.getReader();while(this._currentIndex<this._targetIndex&&!this._disposed){let{done:$,value:J}=await this._reader.read();if($){for(let Q of this._pendingSlices)Q.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let Y=this._currentIndex,X=this._currentIndex+J.byteLength;this._dispatchRead(Y,X);for(let Q=0;Q<this._pendingSlices.length;Q++){let Z=this._pendingSlices[Q],K=Math.max(Y,Z.start),G=Math.min(X,Z.end);if(K<G){if(Z.bytes.set(J.subarray(K-Y,G-Y),K-Z.start),G===Z.end)Z.resolve({bytes:Z.bytes,view:l(Z.bytes),offset:Z.start}),this._pendingSlices.splice(Q,1),Q--}}this._cache.push({start:Y,end:X,bytes:J,view:l(J),age:0});while(this._cache.length>0){let Q=this._cache[0];if(this._maxRequestedIndex-Q.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=J.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}var j2={none:($,J)=>({start:$,end:J}),fileSystem:($,J)=>{return $=Math.floor(($-65536)/65536)*65536,J=Math.ceil((J+65536)/65536)*65536,{start:$,end:J}},network:($,J,Y)=>{$=Math.max(0,Math.floor(($-65536)/65536)*65536);for(let Q of Y){let K=Math.max((Q.startPos+Q.targetPos)/2,Q.targetPos-8388608);if(P$($,J,K,Q.targetPos)){let G=Q.targetPos-Q.startPos,W=Math.ceil((G+1)/8388608)*8388608,j=2**Math.ceil(Math.log2(G+1)),U=Math.min(j,W);J=Math.max(J,Q.startPos+U)}}return J=Math.max(J,$+K2),{start:$,end:J}}};class gX{constructor($){this.options=$,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read($,J,Y,X){F(!this.disposed);let Q=this.options.prefetchProfile($,J,this.workers),Z=Math.max(Q.start,Y),K=Math.min(Q.end,this.fileSize??1/0,X);F(Z<=$&&J<=K);let G=null,W=p(this.cache,$,(L)=>L.start),j=W!==-1?this.cache[W]:null;if(j&&j.start<=$&&J<=j.end)j.age=this.nextAge++,G={bytes:j.bytes,view:j.view,offset:j.start};let U=p(this.cache,Z,(L)=>L.start),q=G?null:new Uint8Array(J-$),N=0,_=Z,V=[];if(U!==-1){for(let L=U;L<this.cache.length;L++){let w=this.cache[L];if(w.start>=K)break;if(w.end<=Z)continue;let O=Math.max(Z,w.start),D=Math.min(K,w.end);if(F(O<=D),_<O)V.push({start:_,end:O});if(_=D,q){let B=Math.max($,w.start),C=Math.min(J,w.end);if(B<C){let E=B-$;if(q.set(w.bytes.subarray(B-w.start,C-w.start),E),E===N)N=C-$}}w.age=this.nextAge++}if(_<K)V.push({start:_,end:K})}else V.push({start:Z,end:K});if(q&&N>=q.length)G={bytes:q,view:l(q),offset:$};if(V.length===0)return F(G),G;let{promise:z,resolve:R,reject:H}=q0(),A=[];for(let L of V){let w=Math.max($,L.start),O=Math.min(J,L.end);if(w===L.start&&O===L.end)A.push(L);else if(w<O)A.push({start:w,end:O})}let M=q&&{start:$,bytes:q,holes:A,resolve:R,reject:H};$:for(let L of V){for(let D of this.workers)if(this.checkHoleAgainstWorker(D,L,M?[M]:[])){this.checkQueuedReadsAgainstWorker(D);continue $}let w=L.end<K||this.fileSize!==null,O=this.createWorker(L.start,L.end,w);if(O){if(M)O.pendingSlices=[M];this.runWorker(O)}else{let D=p(this.queuedReads,L.start,(C)=>C.hole.start),B=D!==-1?this.queuedReads[D]:null;if(B&&L.start<=B.hole.end){if(B.hole.end=Math.max(B.hole.end,L.end),B.strictTarget&&=w,M)B.pendingSlices.push(M)}else D++,B={hole:{start:L.start,end:L.end},strictTarget:w,pendingSlices:M?[M]:[],age:this.nextAge++},this.queuedReads.splice(D,0,B);while(D+1<this.queuedReads.length){let C=this.queuedReads[D+1];if(C.hole.start>B.hole.end)break;B.hole.end=Math.max(B.hole.end,C.hole.end),B.pendingSlices.push(...C.pendingSlices),B.strictTarget&&=C.strictTarget,B.age=Math.min(B.age,C.age),this.queuedReads.splice(D+1,1)}}}if(!G)F(q),G=z.then((L)=>L&&{bytes:L,view:l(L),offset:$});else z.catch((L)=>{if(this.disposed)return;throw L});return G}checkHoleAgainstWorker($,J,Y){if(P$(J.start-131072,J.start,$.currentPos,$.targetPos)){$.targetPos=Math.max($.targetPos,J.end);for(let Q=0;Q<Y.length;Q++){let Z=Y[Q];if(!$.pendingSlices.includes(Z))$.pendingSlices.push(Z)}if(!$.running)this.runWorker($);return!0}return!1}checkQueuedReadsAgainstWorker($){let J=!1;for(let Y=0;Y<this.queuedReads.length;Y++){let X=this.queuedReads[Y];if(this.checkHoleAgainstWorker($,X.hole,X.pendingSlices))this.queuedReads.splice(Y,1),Y--,J=!0;else if(J)break}}createWorker($,J,Y){if(this.workers.length>=this.options.maxWorkerCount){let Q=null,Z=null;for(let K=0;K<this.workers.length;K++){let G=this.workers[K];if(!G.running&&G.pendingSlices.length===0&&(!Q||G.age<Q.age))Z=K,Q=G}if(Q)F(Z!==null),F(Q.pendingSlices.length===0),this.workers.splice(Z,1);else return null}let X={startPos:$,currentPos:$,targetPos:J,strictTarget:Y,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(X),X}runWorker($){F(!$.running),F($.currentPos<$.targetPos),$.running=!0,$.age=this.nextAge++,this.options.runWorker($).catch((J)=>{if($.running=!1,$.pendingSlices.length>0)$.pendingSlices.forEach((Y)=>Y.reject(J)),$.pendingSlices.length=0;else if(!$.aborted&&!this.disposed)throw J}).finally(()=>{if($.running)return;if(this.queuedReads.length>0){let J=0;for(let Q=1;Q<this.queuedReads.length;Q++)if(this.queuedReads[Q].age<this.queuedReads[J].age)J=Q;let Y=this.queuedReads[J],X=this.createWorker(Y.hole.start,Y.hole.end,Y.strictTarget);if(!X)return;this.queuedReads.splice(J,1),X.pendingSlices=Y.pendingSlices,this.runWorker(X)}})}consolidateEverythingIntoOneWorker($){let J=new Set($.pendingSlices);for(let Y=0;Y<this.workers.length;Y++){let X=this.workers[Y];if(X===$)continue;for(let Q of X.pendingSlices)J.add(Q);X.aborted=!0,X.pendingSlices.length=0,this.workers.splice(Y,1),Y--}for(let Y=0;Y<this.queuedReads.length;Y++){let X=this.queuedReads[Y];for(let Q of X.pendingSlices)J.add(Q)}$.pendingSlices=[...J],this.queuedReads.length=0}supplyWorkerData($,J){F(!$.aborted);let Y=$.currentPos,X=Y+J.length;if(this.insertIntoCache({start:Y,end:X,bytes:J,view:l(J),age:this.nextAge++}),$.currentPos+=J.length,$.currentPos>$.targetPos)$.targetPos=$.currentPos,this.checkQueuedReadsAgainstWorker($);for(let Q=0;Q<$.pendingSlices.length;Q++){let Z=$.pendingSlices[Q],K=Math.max(Y,Z.start),G=Math.min(X,Z.start+Z.bytes.length);if(K<G)Z.bytes.set(J.subarray(K-Y,G-Y),K-Z.start);for(let W=0;W<Z.holes.length;W++){let j=Z.holes[W];if(Y<=j.start&&X>j.start)j.start=X;if(j.end<=j.start)Z.holes.splice(W,1),W--}if(Z.holes.length===0)Z.resolve(Z.bytes),$.pendingSlices.splice(Q,1),Q--}for(let Q=0;Q<this.workers.length;Q++){let Z=this.workers[Q];if($===Z||Z.running)continue;if(P$(Y,X,Z.currentPos,Z.targetPos))this.workers.splice(Q,1),Q--}}supplyFileSize($){F(this.fileSize===null),this.fileSize=$;for(let J of this.workers){J.targetPos=Math.min(J.targetPos,$),J.strictTarget=!0;for(let Y=0;Y<J.pendingSlices.length;Y++){let X=J.pendingSlices[Y];for(let Q of X.holes)if(Q.end>$){X.resolve(null),J.pendingSlices.splice(Y,1),Y--;break}}}for(let J=0;J<this.queuedReads.length;J++){let Y=this.queuedReads[J];if(Y.hole.start>=$){for(let X of Y.pendingSlices)X.resolve(null);this.queuedReads.splice(J,1),J--}else if(Y.hole.end>$){Y.hole.end=$,Y.strictTarget=!0;for(let X=0;X<Y.pendingSlices.length;X++){let Q=Y.pendingSlices[X];if(Q.start>=$)Q.resolve(null),Y.pendingSlices.splice(X,1),X--}}}}signalWorkerStoppedRunning($){$.running=!1,$.pendingSlices.length=0}onWorkerFinished($){let J=this.workers.indexOf($);if(F(J!==-1),$.running=!1,this.workers.splice(J,1),this.fileSize===null)this.supplyFileSize($.currentPos);for(let Y of $.pendingSlices)Y.resolve(null)}insertIntoCache($){if(this.options.maxCacheSize===0)return;let J=p(this.cache,$.start,(Y)=>Y.start)+1;if(J>0){let Y=this.cache[J-1];if(Y.end>=$.end)return;if(Y.end>$.start){let X=new Uint8Array($.end-Y.start);X.set(Y.bytes,0),X.set($.bytes,$.start-Y.start),this.currentCacheSize+=$.end-Y.end,Y.bytes=X,Y.view=l(X),Y.end=$.end,J--,$=Y}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length;for(let Y=J+1;Y<this.cache.length;Y++){let X=this.cache[Y];if($.end<=X.start)break;if($.end>=X.end){this.cache.splice(Y,1),this.currentCacheSize-=X.bytes.length,Y--;continue}let Q=new Uint8Array(X.end-$.start);Q.set($.bytes,0),Q.set(X.bytes,X.start-$.start),this.currentCacheSize-=$.end-X.start,$.bytes=Q,$.view=l(Q),$.end=X.end,this.cache.splice(Y,1);break}while(this.currentCacheSize>this.options.maxCacheSize){let Y=0,X=this.cache[0];for(let Q=1;Q<this.cache.length;Q++){let Z=this.cache[Q];if(Z.age<X.age)Y=Q,X=Z}if(this.currentCacheSize-X.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(Y,1),this.currentCacheSize-=X.bytes.length}}dispose(){for(let $ of this.workers)$.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}class nY extends Z1{constructor($,J,Y){super();if(this._ref=null,$._disposed)throw Error("Cannot create a slice of a disposed source.");this._baseSource=$,this._offset=J,this._length=Y??null}_getFileSize(){let $=this._baseSource._getFileSize();if($===void 0)return this._length!==null?this._length:void 0;if($===null)if(this._length!==null)return this._length;else return null;return r0($-this._offset,0,this._length??1/0)}_read($,J,Y,X){if(this._length!==null&&J>this._length)return null;let Q=this._baseSource._read(this._offset+$,this._offset+J,this._offset+Y,this._offset+X),Z=(K)=>{if(!K)return null;return K.offset-=this._offset,K};if(Q instanceof Promise)return Q.then(Z);else return Z(Q)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}/*!
|
|
200
200
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
201
201
|
*
|
|
202
202
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
203
203
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
204
204
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
205
|
-
*/class kY extends L0{constructor($){super($);this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{L(this.input._rootSource instanceof R1);let{rootPath:$}=this.input._rootSource,J=await this.input._reader.requestEntireFile();L(J);let Y=r$(J,J.length,{ignore:c$}),X=[],Q=[];for(let U=1;U<Y.length;U++){let q=Y[U];if(q.startsWith(FY)){let V=U,_=Y[++U];if(_===void 0)throw Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");let N=J1($,_),R=new X8(q.slice(FY.length));if(R.getAsNumber("bandwidth")===null)throw Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");X.push({fullPath:N,attributes:R,lineNumber:V,hasOnlyKeyPackets:!1})}else if(q.startsWith(wY)){let V=new X8(q.slice(wY.length)),_=V.get("uri");if(_===null)throw Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(V.getAsNumber("bandwidth")===null)throw Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let R=J1($,_);X.push({fullPath:R,attributes:V,lineNumber:U,hasOnlyKeyPackets:!0})}else if(q.startsWith(OY)){let V=new X8(q.slice(OY.length));if(V.get("type")===null)throw Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(V.get("group-id")===null)throw Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let R=null,z=V.get("uri");if(z!==null)R=J1($,z);Q.push({fullPath:R,attributes:V,lineNumber:U})}else if(q===SX);else if(q.startsWith(J$)){let V=new s$(this,$,null,Y);this.segmentedInputs=[V],this.hasMasterPlaylist=!1,this.trackBackings=await V.getTrackBackings();return}}let Z=[...new Set(Q.filter((U)=>U.attributes.get("type").toLowerCase()==="video").map((U)=>U.attributes.get("group-id")))],K=[...new Set(Q.filter((U)=>U.attributes.get("type").toLowerCase()==="audio").map((U)=>U.attributes.get("group-id")))],G=await Promise.all(X.map(async(U,q)=>{let V=[],_=U.attributes.get("codecs"),N;if(_)N=_.split(",").map((w)=>w.trim());else{let P=await this.getSegmentedInputForPath(U.fullPath).getTrackBackings(),T=await Promise.all(P.map(async(C)=>({track:C,codec:await C.getCodec()})));N=await Promise.all(T.filter((C)=>C.codec!==null).map((C)=>C.track.getDecoderConfig().then((E)=>E.codec)))}let R=U.attributes.get("video"),z=U.attributes.get("audio"),H=N.some((w)=>T1.includes(a1(w))),A=N.some((w)=>v1.includes(a1(w)));if(R!==null&&!H){if(!Z.includes(R))throw Error(`Invalid M3U8 file; variant stream references video group "${R}" which is not defined in any #EXT-X-MEDIA tags.`);let w=Q.find((P)=>{let T=P.attributes.get("group-id"),C=P.attributes.get("type");return T===R&&C.toLowerCase()==="video"});$:if(w){let P=w.attributes.get("uri");if(P===null)break $;let T=J1($,P),v=(await this.getSegmentedInputForPath(T).getTrackBackings()).find((S)=>S.getType()==="video");if(!v||await v.getCodec()===null)break $;let x=await v.getDecoderConfig().then((S)=>S?.codec??null);L(x!==null),N.push(x)}}if(z!==null&&!A){if(!K.includes(z))throw Error(`Invalid M3U8 file; variant stream references audio group "${z}" which is not defined in any #EXT-X-MEDIA tags.`);let w=Q.find((P)=>{let T=P.attributes.get("group-id"),C=P.attributes.get("type");return T===z&&C.toLowerCase()==="audio"});$:if(w){let P=w.attributes.get("uri");if(P===null)break $;let T=J1($,P),v=(await this.getSegmentedInputForPath(T).getTrackBackings()).find((S)=>S.getType()==="audio");if(!v||await v.getCodec()===null)break $;let x=await v.getDecoderConfig().then((S)=>S?.codec??null);L(x!==null),N.push(x)}}N=[...new Set(N)];let M=null,F=null,O=U.attributes.getAsNumber("bandwidth");L(O!==null);let B=U.attributes.getAsNumber("average-bandwidth"),D=U.attributes.get("name");for(let w of N){let P=a1(w);if(P===null)continue;if(T1.includes(P)){if(M!==null)throw Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");M=w;let T=U.attributes.get("video");if(T===null){let C=U.attributes.get("resolution"),E=null,v=null;if(C){let x=C.match(/^(\d+)x(\d+)$/);if(x)E=Number(x[1]),v=Number(x[2])}V.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Z0,lineNumber:U.lineNumber,fullPath:U.fullPath,fullCodecString:M,pairingMask:1n<<BigInt(q),peakBitrate:O,averageBitrate:B,name:D,hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"video",width:E,height:v}})}else{if(!Z.includes(T))throw Error(`Invalid M3U8 file; variant stream references video group "${T}" which is not defined in any #EXT-X-MEDIA tags.`);for(let C of Q){let E=C.attributes.get("group-id"),v=C.attributes.get("type");if(E!==T||v.toLowerCase()!=="video")continue;let x=C.attributes.get("resolution")??U.attributes.get("resolution"),S=null,k=null;if(x){let m=x.match(/^(\d+)x(\d+)$/);if(m)S=Number(m[1]),k=Number(m[2])}V.push({id:-1,demuxer:this,backingTrack:null,default:i$(C.attributes),autoselect:i$(C.attributes)||mX(C.attributes),languageCode:lX(C.attributes.get("language")),lineNumber:C.lineNumber,fullPath:C.fullPath??U.fullPath,fullCodecString:M,pairingMask:1n<<BigInt(q),peakBitrate:null,averageBitrate:null,name:C.attributes.get("name"),hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"video",width:S,height:k}})}}}else if(v1.includes(P)){if(F!==null)throw Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");F=w;let T=U.attributes.get("audio");if(T===null){let C=U.attributes.get("channels"),E=C!==null?Number(C.split("/")[0]):null;V.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Z0,lineNumber:U.lineNumber,fullPath:U.fullPath,fullCodecString:F,pairingMask:1n<<BigInt(q),peakBitrate:O,averageBitrate:B,name:D,hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:E!==null&&Number.isInteger(E)&&E>0?E:null}})}else{if(!K.includes(T))throw Error(`Invalid M3U8 file; variant stream references audio group "${T}" which is not defined in any #EXT-X-MEDIA tags.`);for(let C of Q){let E=C.attributes.get("group-id"),v=C.attributes.get("type");if(E!==T||v.toLowerCase()!=="audio")continue;let x=C.attributes.get("channels")??U.attributes.get("channels"),S=x!==null?Number(x.split("/")[0]):null;V.push({id:-1,demuxer:this,backingTrack:null,default:i$(C.attributes),autoselect:i$(C.attributes)||mX(C.attributes),languageCode:lX(C.attributes.get("language")),lineNumber:C.lineNumber,fullPath:C.fullPath??U.fullPath,fullCodecString:F,pairingMask:1n<<BigInt(q),peakBitrate:null,averageBitrate:null,name:C.attributes.get("name"),hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:S!==null&&Number.isInteger(S)&&S>0?S:null}})}}}}return V})),W=[],j=(U)=>{let q=W.find((V)=>V.fullPath===U.fullPath&&V.info.type===U.info.type);if(q){if(q.pairingMask|=U.pairingMask,q.default||=U.default,q.autoselect||=U.autoselect,q.lineNumber=Math.min(q.lineNumber,U.lineNumber),U.peakBitrate!==null)q.peakBitrate=Math.max(q.peakBitrate??-1/0,U.peakBitrate);if(U.averageBitrate!==null)q.averageBitrate=Math.max(q.averageBitrate??-1/0,U.averageBitrate);if(q.languageCode===Z0)q.languageCode=U.languageCode}else U.id=W.length+1,W.push(U)};for(let U of G)for(let q of U)j(q);W.sort((U,q)=>U.lineNumber-q.lineNumber),this.trackBackings=[];for(let U of W)if(U.info.type==="video")this.trackBackings.push(new mY(U));else this.trackBackings.push(new lY(U));this.internalTracks=W})()}async getTrackBackings(){return await this.readMetadata(),L(this.trackBackings),this.trackBackings}getSegmentedInputForPath($){let J=this.segmentedInputs.find((X)=>X.path===$);if(J)return J;let Y=null;if(this.internalTracks)Y=this.internalTracks.filter((Q)=>Q.fullPath===$).map((Q)=>({id:Q.id,type:Q.info.type}));return J=new s$(this,$,Y,null),this.segmentedInputs.push(J),J}async getMetadataTags(){return{}}async getMimeType(){return R6}dispose(){if(this.segmentedInputs){for(let $ of this.segmentedInputs)$.dispose();this.segmentedInputs.length=0}}}class uY{constructor($){this.internalTrack=$,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let $=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),J=null,X=(await $.getTrackBackings()).filter((Q)=>Q.getType()===this.getType());if(X.length===1)J=X[0];else if(this instanceof mY){for(let Q of X)if(await Q.getCodec()===this.getCodec()){J=Q;break}}else{L(this instanceof lY);for(let Q of X)if(await Q.getCodec()===this.getCodec()){J=Q;break}}if(!J)throw Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=J})()}delegate($){if(this.internalTrack.backingTrack)return $();return this.hydrate().then($)}getCodec(){throw Error("Not implemented on base class.")}getDisposition(){return{...M0,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){L(this.internalTrack.demuxer.internalTracks);let $=this.internalTrack.info.type,J=0;for(let Y of this.internalTrack.demuxer.internalTracks){if(Y.info.type===$)J++;if(Y===this.internalTrack)break}return J}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata($){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata($)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket($){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket($)}async getPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getPacket($,J)}async getKeyPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket($,J)}async getNextPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket($,J)}async getNextKeyPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket($,J)}}class mY extends uY{constructor($){super($)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return a1(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){if(this.backingVideoTrack)return null;return this.internalTrack.info.width}getMetadataDisplayHeight(){if(this.backingVideoTrack)return null;return this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){if(this.backingVideoTrack)return null;return this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class lY extends uY{constructor($){super($)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return a1(this.internalTrack.fullCodecString)}getNumberOfChannels(){if(this.internalTrack.info.numberOfChannels!==null)return this.internalTrack.info.numberOfChannels;return this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){if(this.backingAudioTrack)return null;return this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}var i$=($)=>{let J=$.get("default");if(J===null)return!1;let Y=J.toUpperCase();if(Y==="YES")return!0;if(Y==="NO")return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${J}".`)},mX=($)=>{let J=$.get("autoselect");if(J===null)return!1;let Y=J.toUpperCase();if(Y==="YES")return!0;if(Y==="NO")return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${J}".`)},lX=($)=>{if($===null)return Z0;let J=$.split("-")[0];if(!J)return Z0;return J};/*!
|
|
205
|
+
*/var kX=function($,J,Y){if(J!==null&&J!==void 0){if(typeof J!=="object"&&typeof J!=="function")throw TypeError("Object expected.");var X,Q;if(Y){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");X=J[Symbol.asyncDispose]}if(X===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(X=J[Symbol.dispose],Y)Q=X}if(typeof X!=="function")throw TypeError("Object not disposable.");if(Q)X=function(){try{Q.call(this)}catch(Z){return Promise.reject(Z)}};$.stack.push({value:J,dispose:X,async:Y})}else if(Y)$.stack.push({async:!0});return J},uX=function($){return function(J){function Y(K){J.error=J.hasError?new $(K,J.error,"An error was suppressed during disposal."):K,J.hasError=!0}var X,Q=0;function Z(){while(X=J.stack.pop())try{if(!X.async&&Q===1)return Q=0,J.stack.push(X),Promise.resolve().then(Z);if(X.dispose){var K=X.dispose.call(X.value);if(X.async)return Q|=2,Promise.resolve(K).then(Z,function(G){return Y(G),Z()})}else Q|=1}catch(G){Y(G)}if(Q===1)return J.hasError?Promise.reject(J.error):Promise.resolve();if(J.hasError)throw J.error}return Z()}}(typeof SuppressedError==="function"?SuppressedError:function($,J,Y){var X=Error(Y);return X.name="SuppressedError",X.error=$,X.suppressed=J,X}),q2=/^0[xX][0-9a-fA-F]+$/,N2=/^data:.*;base64,/i;class $J extends mY{constructor($,J,Y,X){super($.input,J,Y);this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=J,this.demuxer=$,this.nextLines=X}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let $=this.getRemainingWaitTimeMs();if($>0)await J6($);this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let $=performance.now()-this.lastSegmentUpdateTime,J=Math.max(0,1000*this.refreshInterval-$);if(J<=50)return 0;return J}async updateSegments(){let $=this.nextLines;if(this.nextLines=null,!$){let A={stack:[],error:void 0,hasError:!1};try{let M=kX(A,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),w=await new l8(M.source).requestEntireFile();if(F(w),$=JJ(w,w.length,{ignore:a$}),M.source instanceof Q1)this.rootPath=M.source.rootPath}catch(M){A.error=M,A.hasError=!0}finally{uX(A)}}let J=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,Y=!1,X=0,Q=null,Z=null,K=null,G=0,W=null,j=null,U=null,q=null,N=null,_=null,V=!1,z=W0(this.segments)??null,R=(A)=>{let M=A.indexOf("@"),L=Number(M===-1?A:A.slice(0,M));if(!Number.isInteger(L)||L<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${A}'.`);let w=null;if(M!==-1){if(w=Number(A.slice(M+1)),!Number.isInteger(w)||w<0)throw Error(`Invalid #EXT-X-BYTERANGE offset '${A}'.`)}return{length:L,offset:w}},H=(A)=>{if(G=A,z){if(F(z.sequenceNumber!==null),z.sequenceNumber<A)X=z.timestamp+z.duration,W=z.firstSegment,j=z.initSegment,N=z.lastProgramDateTimeSeconds,Q=z.unixEpochTimestamp!==null?z.unixEpochTimestamp+z.duration:null,z=null}};for(let A=0;A<$.length;A++){let M=$[A];if(!Y){if(M!=="#EXTM3U")throw Error("Invalid M3U8 file; expected first line to be #EXTM3U.");Y=!0;continue}if(!M.startsWith("#")){if(!z){if(Z===null)throw Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let L=K;if(L&&L.method==="AES-128"&&!L.iv){let B=new Uint8Array(N1),C=l(B);C.setUint32(8,Math.floor(G/4294967296)),C.setUint32(12,G),L={...L,iv:B}}let O={path:U1(this.rootPath,M),offset:q?.offset??0,length:q?.length??null},D={timestamp:X,unixEpochTimestamp:Q,firstSegment:W,sequenceNumber:G,location:O,duration:Z,encryption:L,initSegment:j,lastProgramDateTimeSeconds:N};if(W??=D,X+=Z,Q!==null)Q+=Z;this.segments.push(D)}if(Z=null,q===null)U=null;else q=null;H(G+1)}if(M.startsWith(W$)){if(z){V=!0;continue}if(!V){if(N===null&&G>0&&_!==null)X=G*_;V=!0}let L=M.slice(W$.length),w=L.indexOf(","),O=w===-1?L:L.slice(0,w),D=Number(O);if(!Number.isFinite(D)||D<0)throw Error(`Invalid #EXTINF tag duration '${O}'.`);Z=D}else if(M.startsWith(xY)){let L=new j8(M.slice(xY.length)),w=L.get("uri");if(!w)throw Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let O=L.get("byterange"),D=null;if(O!==null)D=R(O);if(D&&D.offset===null)throw Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!z){let C={path:U1(this.rootPath,w),offset:D?.offset??0,length:D?.length??null};if(K?.method==="AES-128"&&!K.iv)throw Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");j={timestamp:X,unixEpochTimestamp:Q,firstSegment:null,sequenceNumber:null,location:C,duration:0,encryption:K,initSegment:null,lastProgramDateTimeSeconds:N}}if(Z=null,q===null)U=null;else q=null}else if(M.startsWith(IY)){let L=new j8(M.slice(IY.length)),w=L.get("method");if(w==="NONE")K=null;else if(w==="AES-128"){let O=L.get("uri");if(!O)throw Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let D=null,B=L.get("iv");if(B){if(!q2.test(B))throw Error(`Unsupported IV format '${B}'.`);let E=B.slice(2);E=E.padStart(N1*2,"0"),D=new Uint8Array(N1);for(let P=0;P<N1;P++){let v=-N1*2+P;D[P]=parseInt(E.slice(v,v+2),16)}}let C=L.get("keyformat")??"identity";if(C!=="identity")throw Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");K={method:"AES-128",keyUri:U1(this.rootPath,O),iv:D,keyFormat:C}}else if(w==="SAMPLE-AES"||w==="SAMPLE-AES-CTR"){let O=L.get("uri");if(!O)throw Error(`Invalid #EXT-X-KEY: ${w} requires a URI attribute.`);if((L.get("keyformat")??"identity")==="identity")throw Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let B=null;if(N2.test(O)){let C=O.indexOf(","),E=c6(O.slice(C+1));if(E.length>=8&&E[4]===112&&E[5]===115&&E[6]===115&&E[7]===104){let P=l(E).getUint32(0);B=f$(E.subarray(8,Math.min(P,E.length)))}}K={method:w,psshBox:B}}else throw Error(`Unsupported encryption method '${w}'. If you think this method should be supported, please raise an issue.`)}else if(M.startsWith(yY)){let L=M.slice(yY.length),w=Number(L);if(!Number.isInteger(w)||w<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${L}'.`);H(w)}else if(M.startsWith(SY)){let L=R(M.slice(SY.length));if(L.offset===null){if(U===null)throw Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");L.offset=U}q=L,U=L.offset+L.length}else if(M.startsWith(hY)){if(z)continue;let L=M.slice(hY.length),w=Date.parse(L);if(!Number.isFinite(w))continue;let O=w/1000;if(N===O)continue;if(N===null&&this.segments.length>0){let D=W0(this.segments),B=D.timestamp+D.duration,C=O-B;for(let E of this.segments)if(E.unixEpochTimestamp=E.timestamp+C,J)E.timestamp=E.unixEpochTimestamp}if(N=O,Q=O,J)X=O}else if(M===yX)W=null;else if(M.startsWith(fY)){let L=M.slice(fY.length),w=Number(L);if(!Number.isFinite(w)||w<0)throw Error(`Invalid EXT-X-TARGETDURATION value '${L}'.`);this.refreshInterval=w,_=w}else if(M===SX){this.streamHasEnded=!0;break}else if(M.startsWith(gY)){if(M.slice(gY.length).toLowerCase()==="vod")this.streamHasEnded=!0}}if(!Y)throw Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){if(this.segments.length===0)await this.runUpdateSegments();return this.segments[0]??null}async getSegmentAt($,J){if(this.segments.length===0)await this.runUpdateSegments();let Y=!!J.skipLiveWait&&this.getRemainingWaitTimeMs()>0;while(!0){let X=p(this.segments,$,(Z)=>Z.timestamp);if(X===-1)return null;if(X<this.segments.length-1||this.streamHasEnded||Y)return this.segments[X];let Q=this.segments[X];if($<Q.timestamp+Q.duration)return Q;if(await this.runUpdateSegments(),J.skipLiveWait)Y=!0}}async getNextSegment($,J){let Y=this.segments.indexOf($);F(Y!==-1);let X=Y+1,Q=!!J.skipLiveWait&&this.getRemainingWaitTimeMs()>0;while(!0){if(X<this.segments.length)return this.segments[X];if(this.streamHasEnded||Q)return null;if(await this.runUpdateSegments(),J.skipLiveWait)Q=!0}}async getPreviousSegment($){let J=this.segments.indexOf($);return F(J!==-1),this.segments[J-1]??null}getInputForSegment($){let J=$,Y=this.inputCache.find((G)=>G.segment===J);if(Y)return Y.age=this.nextInputCacheAge++,Y.input;let X=null;if(J.initSegment||J.firstSegment)X=this.getInputForSegment(J.initSegment??J.firstSegment);let Q={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&((G)=>{if(!J.encryption||!(J.encryption.method==="SAMPLE-AES"||J.encryption.method==="SAMPLE-AES-CTR")||!J.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(G);let W=G.psshBoxes,{psshBox:j}=J.encryption;if((j.keyIds===null||j.keyIds.includes(G.keyId))&&!W.some((U)=>g$(U,j)))W=[...W,j];return this.input._formatOptions.isobmff.resolveKeyId({...G,psshBoxes:W})})}},Z=new C1({source:new t$(J.location.path,async(G)=>{F(G.isRoot);let W={...G,isRoot:!1},j,U=J.location.offset>0||J.location.length!==null;if(!J.encryption||J.encryption.method==="SAMPLE-AES"||J.encryption.method==="SAMPLE-AES-CTR"){if(j=await this.input._getSourceCached(W),U){let N=j.source.slice(J.location.offset,J.location.length??void 0).ref();j.free(),j=N}}else if(J.encryption.method==="AES-128"){let q=J.encryption;F(q.iv);let N=await this.input._getSourceCached(W);if(U){let R=N.source.slice(J.location.offset,J.location.length??void 0).ref();N.free(),N=R}let _=new l8(N.source),V=ZX(_,async()=>{let z={stack:[],error:void 0,hasError:!1};try{let R=kX(z,await this.input._getSourceCached({path:q.keyUri,isRoot:!1},mX),!1),A=await new l8(R.source).requestSlice(0,N1);if(!A)throw Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:f(A,N1),iv:q.iv}}catch(R){z.error=R,z.hasError=!0}finally{uX(z)}},()=>{N.free()});j=new e$(V).ref()}else F(!1);return j}),formats:this.input._formats.filter((G)=>!(G instanceof U$)),initInput:X??void 0,formatOptions:Q});Z._onFormatDetermined=(G)=>{if((J.encryption?.method==="SAMPLE-AES"||J.encryption?.method==="SAMPLE-AES-CTR")&&!G._isIsobmff)throw Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:J,input:Z,age:this.nextInputCacheAge++});let K=4;if(this.inputCache.length>K){let G=$6(this.inputCache,(W)=>W.age);F(G!==-1),this.inputCache.splice(G,1)}return Z}async getLiveRefreshInterval(){if(this.getRemainingWaitTimeMs()===0)await this.runUpdateSegments();return this.streamHasEnded?null:this.refreshInterval}}/*!
|
|
206
206
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
207
207
|
*
|
|
208
208
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
209
209
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
210
210
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
211
|
-
*/class c0{constructor(){this._isIsobmff=!1}}class a$ extends c0{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return null;J.skip(4);let Y=J0(J,4);if(Y!=="ftyp"&&Y!=="styp")return null;return J0(J,4)}_createDemuxer($){return new h$($)}}class pY extends a${async _canReadInput($){let J=await this._getMajorBrand($);if(J!==null)return J!=="qt ";let Y=$._reader.requestSlice(4,4);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=J0(Y,4);return X==="moof"||X==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class dY extends a${async _canReadInput($){return await this._getMajorBrand($)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class t$ extends c0{async isSupportedEBMLOfDocType($,J){let Y=$._reader.requestSlice(0,Q1);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=tJ(Y);if(X===null)return!1;if(X<1||X>8)return!1;if(d(Y,X)!==b.EBML)return!1;let Z=eJ(Y);if(typeof Z!=="number")return!1;let K=$._reader.requestSlice(Y.filePos,Z);if(K instanceof Promise)K=await K;if(!K)return!1;let G=Y.filePos;while(K.filePos<=G+Z-u0){let W=K1(K);if(!W)break;let{id:j,size:U}=W,q=K.filePos;if(U===void 0)return!1;switch(j){case b.EBMLVersion:if(d(K,U)!==1)return!1;break;case b.EBMLReadVersion:if(d(K,U)!==1)return!1;break;case b.DocType:if(J8(K,U)!==J)return!1;break;case b.DocTypeVersion:if(d(K,U)>4)return!1;break}K.filePos=q+U}return!0}_canReadInput($){return this.isSupportedEBMLOfDocType($,"matroska")}_createDemuxer($){return new XY($)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class cY extends t${_canReadInput($){return this.isSupportedEBMLOfDocType($,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class nY extends c0{async _canReadInput($){let J=0;while(!0){let U=$._reader.requestSlice(J,d0);if(U instanceof Promise)U=await U;if(!U)break;let q=G1(U);if(!q)break;J=U.filePos+q.size}let Y=await t6($._reader,J,J+4096);if(!Y)return!1;let X=Y.header,Q=$6(X.mpegVersionId,X.channel),Z=$._reader.requestSlice(Y.startPos+Q,4);if(Z instanceof Promise)Z=await Z;if(!Z)return!1;let K=I(Z);if(K===e8||K===m6)return!0;J=Y.startPos+Y.header.totalSize;let W=await t6($._reader,J,J+V1);if(!W)return!1;let j=W.header;if(X.channel!==j.channel||X.sampleRate!==j.sampleRate)return!1;return!0}_createDemuxer($){return new QY($)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class oY extends c0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=J0(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),J0(J,4)==="WAVE"}_createDemuxer($){return new NY($)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class sY extends c0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return J0(J,4)==="OggS"}_createDemuxer($){return new jY($)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class rY extends c0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return J0(J,4)==="fLaC"}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer($){return new RY($)}}class iY extends c0{async _canReadInput($){let J=0;while(!0){let Z=$._reader.requestSlice(J,d0);if(Z instanceof Promise)Z=await Z;if(!Z)break;let K=G1(Z);if(!K)break;J=Z.filePos+K.size}let Y=$._reader.requestSliceRange(J,y8,U1);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=z1(Y);if(!X)return!1;if(J+=X.frameLength,Y=$._reader.requestSliceRange(J,y8,U1),Y instanceof Promise)Y=await Y;if(!Y)return!1;let Q=z1(Y);if(!Q)return!1;return X.objectType===Q.objectType&&X.samplingFrequencyIndex===Q.samplingFrequencyIndex&&X.channelConfiguration===Q.channelConfiguration}_createDemuxer($){return new VY($)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class aY extends c0{async _canReadInput($){let J=I0+16+1,Y=$._reader.requestSlice(0,J);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=h(Y,J);if(X[0]===71&&X[I0]===71)return!0;else if(X[0]===71&&X[I0+16]===71)return!0;else if(X[4]===71&&X[4+I0+4]===71)return!0;return!1}_createDemuxer($){return new MY($)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Y$ extends c0{async _canReadInput($){let J=$._reader.requestSlice(0,7);if(J instanceof Promise)J=await J;if(!J)return!1;if(J0(J,7)!=="#EXTM3U")return!1;if(!($._rootSource instanceof R1))throw TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return $._rootSource._usedForHls=!0,!0}_createDemuxer($){return new kY($)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return R6}}var pX=new pY,dX=new dY,e$=new t$,$J=new cY,cX=new nY,nX=new oY,oX=new sY,sX=new iY,rX=new rY,iX=new aY,aX=new Y$,X$=[aX,pX,dX,e$,$J,nX,oX,rX,cX,sX,iX];var tX=($,J)=>{if(!$||typeof $!=="object")throw TypeError(`${J}, when provided, must be an object.`);if($.isobmff!==void 0){if(!$.isobmff||typeof $.isobmff!=="object")throw TypeError(`${J}.isobmff, when provided, must be an object.`);if($.isobmff.resolveKeyId!==void 0&&typeof $.isobmff.resolveKeyId!=="function")throw TypeError(`${J}.isobmff.resolveKeyId, when provided, must be a function.`)}};/*!
|
|
211
|
+
*/class sY extends P0{constructor($){super($);this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{F(this.input._rootSource instanceof Q1);let $=await this.input._reader.requestEntireFile();F($);let J=JJ($,$.length,{ignore:a$}),{rootPath:Y}=this.input._rootSource,X=[],Q=[];for(let U=1;U<J.length;U++){let q=J[U];if(q.startsWith(bY)){let N=U,_=J[++U];if(_===void 0)throw Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");let V=U1(Y,_),z=new j8(q.slice(bY.length));if(z.getAsNumber("bandwidth")===null)throw Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");X.push({fullPath:V,attributes:z,lineNumber:N,hasOnlyKeyPackets:!1})}else if(q.startsWith(TY)){let N=new j8(q.slice(TY.length)),_=N.get("uri");if(_===null)throw Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(N.getAsNumber("bandwidth")===null)throw Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let z=U1(Y,_);X.push({fullPath:z,attributes:N,lineNumber:U,hasOnlyKeyPackets:!0})}else if(q.startsWith(vY)){let N=new j8(q.slice(vY.length));if(N.get("type")===null)throw Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(N.get("group-id")===null)throw Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let z=null,R=N.get("uri");if(R!==null)z=U1(Y,R);Q.push({fullPath:z,attributes:N,lineNumber:U})}else if(q===hX);else if(q.startsWith(W$)){let N=new $J(this,Y,null,J);this.segmentedInputs=[N],this.hasMasterPlaylist=!1,this.trackBackings=await N.getTrackBackings();return}}let Z=[...new Set(Q.filter((U)=>U.attributes.get("type").toLowerCase()==="video").map((U)=>U.attributes.get("group-id")))],K=[...new Set(Q.filter((U)=>U.attributes.get("type").toLowerCase()==="audio").map((U)=>U.attributes.get("group-id")))],G=await Promise.all(X.map(async(U,q)=>{let N=[],_=U.attributes.get("codecs"),V;if(_)V=_.split(",").map((B)=>B.trim());else{let C=await this.getSegmentedInputForPath(U.fullPath).getTrackBackings(),E=await Promise.all(C.map(async(P)=>({track:P,codec:await P.getCodec()})));V=await Promise.all(E.filter((P)=>P.codec!==null).map((P)=>P.track.getDecoderConfig().then((v)=>v.codec)))}let z=U.attributes.get("video"),R=U.attributes.get("audio"),H=V.some((B)=>f1.includes(X8(B))),A=V.some((B)=>g1.includes(X8(B)));if(z!==null&&!H){if(!Z.includes(z))throw Error(`Invalid M3U8 file; variant stream references video group "${z}" which is not defined in any #EXT-X-MEDIA tags.`);let B=Q.find((C)=>{let E=C.attributes.get("group-id"),P=C.attributes.get("type");return E===z&&P.toLowerCase()==="video"});$:if(B){let C=B.attributes.get("uri");if(C===null)break $;let E=U1(Y,C),T=(await this.getSegmentedInputForPath(E).getTrackBackings()).find((I)=>I.getType()==="video");if(!T||await T.getCodec()===null)break $;let x=await T.getDecoderConfig().then((I)=>I?.codec??null);F(x!==null),V.push(x)}}if(R!==null&&!A){if(!K.includes(R))throw Error(`Invalid M3U8 file; variant stream references audio group "${R}" which is not defined in any #EXT-X-MEDIA tags.`);let B=Q.find((C)=>{let E=C.attributes.get("group-id"),P=C.attributes.get("type");return E===R&&P.toLowerCase()==="audio"});$:if(B){let C=B.attributes.get("uri");if(C===null)break $;let E=U1(Y,C),T=(await this.getSegmentedInputForPath(E).getTrackBackings()).find((I)=>I.getType()==="audio");if(!T||await T.getCodec()===null)break $;let x=await T.getDecoderConfig().then((I)=>I?.codec??null);F(x!==null),V.push(x)}}V=[...new Set(V)];let M=null,L=null,w=U.attributes.getAsNumber("bandwidth");F(w!==null);let O=U.attributes.getAsNumber("average-bandwidth"),D=U.attributes.get("name");for(let B of V){let C=X8(B);if(C===null)continue;if(f1.includes(C)){if(M!==null)throw Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");M=B;let E=U.attributes.get("video");if(E===null){let P=U.attributes.get("resolution"),v=null,T=null;if(P){let x=P.match(/^(\d+)x(\d+)$/);if(x)v=Number(x[1]),T=Number(x[2])}N.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:K0,lineNumber:U.lineNumber,fullPath:U.fullPath,fullCodecString:M,pairingMask:1n<<BigInt(q),peakBitrate:w,averageBitrate:O,name:D,hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"video",width:v,height:T}})}else{if(!Z.includes(E))throw Error(`Invalid M3U8 file; variant stream references video group "${E}" which is not defined in any #EXT-X-MEDIA tags.`);for(let P of Q){let v=P.attributes.get("group-id"),T=P.attributes.get("type");if(v!==E||T.toLowerCase()!=="video")continue;let x=P.attributes.get("resolution")??U.attributes.get("resolution"),I=null,S=null;if(x){let u=x.match(/^(\d+)x(\d+)$/);if(u)I=Number(u[1]),S=Number(u[2])}N.push({id:-1,demuxer:this,backingTrack:null,default:YJ(P.attributes),autoselect:YJ(P.attributes)||lX(P.attributes),languageCode:pX(P.attributes.get("language")),lineNumber:P.lineNumber,fullPath:P.fullPath??U.fullPath,fullCodecString:M,pairingMask:1n<<BigInt(q),peakBitrate:null,averageBitrate:null,name:P.attributes.get("name"),hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"video",width:I,height:S}})}}}else if(g1.includes(C)){if(L!==null)throw Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");L=B;let E=U.attributes.get("audio");if(E===null){let P=U.attributes.get("channels"),v=P!==null?Number(P.split("/")[0]):null;N.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:K0,lineNumber:U.lineNumber,fullPath:U.fullPath,fullCodecString:L,pairingMask:1n<<BigInt(q),peakBitrate:w,averageBitrate:O,name:D,hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:v!==null&&Number.isInteger(v)&&v>0?v:null}})}else{if(!K.includes(E))throw Error(`Invalid M3U8 file; variant stream references audio group "${E}" which is not defined in any #EXT-X-MEDIA tags.`);for(let P of Q){let v=P.attributes.get("group-id"),T=P.attributes.get("type");if(v!==E||T.toLowerCase()!=="audio")continue;let x=P.attributes.get("channels")??U.attributes.get("channels"),I=x!==null?Number(x.split("/")[0]):null;N.push({id:-1,demuxer:this,backingTrack:null,default:YJ(P.attributes),autoselect:YJ(P.attributes)||lX(P.attributes),languageCode:pX(P.attributes.get("language")),lineNumber:P.lineNumber,fullPath:P.fullPath??U.fullPath,fullCodecString:L,pairingMask:1n<<BigInt(q),peakBitrate:null,averageBitrate:null,name:P.attributes.get("name"),hasOnlyKeyPackets:U.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:I!==null&&Number.isInteger(I)&&I>0?I:null}})}}}}return N})),W=[],j=(U)=>{let q=W.find((N)=>N.fullPath===U.fullPath&&N.info.type===U.info.type);if(q){if(q.pairingMask|=U.pairingMask,q.default||=U.default,q.autoselect||=U.autoselect,q.lineNumber=Math.min(q.lineNumber,U.lineNumber),U.peakBitrate!==null)q.peakBitrate=Math.max(q.peakBitrate??-1/0,U.peakBitrate);if(U.averageBitrate!==null)q.averageBitrate=Math.max(q.averageBitrate??-1/0,U.averageBitrate);if(q.languageCode===K0)q.languageCode=U.languageCode}else U.id=W.length+1,W.push(U)};for(let U of G)for(let q of U)j(q);W.sort((U,q)=>U.lineNumber-q.lineNumber),this.trackBackings=[];for(let U of W)if(U.info.type==="video")this.trackBackings.push(new rY(U));else this.trackBackings.push(new iY(U));this.internalTracks=W})()}async getTrackBackings(){return await this.readMetadata(),F(this.trackBackings),this.trackBackings}getSegmentedInputForPath($){let J=this.segmentedInputs.find((X)=>X.path===$);if(J)return J;let Y=null;if(this.internalTracks)Y=this.internalTracks.filter((Q)=>Q.fullPath===$).map((Q)=>({id:Q.id,type:Q.info.type}));return J=new $J(this,$,Y,null),this.segmentedInputs.push(J),J}async getMetadataTags(){return{}}async getMimeType(){return O6}dispose(){if(this.segmentedInputs){for(let $ of this.segmentedInputs)$.dispose();this.segmentedInputs.length=0}}}class oY{constructor($){this.internalTrack=$,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let $=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),J=null,X=(await $.getTrackBackings()).filter((Q)=>Q.getType()===this.getType());if(X.length===1)J=X[0];else if(this instanceof rY){for(let Q of X)if(await Q.getCodec()===this.getCodec()){J=Q;break}}else{F(this instanceof iY);for(let Q of X)if(await Q.getCodec()===this.getCodec()){J=Q;break}}if(!J)throw Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=J})()}delegate($){if(this.internalTrack.backingTrack)return $();return this.hydrate().then($)}getCodec(){throw Error("Not implemented on base class.")}getDisposition(){return{...x0,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){F(this.internalTrack.demuxer.internalTracks);let $=this.internalTrack.info.type,J=0;for(let Y of this.internalTrack.demuxer.internalTracks){if(Y.info.type===$)J++;if(Y===this.internalTrack)break}return J}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp($){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp($))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata($){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata($)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket($){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket($)}async getPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getPacket($,J)}async getKeyPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket($,J)}async getNextPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket($,J)}async getNextKeyPacket($,J){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket($,J)}}class rY extends oY{constructor($){super($)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return X8(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){if(this.backingVideoTrack)return null;return this.internalTrack.info.width}getMetadataDisplayHeight(){if(this.backingVideoTrack)return null;return this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){if(this.backingVideoTrack)return null;return this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class iY extends oY{constructor($){super($)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return X8(this.internalTrack.fullCodecString)}getNumberOfChannels(){if(this.internalTrack.info.numberOfChannels!==null)return this.internalTrack.info.numberOfChannels;return this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){if(this.backingAudioTrack)return null;return this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}var YJ=($)=>{let J=$.get("default");if(J===null)return!1;let Y=J.toUpperCase();if(Y==="YES")return!0;if(Y==="NO")return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${J}".`)},lX=($)=>{let J=$.get("autoselect");if(J===null)return!1;let Y=J.toUpperCase();if(Y==="YES")return!0;if(Y==="NO")return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${J}".`)},pX=($)=>{if($===null)return K0;let J=$.split("-")[0];if(!J)return K0;return J};/*!
|
|
212
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
213
|
+
*
|
|
214
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
215
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
216
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
217
|
+
*/class Y1{constructor(){this._isIsobmff=!1}}class XJ extends Y1{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return null;J.skip(4);let Y=Z0(J,4);if(Y!=="ftyp"&&Y!=="styp")return null;return Z0(J,4)}_createDemuxer($){return new l$($)}}class aY extends XJ{async _canReadInput($){let J=await this._getMajorBrand($);if(J!==null)return J!=="qt ";let Y=$._reader.requestSlice(4,4);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=Z0(Y,4);return X==="moof"||X==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class tY extends XJ{async _canReadInput($){return await this._getMajorBrand($)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class ZJ extends Y1{async isSupportedEBMLOfDocType($,J){let Y=$._reader.requestSlice(0,_1);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=KY(Y);if(X===null)return!1;if(X<1||X>8)return!1;if(d(Y,X)!==b.EBML)return!1;let Z=GY(Y);if(typeof Z!=="number")return!1;let K=$._reader.requestSlice(Y.filePos,Z);if(K instanceof Promise)K=await K;if(!K)return!1;let G=Y.filePos;while(K.filePos<=G+Z-a0){let W=H1(K);if(!W)break;let{id:j,size:U}=W,q=K.filePos;if(U===void 0)return!1;switch(j){case b.EBMLVersion:if(d(K,U)!==1)return!1;break;case b.EBMLReadVersion:if(d(K,U)!==1)return!1;break;case b.DocType:if(G8(K,U)!==J)return!1;break;case b.DocTypeVersion:if(d(K,U)>4)return!1;break}K.filePos=q+U}return!0}_canReadInput($){return this.isSupportedEBMLOfDocType($,"matroska")}_createDemuxer($){return new qY($)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class eY extends ZJ{_canReadInput($){return this.isSupportedEBMLOfDocType($,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class $7 extends Y1{async _canReadInput($){let J=0;while(!0){let U=$._reader.requestSlice(J,f0);if(U instanceof Promise)U=await U;if(!U)break;let q=t0(U);if(!q)break;J=U.filePos+q.size}let Y=await Q$($._reader,J,J+4096);if(!Y)return!1;let X=Y.header,Q=G6(X.mpegVersionId,X.channel),Z=$._reader.requestSlice(Y.startPos+Q,4);if(Z instanceof Promise)Z=await Z;if(!Z)return!1;let K=y(Z);if(K===K6||K===o6)return!0;J=Y.startPos+Y.header.totalSize;let W=await Q$($._reader,J,J+w1);if(!W)return!1;let j=W.header;if(X.channel!==j.channel||X.sampleRate!==j.sampleRate)return!1;return!0}_createDemuxer($){return new VY($)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class J7 extends Y1{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=Z0(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),Z0(J,4)==="WAVE"}_createDemuxer($){return new FY($)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Y7 extends Y1{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return Z0(J,4)==="OggS"}_createDemuxer($){return new AY($)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class X7 extends Y1{async _canReadInput($){let J=0;while(!0){let X=$._reader.requestSlice(J,f0);if(X instanceof Promise)X=await X;if(!X)break;let Q=t0(X);if(!Q)break;J=X.filePos+Q.size}let Y=$._reader.requestSlice(J,4);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;return Z0(Y,4)==="fLaC"}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer($){return new DY($)}}class Z7 extends Y1{async _canReadInput($){let J=0;while(!0){let Z=$._reader.requestSlice(J,f0);if(Z instanceof Promise)Z=await Z;if(!Z)break;let K=t0(Z);if(!K)break;J=Z.filePos+K.size}let Y=$._reader.requestSliceRange(J,k8,z1);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=D1(Y);if(!X)return!1;if(J+=X.frameLength,Y=$._reader.requestSliceRange(J,k8,z1),Y instanceof Promise)Y=await Y;if(!Y)return!1;let Q=D1(Y);if(!Q)return!1;return X.objectType===Q.objectType&&X.samplingFrequencyIndex===Q.samplingFrequencyIndex&&X.channelConfiguration===Q.channelConfiguration}_createDemuxer($){return new LY($)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Q7 extends Y1{async _canReadInput($){let J=m0+16+1,Y=$._reader.requestSlice(0,J);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let X=f(Y,J);if(X[0]===71&&X[m0]===71)return!0;else if(X[0]===71&&X[m0+16]===71)return!0;else if(X[4]===71&&X[4+m0+4]===71)return!0;return!1}_createDemuxer($){return new PY($)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class U$ extends Y1{async _canReadInput($){let J=$._reader.requestSlice(0,7);if(J instanceof Promise)J=await J;if(!J)return!1;if(Z0(J,7)!=="#EXTM3U")return!1;if(!($._rootSource instanceof Q1))throw TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return $._rootSource._usedForHls=!0,!0}_createDemuxer($){return new sY($)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return O6}}var dX=new aY,cX=new tY,QJ=new ZJ,KJ=new eY,nX=new $7,sX=new J7,oX=new Y7,rX=new Z7,iX=new X7,aX=new Q7,tX=new U$,j$=[tX,dX,cX,QJ,KJ,sX,oX,iX,nX,rX,aX];var eX=($,J)=>{if(!$||typeof $!=="object")throw TypeError(`${J}, when provided, must be an object.`);if($.isobmff!==void 0){if(!$.isobmff||typeof $.isobmff!=="object")throw TypeError(`${J}.isobmff, when provided, must be an object.`);if($.isobmff.resolveKeyId!==void 0&&typeof $.isobmff.resolveKeyId!=="function")throw TypeError(`${J}.isobmff.resolveKeyId, when provided, must be a function.`)}if($.hls!==void 0){if(!$.hls||typeof $.hls!=="object")throw TypeError(`${J}.hls, when provided, must be an object.`);if($.hls.offsetTimestampsByDateTime!==void 0&&typeof $.hls.offsetTimestampsByDateTime!=="boolean")throw TypeError(`${J}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};/*!
|
|
212
218
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
213
219
|
*
|
|
214
220
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -220,7 +226,7 @@ var PZ=Object.defineProperty;var bZ=($,J)=>{for(var Y in J)PZ($,Y,{get:J[Y],enum
|
|
|
220
226
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
221
227
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
222
228
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
223
|
-
*/var U2=function($,J,Y){if(J!==null&&J!==void 0){if(typeof J!=="object"&&typeof J!=="function")throw TypeError("Object expected.");var X,Q;if(Y){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");X=J[Symbol.asyncDispose]}if(X===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(X=J[Symbol.dispose],Y)Q=X}if(typeof X!=="function")throw TypeError("Object not disposable.");if(Q)X=function(){try{Q.call(this)}catch(Z){return Promise.reject(Z)}};$.stack.push({value:J,dispose:X,async:Y})}else if(Y)$.stack.push({async:!0});return J},W2=function($){return function(J){function Y(K){J.error=J.hasError?new $(K,J.error,"An error was suppressed during disposal."):K,J.hasError=!0}var X,Q=0;function Z(){while(X=J.stack.pop())try{if(!X.async&&Q===1)return Q=0,J.stack.push(X),Promise.resolve().then(Z);if(X.dispose){var K=X.dispose.call(X.value);if(X.async)return Q|=2,Promise.resolve(K).then(Z,function(G){return Y(G),Z()})}else Q|=1}catch(G){Y(G)}if(Q===1)return J.hasError?Promise.reject(J.error):Promise.resolve();if(J.hasError)throw J.error}return Z()}}(typeof SuppressedError==="function"?SuppressedError:function($,J,Y){var X=Error(Y);return X.name="SuppressedError",X.error=$,X.suppressed=J,X});s8();var eX=-1/0,$5=-1/0,j$=null;if(typeof FinalizationRegistry<"u")j$=new FinalizationRegistry(($)=>{let J=performance.now();if($.type==="video"){if(J-eX>=1000)console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),eX=J;if(typeof VideoFrame<"u"&&$.data instanceof VideoFrame)$.data.close()}else{if(J-$5>=1000)console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),$5=J;if(typeof AudioData<"u"&&$.data instanceof AudioData)$.data.close()}});class m1{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}var YJ=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],j2=new Set(YJ);class l0{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(N1*this.timestamp)}get microsecondDuration(){return Math.trunc(N1*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor($,J){if(this._closed=!1,$ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.format===void 0||!j2.has(J.format))throw TypeError("init.format must be one of: "+YJ.join(", "));if(!Number.isInteger(J.codedWidth)||J.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(J.codedHeight)||J.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(J.layout!==void 0){if(!Array.isArray(J.layout))throw TypeError("init.layout, when provided, must be an array.");for(let X of J.layout){if(!X||typeof X!=="object"||Array.isArray(X))throw TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(X.offset)||X.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(X.stride)||X.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if(J.visibleRect!==void 0)vJ(J.visibleRect,"init.visibleRect");if(J.displayWidth!==void 0&&(!Number.isInteger(J.displayWidth)||J.displayWidth<=0))throw TypeError("init.displayWidth, when provided, must be a positive integer.");if(J.displayHeight!==void 0&&(!Number.isInteger(J.displayHeight)||J.displayHeight<=0))throw TypeError("init.displayHeight, when provided, must be a positive integer.");if(J.displayWidth!==void 0!==(J.displayHeight!==void 0))throw TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=J._doNotCopy?_0($):_0($).slice(),this._layout=J.layout??V2(J.format,J.codedWidth,J.codedHeight),this.format=J.format,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0;let Y=J.colorSpace??null;if(Y===null)if(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX")Y={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0};else Y={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1};if(this.colorSpace=new W$(Y),this.visibleRect={left:J.visibleRect?.left??0,top:J.visibleRect?.top??0,width:J.visibleRect?.width??J.codedWidth,height:J.visibleRect?.height??J.codedHeight},J.displayWidth!==void 0)this.squarePixelWidth=this.rotation%180===0?J.displayWidth:J.displayHeight,this.squarePixelHeight=this.rotation%180===0?J.displayHeight:J.displayWidth;else this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height}else if(typeof VideoFrame<"u"&&$ instanceof VideoFrame){if(J?.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(J?.timestamp!==void 0&&!Number.isFinite(J?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(J?.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(J?.visibleRect!==void 0)vJ(J.visibleRect,"init.visibleRect");this._data=$,this._layout=null,this.format=$.format,this.visibleRect={left:$.visibleRect?.x??0,top:$.visibleRect?.y??0,width:$.visibleRect?.width??$.codedWidth,height:$.visibleRect?.height??$.codedHeight},this.rotation=J?.rotation??0,this.squarePixelWidth=$.displayWidth,this.squarePixelHeight=$.displayHeight,this.timestamp=J?.timestamp??$.timestamp/1e6,this.duration=J?.duration??($.duration??0)/1e6,this.colorSpace=new W$($.colorSpace)}else if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof SVGImageElement<"u"&&$ instanceof SVGImageElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&$ instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new l0(new VideoFrame($,{timestamp:Math.trunc(J.timestamp*N1),duration:Math.trunc((J.duration??0)*N1)||void 0}),J);let Y=0,X=0;if("naturalWidth"in $)Y=$.naturalWidth,X=$.naturalHeight;else if("videoWidth"in $)Y=$.videoWidth,X=$.videoHeight;else if("width"in $)Y=Number($.width),X=Number($.height);if(!Y||!X)throw TypeError("Could not determine dimensions.");let Q=new OffscreenCanvas(Y,X),Z=Q.getContext("2d",{alpha:o8(),willReadFrequently:!0});if(!Z)throw Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");Z.drawImage($,0,0),this._data=Q,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:Y,height:X},this.squarePixelWidth=Y,this.squarePixelHeight=X,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new W$({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if($ instanceof m1){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=$,$._referenceCount++,this.format=$.getFormat(),this.format!==null&&!YJ.includes(this.format))throw TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:$.getCodedWidth(),height:$.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=$.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=$.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=$.getColorSpace()}else throw TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=J?.encodeOptions??{},this.pixelAspectRatio=B8({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),j$?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");if(L(this._data!==null),this._data instanceof m1)return new l0(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions});else if(G$(this._data))return new l0(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions});else if(this._data instanceof Uint8Array)return L(this._layout),new l0(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0});else return new l0(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){if(this._closed)return;if(j$?.unregister(this),this._data instanceof m1){if(this._data._referenceCount--,this._data._referenceCount===0)this._data.close()}else if(G$(this._data))this._data.close();else this._data=null;this._closed=!0}allocationSize($={}){if(Y5($),this._closed)throw Error("VideoSample is closed.");if(($.format??this.format)==null)throw Error("Cannot get allocation size when format is null.");if(G$(this._data))return this._data.allocationSize($);return X5(this,$).allocationSize}async copyTo($,J={}){if(!I6($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Y5(J),this._closed)throw Error("VideoSample is closed.");if((J.format??this.format)==null)throw Error("Cannot copy video sample data when format is null.");if(L(this._data!==null),G$(this._data))return this._data.copyTo($,J);if(J.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(J.format))if(this._data instanceof m1){let W={stack:[],error:void 0,hasError:!1};try{let j=U2(W,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},J.colorSpace??"srgb"),!1);if(!(j instanceof l0))throw TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(j.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${j.format}' instead.`);return await j.copyTo($,J)}catch(j){W.error=j,W.hasError=!0}finally{W2(W)}}else{if(typeof VideoFrame>"u")throw Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let W=this.toVideoFrame(),j=await W.copyTo($,J);return W.close(),j}let Y=X5(this,J);L(this.format);let X=_0($);if(X.byteLength<Y.allocationSize)throw TypeError(`Destination buffer too small. Required: ${Y.allocationSize}, Available: ${X.byteLength}`);let Q=XJ(this.format),Z;if(this._data instanceof m1){let W=this._data.getDataPlanes();if(W instanceof Promise)W=await W;if(!Array.isArray(W)||W.some((j)=>!(j.data instanceof Uint8Array)||!Number.isInteger(j.stride)||j.stride<0))throw TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');Z=W}else if(this._data instanceof Uint8Array)L(this._layout),L(this._layout.length===Q.length),Z=this._layout.map((W,j)=>{let U=Math.ceil(this.codedHeight/Q[j].heightDivisor);return{data:this._data.subarray(W.offset,W.offset+W.stride*U),stride:W.stride}});else{let j=this._data.getContext("2d");L(j);let U=j.getImageData(0,0,this.codedWidth,this.codedHeight);Z=[{data:_0(U.data),stride:4*this.codedWidth}]}let K=[],G=Q.length;for(let W=0;W<G;W++){let j=Y.computedLayouts[W],U=Z[W].stride,q=Z[W].data,V=j.sourceTop*U;V+=j.sourceLeftBytes;let{destinationOffset:_,sourceWidthBytes:N}=j,R={offset:_,stride:j.destinationStride};for(let z=0;z<j.sourceHeight;z++){if(V+N>q.byteLength)throw Error("Source buffer OOB read.");if(_+N>X.byteLength)throw Error("Destination buffer OOB write.");let H=q.subarray(V,V+N);X.set(H,_),V+=U,_+=j.destinationStride}K.push(R)}if(J.format!==void 0){let W=this.format.startsWith("RGB")!==J.format.startsWith("RGB"),j=this.format.includes("X")&&J.format.includes("A");if(W||j)for(let U=0;U<Y.allocationSize;U+=4){if(W){let q=X[U],V=X[U+2];X[U]=V,X[U+2]=q}if(j)X[U+3]=255}}return K}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(L(this._data!==null),this._data instanceof m1){if(this.format===null)throw Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let $=this._data.getDataPlanes();if($ instanceof Promise)throw Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let J=$.reduce((Z,K)=>Z+K.data.byteLength,0),Y=new Uint8Array(J),X=0,Q=[];for(let Z of $)Y.set(Z.data,X),Q.push(X),X+=Z.data.byteLength;return new VideoFrame(Y,{format:this.format,layout:$.map((Z,K)=>({offset:Q[K],stride:Z.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else if(G$(this._data))return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0});else if(this._data instanceof Uint8Array)return new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight});else return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw($,J,Y,X,Q,Z,K,G,W){let j=0,U=0,q=this.displayWidth,V=this.displayHeight,_=0,N=0,R=this.displayWidth,z=this.displayHeight;if(Z!==void 0)if(j=J,U=Y,q=X,V=Q,_=Z,N=K,G!==void 0)R=G,z=W;else R=q,z=V;else if(_=J,N=Y,X!==void 0)R=X,z=Q;if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(j))throw TypeError("sx must be a number.");if(!Number.isFinite(U))throw TypeError("sy must be a number.");if(!Number.isFinite(q)||q<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(V)||V<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(_))throw TypeError("dx must be a number.");if(!Number.isFinite(N))throw TypeError("dy must be a number.");if(!Number.isFinite(R)||R<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(z)||z<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:j,sy:U,sWidth:q,sHeight:V}=this._rotateSourceRegion(j,U,q,V,this.rotation));let H=this.toCanvasImageSource();$.save();let A=_+R/2,M=N+z/2;$.translate(A,M),$.rotate(this.rotation*Math.PI/180);let F=this.rotation%180===0?1:R/z;$.scale(1/F,F),$.drawImage(H,j,U,q,V,-R/2,-z/2,R,z),$.restore()}drawWithFit($,J){if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(J.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(J.crop!==void 0)L6(J.crop,"options.");let Y=$.canvas.width,X=$.canvas.height,Q=J.rotation??this.rotation,[Z,K]=Q%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],G=J.crop;if(G)G=q$(G,Z,K);let W,j,U,q,{sx:V,sy:_,sWidth:N,sHeight:R}=this._rotateSourceRegion(J.crop?.left??0,J.crop?.top??0,J.crop?.width??Z,J.crop?.height??K,Q);if(J.fit==="fill")W=0,j=0,U=Y,q=X;else{let[H,A]=J.crop?[J.crop.width,J.crop.height]:[Z,K],M=J.fit==="contain"?Math.min(Y/H,X/A):Math.max(Y/H,X/A);U=H*M,q=A*M,W=(Y-U)/2,j=(X-q)/2}$.save();let z=Q%180===0?1:U/q;$.translate(Y/2,X/2),$.rotate(Q*Math.PI/180),$.scale(1/z,z),$.translate(-Y/2,-X/2),$.drawImage(this.toCanvasImageSource(),V,_,N,R,W,j,U,q),$.restore()}_rotateSourceRegion($,J,Y,X,Q){if(Q===90)[$,J,Y,X]=[J,this.squarePixelHeight-$-Y,X,Y];else if(Q===180)[$,J]=[this.squarePixelWidth-$-Y,this.squarePixelHeight-J-X];else if(Q===270)[$,J,Y,X]=[this.squarePixelWidth-J-X,$,X,Y];return{sx:$,sy:J,sWidth:Y,sHeight:X}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(L(this._data!==null),this._data instanceof m1||this._data instanceof Uint8Array){let $=this.toVideoFrame();return queueMicrotask(()=>$.close()),$}else return this._data}async transform($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.width!==void 0&&(!Number.isInteger($.width)||$.width<=0))throw TypeError("options.width, when provided, must be a positive integer.");if($.height!==void 0&&(!Number.isInteger($.height)||$.height<=0))throw TypeError("options.height, when provided, must be a positive integer.");if($.roundDimensionsTo!==void 0&&(!Number.isInteger($.roundDimensionsTo)||$.roundDimensionsTo<=0))throw TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if($.fit!==void 0&&!["fill","contain","cover"].includes($.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if($.width!==void 0&&$.height!==void 0&&$.fit===void 0)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if($.rotate!==void 0&&![0,90,180,270].includes($.rotate))throw TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if($.crop!==void 0)L6($.crop,"options.");if($.alpha!==void 0&&!["keep","discard"].includes($.alpha))throw TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let J=s1(this.rotation+($.rotate??0)),[Y,X]=J%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],Q=$.crop;if(Q)Q=q$(Q,Y,X);let Z=Q?Q.width:Y,K=Q?Q.height:X,G=Z/K,W,j;if($.width!==void 0&&$.height===void 0)W=$.width,j=W/G;else if($.width===void 0&&$.height!==void 0)j=$.height,W=j*G;else if($.width!==void 0&&$.height!==void 0)W=$.width,j=$.height;else W=Z,j=K;W=S6(W,$.roundDimensionsTo??1),j=S6(j,$.roundDimensionsTo??1);let U={width:W,height:j,fit:$.fit??"fill",rotation:J,crop:Q??{left:0,top:0,width:Y,height:X},alpha:$.alpha??"keep"};for(let N of q2){let R=N(this,U);if(R instanceof Promise)R=await R;if(R!==null)return R}let q=null,V=!1;for(let N of K$)if(N.canvas.width===U.width&&N.canvas.height===U.height){q=N.canvas,N.age=J5++;break}if(q===null){if(typeof OffscreenCanvas<"u")q=new OffscreenCanvas(U.width,U.height);else{if(typeof window>"u"||typeof document>"u")throw Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");q=document.createElement("canvas"),q.width=U.width,q.height=U.height}if(V=!0,K$.length>=N2)K$.splice(r8(K$,(N)=>N.age),1);K$.push({canvas:q,age:J5++})}let _=q.getContext("2d",{alpha:!0});if(!_)throw Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");if(U.alpha==="discard")_.fillStyle="black",_.fillRect(0,0,U.width,U.height);else if(!V)_.clearRect(0,0,U.width,U.height);return this.drawWithFit(_,{fit:U.fit,rotation:U.rotation,crop:U.crop}),new l0(q,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation($){if(![0,90,180,270].includes($))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=$}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}setDuration($){if(!Number.isFinite($)||$<0)throw TypeError("newDuration must be a non-negative number.");this.duration=$}setEncodeOptions($){if(!$||typeof $!=="object")throw TypeError("newEncodeOptions must be an object.");this.encodeOptions=$}[Symbol.dispose](){this.close()}}var q2=[];var N2=3,K$=[],J5=0;class W${constructor($){if($!==void 0){if(!$||typeof $!=="object")throw TypeError("init.colorSpace, when provided, must be an object.");let J=Object.keys(V8);if($.primaries!=null&&!J.includes($.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${J.join(", ")}.`);let Y=Object.keys(H8);if($.transfer!=null&&!Y.includes($.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${Y.join(", ")}.`);let X=Object.keys(R8);if($.matrix!=null&&!X.includes($.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${X.join(", ")}.`);if($.fullRange!=null&&typeof $.fullRange!=="boolean")throw TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=$?.primaries??null,this.transfer=$?.transfer??null,this.matrix=$?.matrix??null,this.fullRange=$?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}var G$=($)=>{return typeof VideoFrame<"u"&&$ instanceof VideoFrame},q$=($,J,Y)=>{let X=Math.min($.left,J),Q=Math.min($.top,Y),Z=Math.min($.width,J-X),K=Math.min($.height,Y-Q);return L(Z>=0),L(K>=0),{left:X,top:Q,width:Z,height:K}},L6=($,J)=>{if(!$||typeof $!=="object")throw TypeError(J+"crop, when provided, must be an object.");if(!Number.isInteger($.left)||$.left<0)throw TypeError(J+"crop.left must be a non-negative integer.");if(!Number.isInteger($.top)||$.top<0)throw TypeError(J+"crop.top must be a non-negative integer.");if(!Number.isInteger($.width)||$.width<0)throw TypeError(J+"crop.width must be a non-negative integer.");if(!Number.isInteger($.height)||$.height<0)throw TypeError(J+"crop.height must be a non-negative integer.")},Y5=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.colorSpace!==void 0&&!["display-p3","srgb"].includes($.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if($.format!==void 0&&typeof $.format!=="string")throw TypeError("options.format, when provided, must be a string.");if($.layout!==void 0){if(!Array.isArray($.layout))throw TypeError("options.layout, when provided, must be an array.");for(let J of $.layout){if(!J||typeof J!=="object")throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(J.offset)||J.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(J.stride)||J.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if($.rect!==void 0){if(!$.rect||typeof $.rect!=="object")throw TypeError("options.rect, when provided, must be an object.");if($.rect.x!==void 0&&(!Number.isInteger($.rect.x)||$.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if($.rect.y!==void 0&&(!Number.isInteger($.rect.y)||$.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if($.rect.width!==void 0&&(!Number.isInteger($.rect.width)||$.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if($.rect.height!==void 0&&(!Number.isInteger($.rect.height)||$.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},V2=($,J,Y)=>{let X=XJ($),Q=[],Z=0;for(let K of X){let G=Math.ceil(J/K.widthDivisor),W=Math.ceil(Y/K.heightDivisor),j=G*K.sampleBytes,U=j*W;Q.push({offset:Z,stride:j}),Z+=U}return Q},XJ=($)=>{let J=(Y,X,Q,Z,K)=>{let G=[{sampleBytes:Y,widthDivisor:1,heightDivisor:1},{sampleBytes:X,widthDivisor:Q,heightDivisor:Z},{sampleBytes:X,widthDivisor:Q,heightDivisor:Z}];if(K)G.push({sampleBytes:Y,widthDivisor:1,heightDivisor:1});return G};switch($){case"I420":return J(1,1,2,2,!1);case"I420P10":case"I420P12":return J(2,2,2,2,!1);case"I420A":return J(1,1,2,2,!0);case"I420AP10":case"I420AP12":return J(2,2,2,2,!0);case"I422":return J(1,1,2,1,!1);case"I422P10":case"I422P12":return J(2,2,2,1,!1);case"I422A":return J(1,1,2,1,!0);case"I422AP10":case"I422AP12":return J(2,2,2,1,!0);case"I444":return J(1,1,1,1,!1);case"I444P10":case"I444P12":return J(2,2,1,1,!1);case"I444A":return J(1,1,1,1,!0);case"I444AP10":case"I444AP12":return J(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:T0($),L(!1)}},X5=($,J)=>{let Y={left:0,top:0,width:$.codedWidth,height:$.codedHeight},X=J.rect,Q=_2(Y,X,$.codedWidth,$.codedHeight,$.format),Z=J.layout,K;if(!J.format||J.format===$.format)K=$.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(J.format))K=J.format;else throw Error("NotSupportedError: Invalid destination format.");return z2(Q,K,Z)},_2=($,J,Y,X,Q)=>{let Z={...$};if(J!==void 0){if(J.width===0||J.height===0)throw TypeError("visibleRect dimensions cannot be zero.");if((J.x||0)+(J.width||0)>Y)throw TypeError("visibleRect exceeds codedWidth.");if((J.y||0)+(J.height||0)>X)throw TypeError("visibleRect exceeds codedHeight.");Z.x=J.x||0,Z.y=J.y||0,Z.width=J.width||0,Z.height=J.height||0}if(!H2(Q,Z))throw TypeError("visibleRect alignment is invalid for the format.");return Z},H2=($,J)=>{if($===null)return!0;let Y=XJ($);for(let X=0;X<Y.length;X++){let Q=Y[X],Z=Q.widthDivisor,K=Q.heightDivisor;if((J.x||0)%Z!==0)return!1;if((J.y||0)%K!==0)return!1}return!0},z2=($,J,Y)=>{let X=XJ(J),Q=X.length;if(Y!==void 0&&Y.length!==Q)throw TypeError(`Layout must have ${Q} planes.`);let Z=0,K=[],G=[];for(let W=0;W<Q;W++){let j=X[W],U=j.sampleBytes,q=j.widthDivisor,V=j.heightDivisor,_={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(_.sourceTop=Math.ceil(Math.trunc($.y||0)/V),_.sourceHeight=Math.ceil(Math.trunc($.height||0)/V),_.sourceLeftBytes=Math.floor(Math.trunc($.x||0)/q)*U,_.sourceWidthBytes=Math.floor(Math.trunc($.width||0)/q)*U,Y!==void 0){let z=Y[W];if(z.stride<_.sourceWidthBytes)throw TypeError(`Stride for plane ${W} is too small.`);_.destinationOffset=z.offset,_.destinationStride=z.stride}else _.destinationOffset=Z,_.destinationStride=_.sourceWidthBytes;let R=_.destinationStride*_.sourceHeight+_.destinationOffset;if(R>4294967295)throw TypeError("Allocation size exceeds limit.");G.push(R),Z=Math.max(Z,R);for(let z=0;z<W;z++){let H=K[z];if(G[W]<=H.destinationOffset||G[z]<=_.destinationOffset)continue;throw TypeError("Planes overlap.")}K.push(_)}return{allocationSize:Z,computedLayouts:K}},JJ=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class g8{constructor(){this._referenceCount=0}}class h0{get microsecondTimestamp(){return Math.trunc(N1*this.timestamp)}get microsecondDuration(){return Math.trunc(N1*this.duration)}constructor($){if(this._closed=!1,U$($)){if($.format===null)throw TypeError("AudioData with null format is not supported.");this._data=$,this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=$.numberOfFrames,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp/1e6,this.duration=$.numberOfFrames/$.sampleRate}else if($ instanceof g8){if(this._data=$,$._referenceCount++,this.format=$.getFormat(),!JJ.has(this.format))throw TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=$.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=$.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=$.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=$.getTimestamp(),!Number.isFinite(this.timestamp))throw TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!$||typeof $!=="object")throw TypeError("Invalid AudioDataInit: must be an object.");if(!JJ.has($.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite($.sampleRate)||$.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger($.numberOfChannels)||$.numberOfChannels===0)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite($?.timestamp))throw TypeError("init.timestamp must be a number.");let J=$.data.byteLength/(Z8($.format)*$.numberOfChannels);if(!Number.isInteger(J))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=J,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp,this.duration=J/$.sampleRate;let Y;if($.data instanceof ArrayBuffer)Y=new Uint8Array($.data);else if(ArrayBuffer.isView($.data))Y=new Uint8Array($.data.buffer,$.data.byteOffset,$.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let X=this.numberOfFrames*this.numberOfChannels*Z8(this.format);if(Y.byteLength<X)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=Y}j$?.register(this,{type:"audio",data:this._data},this)}allocationSize($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Number.isInteger($.planeIndex)||$.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if($.format!==void 0&&!JJ.has($.format))throw TypeError("Invalid format.");if($.frameOffset!==void 0&&(!Number.isInteger($.frameOffset)||$.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if($.frameCount!==void 0&&(!Number.isInteger($.frameCount)||$.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let J=$.format??this.format,Y=$.frameOffset??0;if(Y>=this.numberOfFrames)throw RangeError("frameOffset out of range");let X=$.frameCount!==void 0?$.frameCount:this.numberOfFrames-Y;if(X>this.numberOfFrames-Y)throw RangeError("frameCount out of range");let Q=Z8(J),Z=k8(J);if(Z&&$.planeIndex>=this.numberOfChannels)throw RangeError("planeIndex out of range");if(!Z&&$.planeIndex!==0)throw RangeError("planeIndex out of range");return(Z?X:X*this.numberOfChannels)*Q}copyTo($,J){if(!I6($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!Number.isInteger(J.planeIndex)||J.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(J.format!==void 0&&!JJ.has(J.format))throw TypeError("Invalid format.");if(J.frameOffset!==void 0&&(!Number.isInteger(J.frameOffset)||J.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(J.frameCount!==void 0&&(!Number.isInteger(J.frameCount)||J.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{format:Y,frameCount:X,frameOffset:Q}=J,{planeIndex:Z}=J,K=this.format,G=Y??this.format;if(!G)throw Error("Destination format not determined");let W=this.numberOfFrames,j=this.numberOfChannels,U=Q??0;if(U>=W)throw RangeError("frameOffset out of range");let q=X!==void 0?X:W-U;if(q>W-U)throw RangeError("frameCount out of range");let V=Z8(G),_=k8(G);if(_&&Z>=j)throw RangeError("planeIndex out of range");if(!_&&Z!==0)throw RangeError("planeIndex out of range");let R=(_?q:q*j)*V;if($.byteLength<R)throw RangeError("Destination buffer is too small");let z=u($),H=Q5(G);if(U$(this._data))if(F8()&&j>2&&G!==K)R2(this._data,z,K,G,j,Z,U,q);else this._data.copyTo($,{planeIndex:Z,frameOffset:U,frameCount:q,format:G});else{let A=Z5(K),M=Z8(K),F=k8(K),O;if(this._data instanceof g8){let D=(w)=>{let P=this._data.getDataPlane(w);if(!(P instanceof Uint8Array))throw TypeError("getDataPlane() must return a Uint8Array.");let T=W*M*(F?1:j);if(P.byteLength!==T)throw TypeError(`Data plane ${w} has invalid size. Expected exactly ${T} bytes, got ${P.byteLength} bytes.`);return P};if(F)if(_)O=D(Z),Z=0;else{O=new Uint8Array(W*M*j);for(let w=0;w<j;w++){let P=D(w);O.set(P,w*W*M)}}else O=D(0)}else O=this._data;let B=u(O);for(let D=0;D<q;D++)if(_){let w=D*V,P;if(F)P=(Z*W+(D+U))*M;else P=((D+U)*j+Z)*M;let T=A(B,P);H(z,w,T)}else for(let w=0;w<j;w++){let T=(D*j+w)*V,C;if(F)C=(w*W+(D+U))*M;else C=((D+U)*j+w)*M;let E=A(B,C);H(z,T,E)}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(this._data instanceof g8){let $=new h0(this._data);return $.setTimestamp(this.timestamp),$}else if(U$(this._data)){let $=new h0(this._data.clone());return $.setTimestamp(this.timestamp),$}else return new h0({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim($,J=this.numberOfFrames){if(!Number.isInteger($)||$<0)throw TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(J)||J<0)throw TypeError("endSample must be a non-negative integer.");if($>this.numberOfFrames)throw RangeError("startSample out of range.");if(J>this.numberOfFrames)throw RangeError("endSample out of range.");if(J<$)throw RangeError("endSample must not be less than startSample.");if(this._closed)throw Error("AudioSample is closed.");let Y=J-$,X=Z8(this.format),Q;if(k8(this.format)){let Z=Y*X;if(Q=new Uint8Array(Z*this.numberOfChannels),Y>0)for(let K=0;K<this.numberOfChannels;K++)this.copyTo(Q.subarray(K*Z,(K+1)*Z),{planeIndex:K,format:this.format,frameOffset:$,frameCount:Y})}else if(Q=new Uint8Array(Y*this.numberOfChannels*X),Y>0)this.copyTo(Q,{planeIndex:0,format:this.format,frameOffset:$,frameCount:Y});return new h0({data:Q,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+$/this.sampleRate})}close(){if(this._closed)return;if(j$?.unregister(this),this._data instanceof g8){if(this._data._referenceCount--,this._data._referenceCount===0)this._data.close()}else if(U$(this._data))this._data.close();else this._data=new Uint8Array(0);this._closed=!0}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(this._data instanceof g8)return this._createAudioDataFromData();else if(U$(this._data))if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();else return this._createAudioDataFromData();else 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()})}_createAudioDataFromData(){if(k8(this.format)){let $=this.allocationSize({planeIndex:0,format:this.format}),J=new ArrayBuffer($*this.numberOfChannels);for(let Y=0;Y<this.numberOfChannels;Y++)this.copyTo(new Uint8Array(J,Y*$,$),{planeIndex:Y,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:J})}else{let $=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo($,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:$})}}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let $=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),J=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let Y=0;Y<this.numberOfChannels;Y++)this.copyTo(J,{planeIndex:Y,format:"f32-planar"}),$.copyToChannel(J,Y);return $}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}[Symbol.dispose](){this.close()}static*_fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,X=$.numberOfChannels,Q=$.sampleRate,Z=$.length,K=Math.floor(Y/X),G=0,W=Z;while(W>0){let j=Math.min(K,W),U=new Float32Array(X*j);for(let q=0;q<X;q++)$.copyFromChannel(U.subarray(q*j,(q+1)*j),q,G);yield new h0({format:"f32-planar",sampleRate:Q,numberOfFrames:j,numberOfChannels:X,timestamp:J+G/Q,data:U}),G+=j,W-=j}}static fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,X=$.numberOfChannels,Q=$.sampleRate,Z=$.length,K=Math.floor(Y/X),G=0,W=Z,j=[];while(W>0){let U=Math.min(K,W),q=new Float32Array(X*U);for(let _=0;_<X;_++)$.copyFromChannel(q.subarray(_*U,(_+1)*U),_,G);let V=new h0({format:"f32-planar",sampleRate:Q,numberOfFrames:U,numberOfChannels:X,timestamp:J+G/Q,data:q});j.push(V),G+=U,W-=U}return j}}var Z8=($)=>{switch($){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},k8=($)=>{switch($){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Z5=($)=>{switch($){case"u8":case"u8-planar":return(J,Y)=>(J.getUint8(Y)-128)/128;case"s16":case"s16-planar":return(J,Y)=>J.getInt16(Y,!0)/32768;case"s32":case"s32-planar":return(J,Y)=>J.getInt32(Y,!0)/2147483648;case"f32":case"f32-planar":return(J,Y)=>J.getFloat32(Y,!0)}},Q5=($)=>{switch($){case"u8":case"u8-planar":return(J,Y,X)=>J.setUint8(Y,s0((X+1)*127.5,0,255));case"s16":case"s16-planar":return(J,Y,X)=>J.setInt16(Y,s0(Math.round(X*32767),-32768,32767),!0);case"s32":case"s32-planar":return(J,Y,X)=>J.setInt32(Y,s0(Math.round(X*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(J,Y,X)=>J.setFloat32(Y,X,!0)}},U$=($)=>{return typeof AudioData<"u"&&$ instanceof AudioData};var R2=($,J,Y,X,Q,Z,K,G)=>{let W=Z5(Y),j=Q5(X),U=Z8(Y),q=Z8(X),V=k8(Y);if(k8(X))if(V){let N=new ArrayBuffer(G*U),R=u(N);$.copyTo(N,{planeIndex:Z,frameOffset:K,frameCount:G,format:Y});for(let z=0;z<G;z++){let H=z*U,A=z*q,M=W(R,H);j(J,A,M)}}else{let N=new ArrayBuffer(G*Q*U),R=u(N);$.copyTo(N,{planeIndex:0,frameOffset:K,frameCount:G,format:Y});for(let z=0;z<G;z++){let H=(z*Q+Z)*U,A=z*q,M=W(R,H);j(J,A,M)}}else if(V){let N=G*U,R=new ArrayBuffer(N),z=u(R);for(let H=0;H<Q;H++){$.copyTo(R,{planeIndex:H,frameOffset:K,frameCount:G,format:Y});for(let A=0;A<G;A++){let M=A*U,F=(A*Q+H)*q,O=W(z,M);j(J,F,O)}}}else{let N=new ArrayBuffer(G*Q*U),R=u(N);$.copyTo(N,{planeIndex:0,frameOffset:K,frameCount:G,format:Y});for(let z=0;z<G;z++)for(let H=0;H<Q;H++){let A=z*Q+H,M=A*U,F=A*q,O=W(R,M);j(J,F,O)}}};/*!
|
|
229
|
+
*/var H2=function($,J,Y){if(J!==null&&J!==void 0){if(typeof J!=="object"&&typeof J!=="function")throw TypeError("Object expected.");var X,Q;if(Y){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");X=J[Symbol.asyncDispose]}if(X===void 0){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");if(X=J[Symbol.dispose],Y)Q=X}if(typeof X!=="function")throw TypeError("Object not disposable.");if(Q)X=function(){try{Q.call(this)}catch(Z){return Promise.reject(Z)}};$.stack.push({value:J,dispose:X,async:Y})}else if(Y)$.stack.push({async:!0});return J},z2=function($){return function(J){function Y(K){J.error=J.hasError?new $(K,J.error,"An error was suppressed during disposal."):K,J.hasError=!0}var X,Q=0;function Z(){while(X=J.stack.pop())try{if(!X.async&&Q===1)return Q=0,J.stack.push(X),Promise.resolve().then(Z);if(X.dispose){var K=X.dispose.call(X.value);if(X.async)return Q|=2,Promise.resolve(K).then(Z,function(G){return Y(G),Z()})}else Q|=1}catch(G){Y(G)}if(Q===1)return J.hasError?Promise.reject(J.error):Promise.resolve();if(J.hasError)throw J.error}return Z()}}(typeof SuppressedError==="function"?SuppressedError:function($,J,Y){var X=Error(Y);return X.name="SuppressedError",X.error=$,X.suppressed=J,X});e8();var $5=-1/0,J5=-1/0,R$=null;if(typeof FinalizationRegistry<"u")R$=new FinalizationRegistry(($)=>{let J=performance.now();if($.type==="video"){if(J-$5>=1000)k._error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),$5=J;if(typeof VideoFrame<"u"&&$.data instanceof VideoFrame)$.data.close()}else{if(J-J5>=1000)k._error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),J5=J;if(typeof AudioData<"u"&&$.data instanceof AudioData)$.data.close()}});class o1{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}var WJ=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],R2=new Set(WJ);class e0{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(F1*this.timestamp)}get microsecondDuration(){return Math.trunc(F1*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor($,J){if(this._closed=!1,$ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.format===void 0||!R2.has(J.format))throw TypeError("init.format must be one of: "+WJ.join(", "));if(!Number.isInteger(J.codedWidth)||J.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(J.codedHeight)||J.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(J.layout!==void 0){if(!Array.isArray(J.layout))throw TypeError("init.layout, when provided, must be an array.");for(let Q of J.layout){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(Q.offset)||Q.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(Q.stride)||Q.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if(J.visibleRect!==void 0)kJ(J.visibleRect,"init.visibleRect");if(J.displayWidth!==void 0&&(!Number.isInteger(J.displayWidth)||J.displayWidth<=0))throw TypeError("init.displayWidth, when provided, must be a positive integer.");if(J.displayHeight!==void 0&&(!Number.isInteger(J.displayHeight)||J.displayHeight<=0))throw TypeError("init.displayHeight, when provided, must be a positive integer.");if(J.displayWidth!==void 0!==(J.displayHeight!==void 0))throw TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=J.format,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0;let Y=J.layout??F2(J.format,J.codedWidth,J.codedHeight),X=J.colorSpace??null;if(X===null)if(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX")X={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0};else X={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1};if(this.visibleRect={left:J.visibleRect?.left??0,top:J.visibleRect?.top??0,width:J.visibleRect?.width??J.codedWidth,height:J.visibleRect?.height??J.codedHeight},J.displayWidth!==void 0)this.squarePixelWidth=this.rotation%180===0?J.displayWidth:J.displayHeight,this.squarePixelHeight=this.rotation%180===0?J.displayHeight:J.displayWidth;else this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height;this._data=J._doNotCopy?O0($):O0($).slice(),this._layout=Y,this.colorSpace=new z$(X)}else if(typeof VideoFrame<"u"&&$ instanceof VideoFrame){if(J?.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(J?.timestamp!==void 0&&!Number.isFinite(J?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(J?.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(J?.visibleRect!==void 0)kJ(J.visibleRect,"init.visibleRect");this._data=$,this._layout=null,this.format=$.format,this.visibleRect={left:$.visibleRect?.x??0,top:$.visibleRect?.y??0,width:$.visibleRect?.width??$.codedWidth,height:$.visibleRect?.height??$.codedHeight},this.rotation=J?.rotation??0,this.squarePixelWidth=$.displayWidth,this.squarePixelHeight=$.displayHeight,this.timestamp=J?.timestamp??$.timestamp/1e6,this.duration=J?.duration??($.duration??0)/1e6,this.colorSpace=new z$($.colorSpace)}else if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof SVGImageElement<"u"&&$ instanceof SVGImageElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&$ instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new e0(new VideoFrame($,{timestamp:Math.trunc(J.timestamp*F1),duration:Math.trunc((J.duration??0)*F1)||void 0}),J);let Y=0,X=0;if("naturalWidth"in $)Y=$.naturalWidth,X=$.naturalHeight;else if("videoWidth"in $)Y=$.videoWidth,X=$.videoHeight;else if("width"in $)Y=Number($.width),X=Number($.height);if(!Y||!X)throw TypeError("Could not determine dimensions.");let Q=new OffscreenCanvas(Y,X),Z=Q.getContext("2d",{alpha:t8(),willReadFrequently:!0});if(!Z)throw Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");Z.drawImage($,0,0),this._data=Q,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:Y,height:X},this.squarePixelWidth=Y,this.squarePixelHeight=X,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new z$({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if($ instanceof o1){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=$,$._referenceCount++,this.format=$.getFormat(),this.format!==null&&!WJ.includes(this.format))throw TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:$.getCodedWidth(),height:$.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=$.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=$.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=$.getColorSpace()}else throw TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=J?.encodeOptions??{},this.pixelAspectRatio=b8({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),R$?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");if(F(this._data!==null),this._data instanceof o1)return new e0(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions});else if(_$(this._data))return new e0(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions});else if(this._data instanceof Uint8Array)return F(this._layout),new e0(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0});else return new e0(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){if(this._closed)return;if(R$?.unregister(this),this._data instanceof o1){if(this._data._referenceCount--,this._data._referenceCount===0)this._data.close()}else if(_$(this._data))this._data.close();else this._data=null;this._closed=!0}allocationSize($={}){if(X5($),this._closed)throw Error("VideoSample is closed.");if(($.format??this.format)==null)throw Error("Cannot get allocation size when format is null.");if(_$(this._data))return this._data.allocationSize($);return Z5(this,$).allocationSize}async copyTo($,J={}){if(!k6($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(X5(J),this._closed)throw Error("VideoSample is closed.");if((J.format??this.format)==null)throw Error("Cannot copy video sample data when format is null.");if(F(this._data!==null),_$(this._data))return this._data.copyTo($,J);if(J.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(J.format))if(this._data instanceof o1){let W={stack:[],error:void 0,hasError:!1};try{let j=H2(W,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},J.colorSpace??"srgb"),!1);if(!(j instanceof e0))throw TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(j.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${j.format}' instead.`);return await j.copyTo($,J)}catch(j){W.error=j,W.hasError=!0}finally{z2(W)}}else{if(typeof VideoFrame>"u")throw Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let W=this.toVideoFrame(),j=await W.copyTo($,J);return W.close(),j}let Y=Z5(this,J);F(this.format);let X=O0($);if(X.byteLength<Y.allocationSize)throw TypeError(`Destination buffer too small. Required: ${Y.allocationSize}, Available: ${X.byteLength}`);let Q=UJ(this.format),Z;if(this._data instanceof o1){let W=this._data.getDataPlanes();if(W instanceof Promise)W=await W;if(!Array.isArray(W)||W.some((j)=>!(j.data instanceof Uint8Array)||!Number.isInteger(j.stride)||j.stride<0))throw TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');Z=W}else if(this._data instanceof Uint8Array)F(this._layout),F(this._layout.length===Q.length),Z=this._layout.map((W,j)=>{let U=Math.ceil(this.codedHeight/Q[j].heightDivisor);return{data:this._data.subarray(W.offset,W.offset+W.stride*U),stride:W.stride}});else{let j=this._data.getContext("2d");F(j);let U=j.getImageData(0,0,this.codedWidth,this.codedHeight);Z=[{data:O0(U.data),stride:4*this.codedWidth}]}let K=[],G=Q.length;for(let W=0;W<G;W++){let j=Y.computedLayouts[W],U=Z[W].stride,q=Z[W].data,N=j.sourceTop*U;N+=j.sourceLeftBytes;let{destinationOffset:_,sourceWidthBytes:V}=j,z={offset:_,stride:j.destinationStride};for(let R=0;R<j.sourceHeight;R++){if(N+V>q.byteLength)throw Error("Source buffer OOB read.");if(_+V>X.byteLength)throw Error("Destination buffer OOB write.");let H=q.subarray(N,N+V);X.set(H,_),N+=U,_+=j.destinationStride}K.push(z)}if(J.format!==void 0){let W=this.format.startsWith("RGB")!==J.format.startsWith("RGB"),j=this.format.includes("X")&&J.format.includes("A");if(W||j)for(let U=0;U<Y.allocationSize;U+=4){if(W){let q=X[U],N=X[U+2];X[U]=N,X[U+2]=q}if(j)X[U+3]=255}}return K}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(F(this._data!==null),this._data instanceof o1){if(this.format===null)throw Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let $=this._data.getDataPlanes();if($ instanceof Promise)throw Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let J=$.reduce((Z,K)=>Z+K.data.byteLength,0),Y=new Uint8Array(J),X=0,Q=[];for(let Z of $)Y.set(Z.data,X),Q.push(X),X+=Z.data.byteLength;return new VideoFrame(Y,{format:this.format,layout:$.map((Z,K)=>({offset:Q[K],stride:Z.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else if(_$(this._data))return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0});else if(this._data instanceof Uint8Array)return F(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight});else return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw($,J,Y,X,Q,Z,K,G,W){let j=0,U=0,q=this.displayWidth,N=this.displayHeight,_=0,V=0,z=this.displayWidth,R=this.displayHeight;if(Z!==void 0)if(j=J,U=Y,q=X,N=Q,_=Z,V=K,G!==void 0)z=G,R=W;else z=q,R=N;else if(_=J,V=Y,X!==void 0)z=X,R=Q;if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(j))throw TypeError("sx must be a number.");if(!Number.isFinite(U))throw TypeError("sy must be a number.");if(!Number.isFinite(q)||q<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(N)||N<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(_))throw TypeError("dx must be a number.");if(!Number.isFinite(V))throw TypeError("dy must be a number.");if(!Number.isFinite(z)||z<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(R)||R<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:j,sy:U,sWidth:q,sHeight:N}=this._rotateSourceRegion(j,U,q,N,this.rotation));let H=this.toCanvasImageSource();$.save();let A=_+z/2,M=V+R/2;$.translate(A,M),$.rotate(this.rotation*Math.PI/180);let L=this.rotation%180===0?1:z/R;$.scale(1/L,L),$.drawImage(H,j,U,q,N,-z/2,-R/2,z,R),$.restore()}drawWithFit($,J){if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(J.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(J.crop!==void 0)D6(J.crop,"options.");let Y=$.canvas.width,X=$.canvas.height,Q=J.rotation??this.rotation,[Z,K]=Q%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],G=J.crop;if(G)G=A$(G,Z,K);let W,j,U,q,{sx:N,sy:_,sWidth:V,sHeight:z}=this._rotateSourceRegion(J.crop?.left??0,J.crop?.top??0,J.crop?.width??Z,J.crop?.height??K,Q);if(J.fit==="fill")W=0,j=0,U=Y,q=X;else{let[H,A]=J.crop?[J.crop.width,J.crop.height]:[Z,K],M=J.fit==="contain"?Math.min(Y/H,X/A):Math.max(Y/H,X/A);U=H*M,q=A*M,W=(Y-U)/2,j=(X-q)/2}$.save();let R=Q%180===0?1:U/q;$.translate(Y/2,X/2),$.rotate(Q*Math.PI/180),$.scale(1/R,R),$.translate(-Y/2,-X/2),$.drawImage(this.toCanvasImageSource(),N,_,V,z,W,j,U,q),$.restore()}_rotateSourceRegion($,J,Y,X,Q){if(Q===90)[$,J,Y,X]=[J,this.squarePixelHeight-$-Y,X,Y];else if(Q===180)[$,J]=[this.squarePixelWidth-$-Y,this.squarePixelHeight-J-X];else if(Q===270)[$,J,Y,X]=[this.squarePixelWidth-J-X,$,X,Y];return{sx:$,sy:J,sWidth:Y,sHeight:X}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(F(this._data!==null),this._data instanceof o1||this._data instanceof Uint8Array){let $=this.toVideoFrame();return queueMicrotask(()=>$.close()),$}else return this._data}async transform($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.width!==void 0&&(!Number.isInteger($.width)||$.width<=0))throw TypeError("options.width, when provided, must be a positive integer.");if($.height!==void 0&&(!Number.isInteger($.height)||$.height<=0))throw TypeError("options.height, when provided, must be a positive integer.");if($.roundDimensionsTo!==void 0&&(!Number.isInteger($.roundDimensionsTo)||$.roundDimensionsTo<=0))throw TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if($.fit!==void 0&&!["fill","contain","cover"].includes($.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if($.width!==void 0&&$.height!==void 0&&$.fit===void 0)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if($.rotate!==void 0&&![0,90,180,270].includes($.rotate))throw TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if($.crop!==void 0)D6($.crop,"options.");if($.alpha!==void 0&&!["keep","discard"].includes($.alpha))throw TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let J=J8(this.rotation+($.rotate??0)),[Y,X]=J%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],Q=$.crop;if(Q)Q=A$(Q,Y,X);let Z=Q?Q.width:Y,K=Q?Q.height:X,G=Z/K,W,j;if($.width!==void 0&&$.height===void 0)W=$.width,j=W/G;else if($.width===void 0&&$.height!==void 0)j=$.height,W=j*G;else if($.width!==void 0&&$.height!==void 0)W=$.width,j=$.height;else W=Z,j=K;W=l6(W,$.roundDimensionsTo??1),j=l6(j,$.roundDimensionsTo??1);let U={width:W,height:j,fit:$.fit??"fill",rotation:J,crop:Q??{left:0,top:0,width:Y,height:X},alpha:$.alpha??"keep"};for(let V of A2){let z=V(this,U);if(z instanceof Promise)z=await z;if(z!==null)return z}let q=null,N=!1;for(let V of V$)if(V.canvas.width===U.width&&V.canvas.height===U.height){q=V.canvas,V.age=Y5++;break}if(q===null){if(typeof OffscreenCanvas<"u")q=new OffscreenCanvas(U.width,U.height);else{if(typeof window>"u"||typeof document>"u")throw Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");q=document.createElement("canvas"),q.width=U.width,q.height=U.height}if(N=!0,V$.length>=M2)V$.splice($6(V$,(V)=>V.age),1);V$.push({canvas:q,age:Y5++})}let _=q.getContext("2d",{alpha:!0});if(!_)throw Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");if(U.alpha==="discard")_.fillStyle="black",_.fillRect(0,0,U.width,U.height);else if(!N)_.clearRect(0,0,U.width,U.height);return this.drawWithFit(_,{fit:U.fit,rotation:U.rotation,crop:U.crop}),new e0(q,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation($){if(![0,90,180,270].includes($))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=$}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}setDuration($){if(!Number.isFinite($)||$<0)throw TypeError("newDuration must be a non-negative number.");this.duration=$}setEncodeOptions($){if(!$||typeof $!=="object")throw TypeError("newEncodeOptions must be an object.");this.encodeOptions=$}[Symbol.dispose](){this.close()}}var A2=[];var M2=3,V$=[],Y5=0;class z${constructor($){if($!==void 0){if(!$||typeof $!=="object")throw TypeError("init.colorSpace, when provided, must be an object.");let J=Object.keys(A8);if($.primaries!=null&&!J.includes($.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${J.join(", ")}.`);let Y=Object.keys(F8);if($.transfer!=null&&!Y.includes($.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${Y.join(", ")}.`);let X=Object.keys(w8);if($.matrix!=null&&!X.includes($.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${X.join(", ")}.`);if($.fullRange!=null&&typeof $.fullRange!=="boolean")throw TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=$?.primaries??null,this.transfer=$?.transfer??null,this.matrix=$?.matrix??null,this.fullRange=$?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}var _$=($)=>{return typeof VideoFrame<"u"&&$ instanceof VideoFrame},A$=($,J,Y)=>{let X=Math.min($.left,J),Q=Math.min($.top,Y),Z=Math.min($.width,J-X),K=Math.min($.height,Y-Q);return F(Z>=0),F(K>=0),{left:X,top:Q,width:Z,height:K}},D6=($,J)=>{if(!$||typeof $!=="object")throw TypeError(J+"crop, when provided, must be an object.");if(!Number.isInteger($.left)||$.left<0)throw TypeError(J+"crop.left must be a non-negative integer.");if(!Number.isInteger($.top)||$.top<0)throw TypeError(J+"crop.top must be a non-negative integer.");if(!Number.isInteger($.width)||$.width<0)throw TypeError(J+"crop.width must be a non-negative integer.");if(!Number.isInteger($.height)||$.height<0)throw TypeError(J+"crop.height must be a non-negative integer.")},X5=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.colorSpace!==void 0&&!["display-p3","srgb"].includes($.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if($.format!==void 0&&typeof $.format!=="string")throw TypeError("options.format, when provided, must be a string.");if($.layout!==void 0){if(!Array.isArray($.layout))throw TypeError("options.layout, when provided, must be an array.");for(let J of $.layout){if(!J||typeof J!=="object")throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(J.offset)||J.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(J.stride)||J.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if($.rect!==void 0){if(!$.rect||typeof $.rect!=="object")throw TypeError("options.rect, when provided, must be an object.");if($.rect.x!==void 0&&(!Number.isInteger($.rect.x)||$.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if($.rect.y!==void 0&&(!Number.isInteger($.rect.y)||$.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if($.rect.width!==void 0&&(!Number.isInteger($.rect.width)||$.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if($.rect.height!==void 0&&(!Number.isInteger($.rect.height)||$.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},F2=($,J,Y)=>{let X=UJ($),Q=[],Z=0;for(let K of X){let G=Math.ceil(J/K.widthDivisor),W=Math.ceil(Y/K.heightDivisor),j=G*K.sampleBytes,U=j*W;Q.push({offset:Z,stride:j}),Z+=U}return Q},UJ=($)=>{let J=(Y,X,Q,Z,K)=>{let G=[{sampleBytes:Y,widthDivisor:1,heightDivisor:1},{sampleBytes:X,widthDivisor:Q,heightDivisor:Z},{sampleBytes:X,widthDivisor:Q,heightDivisor:Z}];if(K)G.push({sampleBytes:Y,widthDivisor:1,heightDivisor:1});return G};switch($){case"I420":return J(1,1,2,2,!1);case"I420P10":case"I420P12":return J(2,2,2,2,!1);case"I420A":return J(1,1,2,2,!0);case"I420AP10":case"I420AP12":return J(2,2,2,2,!0);case"I422":return J(1,1,2,1,!1);case"I422P10":case"I422P12":return J(2,2,2,1,!1);case"I422A":return J(1,1,2,1,!0);case"I422AP10":case"I422AP12":return J(2,2,2,1,!0);case"I444":return J(1,1,1,1,!1);case"I444P10":case"I444P12":return J(2,2,1,1,!1);case"I444A":return J(1,1,1,1,!0);case"I444AP10":case"I444AP12":return J(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:v0($),F(!1)}},Z5=($,J)=>{let Y={left:0,top:0,width:$.codedWidth,height:$.codedHeight},X=J.rect,Q=L2(Y,X,$.codedWidth,$.codedHeight,$.format),Z=J.layout,K;if(!J.format||J.format===$.format)K=$.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(J.format))K=J.format;else throw Error("NotSupportedError: Invalid destination format.");return O2(Q,K,Z)},L2=($,J,Y,X,Q)=>{let Z={...$};if(J!==void 0){if(J.width===0||J.height===0)throw TypeError("visibleRect dimensions cannot be zero.");if((J.x||0)+(J.width||0)>Y)throw TypeError("visibleRect exceeds codedWidth.");if((J.y||0)+(J.height||0)>X)throw TypeError("visibleRect exceeds codedHeight.");Z.x=J.x||0,Z.y=J.y||0,Z.width=J.width||0,Z.height=J.height||0}if(!w2(Q,Z))throw TypeError("visibleRect alignment is invalid for the format.");return Z},w2=($,J)=>{if($===null)return!0;let Y=UJ($);for(let X=0;X<Y.length;X++){let Q=Y[X],Z=Q.widthDivisor,K=Q.heightDivisor;if((J.x||0)%Z!==0)return!1;if((J.y||0)%K!==0)return!1}return!0},O2=($,J,Y)=>{let X=UJ(J),Q=X.length;if(Y!==void 0&&Y.length!==Q)throw TypeError(`Layout must have ${Q} planes.`);let Z=0,K=[],G=[];for(let W=0;W<Q;W++){let j=X[W],U=j.sampleBytes,q=j.widthDivisor,N=j.heightDivisor,_={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(_.sourceTop=Math.ceil(Math.trunc($.y||0)/N),_.sourceHeight=Math.ceil(Math.trunc($.height||0)/N),_.sourceLeftBytes=Math.floor(Math.trunc($.x||0)/q)*U,_.sourceWidthBytes=Math.floor(Math.trunc($.width||0)/q)*U,Y!==void 0){let R=Y[W];if(R.stride<_.sourceWidthBytes)throw TypeError(`Stride for plane ${W} is too small.`);_.destinationOffset=R.offset,_.destinationStride=R.stride}else _.destinationOffset=Z,_.destinationStride=_.sourceWidthBytes;let z=_.destinationStride*_.sourceHeight+_.destinationOffset;if(z>4294967295)throw TypeError("Allocation size exceeds limit.");G.push(z),Z=Math.max(Z,z);for(let R=0;R<W;R++){let H=K[R];if(G[W]<=H.destinationOffset||G[R]<=_.destinationOffset)continue;throw TypeError("Planes overlap.")}K.push(_)}return{allocationSize:Z,computedLayouts:K}},GJ=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class p8{constructor(){this._referenceCount=0}}class c0{get microsecondTimestamp(){return Math.trunc(F1*this.timestamp)}get microsecondDuration(){return Math.trunc(F1*this.duration)}constructor($){if(this._closed=!1,H$($)){if($.format===null)throw TypeError("AudioData with null format is not supported.");this._data=$,this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=$.numberOfFrames,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp/1e6,this.duration=$.numberOfFrames/$.sampleRate}else if($ instanceof p8){if(this._data=$,$._referenceCount++,this.format=$.getFormat(),!GJ.has(this.format))throw TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=$.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=$.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=$.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=$.getTimestamp(),!Number.isFinite(this.timestamp))throw TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!$||typeof $!=="object")throw TypeError("Invalid AudioDataInit: must be an object.");if(!GJ.has($.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite($.sampleRate)||$.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger($.numberOfChannels)||$.numberOfChannels===0)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite($?.timestamp))throw TypeError("init.timestamp must be a number.");let J=$.data.byteLength/(r1($.format)*$.numberOfChannels);if(!Number.isInteger(J))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=J,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp,this.duration=J/$.sampleRate;let Y;if($.data instanceof ArrayBuffer)Y=new Uint8Array($.data);else if(ArrayBuffer.isView($.data))Y=new Uint8Array($.data.buffer,$.data.byteOffset,$.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let X=this.numberOfFrames*this.numberOfChannels*r1(this.format);if(Y.byteLength<X)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=Y}R$?.register(this,{type:"audio",data:this._data},this)}allocationSize($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Number.isInteger($.planeIndex)||$.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if($.format!==void 0&&!GJ.has($.format))throw TypeError("Invalid format.");if($.frameOffset!==void 0&&(!Number.isInteger($.frameOffset)||$.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if($.frameCount!==void 0&&(!Number.isInteger($.frameCount)||$.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let J=$.format??this.format,Y=$.frameOffset??0;if(Y>=this.numberOfFrames)throw RangeError("frameOffset out of range");let X=$.frameCount!==void 0?$.frameCount:this.numberOfFrames-Y;if(X>this.numberOfFrames-Y)throw RangeError("frameCount out of range");let Q=r1(J),Z=d8(J);if(Z&&$.planeIndex>=this.numberOfChannels)throw RangeError("planeIndex out of range");if(!Z&&$.planeIndex!==0)throw RangeError("planeIndex out of range");return(Z?X:X*this.numberOfChannels)*Q}copyTo($,J){if(!k6($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!Number.isInteger(J.planeIndex)||J.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(J.format!==void 0&&!GJ.has(J.format))throw TypeError("Invalid format.");if(J.frameOffset!==void 0&&(!Number.isInteger(J.frameOffset)||J.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(J.frameCount!==void 0&&(!Number.isInteger(J.frameCount)||J.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{format:Y,frameCount:X,frameOffset:Q}=J,{planeIndex:Z}=J,K=this.format,G=Y??this.format;if(!G)throw Error("Destination format not determined");let W=this.numberOfFrames,j=this.numberOfChannels,U=Q??0;if(U>=W)throw RangeError("frameOffset out of range");let q=X!==void 0?X:W-U;if(q>W-U)throw RangeError("frameCount out of range");let N=r1(G),_=d8(G);if(_&&Z>=j)throw RangeError("planeIndex out of range");if(!_&&Z!==0)throw RangeError("planeIndex out of range");let z=(_?q:q*j)*N;if($.byteLength<z)throw RangeError("Destination buffer is too small");let R=l($),H=K5(G);if(H$(this._data))if(C8()&&j>2&&G!==K)B2(this._data,R,K,G,j,Z,U,q);else this._data.copyTo($,{planeIndex:Z,frameOffset:U,frameCount:q,format:G});else{let A=Q5(K),M=r1(K),L=d8(K),w;if(this._data instanceof p8){let D=(B)=>{let C=this._data.getDataPlane(B);if(!(C instanceof Uint8Array))throw TypeError("getDataPlane() must return a Uint8Array.");let E=W*M*(L?1:j);if(C.byteLength!==E)throw TypeError(`Data plane ${B} has invalid size. Expected exactly ${E} bytes, got ${C.byteLength} bytes.`);return C};if(L)if(_)w=D(Z),Z=0;else{w=new Uint8Array(W*M*j);for(let B=0;B<j;B++){let C=D(B);w.set(C,B*W*M)}}else w=D(0)}else w=this._data;let O=l(w);for(let D=0;D<q;D++)if(_){let B=D*N,C;if(L)C=(Z*W+(D+U))*M;else C=((D+U)*j+Z)*M;let E=A(O,C);H(R,B,E)}else for(let B=0;B<j;B++){let E=(D*j+B)*N,P;if(L)P=(B*W+(D+U))*M;else P=((D+U)*j+B)*M;let v=A(O,P);H(R,E,v)}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(this._data instanceof p8){let $=new c0(this._data);return $.setTimestamp(this.timestamp),$}else if(H$(this._data)){let $=new c0(this._data.clone());return $.setTimestamp(this.timestamp),$}else return new c0({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim($,J=this.numberOfFrames){if(!Number.isInteger($)||$<0)throw TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(J)||J<0)throw TypeError("endSample must be a non-negative integer.");if($>this.numberOfFrames)throw RangeError("startSample out of range.");if(J>this.numberOfFrames)throw RangeError("endSample out of range.");if(J<$)throw RangeError("endSample must not be less than startSample.");if(this._closed)throw Error("AudioSample is closed.");let Y=J-$,X=r1(this.format),Q;if(d8(this.format)){let Z=Y*X;if(Q=new Uint8Array(Z*this.numberOfChannels),Y>0)for(let K=0;K<this.numberOfChannels;K++)this.copyTo(Q.subarray(K*Z,(K+1)*Z),{planeIndex:K,format:this.format,frameOffset:$,frameCount:Y})}else if(Q=new Uint8Array(Y*this.numberOfChannels*X),Y>0)this.copyTo(Q,{planeIndex:0,format:this.format,frameOffset:$,frameCount:Y});return new c0({data:Q,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+$/this.sampleRate})}close(){if(this._closed)return;if(R$?.unregister(this),this._data instanceof p8){if(this._data._referenceCount--,this._data._referenceCount===0)this._data.close()}else if(H$(this._data))this._data.close();else this._data=new Uint8Array(0);this._closed=!0}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(this._data instanceof p8)return this._createAudioDataFromData();else if(H$(this._data))if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();else return this._createAudioDataFromData();else 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()})}_createAudioDataFromData(){if(d8(this.format)){let $=this.allocationSize({planeIndex:0,format:this.format}),J=new ArrayBuffer($*this.numberOfChannels);for(let Y=0;Y<this.numberOfChannels;Y++)this.copyTo(new Uint8Array(J,Y*$,$),{planeIndex:Y,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:J})}else{let $=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo($,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:$})}}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let $=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),J=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let Y=0;Y<this.numberOfChannels;Y++)this.copyTo(J,{planeIndex:Y,format:"f32-planar"}),$.copyToChannel(J,Y);return $}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}[Symbol.dispose](){this.close()}static*_fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,X=$.numberOfChannels,Q=$.sampleRate,Z=$.length,K=Math.floor(Y/X),G=0,W=Z;while(W>0){let j=Math.min(K,W),U=new Float32Array(X*j);for(let q=0;q<X;q++)$.copyFromChannel(U.subarray(q*j,(q+1)*j),q,G);yield new c0({format:"f32-planar",sampleRate:Q,numberOfFrames:j,numberOfChannels:X,timestamp:J+G/Q,data:U}),G+=j,W-=j}}static fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,X=$.numberOfChannels,Q=$.sampleRate,Z=$.length,K=Math.floor(Y/X),G=0,W=Z,j=[];while(W>0){let U=Math.min(K,W),q=new Float32Array(X*U);for(let _=0;_<X;_++)$.copyFromChannel(q.subarray(_*U,(_+1)*U),_,G);let N=new c0({format:"f32-planar",sampleRate:Q,numberOfFrames:U,numberOfChannels:X,timestamp:J+G/Q,data:q});j.push(N),G+=U,W-=U}return j}}var r1=($)=>{switch($){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},d8=($)=>{switch($){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Q5=($)=>{switch($){case"u8":case"u8-planar":return(J,Y)=>(J.getUint8(Y)-128)/128;case"s16":case"s16-planar":return(J,Y)=>J.getInt16(Y,!0)/32768;case"s32":case"s32-planar":return(J,Y)=>J.getInt32(Y,!0)/2147483648;case"f32":case"f32-planar":return(J,Y)=>J.getFloat32(Y,!0)}},K5=($)=>{switch($){case"u8":case"u8-planar":return(J,Y,X)=>J.setUint8(Y,r0((X+1)*127.5,0,255));case"s16":case"s16-planar":return(J,Y,X)=>J.setInt16(Y,r0(Math.round(X*32767),-32768,32767),!0);case"s32":case"s32-planar":return(J,Y,X)=>J.setInt32(Y,r0(Math.round(X*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(J,Y,X)=>J.setFloat32(Y,X,!0)}},H$=($)=>{return typeof AudioData<"u"&&$ instanceof AudioData};var B2=($,J,Y,X,Q,Z,K,G)=>{let W=Q5(Y),j=K5(X),U=r1(Y),q=r1(X),N=d8(Y);if(d8(X))if(N){let V=new ArrayBuffer(G*U),z=l(V);$.copyTo(V,{planeIndex:Z,frameOffset:K,frameCount:G,format:Y});for(let R=0;R<G;R++){let H=R*U,A=R*q,M=W(z,H);j(J,A,M)}}else{let V=new ArrayBuffer(G*Q*U),z=l(V);$.copyTo(V,{planeIndex:0,frameOffset:K,frameCount:G,format:Y});for(let R=0;R<G;R++){let H=(R*Q+Z)*U,A=R*q,M=W(z,H);j(J,A,M)}}else if(N){let V=G*U,z=new ArrayBuffer(V),R=l(z);for(let H=0;H<Q;H++){$.copyTo(z,{planeIndex:H,frameOffset:K,frameCount:G,format:Y});for(let A=0;A<G;A++){let M=A*U,L=(A*Q+H)*q,w=W(R,M);j(J,L,w)}}}else{let V=new ArrayBuffer(G*Q*U),z=l(V);$.copyTo(V,{planeIndex:0,frameOffset:K,frameCount:G,format:Y});for(let R=0;R<G;R++)for(let H=0;H<Q;H++){let A=R*Q+H,M=A*U,L=A*q,w=W(z,M);j(J,L,w)}}};/*!
|
|
224
230
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
225
231
|
*
|
|
226
232
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -232,66 +238,44 @@ var PZ=Object.defineProperty;var bZ=($,J)=>{for(var Y in J)PZ($,Y,{get:J[Y],enum
|
|
|
232
238
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
233
239
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
234
240
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
235
|
-
*/var
|
|
241
|
+
*/var q$=[],N$=[];/*!
|
|
236
242
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
237
243
|
*
|
|
238
244
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
239
245
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
240
246
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
241
|
-
*/var
|
|
247
|
+
*/var G5=($)=>{let Y=0,X=0,Q=~$;if(Q&128)Q&=-129,Y=-1;X=((Q&240)>>4)+5;let Z=(1<<X|(Q&15)<<X-4|1<<X-5)-33;return Y===0?Z:-Z};var W5=($)=>{let J=0,Y=0,X=$^85;if(X&128)X&=-129,J=-1;Y=((X&240)>>4)+4;let Q=0;if(Y!==4)Q=1<<Y|(X&15)<<Y-4|1<<Y-5;else Q=X<<1|1;return J===0?Q:-Q};/*!
|
|
242
248
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
243
249
|
*
|
|
244
250
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
245
251
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
246
252
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
247
|
-
*/var u8=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.metadataOnly!==void 0&&typeof $.metadataOnly!=="boolean")throw TypeError("options.metadataOnly, when defined, must be a boolean.");if($.verifyKeyPackets!==void 0&&typeof $.verifyKeyPackets!=="boolean")throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if($.verifyKeyPackets&&$.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if($.skipLiveWait!==void 0&&typeof $.skipLiveWait!=="boolean")throw TypeError("options.skipLiveWait, when defined, must be a boolean.")},l1=($)=>{if(!g6($))throw TypeError("timestamp must be a number.")},eY=($,J,Y)=>{if(Y.verifyKeyPackets)return J.then(async(X)=>{if(!X||X.type==="delta")return X;let Q=await $.determinePacketType(X);if(Q)X.type=Q;return X});else return J};class p1{constructor($){if(!($ instanceof m8))throw TypeError("track must be an InputTrack.");this._track=$}async getFirstPacket($={}){if(u8($),this._track.input._disposed)throw new R0;return eY(this._track,this._track._backing.getFirstPacket($),$)}async getFirstKeyPacket($={}){u8($);let J=await this.getFirstPacket($);if(!J)return null;if(J.type==="key")return J;return this.getNextKeyPacket(J,$)}async getPacket($,J={}){if(l1($),u8(J),this._track.input._disposed)throw new R0;return eY(this._track,this._track._backing.getPacket($,J),J)}async getNextPacket($,J={}){if(!($ instanceof i))throw TypeError("packet must be an EncodedPacket.");if(u8(J),this._track.input._disposed)throw new R0;return eY(this._track,this._track._backing.getNextPacket($,J),J)}async getKeyPacket($,J={}){if(l1($),u8(J),this._track.input._disposed)throw new R0;if(!J.verifyKeyPackets)return this._track._backing.getKeyPacket($,J);let Y=await this._track._backing.getKeyPacket($,J);if(!Y)return Y;if(L(Y.type==="key"),await this._track.determinePacketType(Y)==="delta")return this.getKeyPacket(Y.timestamp-1/await this._track.getTimeResolution(),J);return Y}async getNextKeyPacket($,J={}){if(!($ instanceof i))throw TypeError("packet must be an EncodedPacket.");if(u8(J),this._track.input._disposed)throw new R0;if(!J.verifyKeyPackets)return this._track._backing.getNextKeyPacket($,J);let Y=await this._track._backing.getNextKeyPacket($,J);if(!Y)return Y;if(L(Y.type==="key"),await this._track.determinePacketType(Y)==="delta")return this.getNextKeyPacket(Y,J);return Y}packets($,J,Y={}){if($!==void 0&&!($ instanceof i))throw TypeError("startPacket must be an EncodedPacket.");if($!==void 0&&$.isMetadataOnly&&!Y?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(J!==void 0&&!(J instanceof i))throw TypeError("endPacket must be an EncodedPacket.");if(u8(Y),this._track.input._disposed)throw new R0;let X=[],{promise:Q,resolve:Z}=U0(),{promise:K,resolve:G}=U0(),W=!1,j=!1,U=null,q=[],V=()=>Math.max(2,q.length);(async()=>{let N=$??await this.getFirstPacket(Y);while(N&&!j&&!this._track.input._disposed){if(J&&N.sequenceNumber>=J?.sequenceNumber)break;if(X.length>V()){({promise:K,resolve:G}=U0()),await K;continue}X.push(N),Z(),{promise:Q,resolve:Z}=U0(),N=await this.getNextPacket(N,Y)}W=!0,Z()})().catch((N)=>{if(!U)U=N,Z()});let _=this._track;return{async next(){while(!0)if(_.input._disposed)throw new R0;else if(j)return{value:void 0,done:!0};else if(U)throw U;else if(X.length>0){let N=X.shift(),R=performance.now();q.push(R);while(q.length>0&&R-q[0]>=1000)q.shift();return G(),{value:N,done:!1}}else if(W)return{value:void 0,done:!0};else await Q},async return(){return j=!0,G(),Z(),{value:void 0,done:!0}},async throw(N){throw N},[Symbol.asyncIterator](){return this}}}}class ZJ{constructor($,J){this.onSample=$,this.onError=J}}class QJ{mediaSamplesInRange($=-1/0,J=1/0,Y){l1($),l1(J);let X=[],Q=!1,Z=null,{promise:K,resolve:G}=U0(),{promise:W,resolve:j}=U0(),U=!1,q=!1,V=!1,_=null,N={...Y,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let H=await this._createDecoder((D)=>{if(j(),D.timestamp>=J)q=!0;if(q){D.close();return}if(Z)if(D.timestamp>$)X.push(Z),Q=!0;else Z.close();if(D.timestamp>=$)X.push(D),Q=!0;if(Z=Q?null:D,X.length>0)G(),{promise:K,resolve:G}=U0()},(D)=>{if(!_)_=D,G()}),A=this._createPacketSink(),M=await A.getKeyPacket($,N)??await A.getFirstKeyPacket(N),F=M,O=void 0,B=A.packets(M??void 0,O,N);await B.next();while(F&&!q&&!this._track.input._disposed){let D=U5(X.length);if(X.length+H.getDecodeQueueSize()>D){({promise:W,resolve:j}=U0()),await W;continue}H.decode(F);let w=await B.next();if(w.done)break;F=w.value}if(await B.return(),!V&&!this._track.input._disposed)await H.flush();if(H.close(),!Q&&Z)X.push(Z);U=!0,G()})().catch((H)=>{if(!_)_=H,G()});let R=this._track,z=()=>{Z?.close();for(let H of X)H.close()};return{async next(){while(!0)if(R.input._disposed)throw z(),new R0;else if(V)return{value:void 0,done:!0};else if(_)throw z(),_;else if(X.length>0){let H=X.shift();return j(),{value:H,done:!1}}else if(!U)await K;else return{value:void 0,done:!0}},async return(){return V=!0,q=!0,j(),G(),z(),{value:void 0,done:!0}},async throw(H){throw H},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps($,J){x7($);let Y=v7($),X=[],Q=[],{promise:Z,resolve:K}=U0(),{promise:G,resolve:W}=U0(),j=!1,U=!1,q=null,V=(z)=>{Q.push(z),K(),{promise:Z,resolve:K}=U0()},_={...J,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let z=await this._createDecoder((D)=>{if(W(),U){D.close();return}let w=0;while(X.length>0&&D.timestamp-X[0]>-0.0000000001)w++,X.shift();if(w>0)for(let P=0;P<w;P++)V(P<w-1?D.clone():D);else D.close()},(D)=>{if(!q)q=D,K()}),H=this._createPacketSink(),A=null,M=null,F=-1,O=async()=>{L(M);let D=M;z.decode(D);while(D.sequenceNumber<F){let w=U5(Q.length);while(Q.length+z.getDecodeQueueSize()>w&&!U)({promise:G,resolve:W}=U0()),await G;if(U)break;let P=await H.getNextPacket(D,_);L(P),z.decode(P),D=P}F=-1},B=async()=>{await z.flush();for(let D=0;D<X.length;D++)V(null);X.length=0};for await(let D of Y){if(l1(D),U||this._track.input._disposed)break;let w=await H.getPacket(D,_),P=w&&await H.getKeyPacket(D,_);if(!P){if(F!==-1)await O(),await B();V(null),A=null;continue}if(A&&(P.sequenceNumber!==M.sequenceNumber||w.timestamp<A.timestamp))await O(),await B();X.push(w.timestamp),F=Math.max(w.sequenceNumber,F),A=w,M=P}if(!U&&!this._track.input._disposed){if(F!==-1)await O();await B()}z.close(),j=!0,K()})().catch((z)=>{if(!q)q=z,K()});let N=this._track,R=()=>{for(let z of Q)z?.close()};return{async next(){while(!0)if(N.input._disposed)throw R(),new R0;else if(U)return{value:void 0,done:!0};else if(q)throw R(),q;else if(Q.length>0){let z=Q.shift();return L(z!==void 0),W(),{value:z,done:!1}}else if(!j)await Z;else return{value:void 0,done:!0}},async return(){return U=!0,W(),K(),R(),{value:void 0,done:!0}},async throw(z){throw z},[Symbol.asyncIterator](){return this}}}}var U5=($)=>{return $===0?40:8};class j5 extends ZJ{constructor($,J,Y,X,Q,Z){super($,J);this.codec=Y,this.decoderConfig=X,this.rotation=Q,this.timeResolution=Z,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new n8,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.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new n8;let K=Z$.find((G)=>G.supports(Y,X));if(K)this.customDecoder=new K,this.customDecoder.codec=Y,this.customDecoder.config=X,this.customDecoder.onSample=(G)=>{if(!(G instanceof l0))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(G)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let G=(j)=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){let U=this.alphaQueue.shift();L(U!==void 0),await this.mergeAlpha(j,U)}else this.colorQueue.push(j)}).catch((U)=>this.onError(U))};if(Y==="avc"&&this.decoderConfig.description&&h6()){let j=kJ(_0(this.decoderConfig.description));if(j&&j.sequenceParameterSets.length>0){let U=d6(j.sequenceParameterSets[0]);if(U&&U.frameMbsOnlyFlag===0)this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}}}let W=Error("Decoding error").stack;this.decoder=new VideoDecoder({output:(j)=>{try{G(j)}catch(U){this.onError(U)}},error:(j)=>{j.stack=W,this.onError(j)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;else return L(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0)}decode($){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture($.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).then(()=>this.customDecoderQueueSize--);else{if(L(this.decoder),!F8())PJ(this.inputTimestamps,$.timestamp,(J)=>J);if(h6()&&this.currentPacketIndex===0){if(this.codec==="avc"){let J=[];for(let X of hJ($.data,this.decoderConfig)){let Q=b8($.data[X.offset]);if(Q===S0.AUD)J.length=0;if(!(Q>=20&&Q<=31))J.push($.data.subarray(X.offset,X.offset+X.length))}let Y=n7(J,this.decoderConfig);$=new i(Y,$.type,$.timestamp,$.duration)}else if(this.codec==="hevc"){let J=s7($.data,this.decoderConfig);if(J)$=new i(J,$.type,$.timestamp,$.duration)}}this.decoder.decode($.toEncodedVideoChunk()),this.decodeAlphaData($)}this.currentPacketIndex++}decodeAlphaData($){if(!$.sideData.alpha){this.pushNullAlphaFrame();return}if(!this.merger)this.merger=new KJ;if(!this.alphaDecoder){let Y=(Q)=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){let Z=this.colorQueue.shift();L(Z!==void 0),await this.mergeAlpha(Z,Q)}else this.alphaQueue.push(Q);this.decodedAlphaChunkCount++;while(this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let Z=this.colorQueue.shift();L(Z!==void 0),await this.mergeAlpha(Z,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch((Z)=>this.onError(Z))},X=Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:(Q)=>{try{Y(Q)}catch(Z){this.onError(Z)}},error:(Q)=>{Q.stack=X,this.onError(Q)}}),this.alphaDecoder.configure(this.decoderConfig)}let J=T8(this.codec,this.decoderConfig,$.sideData.alpha);if(!this.alphaHadKeyframe)this.alphaHadKeyframe=J==="key";if(this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture($.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode($.alphaToEncodedVideoChunk(J??$.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){if(this.alphaDecoderQueueSize===0)this.alphaQueue.push(null);else this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture($){for(let J of l6($,this.decoderConfig)){let Y=y1($[J.offset]);if(Y===z0.RASL_N||Y===z0.RASL_R)return!0}return!1}sampleHandler($){if(F8()){if(this.sampleQueue.length>0&&$.timestamp>=K0(this.sampleQueue).timestamp){for(let J of this.sampleQueue)this.finalizeAndEmitSample(J);this.sampleQueue.length=0}PJ(this.sampleQueue,$,(J)=>J.timestamp)}else{let J=this.inputTimestamps.shift();L(J!==void 0),$.setTimestamp(J),this.finalizeAndEmitSample($)}}finalizeAndEmitSample($){$.setTimestamp(Math.round($.timestamp*this.timeResolution)/this.timeResolution),$.setDuration(Math.round($.duration*this.timeResolution)/this.timeResolution),$.setRotation(this.rotation),this.onSample($)}async mergeAlpha($,J){if(!J){let Q=new l0($);this.sampleHandler(Q);return}L(this.merger);let Y=await this.merger.update($,J),X=new l0(Y);this.sampleHandler(X)}async flush(){if(this.customDecoder)await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());else L(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;if(F8()){for(let $ of this.sampleQueue)this.finalizeAndEmitSample($);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else L(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.merger?.close();for(let $ of this.sampleQueue)$.close();this.sampleQueue.length=0}}var W5=!1;class KJ{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let $=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement==="function";if(!KJ.forceCpu&&$&&!W5)try{if(typeof OffscreenCanvas<"u")this.canvas=new OffscreenCanvas(300,150);else this.canvas=document.createElement("canvas");let J=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!J)throw Error("Couldn't acquire WebGL 2 context.");this.gl=J,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)}catch(J){this.gl=null,this.canvas=null,W5=!0,console.warn("Falling back to CPU for color/alpha merging.",J)}}async update($,J){if(this.gl)return this.updateGpu($,J);else return this.updateCpu($,J)}createProgram(){L(this.gl);let $=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
248
|
-
in vec2 a_position;
|
|
249
|
-
in vec2 a_texCoord;
|
|
250
|
-
out vec2 v_texCoord;
|
|
251
|
-
|
|
252
|
-
void main() {
|
|
253
|
-
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
254
|
-
v_texCoord = a_texCoord;
|
|
255
|
-
}
|
|
256
|
-
`),J=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
257
|
-
precision highp float;
|
|
258
|
-
|
|
259
|
-
uniform sampler2D u_colorTexture;
|
|
260
|
-
uniform sampler2D u_alphaTexture;
|
|
261
|
-
in vec2 v_texCoord;
|
|
262
|
-
out vec4 fragColor;
|
|
263
|
-
|
|
264
|
-
void main() {
|
|
265
|
-
vec3 color = texture(u_colorTexture, v_texCoord).rgb;
|
|
266
|
-
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
267
|
-
fragColor = vec4(color, alpha);
|
|
268
|
-
}
|
|
269
|
-
`),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createShader($,J){L(this.gl);let Y=this.gl.createShader($);return this.gl.shaderSource(Y,J),this.gl.compileShader(Y),Y}createVAO(){L(this.gl),L(this.program);let $=this.gl.createVertexArray();this.gl.bindVertexArray($);let J=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),Y=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,Y),this.gl.bufferData(this.gl.ARRAY_BUFFER,J,this.gl.STATIC_DRAW);let X=this.gl.getAttribLocation(this.program,"a_position"),Q=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(X),this.gl.vertexAttribPointer(X,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(Q),this.gl.vertexAttribPointer(Q,2,this.gl.FLOAT,!1,16,8),$}createTexture(){L(this.gl);let $=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,$),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),$}updateGpu($,J){if(L(this.gl),L(this.canvas),$.displayWidth!==this.canvas.width||$.displayHeight!==this.canvas.height)this.canvas.width=$.displayWidth,this.canvas.height=$.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,$),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,J),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);let Y=new VideoFrame(this.canvas,{timestamp:$.timestamp,duration:$.duration??void 0});return $.close(),J.close(),Y}updateCpu($,J){if(!this.worker){let Q=new Blob([`(${M2.toString()})()`],{type:"application/javascript"}),Z=URL.createObjectURL(Q);this.worker=new Worker(Z),URL.revokeObjectURL(Z),this.worker.addEventListener("message",(K)=>{let G=K.data,W=this.pendingRequests.get(G.id);if(!W)return;if(this.pendingRequests.delete(G.id),"error"in G)W.reject(Error(G.error));else W.resolve(G.frame)}),this.worker.addEventListener("error",(K)=>{let G=Error(K.message||"Color/alpha merge worker error.");for(let W of this.pendingRequests.values())W.reject(G);this.pendingRequests.clear()})}let Y=this.nextRequestId++,X=U0();return this.pendingRequests.set(Y,X),this.worker.postMessage({id:Y,color:$,alpha:J},{transfer:[$,J]}),X.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let $=Error("Color/alpha merger closed.");for(let J of this.pendingRequests.values())J.reject($);this.pendingRequests.clear()}}KJ.forceCpu=!0;var M2=()=>{let $=null,J=null,Y=Promise.resolve();self.addEventListener("message",(W)=>{let{id:j,color:U,alpha:q}=W.data;Y=Y.then(async()=>{try{let V=await X(U,q);self.postMessage({id:j,frame:V},{transfer:[V]})}catch(V){self.postMessage({id:j,error:V.message})}finally{U.close(),q.close()}})});let X=async(W,j)=>{let U=W.format,q=j.format;if(!U||!q)throw Error("CPU color/alpha merging requires a known VideoFrame format.");let V=U.includes("P10"),_=U.includes("P12"),N=q.includes("P10"),R=q.includes("P12");if(N!==V||R!==_)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${U}', alpha: '${q}').`);let{codedWidth:z,codedHeight:H}=W;if(U==="RGBX"||U==="RGBA"||U==="BGRX"||U==="BGRA")return await Q(W,j,z,H,U);else if(U==="I420"||U==="I420P10"||U==="I420P12"||U==="I422"||U==="I422P10"||U==="I422P12"||U==="I444"||U==="I444P10"||U==="I444P12")return await Z(W,j,z,H,U);else if(U==="NV12")return await K(W,j,z,H);throw Error(`CPU color/alpha merging does not support format '${U}'.`)},Q=async(W,j,U,q,V)=>{let _=U*q,N=new Uint8Array(_*4);await W.copyTo(N);let R=await G(j,U,q,1);for(let A=0,M=3;A<_;A++,M+=4)N[M]=R[A];let H={format:V==="RGBX"||V==="RGBA"?"RGBA":"BGRA",codedWidth:U,codedHeight:q,timestamp:W.timestamp,duration:W.duration??void 0,transfer:[N.buffer]};return new VideoFrame(N,H)},Z=async(W,j,U,q,V)=>{let _=V.includes("P10"),N=V.includes("P12"),R=_||N?2:1,z,H;if(V.startsWith("I420"))z=Math.ceil(U/2),H=Math.ceil(q/2);else if(V.startsWith("I422"))z=Math.ceil(U/2),H=q;else z=U,H=q;let A=U*q,M=z*H,F=A*R,O=M*R,B=A*R,D=F+2*O+B,w=new Uint8Array(D);await W.copyTo(w);let P=await G(j,U,q,R),T=F+2*O;w.set(P,T);let E={format:V.slice(0,4)+"A"+V.slice(4),codedWidth:U,codedHeight:q,timestamp:W.timestamp,duration:W.duration??void 0,transfer:[w.buffer]};return new VideoFrame(w,E)},K=async(W,j,U,q)=>{let V=U*q,_=Math.ceil(U/2),N=Math.ceil(q/2),R=_*N,z=W.allocationSize();if(!J||J.byteLength!==z)J=new Uint8Array(z);await W.copyTo(J);let H=new Uint8Array(V+2*R+V);H.set(J.subarray(0,V),0);let A=V,M=V+R,F=V;for(let D=0;D<R;D++)H[A+D]=J[F+D*2],H[M+D]=J[F+D*2+1];let O=await G(j,U,q,1);H.set(O,V+2*R);let B={format:"I420A",codedWidth:U,codedHeight:q,timestamp:W.timestamp,duration:W.duration??void 0,transfer:[H.buffer]};return new VideoFrame(H,B)},G=async(W,j,U,q)=>{let V=W.allocationSize();if(!$||$.byteLength!==V)$=new Uint8Array(V);await W.copyTo($);let _=W.format;if(_==="RGBA"||_==="BGRA"||_==="RGBX"||_==="BGRX"){let N=_==="RGBA"||_==="RGBX"?0:2,R=j*U;for(let z=0;z<R;z++)$[z]=$[z*4+N];return $.subarray(0,R)}else return $.subarray(0,j*U*q)}};class M6 extends QJ{constructor($){if(!($ instanceof Q8))throw TypeError("videoTrack must be an InputVideoTrack.");super();this._track=$}async _createDecoder($,J){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.");let Y=await this._track.getCodec(),X=await this._track.getRotation(),Q=await this._track.getDecoderConfig(),Z=await this._track.getTimeResolution();return L(Y&&Q),new j5($,J,Y,Q,X,Z)}_createPacketSink(){return new p1(this._track)}async getSample($,J={}){l1($);for await(let Y of this.mediaSamplesAtTimestamps([$],J))return Y;throw Error("Internal error: Iterator returned nothing.")}samples($,J,Y={}){return this.mediaSamplesInRange($,J,Y)}samplesAtTimestamps($,J={}){return this.mediaSamplesAtTimestamps($,J)}}class GJ{constructor($,J={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!($ instanceof Q8))throw TypeError("videoTrack must be an InputVideoTrack.");if(J&&typeof J!=="object")throw TypeError("options must be an object.");if(J.alpha!==void 0&&typeof J.alpha!=="boolean")throw TypeError("options.alpha, when provided, must be a boolean.");if(J.width!==void 0&&(!Number.isInteger(J.width)||J.width<=0))throw TypeError("options.width, when defined, must be a positive integer.");if(J.height!==void 0&&(!Number.isInteger(J.height)||J.height<=0))throw TypeError("options.height, when defined, must be a positive integer.");if(J.fit!==void 0&&!["fill","contain","cover"].includes(J.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(J.width!==void 0&&J.height!==void 0&&J.fit===void 0)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(J.crop!==void 0)L6(J.crop,"options.");if(J.poolSize!==void 0&&(typeof J.poolSize!=="number"||!Number.isInteger(J.poolSize)||J.poolSize<0))throw TypeError("poolSize must be a non-negative integer.");this._videoTrack=$,this._alpha=J.alpha??!1,this._options=J,this._fit=J.fit??"fill",this._videoSampleSink=new M6($),this._canvasPool=Array.from({length:J.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let $=this._options,J=this._videoTrack,Y=$.rotation??await J.getRotation(),X=await J.getSquarePixelWidth(),Q=await J.getSquarePixelHeight(),[Z,K]=Y%180===0?[X,Q]:[Q,X],G=$.crop;if(G)G=q$(G,Z,K);let[W,j]=G?[G.width,G.height]:[Z,K],U=W/j;if($.width!==void 0&&$.height===void 0)W=$.width,j=Math.round(W/U);else if($.width===void 0&&$.height!==void 0)j=$.height,W=Math.round(j*U);else if($.width!==void 0&&$.height!==void 0)W=$.width,j=$.height;this._width=W,this._height=j,this._rotation=Y,this._crop=G})()}_videoSampleToWrappedCanvas($){let J=this._width,Y=this._height,X=this._canvasPool[this._nextCanvasIndex],Q=!1;if(!X){if(typeof document<"u")X=document.createElement("canvas"),X.width=J,X.height=Y;else X=new OffscreenCanvas(J,Y);if(this._canvasPool.length>0)this._canvasPool[this._nextCanvasIndex]=X;Q=!0}if(this._canvasPool.length>0)this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length;let Z=X.getContext("2d",{alpha:this._alpha||o8()});if(L(Z),Z.resetTransform(),!Q)if(!this._alpha&&o8())Z.fillStyle="black",Z.fillRect(0,0,J,Y);else Z.clearRect(0,0,J,Y);$.drawWithFit(Z,{fit:this._fit,rotation:this._rotation,crop:this._crop});let K={canvas:X,timestamp:$.timestamp,duration:$.duration};return $.close(),K}async getCanvas($,J){l1($),await this._ensureInit();let Y=await this._videoSampleSink.getSample($,J);return Y&&this._videoSampleToWrappedCanvas(Y)}async*canvases($,J,Y){await this._ensureInit(),yield*y6(this._videoSampleSink.samples($,J,Y),(X)=>this._videoSampleToWrappedCanvas(X))}async*canvasesAtTimestamps($,J){await this._ensureInit(),yield*y6(this._videoSampleSink.samplesAtTimestamps($,J),(Y)=>Y&&this._videoSampleToWrappedCanvas(Y))}}class q5 extends ZJ{constructor($,J,Y,X){super($,J);this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new n8,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let Q=(K)=>{let G=K.timestamp;if(this.expectedFirstTimestamp&&this.currentTimestamp===null)this.timestampOffset=this.expectedFirstTimestamp-G;if(G+=this.timestampOffset,this.currentTimestamp===null||Math.abs(G-this.currentTimestamp)>=K.duration)this.currentTimestamp=G;let W=this.currentTimestamp;if(this.currentTimestamp+=K.duration,K.numberOfFrames===0){K.close();return}let j=X.sampleRate;K.setTimestamp(Math.round(W*j)/j),$(K)},Z=Q$.find((K)=>K.supports(Y,X));if(Z)this.customDecoder=new Z,this.customDecoder.codec=Y,this.customDecoder.config=X,this.customDecoder.onSample=(K)=>{if(!(K instanceof h0))throw TypeError("The argument passed to onSample must be an AudioSample.");Q(K)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let K=Error("Decoding error").stack;this.decoder=new AudioDecoder({output:(G)=>{try{Q(new h0(G))}catch(W){this.onError(W)}},error:(G)=>{G.stack=K,this.onError(G)}}),this.decoder.configure(X)}}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;else return L(this.decoder),this.decoder.decodeQueueSize}decode($){if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).then(()=>this.customDecoderQueueSize--);else L(this.decoder),this.expectedFirstTimestamp??=$.timestamp,this.decoder.decode($.toEncodedAudioChunk())}async flush(){if(this.customDecoder)await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());else L(this.decoder),await this.decoder.flush();this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else L(this.decoder),this.decoder.close()}}class N5 extends ZJ{constructor($,J,Y){super($,J);this.decoderConfig=Y,this.currentTimestamp=null,L(B0.includes(Y.codec)),this.codec=Y.codec;let{dataType:X,sampleSize:Q,littleEndian:Z}=I1(this.codec);switch(this.inputSampleSize=Q,Q){case 1:if(X==="unsigned")this.readInputValue=(K,G)=>K.getUint8(G)-128;else if(X==="signed")this.readInputValue=(K,G)=>K.getInt8(G);else if(X==="ulaw")this.readInputValue=(K,G)=>K5(K.getUint8(G));else if(X==="alaw")this.readInputValue=(K,G)=>G5(K.getUint8(G));else L(!1);break;case 2:if(X==="unsigned")this.readInputValue=(K,G)=>K.getUint16(G,Z)-32768;else if(X==="signed")this.readInputValue=(K,G)=>K.getInt16(G,Z);else L(!1);break;case 3:if(X==="unsigned")this.readInputValue=(K,G)=>M8(K,G,Z)-8388608;else if(X==="signed")this.readInputValue=(K,G)=>I7(K,G,Z);else L(!1);break;case 4:if(X==="unsigned")this.readInputValue=(K,G)=>K.getUint32(G,Z)-2147483648;else if(X==="signed")this.readInputValue=(K,G)=>K.getInt32(G,Z);else if(X==="float")this.readInputValue=(K,G)=>K.getFloat32(G,Z);else L(!1);break;case 8:if(X==="float")this.readInputValue=(K,G)=>K.getFloat64(G,Z);else L(!1);break;default:T0(Q),L(!1)}switch(Q){case 1:if(X==="ulaw"||X==="alaw")this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(K,G,W)=>K.setInt16(G,W,!0);else this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(K,G,W)=>K.setUint8(G,W+128);break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(K,G,W)=>K.setInt16(G,W,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(K,G,W)=>K.setInt32(G,W<<8,!0);break;case 4:if(this.outputSampleSize=4,X==="float")this.outputFormat="f32",this.writeOutputValue=(K,G,W)=>K.setFloat32(G,W,!0);else this.outputFormat="s32",this.writeOutputValue=(K,G,W)=>K.setInt32(G,W,!0);break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(K,G,W)=>K.setFloat32(G,W,!0);break;default:T0(Q),L(!1)}}getDecodeQueueSize(){return 0}decode($){let J=u($.data),Y=$.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,X=Y*this.decoderConfig.numberOfChannels*this.outputSampleSize,Q=new ArrayBuffer(X),Z=new DataView(Q);for(let j=0;j<Y*this.decoderConfig.numberOfChannels;j++){let U=j*this.inputSampleSize,q=j*this.outputSampleSize,V=this.readInputValue(J,U);this.writeOutputValue(Z,q,V)}let K=Y/this.decoderConfig.sampleRate;if(this.currentTimestamp===null||Math.abs($.timestamp-this.currentTimestamp)>=K)this.currentTimestamp=$.timestamp;let G=this.currentTimestamp;this.currentTimestamp+=K;let W=new h0({format:this.outputFormat,data:Q,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:Y,timestamp:G});this.onSample(W)}async flush(){}close(){}}class F6 extends QJ{constructor($){if(!($ instanceof K8))throw TypeError("audioTrack must be an InputAudioTrack.");super();this._track=$}async _createDecoder($,J){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.");let Y=await this._track.getCodec(),X=await this._track.getDecoderConfig();if(L(Y&&X),B0.includes(X.codec))return new N5($,J,X);else return new q5($,J,Y,X)}_createPacketSink(){return new p1(this._track)}async getSample($,J={}){l1($);for await(let Y of this.mediaSamplesAtTimestamps([$],J))return Y;throw Error("Internal error: Iterator returned nothing.")}samples($,J,Y={}){return this.mediaSamplesInRange($,J,Y)}samplesAtTimestamps($,J={}){return this.mediaSamplesAtTimestamps($,J)}}class UJ{constructor($){if(!($ instanceof K8))throw TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new F6($)}_audioSampleToWrappedArrayBuffer($){let J={buffer:$.toAudioBuffer(),timestamp:$.timestamp,duration:$.duration};return $.close(),J}async getBuffer($,J){l1($);let Y=await this._audioSampleSink.getSample($,J);return Y&&this._audioSampleToWrappedArrayBuffer(Y)}buffers($,J,Y){return y6(this._audioSampleSink.samples($,J,Y),(X)=>this._audioSampleToWrappedArrayBuffer(X))}buffersAtTimestamps($,J){return y6(this._audioSampleSink.samplesAtTimestamps($,J),(Y)=>Y&&this._audioSampleToWrappedArrayBuffer(Y))}}/*!
|
|
253
|
+
*/var c8=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.metadataOnly!==void 0&&typeof $.metadataOnly!=="boolean")throw TypeError("options.metadataOnly, when defined, must be a boolean.");if($.verifyKeyPackets!==void 0&&typeof $.verifyKeyPackets!=="boolean")throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if($.verifyKeyPackets&&$.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if($.skipLiveWait!==void 0&&typeof $.skipLiveWait!=="boolean")throw TypeError("options.skipLiveWait, when defined, must be a boolean.")},i1=($)=>{if(!n6($))throw TypeError("timestamp must be a number.")},G7=($,J,Y)=>{if(Y.verifyKeyPackets)return J.then(async(X)=>{if(!X||X.type==="delta")return X;let Q=await $.determinePacketType(X);if(Q)X.type=Q;return X});else return J};class a1{constructor($){if(!($ instanceof n8))throw TypeError("track must be an InputTrack.");this._track=$}async getFirstPacket($={}){if(c8($),this._track.input._disposed)throw new D0;return G7(this._track,this._track._backing.getFirstPacket($),$)}async getFirstKeyPacket($={}){c8($);let J=await this.getFirstPacket($);if(!J)return null;if(J.type==="key")return J;return this.getNextKeyPacket(J,$)}async getPacket($,J={}){if(i1($),c8(J),this._track.input._disposed)throw new D0;return G7(this._track,this._track._backing.getPacket($,J),J)}async getNextPacket($,J={}){if(!($ instanceof t))throw TypeError("packet must be an EncodedPacket.");if(c8(J),this._track.input._disposed)throw new D0;return G7(this._track,this._track._backing.getNextPacket($,J),J)}async getKeyPacket($,J={}){if(i1($),c8(J),this._track.input._disposed)throw new D0;if(!J.verifyKeyPackets)return this._track._backing.getKeyPacket($,J);let Y=await this._track._backing.getKeyPacket($,J);if(!Y)return Y;if(F(Y.type==="key"),await this._track.determinePacketType(Y)==="delta")return this.getKeyPacket(Y.timestamp-1/await this._track.getTimeResolution(),J);return Y}async getNextKeyPacket($,J={}){if(!($ instanceof t))throw TypeError("packet must be an EncodedPacket.");if(c8(J),this._track.input._disposed)throw new D0;if(!J.verifyKeyPackets)return this._track._backing.getNextKeyPacket($,J);let Y=await this._track._backing.getNextKeyPacket($,J);if(!Y)return Y;if(F(Y.type==="key"),await this._track.determinePacketType(Y)==="delta")return this.getNextKeyPacket(Y,J);return Y}packets($,J,Y={}){if($!==void 0&&!($ instanceof t))throw TypeError("startPacket must be an EncodedPacket.");if($!==void 0&&$.isMetadataOnly&&!Y?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(J!==void 0&&!(J instanceof t))throw TypeError("endPacket must be an EncodedPacket.");if(c8(Y),this._track.input._disposed)throw new D0;let X=[],{promise:Q,resolve:Z}=q0(),{promise:K,resolve:G}=q0(),W=!1,j=!1,U=null,q=!1,N=[],_=()=>Math.max(2,N.length);(async()=>{let z=$??await this.getFirstPacket(Y);while(z&&!j&&!this._track.input._disposed){if(J&&z.sequenceNumber>=J?.sequenceNumber)break;if(X.length>_()){({promise:K,resolve:G}=q0()),await K;continue}X.push(z),Z(),{promise:Q,resolve:Z}=q0(),z=await this.getNextPacket(z,Y)}W=!0,Z()})().catch((z)=>{if(!q)U=z,q=!0,Z()});let V=this._track;return{async next(){while(!0)if(V.input._disposed)throw new D0;else if(j)return{value:void 0,done:!0};else if(q)throw U;else if(X.length>0){let z=X.shift(),R=performance.now();N.push(R);while(N.length>0&&R-N[0]>=1000)N.shift();return G(),{value:z,done:!1}}else if(W)return{value:void 0,done:!0};else await Q},async return(){return j=!0,G(),Z(),{value:void 0,done:!0}},async throw(z){throw z},[Symbol.asyncIterator](){return this}}}}class jJ{constructor($,J){this.onSample=$,this.onError=J}}class qJ{mediaSamplesInRange($=-1/0,J=1/0,Y){i1($),i1(J);let X=[],Q=!1,Z=null,{promise:K,resolve:G}=q0(),{promise:W,resolve:j}=q0(),U=!1,q=!1,N=!1,_=null,V=!1,z={...Y,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let A=await this._createDecoder((B)=>{if(j(),B.timestamp>=J)q=!0;if(q){B.close();return}if(Z)if(B.timestamp>$)X.push(Z),Q=!0;else Z.close();if(B.timestamp>=$)X.push(B),Q=!0;if(Z=Q?null:B,X.length>0)G(),{promise:K,resolve:G}=q0()},(B)=>{if(!V)_=B,V=!0,G()}),M=this._createPacketSink(),L=await M.getKeyPacket($,z)??await M.getFirstKeyPacket(z),w=L,O=void 0,D=M.packets(L??void 0,O,z);await D.next();while(w&&!q&&!this._track.input._disposed){let B=U5(X.length);if(X.length+A.getDecodeQueueSize()>B){({promise:W,resolve:j}=q0()),await W;continue}A.decode(w);let C=await D.next();if(C.done)break;w=C.value}if(await D.return(),!N&&!this._track.input._disposed)await A.flush();if(A.close(),!Q&&Z)X.push(Z);U=!0,G()})().catch((A)=>{if(!V)_=A,V=!0,G()});let R=this._track,H=()=>{Z?.close();for(let A of X)A.close()};return{async next(){while(!0)if(R.input._disposed)throw H(),new D0;else if(N)return{value:void 0,done:!0};else if(V)throw H(),_;else if(X.length>0){let A=X.shift();return j(),{value:A,done:!1}}else if(!U)await K;else return{value:void 0,done:!0}},async return(){return N=!0,q=!0,j(),G(),H(),{value:void 0,done:!0}},async throw(A){throw A},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps($,J){I7($);let Y=x7($),X=[],Q=[],{promise:Z,resolve:K}=q0(),{promise:G,resolve:W}=q0(),j=!1,U=!1,q=null,N=!1,_=(H)=>{Q.push(H),K(),{promise:Z,resolve:K}=q0()},V={...J,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let H=await this._createDecoder((B)=>{if(W(),U){B.close();return}let C=0;while(X.length>0&&B.timestamp-X[0]>-0.0000000001)C++,X.shift();if(C>0)for(let E=0;E<C;E++)_(E<C-1?B.clone():B);else B.close()},(B)=>{if(!N)q=B,N=!0,K()}),A=this._createPacketSink(),M=null,L=null,w=-1,O=async()=>{F(L);let B=L;H.decode(B);while(B.sequenceNumber<w){let C=U5(Q.length);while(Q.length+H.getDecodeQueueSize()>C&&!U)({promise:G,resolve:W}=q0()),await G;if(U)break;let E=await A.getNextPacket(B,V);F(E),H.decode(E),B=E}w=-1},D=async()=>{await H.flush();for(let B=0;B<X.length;B++)_(null);X.length=0};for await(let B of Y){if(i1(B),U||this._track.input._disposed)break;let C=await A.getPacket(B,V),E=C&&await A.getKeyPacket(B,V);if(!E){if(w!==-1)await O(),await D();_(null),M=null;continue}if(M&&(E.sequenceNumber!==L.sequenceNumber||C.timestamp<M.timestamp))await O(),await D();X.push(C.timestamp),w=Math.max(C.sequenceNumber,w),M=C,L=E}if(!U&&!this._track.input._disposed){if(w!==-1)await O();await D()}H.close(),j=!0,K()})().catch((H)=>{if(!N)q=H,N=!0,K()});let z=this._track,R=()=>{for(let H of Q)H?.close()};return{async next(){while(!0)if(z.input._disposed)throw R(),new D0;else if(U)return{value:void 0,done:!0};else if(N)throw R(),q;else if(Q.length>0){let H=Q.shift();return F(H!==void 0),W(),{value:H,done:!1}}else if(!j)await Z;else return{value:void 0,done:!0}},async return(){return U=!0,W(),K(),R(),{value:void 0,done:!0}},async throw(H){throw H},[Symbol.asyncIterator](){return this}}}}var U5=($)=>{return $===0?40:8};class j5 extends jJ{constructor($,J,Y,X,Q,Z){super($,J);this.codec=Y,this.decoderConfig=X,this.rotation=Q,this.timeResolution=Z,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new p6,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.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];let K=q$.find((G)=>G.supports(Y,X));if(K)this.customDecoder=new K,this.customDecoder.codec=Y,this.customDecoder.config=X,this.customDecoder.onSample=(G)=>{if(!(G instanceof e0))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(G)},this.customDecoder.onError=(G)=>{J(G)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch((G)=>J(G));else{let G=(j)=>{if(this.alphaQueue.length>0){let U=this.alphaQueue.shift();F(U!==void 0),this.mergeAlpha(j,U)}else this.colorQueue.push(j)};if(Y==="avc"&&this.decoderConfig.description&&d6()){let j=sJ(O0(this.decoderConfig.description));if(j&&j.sequenceParameterSets.length>0){let U=a6(j.sequenceParameterSets[0]);if(U&&U.frameMbsOnlyFlag===0)this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}}}let W=Error("Decoding error").stack;this.decoder=new VideoDecoder({output:(j)=>{try{G(j)}catch(U){this.onError(U)}},error:(j)=>{j.stack=W,this.onError(j)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;else return F(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0)}decode($){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture($.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).catch((J)=>this.onError(J)).finally(()=>this.customDecoderQueueSize--);else{if(F(this.decoder),!C8())hJ(this.inputTimestamps,$.timestamp,(J)=>J);if(d6()&&this.currentPacketIndex===0){if(this.codec==="avc"){let J=[],Y=!1;for(let Q of dJ($.data,this.decoderConfig)){let Z=y8($.data[Q.offset]);if(Y||=Z>=1&&Z<=5,Z===B0.AUD)if(Y)break;else J.length=0;if(!(Z>=20&&Z<=31))J.push($.data.subarray(Q.offset,Q.offset+Q.length))}let X=s7(J,this.decoderConfig);$=new t(X,$.type,$.timestamp,$.duration)}else if(this.codec==="hevc"){let J=r7($.data,this.decoderConfig);if(J)$=new t(J,$.type,$.timestamp,$.duration)}}this.decoder.decode($.toEncodedVideoChunk()),this.decodeAlphaData($)}this.currentPacketIndex++}decodeAlphaData($){if(!$.sideData.alpha){this.pushNullAlphaFrame();return}if(!this.merger)this.merger=new q5;if(!this.alphaDecoder){let Y=(Q)=>{if(this.colorQueue.length>0){let Z=this.colorQueue.shift();F(Z!==void 0),this.mergeAlpha(Z,Q)}else this.alphaQueue.push(Q);this.decodedAlphaChunkCount++;while(this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let Z=this.colorQueue.shift();F(Z!==void 0),this.mergeAlpha(Z,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},X=Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:(Q)=>{try{Y(Q)}catch(Z){this.onError(Z)}},error:(Q)=>{Q.stack=X,this.onError(Q)}}),this.alphaDecoder.configure(this.decoderConfig)}let J=S8(this.codec,this.decoderConfig,$.sideData.alpha);if(!this.alphaHadKeyframe)this.alphaHadKeyframe=J==="key";if(this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture($.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode($.alphaToEncodedVideoChunk(J??$.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){if(this.alphaDecoderQueueSize===0)this.alphaQueue.push(null);else this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture($){for(let J of r6($,this.decoderConfig)){let Y=m1($[J.offset]);if(Y===M0.RASL_N||Y===M0.RASL_R)return!0}return!1}sampleHandler($){if(C8()){if(this.sampleQueue.length>0&&$.timestamp>=W0(this.sampleQueue).timestamp){for(let J of this.sampleQueue)this.finalizeAndEmitSample(J);this.sampleQueue.length=0}hJ(this.sampleQueue,$,(J)=>J.timestamp)}else{let J=this.inputTimestamps.shift();F(J!==void 0),$.setTimestamp(J),this.finalizeAndEmitSample($)}}finalizeAndEmitSample($){$.setTimestamp(Math.round($.timestamp*this.timeResolution)/this.timeResolution),$.setDuration(Math.round($.duration*this.timeResolution)/this.timeResolution),$.setRotation(this.rotation),this.onSample($)}async mergeAlpha($,J){let Y=q0();this.mergeAlphaPromises.push(Y.promise);let X={sample:null};this.finalSamples.push(X);try{if(!J)X.sample=new e0($);else{F(this.merger);let Q=await this.merger.merge($,J);X.sample=new e0(Q)}while(this.finalSamples.length>0&&this.finalSamples[0].sample!==null){let Q=this.finalSamples.shift();this.sampleHandler(Q.sample)}}catch(Q){u6(this.finalSamples,X),this.onError(Q)}finally{u6(this.mergeAlphaPromises,Y.promise),Y.resolve()}}async flush(){if(this.customDecoder)await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());else F(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;if(C8()){for(let $ of this.sampleQueue)this.finalizeAndEmitSample($);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else F(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.merger?.close();for(let $ of this.sampleQueue)$.close();this.sampleQueue.length=0}}var W7=null;class q5{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge($,J){if(this.workers.length===0){if(!W7){let K=new Blob([`(${E2.toString()})()`],{type:"application/javascript"});W7=URL.createObjectURL(K)}let Z=r0(navigator.hardwareConcurrency,1,4);for(let K=0;K<Z;K++){let G=new Worker(W7);G.addEventListener("message",(W)=>{let j=W.data,U=this.pendingRequests.get(j.id);if(!U)return;if(this.pendingRequests.delete(j.id),"error"in j)U.reject(Error(j.error));else U.resolve(j.frame)}),G.addEventListener("error",(W)=>{let j=Error(W.message||"Color/alpha merge worker error.");for(let U of this.pendingRequests.values())U.reject(j);this.pendingRequests.clear()}),this.workers.push(G)}}let Y=this.nextRequestId++,X=q0();this.pendingRequests.set(Y,X);let Q=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,Q.postMessage({id:Y,color:$,alpha:J},{transfer:[$,J]}),X.promise}close(){for(let J of this.workers)J.terminate();this.workers.length=0;let $=Error("Color/alpha merger closed.");for(let J of this.pendingRequests.values())J.reject($);this.pendingRequests.clear()}}var E2=()=>{let $=null,J=null,Y=Promise.resolve();self.addEventListener("message",(W)=>{let{id:j,color:U,alpha:q}=W.data;Y=Y.then(async()=>{try{let N=await X(U,q);self.postMessage({id:j,frame:N},{transfer:[N]})}catch(N){self.postMessage({id:j,error:N.message})}finally{U.close(),q.close()}})});let X=async(W,j)=>{let U=W.format,q=j.format;if(!U||!q)throw Error("CPU color/alpha merging requires a known VideoFrame format.");let N=U.includes("P10"),_=U.includes("P12"),V=q.includes("P10"),z=q.includes("P12");if(V!==N||z!==_)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${U}', alpha: '${q}').`);if(U==="RGBX"||U==="RGBA"||U==="BGRX"||U==="BGRA")return await Q(W,j,U);else if(U==="I420"||U==="I420P10"||U==="I420P12"||U==="I422"||U==="I422P10"||U==="I422P12"||U==="I444"||U==="I444P10"||U==="I444P12")return await Z(W,j,U);else if(U==="NV12")return await K(W,j);throw Error(`CPU color/alpha merging does not support format '${U}'.`)},Q=async(W,j,U)=>{let q=W.visibleRect?.width??W.codedWidth,N=W.visibleRect?.height??W.codedHeight,_=q*N,V=new Uint8Array(_*4);await W.copyTo(V);let z=await G(j,q,N,1);for(let A=0,M=3;A<_;A++,M+=4)V[M]=z[A];let H={format:U==="RGBX"||U==="RGBA"?"RGBA":"BGRA",codedWidth:q,codedHeight:N,timestamp:W.timestamp,duration:W.duration??void 0,transfer:[V.buffer]};return new VideoFrame(V,H)},Z=async(W,j,U)=>{let q=W.visibleRect?.width??W.codedWidth,N=W.visibleRect?.height??W.codedHeight,_=U.includes("P10"),V=U.includes("P12"),z=_||V?2:1,R,H;if(U.startsWith("I420"))R=Math.ceil(q/2),H=Math.ceil(N/2);else if(U.startsWith("I422"))R=Math.ceil(q/2),H=N;else R=q,H=N;let A=q*N,M=R*H,L=A*z,w=M*z,O=A*z,D=L+2*w+O,B=new Uint8Array(D);await W.copyTo(B);let C=await G(j,q,N,z),E=L+2*w;B.set(C,E);let v={format:U.slice(0,4)+"A"+U.slice(4),codedWidth:q,codedHeight:N,timestamp:W.timestamp,duration:W.duration??void 0,transfer:[B.buffer]};return new VideoFrame(B,v)},K=async(W,j)=>{let U=W.visibleRect?.width??W.codedWidth,q=W.visibleRect?.height??W.codedHeight,N=U*q,_=Math.ceil(U/2),V=Math.ceil(q/2),z=_*V,R=W.allocationSize();if(!J||J.byteLength!==R)J=new Uint8Array(R);await W.copyTo(J);let H=new Uint8Array(N+2*z+N);H.set(J.subarray(0,N),0);let A=N,M=N+z,L=N;for(let D=0;D<z;D++)H[A+D]=J[L+D*2],H[M+D]=J[L+D*2+1];let w=await G(j,U,q,1);H.set(w,N+2*z);let O={format:"I420A",codedWidth:U,codedHeight:q,timestamp:W.timestamp,duration:W.duration??void 0,transfer:[H.buffer]};return new VideoFrame(H,O)},G=async(W,j,U,q)=>{let N=W.allocationSize();if(!$||$.byteLength!==N)$=new Uint8Array(N);await W.copyTo($);let _=W.format;if(_==="RGBA"||_==="BGRA"||_==="RGBX"||_==="BGRX"){let V=_==="RGBA"||_==="RGBX"?0:2,z=j*U;for(let R=0;R<z;R++)$[R]=$[R*4+V];return $.subarray(0,z)}else return $.subarray(0,j*U*q)}},N5=($)=>{if(!$||typeof $!=="object")throw TypeError("decoderOptions must be an object.");if($.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes($.hardwareAcceleration))throw TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if($.optimizeForLatency!==void 0&&typeof $.optimizeForLatency!=="boolean")throw TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class C6 extends qJ{constructor($,J={}){if(!($ instanceof q8))throw TypeError("videoTrack must be an InputVideoTrack.");N5(J);super();this._track=$,this._decoderOptions=J}async _createDecoder($,J){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.");let Y=await this._track.getCodec(),X=await this._track.getRotation(),Q=await this._track.getDecoderConfig(),Z=await this._track.getTimeResolution();return F(Y&&Q),Q={...Q,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new j5($,J,Y,Q,X,Z)}_createPacketSink(){return new a1(this._track)}async getSample($,J={}){i1($);for await(let Y of this.mediaSamplesAtTimestamps([$],J))return Y;throw Error("Internal error: Iterator returned nothing.")}samples($,J,Y={}){return this.mediaSamplesInRange($,J,Y)}samplesAtTimestamps($,J={}){return this.mediaSamplesAtTimestamps($,J)}}class NJ{constructor($,J={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!($ instanceof q8))throw TypeError("videoTrack must be an InputVideoTrack.");if(J&&typeof J!=="object")throw TypeError("options must be an object.");if(J.alpha!==void 0&&typeof J.alpha!=="boolean")throw TypeError("options.alpha, when provided, must be a boolean.");if(J.width!==void 0&&(!Number.isInteger(J.width)||J.width<=0))throw TypeError("options.width, when defined, must be a positive integer.");if(J.height!==void 0&&(!Number.isInteger(J.height)||J.height<=0))throw TypeError("options.height, when defined, must be a positive integer.");if(J.fit!==void 0&&!["fill","contain","cover"].includes(J.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(J.width!==void 0&&J.height!==void 0&&J.fit===void 0)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(J.crop!==void 0)D6(J.crop,"options.");if(J.poolSize!==void 0&&(typeof J.poolSize!=="number"||!Number.isInteger(J.poolSize)||J.poolSize<0))throw TypeError("poolSize must be a non-negative integer.");if(J.decoderOptions!==void 0)N5(J.decoderOptions);this._videoTrack=$,this._alpha=J.alpha??!1,this._options=J,this._fit=J.fit??"fill",this._videoSampleSink=new C6($,J.decoderOptions),this._canvasPool=Array.from({length:J.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let $=this._options,J=this._videoTrack,Y=$.rotation??await J.getRotation(),X=await J.getSquarePixelWidth(),Q=await J.getSquarePixelHeight(),[Z,K]=Y%180===0?[X,Q]:[Q,X],G=$.crop;if(G)G=A$(G,Z,K);let[W,j]=G?[G.width,G.height]:[Z,K],U=W/j;if($.width!==void 0&&$.height===void 0)W=$.width,j=Math.round(W/U);else if($.width===void 0&&$.height!==void 0)j=$.height,W=Math.round(j*U);else if($.width!==void 0&&$.height!==void 0)W=$.width,j=$.height;this._width=W,this._height=j,this._rotation=Y,this._crop=G})()}_videoSampleToWrappedCanvas($){let J=this._width,Y=this._height,X=this._canvasPool[this._nextCanvasIndex],Q=!1;if(!X){if(typeof document<"u")X=document.createElement("canvas"),X.width=J,X.height=Y;else X=new OffscreenCanvas(J,Y);if(this._canvasPool.length>0)this._canvasPool[this._nextCanvasIndex]=X;Q=!0}if(this._canvasPool.length>0)this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length;let Z=X.getContext("2d",{alpha:this._alpha||t8()});if(F(Z),Z.resetTransform(),!Q)if(!this._alpha&&t8())Z.fillStyle="black",Z.fillRect(0,0,J,Y);else Z.clearRect(0,0,J,Y);$.drawWithFit(Z,{fit:this._fit,rotation:this._rotation,crop:this._crop});let K={canvas:X,timestamp:$.timestamp,duration:$.duration};return $.close(),K}async getCanvas($,J){i1($),await this._ensureInit();let Y=await this._videoSampleSink.getSample($,J);return Y&&this._videoSampleToWrappedCanvas(Y)}async*canvases($,J,Y){await this._ensureInit(),yield*m6(this._videoSampleSink.samples($,J,Y),(X)=>this._videoSampleToWrappedCanvas(X))}async*canvasesAtTimestamps($,J){await this._ensureInit(),yield*m6(this._videoSampleSink.samplesAtTimestamps($,J),(Y)=>Y&&this._videoSampleToWrappedCanvas(Y))}}class V5 extends jJ{constructor($,J,Y,X){super($,J);this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new p6,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let Q=(K)=>{let G=K.timestamp;if(this.expectedFirstTimestamp&&this.currentTimestamp===null)this.timestampOffset=this.expectedFirstTimestamp-G;if(G+=this.timestampOffset,this.currentTimestamp===null||Math.abs(G-this.currentTimestamp)>=K.duration)this.currentTimestamp=G;let W=this.currentTimestamp;if(this.currentTimestamp+=K.duration,K.numberOfFrames===0){K.close();return}let j=X.sampleRate;K.setTimestamp(Math.round(W*j)/j),$(K)},Z=N$.find((K)=>K.supports(Y,X));if(Z)this.customDecoder=new Z,this.customDecoder.codec=Y,this.customDecoder.config=X,this.customDecoder.onSample=(K)=>{if(!(K instanceof c0))throw TypeError("The argument passed to onSample must be an AudioSample.");Q(K)},this.customDecoder.onError=(K)=>{J(K)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch((K)=>J(K));else{let K=Error("Decoding error").stack;this.decoder=new AudioDecoder({output:(G)=>{try{Q(new c0(G))}catch(W){this.onError(W)}},error:(G)=>{G.stack=K,this.onError(G)}}),this.decoder.configure(X)}}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;else return F(this.decoder),this.decoder.decodeQueueSize}decode($){if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).catch((J)=>this.onError(J)).finally(()=>this.customDecoderQueueSize--);else F(this.decoder),this.expectedFirstTimestamp??=$.timestamp,this.decoder.decode($.toEncodedAudioChunk())}async flush(){if(this.customDecoder)await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());else F(this.decoder),await this.decoder.flush();this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else F(this.decoder),this.decoder.close()}}class _5 extends jJ{constructor($,J,Y){super($,J);this.decoderConfig=Y,this.currentTimestamp=null,F(S0.includes(Y.codec)),this.codec=Y.codec;let{dataType:X,sampleSize:Q,littleEndian:Z}=u1(this.codec);switch(this.inputSampleSize=Q,Q){case 1:if(X==="unsigned")this.readInputValue=(K,G)=>K.getUint8(G)-128;else if(X==="signed")this.readInputValue=(K,G)=>K.getInt8(G);else if(X==="ulaw")this.readInputValue=(K,G)=>G5(K.getUint8(G));else if(X==="alaw")this.readInputValue=(K,G)=>W5(K.getUint8(G));else F(!1);break;case 2:if(X==="unsigned")this.readInputValue=(K,G)=>K.getUint16(G,Z)-32768;else if(X==="signed")this.readInputValue=(K,G)=>K.getInt16(G,Z);else F(!1);break;case 3:if(X==="unsigned")this.readInputValue=(K,G)=>D8(K,G,Z)-8388608;else if(X==="signed")this.readInputValue=(K,G)=>y7(K,G,Z);else F(!1);break;case 4:if(X==="unsigned")this.readInputValue=(K,G)=>K.getUint32(G,Z)-2147483648;else if(X==="signed")this.readInputValue=(K,G)=>K.getInt32(G,Z);else if(X==="float")this.readInputValue=(K,G)=>K.getFloat32(G,Z);else F(!1);break;case 8:if(X==="float")this.readInputValue=(K,G)=>K.getFloat64(G,Z);else F(!1);break;default:v0(Q),F(!1)}switch(Q){case 1:if(X==="ulaw"||X==="alaw")this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(K,G,W)=>K.setInt16(G,W,!0);else this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(K,G,W)=>K.setUint8(G,W+128);break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(K,G,W)=>K.setInt16(G,W,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(K,G,W)=>K.setInt32(G,W<<8,!0);break;case 4:if(this.outputSampleSize=4,X==="float")this.outputFormat="f32",this.writeOutputValue=(K,G,W)=>K.setFloat32(G,W,!0);else this.outputFormat="s32",this.writeOutputValue=(K,G,W)=>K.setInt32(G,W,!0);break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(K,G,W)=>K.setFloat32(G,W,!0);break;default:v0(Q),F(!1)}}getDecodeQueueSize(){return 0}decode($){let J=l($.data),Y=$.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,X=Y*this.decoderConfig.numberOfChannels*this.outputSampleSize,Q=new ArrayBuffer(X),Z=new DataView(Q);for(let j=0;j<Y*this.decoderConfig.numberOfChannels;j++){let U=j*this.inputSampleSize,q=j*this.outputSampleSize,N=this.readInputValue(J,U);this.writeOutputValue(Z,q,N)}let K=Y/this.decoderConfig.sampleRate;if(this.currentTimestamp===null||Math.abs($.timestamp-this.currentTimestamp)>=K)this.currentTimestamp=$.timestamp;let G=this.currentTimestamp;this.currentTimestamp+=K;let W=new c0({format:this.outputFormat,data:Q,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:Y,timestamp:G});this.onSample(W)}async flush(){}close(){}}class E6 extends qJ{constructor($){if(!($ instanceof N8))throw TypeError("audioTrack must be an InputAudioTrack.");super();this._track=$}async _createDecoder($,J){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.");let Y=await this._track.getCodec(),X=await this._track.getDecoderConfig();if(F(Y&&X),S0.includes(X.codec))return new _5($,J,X);else return new V5($,J,Y,X)}_createPacketSink(){return new a1(this._track)}async getSample($,J={}){i1($);for await(let Y of this.mediaSamplesAtTimestamps([$],J))return Y;throw Error("Internal error: Iterator returned nothing.")}samples($,J,Y={}){return this.mediaSamplesInRange($,J,Y)}samplesAtTimestamps($,J={}){return this.mediaSamplesAtTimestamps($,J)}}class VJ{constructor($){if(!($ instanceof N8))throw TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new E6($)}_audioSampleToWrappedArrayBuffer($){let J={buffer:$.toAudioBuffer(),timestamp:$.timestamp,duration:$.duration};return $.close(),J}async getBuffer($,J){i1($);let Y=await this._audioSampleSink.getSample($,J);return Y&&this._audioSampleToWrappedArrayBuffer(Y)}buffers($,J,Y){return m6(this._audioSampleSink.samples($,J,Y),(X)=>this._audioSampleToWrappedArrayBuffer(X))}buffersAtTimestamps($,J){return m6(this._audioSampleSink.samplesAtTimestamps($,J),(Y)=>Y&&this._audioSampleToWrappedArrayBuffer(Y))}}/*!
|
|
270
254
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
271
255
|
*
|
|
272
256
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
273
257
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
274
258
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
275
|
-
*/class m8{constructor($,J){this.input=$,this._backing=J}isVideoTrack(){return this instanceof Q8}isAudioTrack(){return this instanceof K8}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return W0(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return W0(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return W0(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return W0(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return W0(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration($){let J=await this._backing.getPacket(1/0,{metadataOnly:!0,...$}),Y=(J?.timestamp??0)+(J?.duration??0);return d8(Y,await this.getTimeResolution())}async getDurationFromMetadata($={}){return this._backing.getDurationFromMetadata($)}async computePacketStats($=1/0,J){let Y=new p1(this),X=1/0,Q=-1/0,Z=0,K=0;for await(let G of Y.packets(void 0,void 0,{metadataOnly:!0,...J})){if(Z>=$&&G.timestamp>=Q)break;X=Math.min(X,G.timestamp),Q=Math.max(Q,G.timestamp+G.duration),Z++,K+=G.byteLength}return{packetCount:Z,averagePacketRate:Z?Number((Z/(Q-X)).toPrecision(16)):0,averageBitrate:Z?Number((8*K/(Q-X)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith($){if(!($ instanceof m8))throw TypeError("other must be an InputTrack.");if(this.input!==$.input||this===$)return!1;return(this._backing.getPairingMask()&$._backing.getPairingMask())!==0n}async getPairableTracks($){return this.input.getTracks(G8({filter:(J)=>J.canBePairedWith(this)},$))}async getPairableVideoTracks($){return this.input.getVideoTracks(G8({filter:(J)=>J.canBePairedWith(this)},$))}async getPairableAudioTracks($){return this.input.getAudioTracks(G8({filter:(J)=>J.canBePairedWith(this)},$))}async getPrimaryPairableVideoTrack($){return this.input.getPrimaryVideoTrack(G8({filter:(J)=>J.canBePairedWith(this)},$))}async getPrimaryPairableAudioTrack($){return this.input.getPrimaryAudioTrack(G8({filter:(J)=>J.canBePairedWith(this)},$))}async hasPairableTrack($){$&&=$7($);let J=await this.input.getTracks();for(let Y of J){if(!this.canBePairedWith(Y))continue;if(!$||await $(Y))return!0}return!1}hasPairableVideoTrack($){return $&&=$7($),this.hasPairableTrack(async(J)=>J.isVideoTrack()&&(!$||await $(J)))}hasPairableAudioTrack($){return $&&=$7($),this.hasPairableTrack(async(J)=>J.isAudioTrack()&&(!$||await $(J)))}}var W0=($,J,Y)=>{if($ instanceof Promise)throw Error(`'${J}' is deprecated and not available synchronously for this track. Use the preferred '${Y}()' instead.`);return $},$7=($)=>{if($!==void 0&&typeof $!=="function")throw TypeError("predicate, when provided, must be a function.");return $?(J)=>{let Y=(Q)=>{if(typeof Q!=="boolean")throw TypeError("predicate must return or resolve to a boolean value.");return Q},X=$(J);if(X instanceof Promise)return X.then(Y);return Y(X)}:void 0};class Q8 extends m8{constructor($,J){super($,J);this._pixelAspectRatioCache=null,this._backing=J}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return W0(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return W0(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return W0(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return W0(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return W0(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return W0(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=B8({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=B8({num:W0(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*W0(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:W0(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*W0(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let $=await this._backing.getMetadataDisplayWidth?.();if($!=null)return $;return await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){let $=this._backing.getMetadataDisplayWidth?.();if($!==void 0){let X=W0($,"displayWidth","getDisplayWidth");if(X!==null)return X}let Y=W0(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return W0(Y,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let $=await this._backing.getMetadataDisplayHeight?.();if($!=null)return $;return await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){let $=this._backing.getMetadataDisplayHeight?.();if($!==void 0){let X=W0($,"displayHeight","getDisplayHeight");if(X!==null)return X}let Y=W0(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return W0(Y,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let $=await this._backing.getColorSpace();return $.primaries==="bt2020"||$.primaries==="smpte432"||$.transfer==="pq"||$.transfer==="hlg"||$.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let $=await this._backing.getMetadataCodecParameterString?.();if($!=null)return $;return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=await this._backing.getCodec();if(L(J!==null),Z$.some((X)=>X.supports(J,$)))return!0;if(typeof VideoDecoder>"u")return!1;return(await VideoDecoder.isConfigSupported($)).supported===!0}catch($){return console.error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof i))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("packet must not be metadata-only to determine its type.");let J=await this.getCodec();if(J===null)return null;let Y=await this.getDecoderConfig();return L(Y),T8(J,Y,$.data)}}class K8 extends m8{constructor($,J){super($,J);this._backing=J}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return W0(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return W0(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return W0(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let $=await this._backing.getMetadataCodecParameterString?.();if($!=null)return $;return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=await this._backing.getCodec();if(L(J!==null),Q$.some((Y)=>Y.supports(J,$)))return!0;if($.codec.startsWith("pcm-"))return!0;else{if(typeof AudioDecoder>"u")return!1;return(await AudioDecoder.isConfigSupported($)).supported===!0}}catch($){return console.error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof i))throw TypeError("packet must be an EncodedPacket.");if(await this.getCodec()===null)return null;return"key"}}var WJ=($)=>{return-($??-1/0)},l8=($)=>{return-$},w6=($)=>{if(typeof $!=="object"||!$)throw TypeError("query must be an object.");if($.filter!==void 0&&typeof $.filter!=="function")throw TypeError("query.filter, when provided, must be a function.");if($.sortBy!==void 0&&typeof $.sortBy!=="function")throw TypeError("query.sortBy, when provided, must be a function.");return{filter:$.filter?(J)=>{let Y=(Q)=>{if(typeof Q!=="boolean")throw TypeError("query.filter must return or resolve to a boolean.");return Q},X=$.filter(J);if(X instanceof Promise)return X.then(Y);else return Y(X)}:void 0,sortBy:$.sortBy?(J)=>{let Y=(Q)=>{if(typeof Q!=="number"&&(!Array.isArray(Q)||!Q.every((Z)=>typeof Z==="number")))throw TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return Q},X=$.sortBy(J);if(X instanceof Promise)return X.then(Y);else return Y(X)}:void 0}},G8=($,J)=>{return{filter:$?.filter||J?.filter?(Y)=>{let X=$?.filter?.(Y)??!0,Q=(Z)=>{if(Z===!1)return!1;return J?.filter?.(Y)??!0};if(X instanceof Promise)return X.then(Q);else return Q(X)}:void 0,sortBy:$?.sortBy||J?.sortBy?(Y)=>{let X=$?.sortBy?.(Y)??[],Q=J?.sortBy?.(Y)??[],Z=(K,G)=>{return[...Array.isArray(K)?K:[K],...Array.isArray(G)?G:[G]]};if(X instanceof Promise||Q instanceof Promise)return Promise.all([X,Q]).then(([K,G])=>{return Z(K,G)});else return Z(X,Q)}:void 0}},jJ=async($,J)=>{let Y=$;if(J?.filter){let K=$.map((W)=>J.filter(W));if(K.some((W)=>W instanceof Promise)){let W=await Promise.all(K);Y=$.filter((j,U)=>W[U])}else Y=$.filter((W,j)=>K[j])}if(!J?.sortBy)return Y;let X=Y.map((K)=>J.sortBy(K)),Z=X.some((K)=>K instanceof Promise)?await Promise.all(X):X;return Y.map((K,G)=>({track:K,sortValue:Z[G]})).sort((K,G)=>{let W=Array.isArray(K.sortValue)?K.sortValue:[K.sortValue],j=Array.isArray(G.sortValue)?G.sortValue:[G.sortValue],U=Math.max(W.length,j.length);for(let q=0;q<U;q++){let V=W[q]??0,_=j[q]??0;if(V===_)continue;return V-_}return 0}).map((K)=>K.track)};/*!
|
|
259
|
+
*/class n8{constructor($,J){this.input=$,this._backing=J}isVideoTrack(){return this instanceof q8}isAudioTrack(){return this instanceof N8}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return N0(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return N0(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return N0(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return N0(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp($){return this._backing.getUnixTimeForTimestamp($)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return N0(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration($){let J=await this._backing.getPacket(1/0,{metadataOnly:!0,...$}),Y=(J?.timestamp??0)+(J?.duration??0);return i8(Y,await this.getTimeResolution())}async getDurationFromMetadata($={}){return this._backing.getDurationFromMetadata($)}async computePacketStats($=1/0,J){let Y=new a1(this),X=1/0,Q=-1/0,Z=0,K=0;for await(let G of Y.packets(void 0,void 0,{metadataOnly:!0,...J})){if(Z>=$&&G.timestamp>=Q)break;X=Math.min(X,G.timestamp),Q=Math.max(Q,G.timestamp+G.duration),Z++,K+=G.byteLength}return{packetCount:Z,averagePacketRate:Z?Number((Z/(Q-X)).toPrecision(16)):0,averageBitrate:Z?Number((8*K/(Q-X)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith($){if(!($ instanceof n8))throw TypeError("other must be an InputTrack.");if(this.input!==$.input||this===$)return!1;return(this._backing.getPairingMask()&$._backing.getPairingMask())!==0n}async getPairableTracks($){return this.input.getTracks(V8({filter:(J)=>J.canBePairedWith(this)},$))}async getPairableVideoTracks($){return this.input.getVideoTracks(V8({filter:(J)=>J.canBePairedWith(this)},$))}async getPairableAudioTracks($){return this.input.getAudioTracks(V8({filter:(J)=>J.canBePairedWith(this)},$))}async getPrimaryPairableVideoTrack($){return this.input.getPrimaryVideoTrack(V8({filter:(J)=>J.canBePairedWith(this)},$))}async getPrimaryPairableAudioTrack($){return this.input.getPrimaryAudioTrack(V8({filter:(J)=>J.canBePairedWith(this)},$))}async hasPairableTrack($){$&&=U7($);let J=await this.input.getTracks();for(let Y of J){if(!this.canBePairedWith(Y))continue;if(!$||await $(Y))return!0}return!1}hasPairableVideoTrack($){return $&&=U7($),this.hasPairableTrack(async(J)=>J.isVideoTrack()&&(!$||await $(J)))}hasPairableAudioTrack($){return $&&=U7($),this.hasPairableTrack(async(J)=>J.isAudioTrack()&&(!$||await $(J)))}}var N0=($,J,Y)=>{if($ instanceof Promise)throw Error(`'${J}' is deprecated and not available synchronously for this track. Use the preferred '${Y}()' instead.`);return $},U7=($)=>{if($!==void 0&&typeof $!=="function")throw TypeError("predicate, when provided, must be a function.");return $?(J)=>{let Y=(Q)=>{if(typeof Q!=="boolean")throw TypeError("predicate must return or resolve to a boolean value.");return Q},X=$(J);if(X instanceof Promise)return X.then(Y);return Y(X)}:void 0};class q8 extends n8{constructor($,J){super($,J);this._pixelAspectRatioCache=null,this._backing=J}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return N0(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return N0(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return N0(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return N0(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return N0(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return N0(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=b8({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=b8({num:N0(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*N0(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:N0(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*N0(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let $=await this._backing.getMetadataDisplayWidth?.();if($!=null)return $;return await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){let $=this._backing.getMetadataDisplayWidth?.();if($!==void 0){let X=N0($,"displayWidth","getDisplayWidth");if(X!==null)return X}let Y=N0(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return N0(Y,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let $=await this._backing.getMetadataDisplayHeight?.();if($!=null)return $;return await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){let $=this._backing.getMetadataDisplayHeight?.();if($!==void 0){let X=N0($,"displayHeight","getDisplayHeight");if(X!==null)return X}let Y=N0(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return N0(Y,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let $=await this._backing.getColorSpace();return $.primaries==="bt2020"||$.primaries==="smpte432"||$.transfer==="pq"||$.transfer==="hlg"||$.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let $=await this._backing.getMetadataCodecParameterString?.();if($!=null)return $;return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=await this._backing.getCodec();if(F(J!==null),q$.some((X)=>X.supports(J,$)))return!0;if(typeof VideoDecoder>"u")return!1;return(await VideoDecoder.isConfigSupported($)).supported===!0}catch($){return k._error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof t))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("packet must not be metadata-only to determine its type.");let J=await this.getCodec();if(J===null)return null;let Y=await this.getDecoderConfig();return F(Y),S8(J,Y,$.data)}}class N8 extends n8{constructor($,J){super($,J);this._backing=J}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return N0(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return N0(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return N0(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let $=await this._backing.getMetadataCodecParameterString?.();if($!=null)return $;return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=await this._backing.getCodec();if(F(J!==null),N$.some((Y)=>Y.supports(J,$)))return!0;if($.codec.startsWith("pcm-"))return!0;else{if(typeof AudioDecoder>"u")return!1;return(await AudioDecoder.isConfigSupported($)).supported===!0}}catch($){return k._error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof t))throw TypeError("packet must be an EncodedPacket.");if(await this.getCodec()===null)return null;return"key"}}var _J=($)=>{return-($??-1/0)},s8=($)=>{return-$},P6=($)=>{if(typeof $!=="object"||!$)throw TypeError("query must be an object.");if($.filter!==void 0&&typeof $.filter!=="function")throw TypeError("query.filter, when provided, must be a function.");if($.sortBy!==void 0&&typeof $.sortBy!=="function")throw TypeError("query.sortBy, when provided, must be a function.");return{filter:$.filter?(J)=>{let Y=(Q)=>{if(typeof Q!=="boolean")throw TypeError("query.filter must return or resolve to a boolean.");return Q},X=$.filter(J);if(X instanceof Promise)return X.then(Y);else return Y(X)}:void 0,sortBy:$.sortBy?(J)=>{let Y=(Q)=>{if(typeof Q!=="number"&&(!Array.isArray(Q)||!Q.every((Z)=>typeof Z==="number")))throw TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return Q},X=$.sortBy(J);if(X instanceof Promise)return X.then(Y);else return Y(X)}:void 0}},V8=($,J)=>{return{filter:$?.filter||J?.filter?(Y)=>{let X=$?.filter?.(Y)??!0,Q=(Z)=>{if(Z===!1)return!1;return J?.filter?.(Y)??!0};if(X instanceof Promise)return X.then(Q);else return Q(X)}:void 0,sortBy:$?.sortBy||J?.sortBy?(Y)=>{let X=$?.sortBy?.(Y)??[],Q=J?.sortBy?.(Y)??[],Z=(K,G)=>{return[...Array.isArray(K)?K:[K],...Array.isArray(G)?G:[G]]};if(X instanceof Promise||Q instanceof Promise)return Promise.all([X,Q]).then(([K,G])=>{return Z(K,G)});else return Z(X,Q)}:void 0}},HJ=async($,J)=>{let Y=$;if(J?.filter){let K=$.map((W)=>J.filter(W));if(K.some((W)=>W instanceof Promise)){let W=await Promise.all(K);Y=$.filter((j,U)=>W[U])}else Y=$.filter((W,j)=>K[j])}if(!J?.sortBy)return Y;let X=Y.map((K)=>J.sortBy(K)),Z=X.some((K)=>K instanceof Promise)?await Promise.all(X):X;return Y.map((K,G)=>({track:K,sortValue:Z[G]})).sort((K,G)=>{let W=Array.isArray(K.sortValue)?K.sortValue:[K.sortValue],j=Array.isArray(G.sortValue)?G.sortValue:[G.sortValue],U=Math.max(W.length,j.length);for(let q=0;q<U;q++){let N=W[q]??0,_=j[q]??0;if(N===_)continue;return N-_}return 0}).map((K)=>K.track)};/*!
|
|
276
260
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
277
261
|
*
|
|
278
262
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
279
263
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
280
264
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
281
|
-
*/
|
|
265
|
+
*/e8();var P2=1,mX=2;class C1 extends L1{get disposed(){return this._disposed}constructor($){super();if(this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Array.isArray($.formats)||$.formats.some((J)=>!(J instanceof Y1)))throw TypeError("options.formats must be an array of InputFormat.");if(!($.source instanceof Z1||$.source instanceof B6))throw TypeError("options.source must be a Source or SourceRef.");if($.source instanceof Z1&&$.source._disposed)throw TypeError("options.source must not be a disposed Source.");if($.initInput!==void 0&&!($.initInput instanceof C1))throw TypeError("options.initInput, when provided, must be an Input.");if($.formatOptions!==void 0)eX($.formatOptions,"formatOptions");if(this._formats=$.formats,this._initInput=$.initInput??null,this._formatOptions=$.formatOptions??{},$.source instanceof Z1)this._rootRef=$.source.ref();else this._rootRef=$.source;this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached($){F(this._rootSource instanceof Q1);let J=await this._rootSource._resolveRequest($);return this._emit("source",{source:J.source,request:$,isRoot:$.isRoot}),J}_getSourceCached($,J=P2){let Y=this._sourceCache.find((Z)=>Z.cacheGroup===J&&cY(Z.request,$));if(Y)return Y.age++,Promise.resolve(Y.sourceRef.source.ref());let X=this._sourceCachePromises.find((Z)=>Z.cacheGroup===J&&cY(Z.request,$));if(X)return X.promise.then((Z)=>Z.sourceRef.source.ref());let Q=(async()=>{let Z=await this._getSourceUncached($),K=4;if(P8(this._sourceCache,(U)=>U.cacheGroup===J&&U.sourceRef.source._refCount===1)>=4){let U=$6(this._sourceCache,(N)=>N.cacheGroup===J&&N.sourceRef.source._refCount===1?N.age:1/0);F(U!==-1);let q=this._sourceCache[U];this._sourceCache.splice(U,1),q.sourceRef.free(),u6(this._sourceRefs,q.sourceRef)}this._sourceRefs.push(Z);let W=this._sourceCachePromises.findIndex((U)=>U.request===$);return F(W!==-1),this._sourceCachePromises.splice(W,1),{request:$,sourceRef:Z,age:this._nextSourceCacheAge++,cacheGroup:J}})();return this._sourceCachePromises.push({request:$,cacheGroup:J,promise:Q}),Q.then((Z)=>{let K=Z.sourceRef.source.ref();return this._sourceCache.push(Z),K})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new l8(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let $ of this._formats)if(await $._canReadInput(this))return this._format=$,this._onFormatDetermined?.($),$._createDemuxer(this);throw new zJ})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),F(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch($){if($ instanceof zJ)return!1;throw $}}async getFirstTimestamp($){$??=await this.getTracks();let J=$.filter((X)=>X!==null);if(J.length===0)return 0;let Y=await Promise.all(J.map((X)=>X.getFirstTimestamp()));return Math.min(...Y)}async computeDuration($,J){$??=await this.getTracks();let Y=$.filter((Q)=>Q!==null);if(Y.length===0)return 0;let X=await Promise.all(Y.map((Q)=>Q.computeDuration(J)));return Math.max(...X)}async getDurationFromMetadata($,J){$??=await this.getTracks();let Y=$.filter((Z)=>Z!==null),Q=(await Promise.all(Y.map((Z)=>Z.getDurationFromMetadata(J)))).filter((Z)=>Z!==null);if(Q.length===0)return null;return Math.max(...Q)}async getTracks($){$&&=P6($);let Y=(await this._getTrackBackings()).map((X)=>this._wrapBackingAsTrack(X));return HJ(Y,$)}async getVideoTracks($){$&&=P6($);let Y=(await this.getTracks()).filter((X)=>X.isVideoTrack());return HJ(Y,$)}async getAudioTracks($){$&&=P6($);let Y=(await this.getTracks()).filter((X)=>X.isAudioTrack());return HJ(Y,$)}async getPrimaryVideoTrack($){$&&=P6($);let J=V8($,{sortBy:async(X)=>[s8((await X.getDisposition()).default),s8(await X.hasPairableAudioTrack()),s8(!await X.hasOnlyKeyPackets()),_J(await X.getBitrate())]});return(await this.getVideoTracks(J))[0]??null}async getPrimaryAudioTrack($){$&&=P6($);let J=await this.getPrimaryVideoTrack(),Y=V8($,{sortBy:async(Q)=>[s8(!J||Q.canBePairedWith(J)),s8((await Q.getDisposition()).default),_J(await Q.getBitrate())]});return(await this.getAudioTracks(Y))[0]??null}async _getTrackBackings(){let $=await this._getDemuxer();return this._trackBackingsCache??=await $.getTrackBackings()}_wrapBackingAsTrack($){let J=this._backingToTrack.get($);if(J)return J;let X=$.getType()==="video"?new q8(this,$):new N8(this,$);return this._backingToTrack.set($,X),X}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(this._disposed)return;this._disposed=!0;for(let $ of this._sourceRefs)$.free();if(this._sourceRefs.length=0,this._demuxerPromise)this._demuxerPromise.then(($)=>$.dispose()).catch(()=>{})}[Symbol.dispose](){this.dispose()}}class zJ extends Error{constructor($="Input has an unsupported or unrecognizable format."){super($);this.name="UnsupportedInputFormatError"}}class D0 extends Error{constructor($="Input has been disposed."){super($);this.name="InputDisposedError"}}/*!
|
|
282
266
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
283
267
|
*
|
|
284
268
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
285
269
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
286
270
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
287
|
-
*/class
|
|
271
|
+
*/class l8{constructor($){this.source=$}get fileSize(){let $=this.source._getFileSize();if($===void 0)throw Error("Reading file size too early; read required first.");return $}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice($,J){if(this.source._disposed)throw new D0;if($<0)return null;if(this.fileSizeNonStrict!==null&&$+J>this.fileSizeNonStrict)return null;if(J===0){let Q=new Uint8Array(0);return new u0(Q,l(Q),0,$,$)}let Y=$+J,X=this.source._read($,Y,pY,dY);if(X instanceof Promise)return X.then((Q)=>{if(!Q)return null;return new u0(Q.bytes,Q.view,Q.offset,$,Y)});else{if(!X)return null;return new u0(X.bytes,X.view,X.offset,$,Y)}}requestSliceRange($,J,Y){if(this.source._disposed)throw new D0;if($<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice($,r0(this.fileSizeNonStrict-$,J,Y));else{let X=this.requestSlice($,Y),Q=(Z)=>{if(Z)return Z;return F(this.fileSizeNonStrict!==null),this.requestSlice($,r0(this.fileSizeNonStrict-$,J,Y))};if(X instanceof Promise)return X.then(Q);else return Q(X)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let $=1024;return(async()=>{let J=[],Y=0;while(!0){if(J.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let Z=this.requestSliceRange(Y,0,$);if(Z instanceof Promise)Z=await Z;if(!Z||Z.length===0)break;let K=f(Z,Z.length);J.push(K),Y+=Z.length}let X=new Uint8Array(Y),Q=0;for(let Z of J)X.set(Z,Q),Q+=Z.length;return new u0(X,l(X),0,0,Y)})()}}class u0{constructor($,J,Y,X,Q){this.bytes=$,this.view=J,this.offset=Y,this.start=X,this.end=Q,this.bufferPos=X-Y}static tempFromBytes($){return new u0($,l($),0,0,$.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos($){this.bufferPos=$-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip($){this.bufferPos+=$}slice($,J=this.end-$){if($<this.start||$+J>this.end)throw RangeError("Slicing outside of original slice.");return new u0(this.bytes,this.view,this.offset,$,$+J)}}var $1=($,J)=>{if($.filePos<$.start||$.filePos+J>$.end)throw RangeError(`Tried reading [${$.filePos}, ${$.filePos+J}), but slice is [${$.start}, ${$.end}). This is likely an internal error, please report it alongside the file that caused it.`)},f=($,J)=>{$1($,J);let Y=$.bytes.subarray($.bufferPos,$.bufferPos+J);return $.bufferPos+=J,Y},g=($)=>{return $1($,1),$.view.getUint8($.bufferPos++)},F6=($,J)=>{$1($,2);let Y=$.view.getUint16($.bufferPos,J);return $.bufferPos+=2,Y},U0=($)=>{$1($,2);let J=$.view.getUint16($.bufferPos,!1);return $.bufferPos+=2,J},V1=($)=>{$1($,3);let J=D8($.view,$.bufferPos,!1);return $.bufferPos+=3,J},Y$=($)=>{$1($,2);let J=$.view.getInt16($.bufferPos,!1);return $.bufferPos+=2,J},s1=($,J)=>{$1($,4);let Y=$.view.getUint32($.bufferPos,J);return $.bufferPos+=4,Y},y=($)=>{$1($,4);let J=$.view.getUint32($.bufferPos,!1);return $.bufferPos+=4,J},f8=($)=>{$1($,4);let J=$.view.getUint32($.bufferPos,!0);return $.bufferPos+=4,J},p1=($)=>{$1($,4);let J=$.view.getInt32($.bufferPos,!1);return $.bufferPos+=4,J},b2=($)=>{$1($,4);let J=$.view.getInt32($.bufferPos,!0);return $.bufferPos+=4,J},MY=($,J)=>{let Y,X;if(J)Y=s1($,!0),X=s1($,!0);else X=s1($,!1),Y=s1($,!1);return X*4294967296+Y},i0=($)=>{let J=y($),Y=y($);return J*4294967296+Y},jX=($)=>{let J=p1($),Y=y($);return J*4294967296+Y},FX=($)=>{let J=f8($);return b2($)*4294967296+J},NX=($)=>{$1($,4);let J=$.view.getFloat32($.bufferPos,!1);return $.bufferPos+=4,J},p$=($)=>{$1($,8);let J=$.view.getFloat64($.bufferPos,!1);return $.bufferPos+=8,J},Z0=($,J)=>{$1($,J);let Y="";for(let X=0;X<J;X++)Y+=String.fromCharCode($.bytes[$.bufferPos++]);return Y},JJ=($,J,Y)=>{return A0.decode(f($,J)).split(`
|
|
288
272
|
`).map((Z)=>Z.trim()).filter((Z)=>Z.length>0&&!Y?.ignore?.(Z))};/*!
|
|
289
273
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
290
274
|
*
|
|
291
275
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
292
276
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
293
277
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
294
|
-
*/var
|
|
278
|
+
*/var o8;(function($){$[$.Unsynchronisation=128]="Unsynchronisation",$[$.ExtendedHeader=64]="ExtendedHeader",$[$.ExperimentalIndicator=32]="ExperimentalIndicator",$[$.Footer=16]="Footer"})(o8||(o8={}));var T6;(function($){$[$.ISO_8859_1=0]="ISO_8859_1",$[$.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",$[$.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",$[$.UTF_8=3]="UTF_8"})(T6||(T6={}));var K$=128,f0=10,v6=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],RX=($,J)=>{let Y=$.filePos;J.raw??={},J.raw.TAG??=f($,K$-3),$.filePos=Y;let X=b6($,30);if(X)J.title??=X;let Q=b6($,30);if(Q)J.artist??=Q;let Z=b6($,30);if(Z)J.album??=Z;let K=b6($,4),G=Number.parseInt(K,10);if(Number.isInteger(G)&&G>0)J.date??=new Date(String(G));let W=f($,30),j;if(W[28]===0&&W[29]!==0){let q=W[29];if(q>0)J.trackNumber??=q;$.skip(-30),j=b6($,28),$.skip(2)}else $.skip(-30),j=b6($,30);if(j)J.comment??=j;let U=g($);if(U<v6.length)J.genre??=v6[U]},b6=($,J)=>{let Y=f($,J),X=E8(Y.indexOf(0),Y.length),Q=Y.subarray(0,X),Z="";for(let K=0;K<Q.length;K++)Z+=String.fromCharCode(Q[K]);return Z.trimEnd()},t0=($)=>{let J=$.filePos,Y=Z0($,3),X=g($),Q=g($),Z=g($),K=y($);if(Y!=="ID3"||X===255||Q===255||(K&2155905152)!==0)return $.filePos=J,null;let G=T$(K);if(Z&o8.Footer)G+=f0;return{majorVersion:X,revision:Q,flags:Z,size:G}},W8=($,J,Y)=>{if(![2,3,4].includes(J.majorVersion)){k._warn(`Unsupported ID3v2 major version: ${J.majorVersion}`);return}let X=J.flags&o8.Footer?J.size-f0:J.size,Q=f($,X),Z=new H5(J,Q);if(J.flags&o8.Unsynchronisation&&J.majorVersion===3)Z.ununsynchronizeAll();if(J.flags&o8.ExtendedHeader){let K=Z.readU32();if(J.majorVersion===3)Z.pos+=K;else Z.pos+=K-4}while(Z.pos<=Z.bytes.length-Z.frameHeaderSize()){let K=Z.readId3V2Frame();if(!K)break;let G=Z.pos,W=Z.pos+K.size,j=!1,U=!1,q=!1;if(J.majorVersion===3)j=!!(K.flags&64),U=!!(K.flags&128);else if(J.majorVersion===4)j=!!(K.flags&4),U=!!(K.flags&8),q=!!(K.flags&2)||!!(J.flags&o8.Unsynchronisation);if(j){k._warn(`Skipping encrypted ID3v2 frame ${K.id}`),Z.pos=W;continue}if(U){k._warn(`Skipping compressed ID3v2 frame ${K.id}`),Z.pos=W;continue}if(q)Z.ununsynchronizeRegion(Z.pos,W);if(Y.raw??={},K.id==="TXXX"){let N=Y.raw.TXXX??={},_=Z.readId3V2TextEncoding(),V=Z.readId3V2Text(_,W),z=Z.readId3V2Text(_,W);N[V]??=z}else if(K.id[0]==="T")Y.raw[K.id]??=Z.readId3V2EncodingAndText(W);else Y.raw[K.id]??=Z.readBytes(K.size);switch(Z.pos=G,K.id){case"TIT2":case"TT2":Y.title??=Z.readId3V2EncodingAndText(W);break;case"TIT3":case"TT3":Y.description??=Z.readId3V2EncodingAndText(W);break;case"TPE1":case"TP1":Y.artist??=Z.readId3V2EncodingAndText(W);break;case"TALB":case"TAL":Y.album??=Z.readId3V2EncodingAndText(W);break;case"TPE2":case"TP2":Y.albumArtist??=Z.readId3V2EncodingAndText(W);break;case"TRCK":case"TRK":{let _=Z.readId3V2EncodingAndText(W).split("/"),V=Number.parseInt(_[0],10),z=_[1]&&Number.parseInt(_[1],10);if(Number.isInteger(V)&&V>0)Y.trackNumber??=V;if(z&&Number.isInteger(z)&&z>0)Y.tracksTotal??=z}break;case"TPOS":case"TPA":{let _=Z.readId3V2EncodingAndText(W).split("/"),V=Number.parseInt(_[0],10),z=_[1]&&Number.parseInt(_[1],10);if(Number.isInteger(V)&&V>0)Y.discNumber??=V;if(z&&Number.isInteger(z)&&z>0)Y.discsTotal??=z}break;case"TCON":case"TCO":{let N=Z.readId3V2EncodingAndText(W),_=/^\((\d+)\)/.exec(N);if(_){let V=Number.parseInt(_[1]);if(v6[V]!==void 0){Y.genre??=v6[V];break}}if(_=/^\d+$/.exec(N),_){let V=Number.parseInt(_[0]);if(v6[V]!==void 0){Y.genre??=v6[V];break}}Y.genre??=N}break;case"TDRC":case"TDAT":{let N=Z.readId3V2EncodingAndText(W),_=new Date(N);if(!Number.isNaN(_.getTime()))Y.date??=_}break;case"TYER":case"TYE":{let N=Z.readId3V2EncodingAndText(W),_=Number.parseInt(N,10);if(Number.isInteger(_))Y.date??=new Date(String(_))}break;case"USLT":case"ULT":{let N=Z.readU8();Z.pos+=3,Z.readId3V2Text(N,W),Y.lyrics??=Z.readId3V2Text(N,W)}break;case"COMM":case"COM":{let N=Z.readU8();Z.pos+=3,Z.readId3V2Text(N,W),Y.comment??=Z.readId3V2Text(N,W)}break;case"APIC":case"PIC":{let N=Z.readId3V2TextEncoding(),_;if(J.majorVersion===2){let H=Z.readAscii(3);_=H==="PNG"?"image/png":H==="JPG"?"image/jpeg":"image/*"}else _=Z.readId3V2Text(N,W);let V=Z.readU8(),z=Z.readId3V2Text(N,W).trimEnd(),R=W-Z.pos;if(R>=0){let H=Z.readBytes(R);if(!Y.images)Y.images=[];Y.images.push({data:H,mimeType:_,kind:V===3?"coverFront":V===4?"coverBack":"unknown",description:z})}}break;default:Z.pos+=K.size;break}Z.pos=W}};class H5{constructor($,J){this.header=$,this.bytes=J,this.pos=0,this.view=new DataView(J.buffer,J.byteOffset,J.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let $=[];for(let J=0;J<this.bytes.length;J++){let Y=this.bytes[J];if($.push(Y),Y===255&&J!==this.bytes.length-1){if(this.bytes[J]===0)J++}}this.bytes=new Uint8Array($),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion($,J){let Y=[];for(let Z=$;Z<J;Z++){let K=this.bytes[Z];if(Y.push(K),K===255&&Z!==J-1){if(this.bytes[Z+1]===0)Z++}}let X=this.bytes.subarray(0,$),Q=this.bytes.subarray(J);this.bytes=new Uint8Array(X.length+Y.length+Q.length),this.bytes.set(X,0),this.bytes.set(Y,X.length),this.bytes.set(Q,X.length+Y.length),this.view=new DataView(this.bytes.buffer)}readBytes($){let J=this.bytes.subarray(this.pos,this.pos+$);return this.pos+=$,J}readU8(){let $=this.view.getUint8(this.pos);return this.pos+=1,$}readU16(){let $=this.view.getUint16(this.pos,!1);return this.pos+=2,$}readU24(){let $=this.view.getUint16(this.pos,!1),J=this.view.getUint8(this.pos+2);return this.pos+=3,$*256+J}readU32(){let $=this.view.getUint32(this.pos,!1);return this.pos+=4,$}readAscii($){let J="";for(let Y=0;Y<$;Y++)J+=String.fromCharCode(this.view.getUint8(this.pos+Y));return this.pos+=$,J}readId3V2Frame(){if(this.header.majorVersion===2){let $=this.readAscii(3);if($==="\x00\x00\x00")return null;let J=this.readU24();return{id:$,size:J,flags:0}}else{let $=this.readAscii(4);if($==="\x00\x00\x00\x00")return null;let J=this.readU32(),Y=this.header.majorVersion===4?T$(J):J,X=this.readU16(),Q=this.pos,Z=(K)=>{let G=this.pos+K;if(G>this.bytes.length)return!1;if(G<=this.bytes.length-this.frameHeaderSize()){this.pos+=K;let W=this.readAscii(4);if(W!=="\x00\x00\x00\x00"&&!/[0-9A-Z]{4}/.test(W))return!1}return!0};if(!Z(Y)){let K=this.header.majorVersion===4?J:T$(J);if(Z(K))Y=K}return this.pos=Q,{id:$,size:Y,flags:X}}}readId3V2TextEncoding(){let $=this.readU8();if($>3)throw Error(`Unsupported text encoding: ${$}`);return $}readId3V2Text($,J){let Y=this.pos,X=this.readBytes(J-this.pos);switch($){case T6.ISO_8859_1:{let Q="";for(let Z=0;Z<X.length;Z++){let K=X[Z];if(K===0){this.pos=Y+Z+1;break}Q+=String.fromCharCode(K)}return Q}case T6.UTF_16_WITH_BOM:if(X[0]===255&&X[1]===254){let Q=new TextDecoder("utf-16le"),Z=E8(X.findIndex((K,G)=>K===0&&X[G+1]===0&&G%2===0),X.length);return this.pos=Y+Math.min(Z+2,X.length),Q.decode(X.subarray(2,Z))}else if(X[0]===254&&X[1]===255){let Q=new TextDecoder("utf-16be"),Z=E8(X.findIndex((K,G)=>K===0&&X[G+1]===0&&G%2===0),X.length);return this.pos=Y+Math.min(Z+2,X.length),Q.decode(X.subarray(2,Z))}else{let Q=E8(X.findIndex((Z)=>Z===0),X.length);return this.pos=Y+Math.min(Q+1,X.length),A0.decode(X.subarray(0,Q))}case T6.UTF_16_BE_NO_BOM:{let Q=new TextDecoder("utf-16be"),Z=E8(X.findIndex((K,G)=>K===0&&X[G+1]===0&&G%2===0),X.length);return this.pos=Y+Math.min(Z+2,X.length),Q.decode(X.subarray(0,Z))}case T6.UTF_8:{let Q=E8(X.findIndex((Z)=>Z===0),X.length);return this.pos=Y+Math.min(Q+1,X.length),A0.decode(X.subarray(0,Q))}}}readId3V2EncodingAndText($){if(this.pos>=$)return"";let J=this.readId3V2TextEncoding();return this.readId3V2Text(J,$)}}/*!
|
|
295
279
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
296
280
|
*
|
|
297
281
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -321,13 +305,13 @@ var PZ=Object.defineProperty;var bZ=($,J)=>{for(var Y in J)PZ($,Y,{get:J[Y],enum
|
|
|
321
305
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
322
306
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
323
307
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
324
|
-
*/var
|
|
308
|
+
*/var f2=new Uint8Array(8),sU=new DataView(f2.buffer);/*!
|
|
325
309
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
326
310
|
*
|
|
327
311
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
328
312
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
329
313
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
330
|
-
*/var
|
|
314
|
+
*/var $j=(()=>({}));/*!
|
|
331
315
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
332
316
|
*
|
|
333
317
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -369,7 +353,7 @@ var PZ=Object.defineProperty;var bZ=($,J)=>{for(var Y in J)PZ($,Y,{get:J[Y],enum
|
|
|
369
353
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
370
354
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
371
355
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
372
|
-
*/var
|
|
356
|
+
*/var d2=4096;var Pq=new Uint8Array([9,240]),bq=new Uint8Array([70,1]);var c2=79764919,M5=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let Y=0;Y<8;Y++)J=J&2147483648?J<<1^c2:J<<1;M5[$]=J>>>0&4294967295}var n2=($)=>{let J=4294967295;for(let Y=0;Y<$.length;Y++){let X=$[Y];J=(J<<8^M5[J>>>24^X])>>>0}return J},x6=new Uint8Array(16);{let $=l(x6);x6[0]=0,$.setUint16(1,45069,!1),$.setUint16(3,1,!1),x6[5]=193,x6[6]=0,x6[7]=0,$.setUint16(8,1,!1),$.setUint16(10,57344|d2&8191,!1),$.setUint32(12,n2(x6.subarray(0,12)),!1)}/*!
|
|
373
357
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
374
358
|
*
|
|
375
359
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -393,71 +377,7 @@ var PZ=Object.defineProperty;var bZ=($,J)=>{for(var Y in J)PZ($,Y,{get:J[Y],enum
|
|
|
393
377
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
394
378
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
395
379
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
396
|
-
|
|
397
|
-
in vec2 a_position;
|
|
398
|
-
in vec2 a_texCoord;
|
|
399
|
-
out vec2 v_texCoord;
|
|
400
|
-
|
|
401
|
-
void main() {
|
|
402
|
-
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
403
|
-
v_texCoord = a_texCoord;
|
|
404
|
-
}
|
|
405
|
-
`)}createColorProgram(){L(this.gl);let $=this.createVertexShader(),J=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
406
|
-
precision highp float;
|
|
407
|
-
|
|
408
|
-
uniform sampler2D u_sourceTexture;
|
|
409
|
-
in vec2 v_texCoord;
|
|
410
|
-
out vec4 fragColor;
|
|
411
|
-
|
|
412
|
-
void main() {
|
|
413
|
-
vec4 source = texture(u_sourceTexture, v_texCoord);
|
|
414
|
-
fragColor = vec4(source.rgb, 1.0);
|
|
415
|
-
}
|
|
416
|
-
`),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createAlphaProgram(){L(this.gl);let $=this.createVertexShader(),J=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
417
|
-
precision highp float;
|
|
418
|
-
|
|
419
|
-
uniform sampler2D u_sourceTexture;
|
|
420
|
-
uniform vec2 u_resolution; // The width and height of the canvas
|
|
421
|
-
in vec2 v_texCoord;
|
|
422
|
-
out vec4 fragColor;
|
|
423
|
-
|
|
424
|
-
// This function determines the value for a single byte in the YUV stream
|
|
425
|
-
float getByteValue(float byteOffset) {
|
|
426
|
-
float width = u_resolution.x;
|
|
427
|
-
float height = u_resolution.y;
|
|
428
|
-
|
|
429
|
-
float yPlaneSize = width * height;
|
|
430
|
-
|
|
431
|
-
if (byteOffset < yPlaneSize) {
|
|
432
|
-
// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
|
|
433
|
-
float y = floor(byteOffset / width);
|
|
434
|
-
float x = mod(byteOffset, width);
|
|
435
|
-
|
|
436
|
-
// Add 0.5 to sample the center of the texel
|
|
437
|
-
vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
|
|
438
|
-
|
|
439
|
-
// The luma value is the alpha from the source texture
|
|
440
|
-
return texture(u_sourceTexture, sampleCoord).a;
|
|
441
|
-
} else {
|
|
442
|
-
// Write a fixed value for chroma and beyond
|
|
443
|
-
return 128.0 / 255.0;
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
void main() {
|
|
448
|
-
// Each fragment writes 4 bytes (R, G, B, A)
|
|
449
|
-
float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
|
|
450
|
-
float baseByteOffset = pixelIndex * 4.0;
|
|
451
|
-
|
|
452
|
-
vec4 result;
|
|
453
|
-
for (int i = 0; i < 4; i++) {
|
|
454
|
-
float currentByteOffset = baseByteOffset + float(i);
|
|
455
|
-
result[i] = getByteValue(currentByteOffset);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
fragColor = result;
|
|
459
|
-
}
|
|
460
|
-
`),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createShader($,J){L(this.gl);let Y=this.gl.createShader($);if(this.gl.shaderSource(Y,J),this.gl.compileShader(Y),!this.gl.getShaderParameter(Y,this.gl.COMPILE_STATUS))console.error("Shader compile error:",this.gl.getShaderInfoLog(Y));return Y}createVAO(){L(this.gl),L(this.colorProgram);let $=this.gl.createVertexArray();this.gl.bindVertexArray($);let J=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),Y=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,Y),this.gl.bufferData(this.gl.ARRAY_BUFFER,J,this.gl.STATIC_DRAW);let X=this.gl.getAttribLocation(this.colorProgram,"a_position"),Q=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(X),this.gl.vertexAttribPointer(X,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(Q),this.gl.vertexAttribPointer(Q,2,this.gl.FLOAT,!1,16,8),$}createTexture(){L(this.gl);let $=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,$),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),$}runColorProgram($){return L(this.gl),L(this.canvas),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:$.timestamp,duration:$.duration??void 0,alpha:"discard"})}runAlphaProgram($){L(this.gl),L(this.canvas),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);let{width:J,height:Y}=this.canvas,X=Math.ceil(J/2)*Math.ceil(Y/2),Q=J*Y+X*2,Z=Math.ceil(Q/(J*4)),K=new Uint8Array(4*J*Z);this.gl.readPixels(0,0,J,Z,this.gl.RGBA,this.gl.UNSIGNED_BYTE,K),K=K.subarray(0,Q),L(K[J*Y]===128),L(K[K.length-1]===128);let G={format:"I420",codedWidth:J,codedHeight:Y,timestamp:$.timestamp,duration:$.duration??void 0,transfer:[K.buffer]};return new VideoFrame(K,G)}updateCpu($){if(!this.worker){let X=new Blob([`(${u2.toString()})()`],{type:"application/javascript"}),Q=URL.createObjectURL(X);this.worker=new Worker(Q),URL.revokeObjectURL(Q),this.worker.addEventListener("message",(Z)=>{let K=Z.data,G=this.pendingRequests.get(K.id);if(!G)return;if(this.pendingRequests.delete(K.id),"error"in K)G.reject(Error(K.error));else G.resolve({colorFrame:K.colorFrame,alphaFrame:K.alphaFrame})}),this.worker.addEventListener("error",(Z)=>{let K=Error(Z.message||"Color/alpha splitter worker error.");for(let G of this.pendingRequests.values())G.reject(K);this.pendingRequests.clear()})}let J=this.nextRequestId++,Y=U0();return this.pendingRequests.set(J,Y),this.worker.postMessage({id:J,sourceFrame:$},{transfer:[$]}),Y.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let $=Error("Color/alpha splitter closed.");for(let J of this.pendingRequests.values())J.reject($);this.pendingRequests.clear()}}X7.forceCpu=!0;var u2=()=>{let $=null,J=Promise.resolve();self.addEventListener("message",(Z)=>{let{id:K,sourceFrame:G}=Z.data;J=J.then(async()=>{try{let{colorFrame:W,alphaFrame:j}=await Y(G);self.postMessage({id:K,colorFrame:W,alphaFrame:j},{transfer:[W,j]})}catch(W){self.postMessage({id:K,error:W.message})}finally{G.close()}})});let Y=async(Z)=>{let K=Z.format;if(!K)throw Error("CPU color/alpha splitting requires a known VideoFrame format.");let{codedWidth:G,codedHeight:W}=Z,j=Z.allocationSize();if(!$||$.byteLength!==j)$=new Uint8Array(j);if(await Z.copyTo($),K==="RGBA"||K==="BGRA")return X($,G,W,K,Z);else if(K==="I420A"||K==="I420AP10"||K==="I420AP12"||K==="I422A"||K==="I422AP10"||K==="I422AP12"||K==="I444A"||K==="I444AP10"||K==="I444AP12")return Q($,G,W,K,Z);throw Error(`CPU color/alpha splitting does not support format '${K}'.`)},X=(Z,K,G,W,j)=>{let U=K*G,q=Math.ceil(K/2),V=Math.ceil(G/2),_=U+q*V*2,N=new Uint8Array(_);for(let A=0,M=3;A<U;A++,M+=4)N[A]=Z[M];N.fill(128,U);let R=new VideoFrame(Z,{format:W==="RGBA"?"RGBX":"BGRX",codedWidth:K,codedHeight:G,timestamp:j.timestamp,duration:j.duration??void 0}),z={format:"I420",codedWidth:K,codedHeight:G,timestamp:j.timestamp,duration:j.duration??void 0,transfer:[N.buffer]},H=new VideoFrame(N,z);return{colorFrame:R,alphaFrame:H}},Q=(Z,K,G,W,j)=>{let U=W.includes("P10"),q=W.includes("P12"),V=U||q?2:1,_,N;if(W.startsWith("I420"))_=Math.ceil(K/2),N=Math.ceil(G/2);else if(W.startsWith("I422"))_=Math.ceil(K/2),N=G;else _=K,N=G;let R=K*G,z=_*N,H=R*V,A=z*V,M=R*V,F=H+A*2,O=W.replace("A",""),B=Math.ceil(K/2),D=Math.ceil(G/2),w=B*D,P=w*V,T=M+2*P,C=new Uint8Array(T),E=F;C.set(Z.subarray(E,E+M),0);let v=M,x=U?512:q?2048:128;if(V===1)C.fill(x,v);else new Uint16Array(C.buffer,v,2*w).fill(x);let S=U?"I420P10":q?"I420P12":"I420",k=new VideoFrame(Z.subarray(0,F),{format:O,codedWidth:K,codedHeight:G,timestamp:j.timestamp,duration:j.duration??void 0}),m={format:S,codedWidth:K,codedHeight:G,timestamp:j.timestamp,duration:j.duration??void 0,transfer:[C.buffer]},f=new VideoFrame(C,m);return{colorFrame:k,alphaFrame:f}}};/*!
|
|
380
|
+
*//*!
|
|
461
381
|
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
462
382
|
*
|
|
463
383
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
@@ -487,5 +407,5 @@ var PZ=Object.defineProperty;var bZ=($,J)=>{for(var Y in J)PZ($,Y,{get:J[Y],enum
|
|
|
487
407
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
488
408
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
489
409
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
490
|
-
*/var
|
|
491
|
-
Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[D5]=!0;import{Internals as NJ}from"remotion";import{Internals as H9}from"remotion";import{Internals as z7}from"remotion";import{useContext as f9,useLayoutEffect as f0}from"react";import{Internals as P5}from"remotion";import{jsx as KZ}from"react/jsx-runtime";import{useContext as b5,useLayoutEffect as s9,useMemo as r9,useState as T5}from"react";import{cancelRender as v5,Html5Audio as i9,Internals as L1,random as a9,useCurrentFrame as t9,useDelayRender as e9,useRemotionEnvironment as $Q}from"remotion";import JQ from"react";import{cancelRender as x5,Internals as _$}from"remotion";import{Internals as I5}from"remotion";import{Internals as WZ}from"remotion";import{Internals as d1}from"remotion";import{Internals as VJ}from"remotion";import{Internals as _Q}from"remotion";import{Internals as HQ}from"remotion";import{Internals as DQ}from"remotion";import{jsx as xQ}from"react/jsx-runtime";import{jsx as W7}from"react/jsx-runtime";import fQ,{useMemo as l5,useState as gQ}from"react";import{Internals as w1,Interactive as kQ,Sequence as uQ,useRemotionEnvironment as mQ,useVideoConfig as lQ}from"remotion";import{useCallback as p5,useContext as j7,useEffect as pQ,useLayoutEffect as V$,useMemo as L7,useRef as F0,useState as q7}from"react";import{Html5Video as dQ,Internals as M1,useBufferState as cQ,useCurrentFrame as AZ,useVideoConfig as nQ}from"remotion";import{Internals as d5}from"remotion";import{jsx as F7}from"react/jsx-runtime";import{useContext as s5,useLayoutEffect as UK,useMemo as N7,useRef as WK,useState as V7}from"react";import{Internals as y0,Loop as jK,random as qK,useCurrentFrame as NK,useDelayRender as VK,useRemotionEnvironment as _K,useVideoConfig as HK}from"remotion";import{jsx as _7}from"react/jsx-runtime";import{jsx as AJ}from"react/jsx-runtime";var J9=Symbol.dispose||Symbol.for("Symbol.dispose"),Y9=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),r5=($,J,Y)=>{if(J!=null){if(typeof J!=="object"&&typeof J!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var X;if(Y)X=J[Y9];if(X===void 0)X=J[J9];if(typeof X!=="function")throw TypeError("Object not disposable");$.push([Y,X,J])}else if(Y)$.push([Y]);return J},i5=($,J,Y)=>{var X=typeof SuppressedError==="function"?SuppressedError:function(K,G,W,j){return j=Error(W),j.name="SuppressedError",j.error=K,j.suppressed=G,j},Q=(K)=>J=Y?new X(K,J,"An error was suppressed during disposal"):(Y=!0,K),Z=(K)=>{while(K=$.pop())try{var G=K[1]&&K[1].call(K[2]);if(K[0])return Promise.resolve(G).then(Z,(W)=>(Q(W),Z()))}catch(W){Q(W)}if(Y)throw J};return Z()},a5=({loop:$,mediaDurationInSeconds:J,playbackRate:Y,trimAfter:X,trimBefore:Q,sequenceDurationInFrames:Z,compFps:K})=>{if(!$||!J)return;let G=U9.calculateMediaDuration({mediaDurationInFrames:J*K,playbackRate:Y,trimAfter:X,trimBefore:Q});return{numberOfTimes:Z/G,startOffset:0,durationInFrames:G}},A$=({loop:$,mediaDurationInSeconds:J,unloopedTimeInSeconds:Y,src:X,trimAfter:Q,trimBefore:Z,fps:K,playbackRate:G,ifNoMediaDuration:W})=>{if(J===null&&$&&W==="fail")throw Error(`Could not determine duration of ${X}, but "loop" was set.`);let j=$?H7.calculateMediaDuration({trimAfter:Q,mediaDurationInFrames:J?J*K:1/0,playbackRate:1,trimBefore:Z})/K:1/0,U=Y*G%j;if((Q??null)!==null&&!$){let q=(Q-(Z??0))/K;if(U>=q)return null}return U+(Z??0)/K},_9=({mediaDurationInSeconds:$,ifNoMediaDuration:J,src:Y,trimAfter:X,trimBefore:Q,fps:Z})=>{if($===null&&J==="fail")throw Error(`Could not determine duration of ${Y}, but "loop" was set.`);return H7.calculateMediaDuration({trimAfter:X,mediaDurationInFrames:$?$*Z:1/0,playbackRate:1,trimBefore:Q})/Z+(Q??0)/Z},z9=0.5;async function*e5($,J,Y){let X=Math.max(0,J-z9),Q=$.buffers(X,Y);for await(let Z of Q){if(Z.timestamp+Z.duration<=J)continue;yield{buffer:Z,timestamp:Z.timestamp}}}async function*R9({audioSink:$,segmentStartInSeconds:J,segmentEndInSeconds:Y,playbackRate:X,sequenceDurationInSeconds:Q}){let Z=Y-J,K=0,G=!1;while(!0){for await(let W of e5($,J,Y)){let j=W.timestamp+K*Z;if(Z*K+(W.timestamp-J+W.buffer.duration)>Q*X){G=!0;break}yield{buffer:W.buffer,timestamp:j}}if(G)break;K++}}var A9=({audioSink:$,timeToSeek:J,maximumTimestamp:Y,loop:X,playbackRate:Q,sequenceDurationInSeconds:Z})=>{if(X)return R9({audioSink:$,segmentStartInSeconds:J,segmentEndInSeconds:Y,playbackRate:Q,sequenceDurationInSeconds:Z});return e5($,J,Y)},L9=0.1,M9=({startFromSecond:$,maximumTimestamp:J,audioSink:Y,loop:X,playbackRate:Q,sequenceDurationInSeconds:Z,unscheduleAudioNode:K})=>{let G=!1,W=A9({audioSink:Y,timeToSeek:$,maximumTimestamp:J,loop:X,playbackRate:Q,sequenceDurationInSeconds:Z}),j=[],U=-1/0,q=()=>{for(let _ of j){K(_.node);try{_.node.stop()}catch{}}j.length=0};return{destroy:()=>{q(),G=!0,W.return().catch(()=>{return})},getNextFn:async()=>{let _=await W.next();if(_.value)U=Math.max(U,_.value.timestamp+_.value.buffer.duration);return _},isDestroyed:()=>{return G},addQueuedAudioNode:({node:_,timestamp:N,buffer:R,scheduledTime:z,scheduledAtAnchor:H})=>{j.push({node:_,timestamp:N,buffer:R,scheduledTime:z,playbackRate:Q,scheduledAtAnchor:H})},guessNextTimestamp:()=>{return!Number.isFinite(U)?$:U},getQueuedPeriod:()=>{let _=-1/0,N=1/0;for(let R of j)_=Math.max(_,R.timestamp+R.buffer.duration),N=Math.min(N,R.timestamp);if(!Number.isFinite(N)||!Number.isFinite(_))return null;return{from:N,until:_}}}},F9=($,J)=>{if(!J)return!1;return $>=J.from&&$<J.until},$Z=({mediaTimestamp:$,targetTime:J,currentTime:Y,sequenceStartTime:X})=>{let Z=$<X?X-$:0,K=J<0?-J:0,G=Z+K;return J+Y+G},w9=({bufferDuration:$,loopSegmentMediaEndTimestamp:J,offset:Y,originalUnloopedMediaTimestamp:X})=>{let Q=X+$,Z=Q>J,K=$-Y;return Z?K-Math.max(0,Q-J):K},O9=({mediaTimestamp:$,targetTime:J,sequenceStartTime:Y,combinedPlaybackRate:X})=>{let Z=$<Y?Y-$:0,K=J<0?-J*X:0;return Z+K};class w7 extends Error{constructor(){super("Waiter became stale before it got its turn");this.name="StaleWaiterError"}}var B9=1,c1=[],K7=0,N$=null,RJ=()=>{if(K7>=B9)if(N$?.waiter.getPriority()===null)N$.cancel();else return;let $=[];for(let G=c1.length-1;G>=0;G--)if(c1[G].getPriority()===null){let[W]=c1.splice(G,1);$.push(W)}for(let G of $)G.onError(new w7);if(c1.length===0)return;let J=0,Y=c1[0].getPriority();if(Y===null)throw Error("Stale waiter should have been removed");for(let G=1;G<c1.length;G++){let W=c1[G].getPriority();if(W===null)throw Error("Stale waiter should have been removed");if(W<Y)Y=W,J=G}if(Y>2)return;let[X]=c1.splice(J,1);K7++;let Q=!1,Z=!1,K={waiter:X,cancel:()=>{Z=!0,K.settle()},settle:()=>{if(Q)return;if(Q=!0,K7--,N$===K)N$=null}};N$=K,X.fn().then((G)=>{if(K.settle(),Z)return;X.onDone(G,RJ)},(G)=>{if(K.settle(),Z)return;X.onError(G)})},D9=({getPriority:$,fn:J,onDone:Y,onError:X})=>{c1.push({getPriority:$,fn:J,onDone:Y,onError:X}),RJ()},C9=({audioTrack:$,delayPlaybackHandleIfNotPremounting:J,sharedAudioContext:Y,getSequenceEndTimestamp:X,getSequenceDurationInSeconds:Q,getMediaEndTimestamp:Z,getStartTime:K,initialMuted:G,drawDebugOverlay:W,initialPlaybackRate:j,initialTrimBefore:U,initialTrimAfter:q,initialSequenceOffset:V,initialSequenceDurationInFrames:_,initialLoop:N,initialFps:R})=>{let z=G,H=1,A={time:-1,playbackRate:j,trimBefore:U,trimAfter:q,sequenceOffset:V,sequenceDurationInFrames:_,loop:N,fps:R},M=Y.audioContext.createGain();M.connect(Y.gainNode);let F=new UJ($),O=null,B=0,D=0,w=null,P=()=>{if(w)w.unblock(),w=null},T=[],C=()=>{for(let f=T.length-1;f>=0;f--){let n=T[f];if(n.remaining--,n.remaining<=0)n.resolve(),T.splice(f,1)}},E=(f)=>{if(f<=0)return Promise.resolve();return new Promise((n)=>{T.push({remaining:f,resolve:n})})},v=({buffer:f,mediaTimestamp:n,originalUnloopedMediaTimestamp:o,playbackRate:s,scheduleAudioNode:a,logLevel:r})=>{if(!O)throw Error("Audio buffer iterator not found");if(z)return;let l=Y.audioContext.createBufferSource();l.buffer=f,l.playbackRate.value=s,l.connect(M);let X0=a(l,n,o);if(X0.type==="not-started"){H9.Log.verbose({logLevel:r,tag:"audio-scheduling"},"not started, disconnected: %s %s",n.toFixed(3),f.duration.toFixed(3)),l.disconnect();return}O.addQueuedAudioNode({node:l,timestamp:n,buffer:f,scheduledTime:X0.scheduledTime,scheduledAtAnchor:Y.audioSyncAnchor.value})},x=({buffer:f,playbackRate:n,scheduleAudioNode:o,logLevel:s})=>{if(z)return;let a=K(),r=X();if(f.timestamp+f.buffer.duration<=a)return;if(f.timestamp>=r)return;let l=Math.max(f.timestamp,a),X0=Math.min(f.timestamp+f.buffer.duration,r);D+=Math.max(0,X0-l),v({buffer:f.buffer.buffer,mediaTimestamp:f.timestamp,playbackRate:n,scheduleAudioNode:o,logLevel:s,originalUnloopedMediaTimestamp:f.buffer.timestamp}),W()},S=({iterator:f,nonce:n,getTargetTime:o,playbackRate:s,scheduleAudioNode:a,onScheduled:r,onDestroyed:l,onDone:X0,logLevel:N0,currentTime:t,getAudioContextCurrentTimeMockedInTest:$0})=>{D9({getPriority:()=>{if(f.isDestroyed())return l(),null;let e=f.guessNextTimestamp(),Y0=o(e,t);if(Y0===null)return null;return $Z({mediaTimestamp:e,targetTime:Y0,currentTime:t,sequenceStartTime:K()})-$0()},fn:()=>f.getNextFn(),onDone:(e,Y0)=>{if(f.isDestroyed()){Y0(),l();return}if(!e.value){Y0(),X0();return}r(e.value.timestamp),C(),x({buffer:e.value,playbackRate:s,scheduleAudioNode:a,logLevel:N0}),S({iterator:f,nonce:n,getTargetTime:o,playbackRate:s,scheduleAudioNode:a,onScheduled:r,onDestroyed:l,onDone:X0,logLevel:N0,currentTime:t,getAudioContextCurrentTimeMockedInTest:$0}),Y0()},onError:(e)=>{if(e instanceof R0){l();return}if(e instanceof w7){l();return}throw e}})},k=({nonce:f,playbackRate:n,startFromSecond:o,scheduleAudioNode:s,getTargetTime:a,logLevel:r,loop:l,unscheduleAudioNode:X0,getAudioContextCurrentTimeMockedInTest:N0})=>{if(z)return;let t=Z();if(o>=t)return;O?.destroy(),P();let $0=J();w=$0;let e=M9({startFromSecond:o,maximumTimestamp:t,audioSink:F,logLevel:r,loop:l,playbackRate:n,sequenceDurationInSeconds:Q(),unscheduleAudioNode:X0});B++,O=e;let Y0=0;S({iterator:e,nonce:f,getTargetTime:a,playbackRate:n,scheduleAudioNode:s,onScheduled:()=>{if(Y0++,Y0===6)$0.unblock()},onDestroyed:()=>{$0.unblock()},onDone:()=>{$0.unblock()},logLevel:r,currentTime:Y.audioContext.currentTime,getAudioContextCurrentTimeMockedInTest:N0})};return{startAudioIterator:k,getAudioBufferIterator:()=>O,destroyIterator:()=>{O?.destroy(),O=null,P()},seek:({newTime:f,nonce:n,playbackRate:o,scheduleAudioNode:s,getTargetTime:a,logLevel:r,loop:l,trimBefore:X0,trimAfter:N0,sequenceOffset:t,sequenceDurationInFrames:$0,fps:e,getAudioContextCurrentTimeMockedInTest:Y0})=>{if(n.isStale())return;if(A.time===f&&A.playbackRate===o&&A.trimBefore===X0&&A.trimAfter===N0&&A.sequenceOffset===t&&A.sequenceDurationInFrames===$0&&A.loop===l&&A.fps===e)return;if(A={time:f,playbackRate:o,trimBefore:X0,trimAfter:N0,sequenceOffset:t,sequenceDurationInFrames:$0,loop:l,fps:e},z)return;if(O&&!O.isDestroyed()){let C0=O.getQueuedPeriod(),B1=C0?{from:C0.from-L9-Y.audioContext.baseLatency-Y.audioContext.outputLatency,until:C0.until}:null;if(F9(f,B1)){RJ();return}let E0=O.guessNextTimestamp();if(E0<f&&Math.abs(E0-f)<1){RJ();return}}k({nonce:n,playbackRate:o,startFromSecond:f,scheduleAudioNode:s,getTargetTime:a,logLevel:r,loop:l,unscheduleAudioNode:Y.unscheduleAudioNode,getAudioContextCurrentTimeMockedInTest:Y0})},getAudioIteratorsCreated:()=>B,getTotalAudioScheduledInSeconds:()=>D,setMuted:(f)=>{z=f,M.gain.value=z?0:H},setVolume:(f)=>{H=Math.max(0,f),M.gain.value=z?0:H},scheduleAudioChunk:v,waitForNScheduledNodes:E}},E9=({context:$,audioTime:J,audioContextState:Y,audioSyncAnchor:X,playing:Q,audioIteratorManager:Z,videoIteratorManager:K,playbackRate:G})=>{let W=X?.value??0,j=["Debug overlay",`Video iterators created: ${K?.getVideoIteratorsCreated()}`,`Audio iterators created: ${Z?.getAudioIteratorsCreated()}`,`Audio scheduled: ${(Z?.getTotalAudioScheduledInSeconds()??0).toFixed(3)}s`,`Frames rendered: ${K?.getFramesRendered()}`,`Audio context state: ${Y}`,J?`Audio time: ${((J-W)*G).toFixed(3)}s`:null].filter(Boolean);if(Z){let H=Z.getAudioBufferIterator()?.getQueuedPeriod();if(H){let A=J?` (${(H.until-(J-W)*G).toFixed(3)}s ahead)`:"";j.push(`Audio queued until ${H.until.toFixed(3)}s${A}`)}j.push(`Playing: ${Q}`)}let U=30,q=10,V=10,_=20,N=20,R=600,z=j.length*U+2*V;$.fillStyle="rgba(0, 0, 0, 1)",$.fillRect(_,N,R,z),$.fillStyle="white",$.font="24px sans-serif",$.textBaseline="top";for(let H=0;H<j.length;H++)$.fillText(j[H],_+q,N+V+H*U)},JZ=async($)=>{return await $.getDurationFromMetadata(void 0,{skipLiveWait:!0})??$.computeDuration(void 0,{skipLiveWait:!0})},YZ=async({videoTrack:$,audioTracks:J,audioStreamIndex:Y})=>{if(Y!==null)return J[Y]??null;if($)return await $.getPrimaryPairableAudioTrack()??null;return J[0]??null};function z$($){if($.message.includes("Failed to fetch")||$.message.includes("Load failed")||$.message.includes("NetworkError when attempting to fetch resource"))return!0;return!1}function P9($){return $.message.includes("Unsupported configuration")}var b9=()=>{let $=0;return{createAsyncOperation:()=>{$++;let Y=$;return{isStale:()=>$!==Y}}}};class XZ{isPremounting;isPostmounting;activeHandles=new Set;delayPlayback;constructor({bufferState:$,isPremounting:J,isPostmounting:Y}){this.delayPlayback=$.delayPlayback,this.isPremounting=J,this.isPostmounting=Y}shouldDelayPlayback(){return!this.isPremounting&&!this.isPostmounting}syncHandles(){for(let $ of this.activeHandles)if(this.shouldDelayPlayback())$.arm();else $.disarm()}setIsPremounting($){this.isPremounting=$,this.syncHandles()}setIsPostmounting($){this.isPostmounting=$,this.syncHandles()}createHandle(){let $=!1,J=null,Y=!1,X=()=>{if($||Y)return;J=this.delayPlayback().unblock,$=!0},Q=()=>{if(!$)return;J?.(),J=null,$=!1},Z={arm:X,disarm:Q,dispose:()=>{}};if(Z.dispose=()=>{if(Y)return;Y=!0,Q(),this.activeHandles.delete(Z)},this.activeHandles.add(Z),this.shouldDelayPlayback())X();return{unblock:Z.dispose,[Symbol.dispose]:Z.dispose}}}var T9=($)=>{if(!$)return;let J=[];if($ instanceof Headers)$.forEach((Y,X)=>{J.push([X.toLowerCase(),Y])});else if(Array.isArray($))for(let[Y,X]of $)J.push([Y.toLowerCase(),X]);else for(let[Y,X]of Object.entries($))J.push([Y.toLowerCase(),X]);return J.sort(([Y],[X])=>Y<X?-1:Y>X?1:0),J},R$=($)=>{if(!$)return;let J=T9($.headers),Y={...$.cache===void 0?null:{cache:$.cache},...$.credentials===void 0?null:{credentials:$.credentials},...J===void 0?null:{headers:J},...$.integrity===void 0?null:{integrity:$.integrity},...$.mode===void 0?null:{mode:$.mode},...$.redirect===void 0?null:{redirect:$.redirect},...$.referrer===void 0?null:{referrer:$.referrer},...$.referrerPolicy===void 0?null:{referrerPolicy:$.referrerPolicy}};return Object.keys(Y).length===0?void 0:Y},v9=($)=>{let J=R$($);if(!J)return null;return[J.cache??null,J.credentials??null,J.integrity??null,J.mode??null,J.redirect??null,J.referrer??null,J.referrerPolicy??null,J.headers??null]},ZZ=({credentials:$,requestInit:J})=>{if($===void 0)return R$(J);return R$({credentials:$,...J})},q0=($)=>{return Math.round($*1000)/1000},x9=3,E5=($,J)=>{let Y=$.canvases(J),X=[],Q=!1,Z=!1,K=!1,G=null,W=(V)=>{V.close?.()},j=()=>{if(Q||Z||K)return;if(X.length>=x9)return;Q=!0;let V={promise:Y.next(),resolved:null};X.push(V),G=V.promise.then((_)=>{if(V.resolved=_,Q=!1,G=null,_.done){Z=!0;return}if(K){W(_.value);return}j()},()=>{Q=!1,G=null})};return j(),{next:()=>{let V=X.shift();if(j(),!V){if(Z||K)return{type:"ready",frame:null};let _=G;return{type:"pending",wait:async()=>{await _;let N=X.shift();if(j(),!N)return null;if(N.resolved)return N.resolved.done?null:N.resolved.value;let R=await N.promise;return R.done?null:R.value}}}if(V.resolved){if(V.resolved.done)return{type:"ready",frame:null};return{type:"ready",frame:V.resolved.value}}return{type:"pending",wait:async()=>{let _=await V.promise;return _.done?null:_.value}}},closeIterator:async()=>{K=!0;for(let V of X)if(V.resolved&&!V.resolved.done)W(V.resolved.value);X.length=0,await Y.return()}}},I9=($)=>{let J=new Map;return{prewarmIteratorForLooping:({timeToSeek:Z})=>{if(!J.has(Z))J.set(Z,E5($,Z))},makeIteratorOrUsePrewarmed:(Z)=>{let K=J.get(Z);if(K)return J.delete(Z),K;return E5($,Z)},destroy:()=>{for(let Z of J.values())Z.closeIterator();J.clear()}}},y9=async($,J)=>{let Y=!1,X=J.makeIteratorOrUsePrewarmed($),Q=!1,Z=X.next(),K=Z&&Z.type==="ready"?Z.frame:await Z.wait(),G=K,W=null,j=async()=>{if(W)return W;let _=X.next();if(_.type==="ready")W=_.frame;else W=await _.wait();return W},U=()=>{if(W){let N=W;G=N;let R={type:"got-frame-or-end",frame:N};return W=null,R}let _=X.next();if(_.type==="pending")return{type:"need-to-wait-for-it",waitPromise:async()=>{let N=await _.wait();if(N)G=N;else Q=!0;return N}};if(_.frame)G=_.frame;else Q=!0;return{type:"got-frame-or-end",frame:_.frame??null}};return{destroy:()=>{Y=!0,G=null,X.closeIterator().catch(()=>{return})},initialFrame:K,isDestroyed:()=>{return Y},tryToSatisfySeek:async(_)=>{if(G){let N=q0(G.timestamp);if(q0(_)<N){if(G===K&&q0(_)>=q0($))return{type:"satisfied",frame:G};return{type:"not-satisfied",reason:`iterator is too far, most recently returned ${N}`}}let R=G.duration;if(R===0){let A=await j();if(A)R=A.timestamp-G.timestamp}let z=q0(G.timestamp+R),H=q0(_);if(N<=H&&z>H)return{type:"satisfied",frame:G}}if(Q){if(G)return{type:"satisfied",frame:G};return{type:"not-satisfied",reason:"iterator ended"}}while(!0){let N=U();if(N.type==="need-to-wait-for-it")return{type:"not-satisfied",reason:"iterator did not have frame ready"};if(N.type==="got-frame-or-end"){if(N.frame===null){if(Q=!0,G)return{type:"satisfied",frame:G};return{type:"not-satisfied",reason:"iterator ended and did not have frame ready"}}let R=q0(N.frame.timestamp),z=q0(N.frame.timestamp+N.frame.duration),H=q0(_);if(R<=H&&z>H)return{type:"satisfied",frame:N.frame};continue}throw Error("Unreachable")}}}},{runEffectChain:S9}=z7,h9=async({delayPlaybackHandleIfNotPremounting:$,canvas:J,context:Y,drawDebugOverlay:X,logLevel:Q,getOnVideoFrameCallback:Z,videoTrack:K,getLoopSegmentMediaEndTimestamp:G,getStartTime:W,getIsLooping:j,getEffects:U,getEffectChainState:q})=>{let V=0,_=null,N=0,R=null,z=null,H=null,A=()=>{z=null};if(J){let T=await K.getDisplayWidth(),C=await K.getDisplayHeight();if(J.width!==T||J.height!==C)J.width=T,J.height=C}let M=new GJ(K,{poolSize:2,fit:"contain",alpha:!0}),F=I9(M),O=async(T)=>{if(Y&&J){let C=U(),E=q(J.width,J.height);if(C.length>0&&E&&J instanceof HTMLCanvasElement)await S9({state:E,source:T.canvas,effects:C,output:J,width:J.width,height:J.height});else Y.clearRect(0,0,J.width,J.height),Y.drawImage(T.canvas,0,0)}},B=async(T)=>{await O(T),z=T,N++,X();let C=Z();if(C)C(T.canvas);z7.Log.trace({logLevel:Q,tag:"@remotion/media"},`[MediaPlayer] Drew frame ${T.timestamp.toFixed(3)}s`)},D=async()=>{if(!z)return;await O(z),X();let T=Z();if(T)T(z.canvas);z7.Log.trace({logLevel:Q,tag:"@remotion/media"},`[MediaPlayer] Redrew frame ${z.timestamp.toFixed(3)}s with updated effects`)},w=async(T,C)=>{let E=[];try{A(),_?.destroy(),R=r5(E,$(),0),H=T;let k=await y9(T,F);if(V++,_=k,k.isDestroyed())return;if(C.isStale())return;if(_.isDestroyed())return;if(!k.initialFrame)return;await B(k.initialFrame)}catch(S){var v=S,x=1}finally{i5(E,v,x)}};return{startVideoIterator:w,getVideoIteratorsCreated:()=>V,seek:async({newTime:T,nonce:C})=>{if(!_)return;if(H!==null&&q0(H)===q0(T))return;if(H=T,j()){if(G()-T<1)F.prewarmIteratorForLooping({timeToSeek:W()})}let E=await _.tryToSatisfySeek(T);if(E.type==="satisfied"){await B(E.frame);return}if(C.isStale())return;await w(T,C)},destroy:()=>{if(A(),F.destroy(),_?.destroy(),Y&&J)Y.clearRect(0,0,J.width,J.height);if(R)R.unblock(),R=null;_=null},getVideoFrameIterator:()=>_,drawFrame:B,redrawCurrentFrame:D,getFramesRendered:()=>N}};class O7{tagType;canvas;context;src;logLevel;playbackRate;globalPlaybackRate;audioStreamIndex;sharedAudioContext;audioIteratorManager=null;videoIteratorManager=null;playing=!1;loop=!1;fps;trimBefore;trimAfter;sequenceDurationInFrames;sequenceOffset;totalDuration;debugOverlay=!1;nonceManager;onVideoFrameCallback=null;getEffects;getEffectChainState;initializationPromise=null;premountAwareDelayPlayback;seekPromiseChain=Promise.resolve();constructor({canvas:$,src:J,logLevel:Y,sharedAudioContext:X,loop:Q,trimBefore:Z,trimAfter:K,playbackRate:G,globalPlaybackRate:W,audioStreamIndex:j,fps:U,debugOverlay:q,bufferState:V,isPremounting:_,isPostmounting:N,durationInFrames:R,onVideoFrameCallback:z,playing:H,sequenceOffset:A,credentials:M,requestInit:F,tagType:O,getEffects:B,getEffectChainState:D}){this.canvas=$??null,this.src=J,this.logLevel=Y,this.sharedAudioContext=X,this.playbackRate=G,this.globalPlaybackRate=W,this.loop=Q,this.trimBefore=Z,this.trimAfter=K,this.audioStreamIndex=j,this.fps=U,this.debugOverlay=q,this.premountAwareDelayPlayback=new XZ({bufferState:V,isPremounting:_,isPostmounting:N}),this.sequenceDurationInFrames=R,this.nonceManager=b9(),this.onVideoFrameCallback=z,this.playing=H,this.sequenceOffset=A;let w=ZZ({credentials:M,requestInit:F});if(this.input=new A1({source:new h8(this.src,w?{requestInit:w}:void 0),formats:X$}),this.tagType=O,this.getEffects=B,this.getEffectChainState=D,$){let P=$.getContext("2d",{alpha:!0,desynchronized:!0});if(!P)throw Error("Could not get 2D context from canvas");this.context=P}else this.context=null}input;isDisposalError(){return this.input.disposed===!0}initialize($,J){let Y=this._initialize($,J);return this.initializationPromise=Y,this.seekPromiseChain=Y,Y}getStartTime(){return(this.trimBefore??0)/this.fps}getSequenceEndTimestamp(){return this.sequenceDurationInFrames/this.fps*this.playbackRate+this.getStartTime()}getSequenceDurationInSeconds(){return this.sequenceDurationInFrames/this.fps}getMediaEndTimestamp(){return _9({mediaDurationInSeconds:this.totalDuration,ifNoMediaDuration:"fail",src:this.src,trimAfter:this.trimAfter,trimBefore:this.trimBefore,fps:this.fps})}getLoopSegmentMediaEndTimestamp(){return Math.min(this.getMediaEndTimestamp(),this.getSequenceEndTimestamp())}async _initialize($,J){let Y=[];try{let Z=r5(Y,this.delayPlaybackHandleIfNotPremounting(),0);try{if(this.input.disposed)return{type:"disposed"};try{await this.input.getFormat()}catch(V){if(this.isDisposalError())return{type:"disposed"};if(z$(V))throw V;return NJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Failed to recognize format for ${this.src}`,V),{type:"unknown-container-format"}}let[K,G,W]=await Promise.all([JZ(this.input),this.input.getPrimaryVideoTrack(),this.input.getAudioTracks()]);if(this.input.disposed)return{type:"disposed"};this.totalDuration=K;let j=await YZ({videoTrack:G,audioTracks:W,audioStreamIndex:this.audioStreamIndex});if(!G&&!j)return{type:"no-tracks"};if(G&&this.tagType==="video"){if(await G.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+this.src);if(await G.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+this.src);if(!await G.canDecode())return{type:"cannot-decode"};if(this.input.disposed)return{type:"disposed"};this.videoIteratorManager=await h9({videoTrack:G,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,context:this.context,canvas:this.canvas,getOnVideoFrameCallback:()=>this.onVideoFrameCallback,logLevel:this.logLevel,drawDebugOverlay:this.drawDebugOverlay,getLoopSegmentMediaEndTimestamp:()=>this.getLoopSegmentMediaEndTimestamp(),getStartTime:()=>this.getStartTime(),getIsLooping:()=>this.loop,getEffects:this.getEffects,getEffectChainState:this.getEffectChainState})}let U=this.getTrimmedTime($);if(U===null)throw Error("should have asserted that the time is not null");if(j&&this.sharedAudioContext){if(await j.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+this.src);if(await j.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+this.src);if(!await j.canDecode())return{type:"cannot-decode"};if(this.input.disposed)return{type:"disposed"};this.audioIteratorManager=C9({audioTrack:j,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,sharedAudioContext:this.sharedAudioContext,getMediaEndTimestamp:()=>this.getMediaEndTimestamp(),getSequenceEndTimestamp:()=>this.getSequenceEndTimestamp(),getStartTime:()=>this.getStartTime(),initialMuted:J,drawDebugOverlay:this.drawDebugOverlay,initialPlaybackRate:this.playbackRate*this.globalPlaybackRate,getSequenceDurationInSeconds:()=>this.getSequenceDurationInSeconds(),initialTrimBefore:this.trimBefore,initialTrimAfter:this.trimAfter,initialSequenceOffset:this.sequenceOffset,initialSequenceDurationInFrames:this.sequenceDurationInFrames,initialLoop:this.loop,initialFps:this.fps})}let q=this.nonceManager.createAsyncOperation();try{await Promise.all([this.audioIteratorManager?this.audioIteratorManager.startAudioIterator({nonce:q,playbackRate:this.playbackRate*this.globalPlaybackRate,startFromSecond:U,scheduleAudioNode:this.scheduleAudioNode,getTargetTime:this.getTargetTime,logLevel:this.logLevel,loop:this.loop,unscheduleAudioNode:this.sharedAudioContext.unscheduleAudioNode,getAudioContextCurrentTimeMockedInTest:()=>this.sharedAudioContext.audioContext.currentTime}):Promise.resolve(),this.videoIteratorManager?this.videoIteratorManager.startVideoIterator(U,q):Promise.resolve()])}catch(V){if(this.isDisposalError())return{type:"disposed"};NJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to start audio and video iterators",V)}return{type:"success",durationInSeconds:K}}catch(K){let G=K;if(z$(G))return NJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Network/CORS error for ${this.src}`,G),{type:"network-error"};throw NJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to initialize",K),K}}catch(Z){var X=Z,Q=1}finally{i5(Y,X,Q)}}seekToWithQueue=async($)=>{let J=this.nonceManager.createAsyncOperation();await this.seekPromiseChain,this.seekPromiseChain=this.seekToDoNotCallDirectly($,J),await this.seekPromiseChain};async seekTo($){let J=this.getTrimmedTime($);if(J===null)throw Error("should have asserted that the time is not null");await this.seekToWithQueue(J)}async seekToDoNotCallDirectly($,J){if(J.isStale())return;try{await Promise.all([this.videoIteratorManager?.seek({newTime:$,nonce:J}),this.audioIteratorManager?.seek({newTime:$,nonce:J,playbackRate:this.playbackRate*this.globalPlaybackRate,getTargetTime:this.getTargetTime,logLevel:this.logLevel,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,sequenceOffset:this.sequenceOffset,sequenceDurationInFrames:this.sequenceDurationInFrames,fps:this.fps,scheduleAudioNode:this.scheduleAudioNode,getAudioContextCurrentTimeMockedInTest:()=>this.sharedAudioContext.audioContext.currentTime})])}catch(Y){if(this.isDisposalError())return;throw Y}}play(){if(this.playing)return;this.playing=!0,this.drawDebugOverlay()}delayPlaybackHandleIfNotPremounting=()=>{return this.premountAwareDelayPlayback.createHandle()};pause(){if(!this.playing)return;this.playing=!1,this.drawDebugOverlay()}setMuted($){this.audioIteratorManager?.setMuted($)}setVolume($){if(!this.audioIteratorManager)return;this.audioIteratorManager.setVolume($)}getTrimmedTime($){return A$({unloopedTimeInSeconds:$,playbackRate:this.playbackRate,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,mediaDurationInSeconds:this.totalDuration??null,fps:this.fps,ifNoMediaDuration:"infinity",src:this.src})}async setTrimBefore($,J){if(this.trimBefore!==$)this.trimBefore=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setTrimAfter($,J){if(this.trimAfter!==$)this.trimAfter=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}setDebugOverlay($){this.debugOverlay=$}async setPlaybackRate($,J){if(this.playbackRate!==$)this.playbackRate=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setGlobalPlaybackRate($,J){if(this.globalPlaybackRate!==$)this.globalPlaybackRate=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setFps($,J){if(this.fps!==$)this.fps=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}setIsPremounting($){this.premountAwareDelayPlayback.setIsPremounting($)}setIsPostmounting($){this.premountAwareDelayPlayback.setIsPostmounting($)}async setLoop($,J){if(this.loop!==$)this.loop=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setSequenceOffset($,J){if(this.sequenceOffset!==$)this.sequenceOffset=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setSequenceDurationInFrames($,J){if(this.sequenceDurationInFrames!==$)this.sequenceDurationInFrames=$,await this.seekTo(J)}async dispose(){if(this.initializationPromise)try{await this.initializationPromise}catch{}this.nonceManager.createAsyncOperation(),this.videoIteratorManager?.destroy(),this.audioIteratorManager?.destroyIterator(),this.input.dispose()}getTargetTime=($,J)=>{if(!this.sharedAudioContext)throw Error("Shared audio context not found");let X=(J-this.sharedAudioContext.audioSyncAnchor.value)*this.globalPlaybackRate-this.sequenceOffset,Q=this.getTrimmedTime(X);if(Q===null)return null;return($-Q)/(this.playbackRate*this.globalPlaybackRate)};scheduleAudioNode=($,J,Y)=>{if(!this.sharedAudioContext)throw Error("Shared audio context not found");let X=this.getTargetTime(J,this.sharedAudioContext.audioContext.currentTime),Q=this.playbackRate*this.globalPlaybackRate;if(X===null)return{type:"not-started",reason:"no target for"+J.toFixed(3)+","+this.sharedAudioContext.audioContext.currentTime.toFixed(3)};let Z=this.getStartTime(),K=this.getLoopSegmentMediaEndTimestamp(),G=O9({mediaTimestamp:J,targetTime:X,sequenceStartTime:Z,combinedPlaybackRate:Q}),W=w9({bufferDuration:$.buffer?.duration??0,loopSegmentMediaEndTimestamp:K,offset:G,originalUnloopedMediaTimestamp:Y}),j=$Z({mediaTimestamp:J,targetTime:X,sequenceStartTime:Z,currentTime:this.sharedAudioContext.audioContext.currentTime});return this.sharedAudioContext.scheduleAudioNode({node:$,mediaTimestamp:J,scheduledTime:j,duration:W,offset:G,originalUnloopedMediaTimestamp:Y})};setVideoFrameCallback($){this.onVideoFrameCallback=$}async redrawVideoEffects(){await this.videoIteratorManager?.redrawCurrentFrame()}drawDebugOverlay=()=>{if(!this.debugOverlay)return;if(this.context&&this.canvas)E9({context:this.context,audioTime:this.sharedAudioContext?.audioContext.currentTime??null,audioContextState:this.sharedAudioContext?.audioContext.state??null,audioSyncAnchor:this.sharedAudioContext?.audioSyncAnchor??null,audioIteratorManager:this.audioIteratorManager,playing:this.playing,videoIteratorManager:this.videoIteratorManager,playbackRate:this.playbackRate*this.globalPlaybackRate})};audioSyncAnchorChanged=()=>{if(!this.audioIteratorManager)return;this.audioIteratorManager.destroyIterator()}}var W8=({onError:$,error:J,disallowFallback:Y,isClientSideRendering:X,clientSideError:Q})=>{let Z=$?.(J);if(X)return["fail",Q];if(Z)return[Z,J];if(Y)return["fail",J];return["fallback",J]},QZ=({mediaPlayerRef:$,mediaPlayerReady:J,currentTimeRef:Y,playing:X,isPlayerBuffering:Q,frame:Z,trimBefore:K,trimAfter:G,effectiveMuted:W,userPreferredVolume:j,playbackRate:U,globalPlaybackRate:q,fps:V,sequenceOffset:_,loop:N,durationInFrames:R,isPremounting:z,isPostmounting:H,currentTime:A,logLevel:M,label:F})=>{let O=f9(P5.SharedAudioContext);f0(()=>{let B=$.current;if(!B)return;if(X&&!Q)B.play();else B.pause()},[Q,X,M,J,Z,$]),f0(()=>{if(!O)return;let{remove:B}=O.audioSyncAnchorEmitter.subscribe((D)=>{if(D==="changed")$.current?.audioSyncAnchorChanged()});return()=>{B()}},[O,$]),f0(()=>{let B=$.current;if(!B||!J)return;B.setTrimBefore(K,Y.current)},[K,J,$,Y]),f0(()=>{let B=$.current;if(!B||!J)return;B.setTrimAfter(G,Y.current)},[G,J,$,Y]),f0(()=>{let B=$.current;if(!B||!J)return;B.setMuted(W)},[W,J,$]),f0(()=>{let B=$.current;if(!B||!J)return;B.setVolume(j)},[j,J,$]),f0(()=>{let B=$.current;if(!B||!J)return;B.setPlaybackRate(U,Y.current)},[U,J,$,Y]),f0(()=>{let B=$.current;if(!B||!J)return;B.setGlobalPlaybackRate(q,Y.current)},[q,J,$,Y]),f0(()=>{let B=$.current;if(!B||!J)return;B.setLoop(N,Y.current)},[N,J,$,Y]),f0(()=>{let B=$.current;if(!B||!J)return;B.setSequenceDurationInFrames(R,Y.current)},[R,J,$,Y]),f0(()=>{let B=$.current;if(!B)return;B.setIsPremounting(z)},[z,J,$]),f0(()=>{let B=$.current;if(!B)return;B.setIsPostmounting(H)},[H,J,$]),f0(()=>{let B=$.current;if(!B||!J)return;B.setFps(V,Y.current)},[V,J,$,Y]),f0(()=>{let B=$.current;if(!B||!J)return;B.setSequenceOffset(_,Y.current)},[_,J,$,Y]),f0(()=>{let B=$.current;if(!B||!J)return;B.seekTo(A).catch(()=>{}),P5.Log.trace({logLevel:M,tag:"@remotion/media"},`[${F}] Updating target time to ${A.toFixed(3)}s`)},[A,M,J,F,$])},{useUnsafeVideoConfig:g9,Timeline:k9,SharedAudioContext:u9,usePlayerMutedState:m9,useMediaVolumeState:l9,useFrameForVolumeProp:p9,evaluateVolume:d9,warnAboutTooHighVolume:c9,usePreload:GZ,SequenceContext:n9}=F1,o9=({src:$,playbackRate:J,logLevel:Y,muted:X,volume:Q,loopVolumeCurveBehavior:Z,loop:K,trimAfter:G,trimBefore:W,name:j,showInTimeline:U,stack:q,disallowFallbackToHtml5Audio:V,toneFrequency:_,audioStreamIndex:N,fallbackHtml5AudioProps:R,onError:z,credentials:H,requestInit:A,setMediaDurationInSeconds:M})=>{let F=g9(),O=t5(),B=i0(null),D=i0(W),w=i0(G),[P]=Q7(A),[T,C]=Q7(!1),[E,v]=Q7(!1),[x]=k9.usePlayingState(),{playbackRate:S}=F1.usePlaybackRate(),k=Z7(u9),m=N9(),[f]=m9(),[n]=l9(),o=p9(Z??"repeat"),s=d9({frame:o,volume:Q,mediaVolume:n});if(c9(s),!F)throw Error("No video config found");if(!$)throw TypeError("No `src` was passed to <NewAudioForPreview>.");let a=O/F.fps,r=i0(a);r.current=a;let l=GZ($),X0=Z7(n9),N0=Boolean(X0?.premounting),t=Boolean(X0?.postmounting),$0=(X0?.absoluteFrom??0)/F.fps,e=Z7(F1.BufferingContextReact);if(!e)throw Error("useMediaPlayback must be used inside a <BufferingContext>");let Y0=X||f||s<=0,C0=F1.useIsPlayerBuffering(e),B1=i0(x&&!C0),a0=i0(N0),E0=i0(t),t0=i0(S),D1=i0(J),n1=i0(Y0),w0=i0(F.durationInFrames),e0=i0($0);if(QZ({mediaPlayerRef:B,mediaPlayerReady:T,currentTimeRef:r,playing:x,isPlayerBuffering:C0,frame:O,trimBefore:W,trimAfter:G,effectiveMuted:Y0,userPreferredVolume:s,playbackRate:J,globalPlaybackRate:S,fps:F.fps,sequenceOffset:$0,loop:K,durationInFrames:F.durationInFrames,isPremounting:N0,isPostmounting:t,currentTime:a,logLevel:Y,label:"AudioForPreview"}),W9(()=>{if(!k)return;if(!k.audioContext)return;let{audioContext:P0,gainNode:n0,audioSyncAnchor:q8,scheduleAudioNode:N8,unscheduleAudioNode:b0}=k;if(!n0)return;try{let Q0=new O7({src:l,logLevel:Y,sharedAudioContext:{audioContext:P0,gainNode:n0,audioSyncAnchor:q8,scheduleAudioNode:N8,unscheduleAudioNode:b0},loop:K,trimAfter:w.current,trimBefore:D.current,fps:F.fps,canvas:null,playbackRate:D1.current,audioStreamIndex:N??null,debugOverlay:!1,bufferState:m,isPostmounting:E0.current,isPremounting:a0.current,globalPlaybackRate:t0.current,durationInFrames:w0.current,onVideoFrameCallback:null,playing:B1.current,sequenceOffset:e0.current,credentials:H,requestInit:P,tagType:"audio",getEffects:()=>[],getEffectChainState:()=>null});B.current=Q0,Q0.initialize(r.current,n1.current).then((A0)=>{if(A0.type==="disposed")return;let g0=(o1,T6)=>{let[v6,MJ]=W8({onError:z,error:o1,disallowFallback:V,isClientSideRendering:!1,clientSideError:o1});if(v6==="fail")throw MJ;else F1.Log.warn({logLevel:Y,tag:"@remotion/media"},T6),v(!0)};if(A0.type==="unknown-container-format"){g0(Error(`Unknown container format ${l}.`),`Unknown container format for ${l} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <Html5Audio>`);return}if(A0.type==="network-error"){g0(Error(`Network error fetching ${l}.`),`Network error fetching ${l}, falling back to <Html5Audio>`);return}if(A0.type==="cannot-decode"){g0(Error(`Cannot decode ${l}.`),`Cannot decode ${l}, falling back to <Html5Audio>`);return}if(A0.type==="no-tracks"){g0(Error(`No video or audio tracks found for ${l}.`),`No video or audio tracks found for ${l}, falling back to <Html5Audio>`);return}if(A0.type==="success")C(!0),M(A0.durationInSeconds),F1.Log.trace({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialized successfully")}).catch((A0)=>{let[g0,o1]=W8({onError:z,error:A0,disallowFallback:V,isClientSideRendering:!1,clientSideError:A0});if(g0==="fail")throw o1;else F1.Log.error({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] Failed to initialize MediaPlayer",A0),v(!0)})}catch(Q0){let[A0,g0]=W8({error:Q0,onError:z,disallowFallback:V,isClientSideRendering:!1,clientSideError:Q0});if(A0==="fail")throw g0;F1.Log.error({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialization failed",g0),v(!0)}return()=>{if(B.current)F1.Log.trace({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] Disposing MediaPlayer"),B.current.dispose(),B.current=null;C(!1),v(!1)}},[l,Y,k,K,F.fps,N,V,m,z,H,P,M]),E&&!V)return KZ(q9,{src:$,muted:X,volume:Q,startFrom:W,endAt:G,playbackRate:J,loopVolumeCurveBehavior:Z,name:j,loop:K,showInTimeline:U,stack:q??void 0,toneFrequency:_,audioStreamIndex:N,pauseWhenBuffering:R?.pauseWhenBuffering,crossOrigin:R?.crossOrigin,...R});return null},UZ=({loop:$=!1,src:J,logLevel:Y,muted:X,name:Q,volume:Z,loopVolumeCurveBehavior:K,playbackRate:G=1,trimAfter:W,trimBefore:j,showInTimeline:U,stack:q,disallowFallbackToHtml5Audio:V,toneFrequency:_,audioStreamIndex:N,fallbackHtml5AudioProps:R,onError:z,credentials:H,requestInit:A,setMediaDurationInSeconds:M})=>{let F=GZ(J),O=F1.useLogLevel(),B=t5(),D=V9(),w=B/D.fps;if(!j9(()=>{return A$({unloopedTimeInSeconds:w,playbackRate:G,loop:$,trimBefore:j,trimAfter:W,mediaDurationInSeconds:1/0,fps:D.fps,ifNoMediaDuration:"infinity",src:J})!==null},[w,G,J,W,j,D.fps,$]))return null;if(!M)throw Error("setMediaDurationInSeconds is required");return KZ(o9,{audioStreamIndex:N,src:F,playbackRate:G,logLevel:Y??O,muted:X??!1,volume:Z??1,loopVolumeCurveBehavior:K??"repeat",loop:$,trimAfter:W,trimBefore:j,name:Q,showInTimeline:U??!0,stack:q,disallowFallbackToHtml5Audio:V??!1,toneFrequency:_,onError:z,credentials:H,requestInit:A,fallbackHtml5AudioProps:R,setMediaDurationInSeconds:M})},YQ=()=>{let $=[],J={};return{addFrame:(j)=>{$.push(j.timestamp),J[j.timestamp]=j},clearBeforeThreshold:(j)=>{for(let U of $.slice())if(U+J[U].duration<j){if(U===$[$.length-1])continue;J[U].close(),delete J[U],$.splice($.indexOf(U),1)}},deleteAll:()=>{for(let j of $)J[j].close(),delete J[j];$.length=0},getSamples:(j,U)=>{let q=[];for(let V=0;V<$.length;V++){let _=$[V],N=J[_];if(N.timestamp+N.duration-0.0000000001<=j)continue;if(N.timestamp>=j+U-0.0000000001)break;q.push(N)}return q},getOldestTimestamp:()=>{return $[0]},getNewestTimestamp:()=>{if($.length===0)return null;let j=J[$[$.length-1]];return j.timestamp+j.duration},getOpenTimestamps:()=>{return $}}},XQ=1.5,y5=0.2,S5={},ZQ=($,J)=>{if(S5[$])return;S5[$]=!0,WZ.Log.warn({logLevel:J,tag:"@remotion/media"},`Audio from ${$} will need to be read from the beginning. https://www.remotion.dev/docs/media/support#matroska-limitation`)},QQ=({audioSampleSink:$,isMatroska:J,startTimestamp:Y,src:X,actualMatroskaTimestamps:Q,logLevel:Z})=>{let K=$.samples(J?0:Math.max(0,Y-XQ));if(J)ZQ(X,Z);let G=null,W=YQ(),j=Date.now(),U=async()=>{j=Date.now();let{value:H,done:A}=await K.next();if(A)return G=W.getNewestTimestamp(),null;let M=Q.getRealTimestamp(H.timestamp);if(M!==null&&M!==H.timestamp)H.setTimestamp(M);return Q.observeTimestamp(H.timestamp),Q.observeTimestamp(H.timestamp+H.duration),W.addFrame(H),H},q=async(H,A)=>{if(j=Date.now(),G!==null&&H>G)return W.clearBeforeThreshold(G-y5),[];let M=W.getSamples(H,A),F=W.getNewestTimestamp();if(F!==null){if(F>=H+A-0.0000000001)return M}while(!0){let O=await U(),B=G===null?H:Math.min(H,G);if(W.clearBeforeThreshold(B-y5),O===null)break;if(O.timestamp+O.duration-0.0000000001<=H)continue;if(O.timestamp>=H+A-0.0000000001)break;M.push(O)}return M},V=()=>{let H=W.getOpenTimestamps();if(H.length>0){let A=H[0],M=H[H.length-1];WZ.Log.verbose({logLevel:Z,tag:"@remotion/media"},"Open audio samples for src",X,`${A.toFixed(3)}...${M.toFixed(3)}`)}},_=()=>{return{count:W.getOpenTimestamps().length,size:W.getOpenTimestamps().reduce((H,A)=>H+A,0)}},N=(H)=>{let A=W.getOldestTimestamp()??Y;if(G!==null&&H>G)return!0;return A<H&&Math.abs(A-H)<10},R=()=>{W.deleteAll(),K.return().then((H)=>{if(H.value)H.value.close()}),G=null},z=Promise.resolve([]);return{src:X,getSamples:(H,A)=>{return z=z.then(()=>q(H,A)),z},waitForCompletion:async()=>{return await z,!0},canSatisfyRequestedTime:N,logOpenFrames:V,getCacheStats:_,getLastUsed:()=>j,prepareForDeletion:R,startTimestamp:Y,clearBeforeThreshold:W.clearBeforeThreshold,getOldestTimestamp:W.getOldestTimestamp,getNewestTimestamp:W.getNewestTimestamp}},KQ=()=>{let $=[],J=({timeInSeconds:j,src:U,audioSampleSink:q,isMatroska:V,actualMatroskaTimestamps:_,logLevel:N})=>{let R=QQ({audioSampleSink:q,isMatroska:V,startTimestamp:j,src:U,actualMatroskaTimestamps:_,logLevel:N});return $.push(R),R},Y=()=>{let j=null,U=null;for(let q of $){let V=q.getLastUsed();if(j===null||V<j)j=V,U=q}return U},X=()=>{let j=Y();if(j)j.prepareForDeletion(),$.splice($.indexOf(j),1)},Q=(j)=>{let U=new Set;for(let q=0;q<$.length;q++){let V=$[q],_=`${V.src}-${V.getOldestTimestamp()}-${V.getNewestTimestamp()}`;if(U.has(_))V.prepareForDeletion(),$.splice($.indexOf(V),1),I5.Log.verbose({logLevel:j,tag:"@remotion/media"},`Deleted duplicate iterator for ${V.src}`);U.add(_)}},Z=async({src:j,timeInSeconds:U,audioSampleSink:q,isMatroska:V,actualMatroskaTimestamps:_,logLevel:N,maxCacheSize:R})=>{let z=0,H=3;while((await H$()).totalSize>R&&z<H)X(),z++;if((await H$()).totalSize>R&&z>=H)I5.Log.warn({logLevel:N,tag:"@remotion/media"},`Audio cache: Exceeded max cache size after ${H} attempts. Still ${(await H$()).totalSize} bytes used, target was ${R} bytes.`);for(let A of $)if(A.src===j&&await A.waitForCompletion()&&A.canSatisfyRequestedTime(U))return A;for(let A=0;A<$.length;A++){let M=$[A];if(M.src===j&&M.startTimestamp===U)M.prepareForDeletion(),$.splice($.indexOf(M),1)}return Q(N),J({src:j,timeInSeconds:U,audioSampleSink:q,isMatroska:V,actualMatroskaTimestamps:_,logLevel:N})},K=()=>{let j=0,U=0;for(let q of $){let{count:V,size:_}=q.getCacheStats();j+=V,U+=_}return{count:j,totalSize:U}},G=()=>{for(let j of $)j.logOpenFrames()},W=Promise.resolve(void 0);return{getIterator:({src:j,timeInSeconds:U,audioSampleSink:q,isMatroska:V,actualMatroskaTimestamps:_,logLevel:N,maxCacheSize:R})=>{return W=W.then(()=>Z({src:j,timeInSeconds:U,audioSampleSink:q,isMatroska:V,actualMatroskaTimestamps:_,logLevel:N,maxCacheSize:R})),W},getCacheStats:K,getIteratorMostInThePast:Y,logOpenFrames:G,deleteDuplicateIterators:Q}},R7=($)=>{if($.length===0)return"(none)";if($.length===1)return $[0].toFixed(3);return`${$[0].toFixed(3)}...${$[$.length-1].toFixed(3)}`},h5=($)=>{if($.format===null)return $.codedHeight*$.codedWidth*4;return $.allocationSize()},GQ=3,f5=async({logLevel:$,src:J,videoSampleSink:Y,initialTimestampRequest:X})=>{let Q=Y.samples(q0(X)),Z={},K=[],G=!1,W=Date.now(),j=0,U=(C)=>{let E=K.indexOf(C);if(E===-1)throw Error(`Frame ${C} not found`);let v=K[E+1];if(!v)return null;return v-C},q=(C)=>{j-=h5(Z[C]),K.splice(K.indexOf(C),1),Z[C].close(),delete Z[C]},V=({logLevel:C,timestampInSeconds:E})=>{let v=[];for(let x of K.slice()){if(G){if(x===K[K.length-1])continue}if(!Z[x])continue;let S=U(x)??Z[x].duration;if(x+S<E)q(x),v.push(x)}if(v.length>0)VJ.Log.verbose({logLevel:C,tag:"@remotion/media"},`Deleted ${v.length} frame${v.length===1?"":"s"} ${R7(v)} for src ${J} because it is lower than ${E}. Remaining: ${R7(K)}`)},_=(C)=>{let E=K[K.length-1];if(!E)return!1;let v=Z[E];if(!v)return!0;let x=U(E)??v.duration;return q0(E+x)>q0(C)},N=(C,E)=>{if(Z[C.timestamp])q(C.timestamp);Z[C.timestamp]=C,K.push(C.timestamp),j+=h5(C),W=Date.now(),VJ.Log.trace({logLevel:E,tag:"@remotion/media"},`Added frame at ${C.timestamp}sec to bank`)},R=async(C,E,v)=>{while(!_(C)){let x=await Q.next();if(x.value)N(x.value,E);if(x.done){G=!0;break}V({logLevel:$,timestampInSeconds:C-jZ(v)})}W=Date.now()},z=async(C,E)=>{W=Date.now();let v=C;if(G&&q0(v)>q0(K[K.length-1]))v=K[K.length-1];await R(v,$,E);for(let x=K.length-1;x>=0;x--){let S=Z[K[x]];if(!S)return null;if(q0(S.timestamp)<=q0(v)||Math.abs(S.timestamp-v)<=0.001)return S}return Z[K[0]]??null},H=async(C,E)=>{return await z(C,E)!==null},A=()=>{return{size:j,timestamps:K}},M=()=>{return W},F=Promise.resolve(void 0),O=await Q.next();if(!O.value)throw Error("No first frame found");let B=O.value.timestamp;VJ.Log.verbose({logLevel:$,tag:"@remotion/media"},`Creating keyframe bank from ${B}sec`),N(O.value,$);let D=()=>{if(K.length===0)return null;let C=K[0],E=K[K.length-1],v=Z[E],x=U(E)??v.duration??0;return{firstTimestamp:C,lastTimestamp:E+x}};return{getFrameFromTimestamp:(C,E)=>{return F=F.then(()=>z(C,E)),F},prepareForDeletion:(C,E)=>{let v=D();if(v)VJ.Log.verbose({logLevel:C,tag:"@remotion/media"},`Preparing for deletion (${E}) of keyframe bank from ${v?.firstTimestamp}sec to ${v?.lastTimestamp}sec`);let x=0;for(let S of K.slice()){if(!Z[S])continue;q(S),x++}return Q.return(),K.length=0,{framesDeleted:x}},hasTimestampInSecond:(C,E)=>{return F=F.then(()=>H(C,E)),F},addFrame:N,deleteFramesBeforeTimestamp:V,src:J,getOpenFrameCount:A,getLastUsed:M,canSatisfyTimestamp:(C)=>{if(K.length===0)return!1;let E=q0(C),v=q0(K[0]),x=D();if(!x)return!1;let S=q0(K[K.length-1]),k=q0(x.lastTimestamp);if(G&&E>S)return!0;if(E<v)return v===B&&E>=X;if(E-GQ>k)return!1;return!0},getRangeOfTimestamps:D}},UQ=()=>{let $={},J=({src:V,bank:_})=>{$[V]=$[V]??[],$[V].push(_)},Y=(V)=>{let _=0,N=0;for(let R in $)for(let z of $[R]){let{size:H,timestamps:A}=z.getOpenFrameCount();if(_+=A.length,N+=H,H===0)continue;d1.Log.verbose({logLevel:V,tag:"@remotion/media"},`Open frames for src ${R}: ${R7(A)}`)}d1.Log.verbose({logLevel:V,tag:"@remotion/media"},`Video cache stats: ${_} open frames, ${N} bytes`)},X=()=>{let V=0,_=0;for(let N in $)for(let R of $[N]){let{timestamps:z,size:H}=R.getOpenFrameCount();if(V+=z.length,_+=H,H===0)continue}return{count:V,totalSize:_}},Q=()=>{let V=null,_=null,N=0;for(let R in $)for(let z of $[R]){let H=$[R].indexOf(z),A=z.getLastUsed();if(V===null||A<V)V=A,_={src:R,bank:z,index:H};N++}if(!_)throw Error("No keyframe bank found");return{mostInThePastBank:_,numberOfBanks:N}},Z=(V)=>{let{mostInThePastBank:{bank:_,src:N,index:R},numberOfBanks:z}=Q();if(z<2)return{finish:!0};if(_){let H=_.getRangeOfTimestamps(),{framesDeleted:A}=_.prepareForDeletion(V,"deleted oldest keyframe bank to stay under max cache size");if($[N].splice(R,1),H)d1.Log.verbose({logLevel:V,tag:"@remotion/media"},`Deleted ${A} frames for src ${N} from ${H?.firstTimestamp}sec to ${H?.lastTimestamp}sec to free up memory.`)}return{finish:!1}},K=(V,_)=>{let N=H$(),R=0,z=3;while(N.totalSize>_&&R<z){let{finish:H}=Z(V);if(H)break;d1.Log.verbose({logLevel:V,tag:"@remotion/media"},"Deleted oldest keyframe bank to stay under max cache size",(N.totalSize/1024/1024).toFixed(1),"out of",(_/1024/1024).toFixed(1)),N=H$(),R++}if(N.totalSize>_&&R>=z)d1.Log.warn({logLevel:V,tag:"@remotion/media"},`Exceeded max cache size after ${z} attempts. Remaining cache size: ${(N.totalSize/1024/1024).toFixed(1)} MB, target was ${(_/1024/1024).toFixed(1)} MB.`)},G=({timestampInSeconds:V,src:_,logLevel:N,fps:R})=>{let z=V-jZ(R);if(!$[_])return;let H=$[_];for(let A of H){let M=A.getRangeOfTimestamps();if(!M)continue;if(M.lastTimestamp<z){A.prepareForDeletion(N,"cleared before threshold "+z),d1.Log.verbose({logLevel:N,tag:"@remotion/media"},`[Video] Cleared frames for src ${_} from ${M.firstTimestamp}sec to ${M.lastTimestamp}sec`);let F=H.indexOf(A);delete $[_][F]}else A.deleteFramesBeforeTimestamp({timestampInSeconds:z,logLevel:N})}$[_]=$[_].filter((A)=>A!==void 0),Y(N)},W=async({timestamp:V,videoSampleSink:_,src:N,logLevel:R})=>{let H=($[N]??[])?.find((M)=>M.canSatisfyTimestamp(V));if(!H){d1.Log.trace({logLevel:R,tag:"@remotion/media"},`Creating new keyframe bank for src ${N} at timestamp ${V}`);let M=await f5({videoSampleSink:_,logLevel:R,src:N,initialTimestampRequest:V});return J({src:N,bank:M}),M}if(H.canSatisfyTimestamp(V))return d1.Log.trace({logLevel:R,tag:"@remotion/media"},`Keyframe bank exists and satisfies timestamp ${V}`),H;d1.Log.verbose({logLevel:R,tag:"@remotion/media"},`Keyframe bank exists but frame at time ${V} does not exist anymore.`),H.prepareForDeletion(R,"already existed but evicted"),$[N]=$[N].filter((M)=>M!==H);let A=await f5({videoSampleSink:_,initialTimestampRequest:V,logLevel:R,src:N});return J({src:N,bank:A}),A},j=async({timestamp:V,videoSampleSink:_,src:N,logLevel:R,maxCacheSize:z,fps:H})=>{return K(R,z),G({timestampInSeconds:V,src:N,logLevel:R,fps:H}),await W({timestamp:V,videoSampleSink:_,src:N,logLevel:R})},U=(V)=>{let _=Object.keys($);for(let N of _){let R=$[N];for(let z of R)z.prepareForDeletion(V,"clearAll");$[N]=[]}$={}},q=Promise.resolve(void 0);return{requestKeyframeBank:({timestamp:V,videoSampleSink:_,src:N,logLevel:R,maxCacheSize:z,fps:H})=>{return q=q.then(()=>j({timestamp:V,videoSampleSink:_,src:N,logLevel:R,maxCacheSize:z,fps:H})),q},getCacheStats:X,clearAll:U}},jZ=($)=>6/$,qZ=UQ(),A7=KQ(),H$=()=>{let $=qZ.getCacheStats(),J=A7.getCacheStats();return{count:$.count+J.count,totalSize:$.totalSize+J.totalSize}},WQ=($)=>{if(typeof window<"u"&&window.remotion_mediaCacheSizeInBytes!==void 0&&window.remotion_mediaCacheSizeInBytes!==null){if(window.remotion_mediaCacheSizeInBytes<251658240)x5(Error(`The minimum value for the "mediaCacheSizeInBytes" prop is 240MB (251658240), got: ${window.remotion_mediaCacheSizeInBytes}`));if(window.remotion_mediaCacheSizeInBytes>20971520000)x5(Error(`The maximum value for the "mediaCacheSizeInBytes" prop is 20GB (20971520000), got: ${window.remotion_mediaCacheSizeInBytes}`));return _$.Log.verbose({logLevel:$,tag:"@remotion/media"},`Using cache size set using "mediaCacheSizeInBytes": ${(window.remotion_mediaCacheSizeInBytes/1024/1024).toFixed(1)} MB`),window.remotion_mediaCacheSizeInBytes}if(typeof window<"u"&&window.remotion_initialMemoryAvailable!==void 0&&window.remotion_initialMemoryAvailable!==null){let J=window.remotion_initialMemoryAvailable/2;if(J<524288000)return _$.Log.verbose({logLevel:$,tag:"@remotion/media"},"Using cache size set based on minimum value of 500MB (which is more than half of the available system memory!)"),524288000;if(J>20971520000)return _$.Log.verbose({logLevel:$,tag:"@remotion/media"},"Using cache size set based on maximum value of 20GB (which is less than half of the available system memory)"),20971520000;return _$.Log.verbose({logLevel:$,tag:"@remotion/media"},`Using cache size set based on available memory (50% of available memory): ${(J/1024/1024).toFixed(1)} MB`),J}return 1e9},_J=null,jQ=($)=>{if(_J!==null)return _J;return _J=WQ($),_J},NZ=($)=>{let J=JQ.useContext(_$.MaxMediaCacheSizeContext);if(J===null)return jQ($);return J},VZ=($,J)=>{if(J===1)return;for(let Y=0;Y<$.length;Y++){let X=$[Y]*J;if(X<-32768)$[Y]=-32768;else if(X>32767)$[Y]=32767;else $[Y]=X}},b6=2,j8=()=>{if(typeof window<"u"&&window.remotion_sampleRate)return window.remotion_sampleRate;return 48000},g5=($)=>{if($%1<0.0000001)return Math.floor($);if($%1>0.9999999)return Math.ceil($);return $},qQ=({srcNumberOfChannels:$,sourceChannels:J,destination:Y,targetFrames:X,chunkSize:Q})=>{let Z=(K,G,W)=>{let j=g5(K),U=g5(G),q=Math.floor(j),V=Math.ceil(j),_=j-q,N=U-Math.floor(U),R=Math.floor(U),z=0,H=0;if(_>0){let M=J[q*$+W];z+=M*(1-_),H+=1-_}for(let M=V;M<R;M++){let F=J[M*$+W];z+=F,H+=1}if(N>0){let M=J[R*$+W];z+=M*N,H+=N}return z/H};for(let K=0;K<X;K++){let G=K*Q,W=G+Q;if(b6===$)for(let j=0;j<$;j++)Y[K*$+j]=Z(G,W,j);if($===1){let j=Z(G,W,0);Y[K*2+0]=j,Y[K*2+1]=j}else if($===4){let j=Z(G,W,0),U=Z(G,W,1),q=Z(G,W,2),V=Z(G,W,3),_=0.5*(j+q),N=0.5*(U+V);Y[K*2+0]=_,Y[K*2+1]=N}else if($===6){let j=Z(G,W,0),U=Z(G,W,1),q=Z(G,W,2),V=Z(G,W,3),_=Z(G,W,4),N=Math.sqrt(0.5),R=j+N*(q+V),z=U+N*(q+_);Y[K*2+0]=R,Y[K*2+1]=z}else for(let j=0;j<$;j++)Y[K*b6+j]=Z(G,W,j)}},_Z=({behavior:$,loop:J,assetDurationInSeconds:Y,fps:X,frame:Q,startsAt:Z})=>{if(!J)return Q+Z;if($==="extend")return Q+Z;let K=Math.floor(Y*X)-Z;return Q%K+Z},k5="s16",O1=($)=>{let J=Math.abs($%1);if(J<0.0000001)return $<0?Math.ceil($):Math.floor($);if(J>0.9999999)return $<0?Math.floor($):Math.ceil($);return $},u5=($)=>{let J=O1($);return Math.ceil(J)},NQ=({audioData:$,trimStartInSeconds:J,trimEndInSeconds:Y,playbackRate:X,audioDataTimestamp:Q,isLast:Z})=>{let{numberOfChannels:K,sampleRate:G,numberOfFrames:W}=$,j=G/j8(),U=Math.floor(O1(J*$.sampleRate)),q=W-Y*$.sampleRate-U,V=Z?u5(q):Math.round(q),_=Z?u5(q/j/X):Math.round(q/j/X);if(_===0)throw Error("Cannot resample - the given sample rate would result in less than 1 sample");let N=new Int16Array(K*V);if($.format==="f32"||$.format==="f32-planar"){let F=V*4,O=new ArrayBuffer(K*F);for(let D=0;D<K;D++)$.copyTo(new Float32Array(O,D*F,V),{planeIndex:D,frameOffset:U,frameCount:V,format:"f32-planar"});let B=new AudioData({format:"f32-planar",sampleRate:G,numberOfFrames:V,numberOfChannels:K,timestamp:$.timestamp,data:O});B.copyTo(N,{planeIndex:0,format:k5,frameOffset:0,frameCount:V}),B.close()}else $.copyTo(N,{planeIndex:0,format:k5,frameOffset:U,frameCount:V});let z=new Int16Array(_*b6),H=V/_,A=U/$.sampleRate*1e6;if(_===V&&b6===K&&X===1)return{data:N,numberOfFrames:_,timestamp:Q*1e6+O1(A),durationInMicroSeconds:O1(_/j8()*1e6)};return qQ({srcNumberOfChannels:K,sourceChannels:N,destination:z,targetFrames:_,chunkSize:H}),{data:z,numberOfFrames:_,timestamp:Q*1e6+O1(A),durationInMicroSeconds:O1(_/j8()*1e6)}},VQ=($)=>{let J=0,Y=0,{timestamp:X}=$[0];for(let K of $)J+=K.numberOfFrames,Y+=K.durationInMicroSeconds;let Q=new Int16Array(J*b6),Z=0;for(let K of $)Q.set(K.data,Z),Z+=K.data.length;return{data:Q,numberOfFrames:J,timestamp:O1(X),durationInMicroSeconds:O1(Y)}},HJ=null,zQ=()=>{return new OffscreenCanvas(1,1).getContext("webgl2")!==null},RQ=()=>{if(HJ!==null)return HJ;return HJ=zQ(),HJ},AQ=($)=>{let J=[];return{observeTimestamp:(Q)=>{if(!$)return;J.push(Q)},getRealTimestamp:(Q)=>{if(!$)return Q;return J.find((Z)=>Math.abs(Q-Z)<0.001)??null}}},LQ=()=>{return null},MQ=async($)=>{try{return await $.getFormat()}catch(J){if(z$(J))return"network-error";return null}},FQ=async($,J,Y,X)=>{let Q=ZZ({credentials:Y,requestInit:X}),Z=new A1({formats:X$,source:new h8($,{getRetryDelay:LQ,...Q?{requestInit:Q}:void 0})}),K=await MQ(Z),G=K===e$||K===$J,W=async()=>{if(K==="network-error")return"network-error";if(K===null)return"unknown-container-format";let N=await Z.getPrimaryVideoTrack();if(!N)return"no-video-track";if(await N.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+$);if(await N.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+$);if(!await N.canDecode())return"cannot-decode";let z=new M6(N);if((await new p1(N).getFirstPacket({verifyKeyPackets:!0}))?.sideData.alpha&&!RQ())HQ.Log.warn({logLevel:J,tag:"@remotion/media"},`WebGL2 is not available, using the non-fast CPU path to decode alpha for ${$}.`);return{sampleSink:z}},j=null,U=()=>{if(j)return j;return j=W(),j},q={},V=async(N)=>{if(K===null)return"unknown-container-format";if(K==="network-error")return"network-error";let[R,z]=await Promise.all([Z.getPrimaryVideoTrack(),Z.getAudioTracks()]),H=await YZ({videoTrack:R,audioTracks:z,audioStreamIndex:N});if(!H)return"no-audio-track";if(!await H.canDecode())return"cannot-decode-audio";return{sampleSink:new F6(H)}},_=(N)=>{let R=N===null?-1:N;if(q[R])return q[R];return q[R]=V(N),q[R]};return{getVideo:()=>U(),getAudio:(N)=>_(N),actualMatroskaTimestamps:AQ(G),isMatroska:G,getDuration:()=>{return JZ(Z)}}},m5={},wQ=({src:$,credentials:J,requestInit:Y})=>JSON.stringify([$,J,v9(Y)]),HZ=($,J,Y,X)=>{let Q=R$(X),Z=wQ({src:$,credentials:Y,requestInit:Q}),K=m5[Z];if(!K)_Q.Log.verbose({logLevel:J,tag:"@remotion/media"},`Sink for ${$} was not found, creating new sink`),K=FQ($,J,Y,Q),m5[Z]=K;return K},OQ=async({src:$,timeInSeconds:J,durationInSeconds:Y,logLevel:X,loop:Q,playbackRate:Z,audioStreamIndex:K,trimBefore:G,trimAfter:W,fps:j,maxCacheSize:U,credentials:q,requestInit:V})=>{let{getAudio:_,actualMatroskaTimestamps:N,isMatroska:R,getDuration:z}=await HZ($,X,q,V),H=null;if(Q)H=await z();let A=await _(K);if(A==="network-error")return"network-error";if(A==="no-audio-track")return{data:null,durationInSeconds:null};if(A==="cannot-decode-audio")return"cannot-decode";if(A==="unknown-container-format")return"unknown-container-format";let M=A$({loop:Q,mediaDurationInSeconds:H,unloopedTimeInSeconds:J,src:$,trimAfter:W,playbackRate:Z,trimBefore:G,fps:j,ifNoMediaDuration:"fail"});if(M===null)return{data:null,durationInSeconds:H};try{let F=await A7.getIterator({src:$,timeInSeconds:M,audioSampleSink:A.sampleSink,isMatroska:R,actualMatroskaTimestamps:N,logLevel:X,maxCacheSize:U}),O=Y*Z,B=await F.getSamples(M,O);A7.logOpenFrames();let D=[];for(let P=0;P<B.length;P++){let T=B[P];if(Math.abs(T.timestamp-(M+O))*T.sampleRate<1)continue;if(T.timestamp+T.duration<=M)continue;let C=P===0,E=P===B.length-1,v=T.toAudioData(),x=0,S=0,k=null;if(C){if(x=O1(M-T.timestamp),x<0){let f=Math.ceil(O1(-x*j8()));k={data:new Int16Array(f*b6),numberOfFrames:f,timestamp:M*1e6,durationInMicroSeconds:f/j8()*1e6},x=0}}if(E)S=Math.max(0,T.timestamp+T.duration-(M+O));let m=NQ({audioData:v,trimStartInSeconds:x,trimEndInSeconds:S,playbackRate:Z,audioDataTimestamp:T.timestamp,isLast:E});if(v.close(),m.numberOfFrames===0)continue;if(k)D.push(k);D.push(m)}if(D.length===0)return{data:null,durationInSeconds:H};return{data:VQ(D),durationInSeconds:H}}catch(F){let O=F;if(z$(O))return"network-error";if(P9(O))return"cannot-decode";throw F}},G7=Promise.resolve(void 0),BQ=($)=>{return G7=G7.then(()=>OQ($)),G7},CQ=async({src:$,timeInSeconds:J,logLevel:Y,loop:X,trimAfter:Q,trimBefore:Z,playbackRate:K,fps:G,maxCacheSize:W,credentials:j,requestInit:U})=>{let q=await HZ($,Y,j,U),[V,_]=await Promise.all([q.getVideo(),X?q.getDuration():Promise.resolve(null)]),N=X?_:null;if(V==="no-video-track")throw Error(`No video track found for ${$}`);if(V==="cannot-decode")return{type:"cannot-decode",durationInSeconds:N};if(V==="unknown-container-format")return{type:"unknown-container-format"};if(V==="network-error")return{type:"network-error"};if(V==="cannot-decode-alpha")return{type:"cannot-decode-alpha",durationInSeconds:N};let R=A$({loop:X,mediaDurationInSeconds:N,unloopedTimeInSeconds:J,src:$,trimAfter:Q,playbackRate:K,trimBefore:Z,fps:G,ifNoMediaDuration:"fail"});if(R===null)return{type:"success",frame:null,rotation:0,durationInSeconds:await q.getDuration()};try{let z=await qZ.requestKeyframeBank({videoSampleSink:V.sampleSink,timestamp:R,src:$,logLevel:Y,maxCacheSize:W,fps:G});if(!z)return{type:"success",frame:null,rotation:0,durationInSeconds:await q.getDuration()};let H=await z.getFrameFromTimestamp(R,G),A=H?.rotation??0;return{type:"success",frame:H?.toVideoFrame()??null,rotation:A,durationInSeconds:await q.getDuration()}}catch(z){return DQ.Log.info({logLevel:Y,tag:"@remotion/media"},`Error decoding ${$} at time ${R}: ${z}`,z),{type:"cannot-decode",durationInSeconds:N}}},U7=Promise.resolve(void 0),EQ=($)=>{return U7=U7.then(()=>CQ($)),U7},PQ=async({frame:$,rotation:J})=>{if(J===0){let G=await createImageBitmap($);return $.close(),G}let Y=J===90||J===270?$.displayHeight:$.displayWidth,X=J===90||J===270?$.displayWidth:$.displayHeight,Q=new OffscreenCanvas(Y,X),Z=Q.getContext("2d");if(!Z)throw Error("Could not get 2d context");if(Q.width=Y,Q.height=X,J===90)Z.translate(Y,0);else if(J===180)Z.translate(Y,X);else if(J===270)Z.translate(0,X);Z.rotate(J*(Math.PI/180)),Z.drawImage($,0,0);let K=await createImageBitmap(Q);return $.close(),K},zZ=async({src:$,timeInSeconds:J,logLevel:Y,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,loop:G,audioStreamIndex:W,trimAfter:j,trimBefore:U,fps:q,maxCacheSize:V,credentials:_,requestInit:N})=>{try{let[R,z]=await Promise.all([K?EQ({src:$,timeInSeconds:J,logLevel:Y,loop:G,trimAfter:j,playbackRate:Q,trimBefore:U,fps:q,maxCacheSize:V,credentials:_,requestInit:N}):null,Z?BQ({src:$,timeInSeconds:J,durationInSeconds:X,logLevel:Y,loop:G,playbackRate:Q,audioStreamIndex:W,trimAfter:j,fps:q,trimBefore:U,maxCacheSize:V,credentials:_,requestInit:N}):null]);if(R?.type==="cannot-decode")return{type:"cannot-decode",durationInSeconds:R.durationInSeconds};if(R?.type==="unknown-container-format")return{type:"unknown-container-format"};if(R?.type==="cannot-decode-alpha")return{type:"cannot-decode-alpha",durationInSeconds:R.durationInSeconds};if(R?.type==="network-error")return{type:"network-error"};if(z==="unknown-container-format")return{type:"unknown-container-format"};if(z==="network-error")return{type:"network-error"};if(z==="cannot-decode")return{type:"cannot-decode",durationInSeconds:R?.type==="success"?R.durationInSeconds:null};return{type:"success",frame:R?.frame?await PQ({frame:R.frame,rotation:R.rotation}):null,audio:z?.data??null,durationInSeconds:z?.durationInSeconds??null}}catch(R){if(z$(R))return{type:"network-error"};throw R}},bQ=($)=>{$.postMessage({type:"main-tab-ready"}),setInterval(()=>{$.postMessage({type:"main-tab-ready"})},300)},TQ=()=>{if(!(typeof window<"u"&&window.remotion_broadcastChannel&&window.remotion_isMainTab))return;window.remotion_broadcastChannel.addEventListener("message",async($)=>{let J=$.data;if(J.type==="request")try{let Y=await zZ({src:J.src,timeInSeconds:J.timeInSeconds,logLevel:J.logLevel,durationInSeconds:J.durationInSeconds,playbackRate:J.playbackRate,includeAudio:J.includeAudio,includeVideo:J.includeVideo,loop:J.loop,audioStreamIndex:J.audioStreamIndex,trimAfter:J.trimAfter,trimBefore:J.trimBefore,fps:J.fps,maxCacheSize:J.maxCacheSize,credentials:J.credentials,requestInit:J.requestInit});if(Y.type==="cannot-decode"){let W={type:"response-cannot-decode",id:J.id,durationInSeconds:Y.durationInSeconds};window.remotion_broadcastChannel.postMessage(W);return}if(Y.type==="cannot-decode-alpha"){let W={type:"response-cannot-decode-alpha",id:J.id,durationInSeconds:Y.durationInSeconds};window.remotion_broadcastChannel.postMessage(W);return}if(Y.type==="network-error"){let W={type:"response-network-error",id:J.id};window.remotion_broadcastChannel.postMessage(W);return}if(Y.type==="unknown-container-format"){let W={type:"response-unknown-container-format",id:J.id};window.remotion_broadcastChannel.postMessage(W);return}let{frame:X,audio:Q,durationInSeconds:Z}=Y,K=X?await createImageBitmap(X):null;if(X)X.close();let G={type:"response-success",id:J.id,frame:K,audio:Q,durationInSeconds:Z??null};window.remotion_broadcastChannel.postMessage(G)}catch(Y){let X={type:"response-error",id:J.id,errorStack:Y.stack??"No stack trace"};window.remotion_broadcastChannel.postMessage(X)}else if(J.type==="main-tab-ready");else throw Error("Invalid message: "+JSON.stringify(J))}),bQ(window.remotion_broadcastChannel)},zJ=null,vQ=($)=>{if(zJ)return zJ;return zJ=new Promise((J)=>{let Y=(X)=>{if(X.data.type==="main-tab-ready")J(),$.removeEventListener("message",Y)};$.addEventListener("message",Y)}),zJ};TQ();var RZ=async({src:$,timeInSeconds:J,logLevel:Y,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,isClientSideRendering:G,loop:W,audioStreamIndex:j,trimAfter:U,trimBefore:q,fps:V,maxCacheSize:_,credentials:N,requestInit:R})=>{if(G||window.remotion_isMainTab)return zZ({logLevel:Y,src:$,timeInSeconds:J,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,loop:W,audioStreamIndex:j,trimAfter:U,trimBefore:q,fps:V,maxCacheSize:_,credentials:N,requestInit:R});await vQ(window.remotion_broadcastChannel);let z=crypto.randomUUID(),H=new Promise((F,O)=>{let B=(D)=>{let w=D.data;if(!w)return;if(w.type==="main-tab-ready")return;if(w.id!==z)return;if(w.type==="response-success"){F({type:"success",frame:w.frame?w.frame:null,audio:w.audio?w.audio:null,durationInSeconds:w.durationInSeconds?w.durationInSeconds:null}),window.remotion_broadcastChannel.removeEventListener("message",B);return}if(w.type==="response-error"){O(w.errorStack),window.remotion_broadcastChannel.removeEventListener("message",B);return}if(w.type==="response-cannot-decode"){F({type:"cannot-decode",durationInSeconds:w.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",B);return}if(w.type==="response-network-error"){F({type:"network-error"}),window.remotion_broadcastChannel.removeEventListener("message",B);return}if(w.type==="response-unknown-container-format"){F({type:"unknown-container-format"}),window.remotion_broadcastChannel.removeEventListener("message",B);return}if(w.type==="response-cannot-decode-alpha"){F({type:"cannot-decode-alpha",durationInSeconds:w.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",B);return}throw Error(`Invalid message: ${JSON.stringify(w)}`)};window.remotion_broadcastChannel.addEventListener("message",B)}),A={type:"request",src:$,timeInSeconds:J,id:z,logLevel:Y,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,loop:W,audioStreamIndex:j,trimAfter:U,trimBefore:q,fps:V,maxCacheSize:_,credentials:N,requestInit:R$(R)};window.remotion_broadcastChannel.postMessage(A);let M;return Promise.race([H.then((F)=>{return clearTimeout(M),F}),new Promise((F,O)=>{M=setTimeout(()=>{O(Error(`Timeout while extracting frame at time ${J}sec from ${$}`))},Math.max(3000,window.remotion_puppeteerTimeout-5000))})])},IQ=({volume:$,playbackRate:J,src:Y,muted:X,loopVolumeCurveBehavior:Q,delayRenderRetries:Z,delayRenderTimeoutInMilliseconds:K,logLevel:G,loop:W,fallbackHtml5AudioProps:j,audioStreamIndex:U,showInTimeline:q,style:V,name:_,disallowFallbackToHtml5Audio:N,toneFrequency:R,trimAfter:z,trimBefore:H,onError:A,credentials:M,requestInit:F})=>{let O=L1.useLogLevel(),B=G??O,D=t9(),w=L1.useTimelinePosition(),P=L1.useUnsafeVideoConfig(),{registerRenderAsset:T,unregisterRenderAsset:C}=b5(L1.RenderAssetManager),E=L1.useMediaStartsAt(),v=$Q();if(!P)throw Error("No video config found");if(!Y)throw TypeError("No `src` was passed to <Audio>.");let{fps:x}=P,{delayRender:S,continueRender:k}=e9(),[m,f]=T5(!1),[n]=T5(F),o=b5(L1.SequenceContext),s=r9(()=>`media-audio-${a9(Y)}-${o?.cumulatedFrom}-${o?.relativeFrom}-${o?.durationInFrames}`,[Y,o?.cumulatedFrom,o?.relativeFrom,o?.durationInFrames]),a=NZ(B),r=L1.useAudioEnabled();if(s9(()=>{let l=D/x,X0=1/x,N0=(()=>{if(!r)return!1;if(X)return!1;return!0})();if(!N0)return;if(m)return;let t=S(`Extracting audio for frame ${D}`,{retries:Z??void 0,timeoutInMilliseconds:K??void 0});return RZ({src:Y,timeInSeconds:l,durationInSeconds:X0,playbackRate:J??1,logLevel:B,includeAudio:N0,includeVideo:!1,isClientSideRendering:v.isClientSideRendering,loop:W??!1,audioStreamIndex:U??null,trimAfter:z,trimBefore:H,fps:x,maxCacheSize:a,credentials:M,requestInit:n}).then(($0)=>{let e=(E0,t0,D1)=>{let[n1,w0]=W8({onError:A,error:E0,disallowFallback:N??!1,isClientSideRendering:v.isClientSideRendering,clientSideError:t0});if(n1==="fail")v5(w0);L1.Log.warn({logLevel:B,tag:"@remotion/media"},D1),f(!0)};if($0.type==="unknown-container-format"){e(Error(`Unknown container format ${Y}.`),Error(`Cannot render audio "${Y}": Unknown container format. See supported formats: https://www.remotion.dev/docs/mediabunny/formats`),`Unknown container format for ${Y} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <Html5Audio>`);return}if($0.type==="cannot-decode"){e(Error(`Cannot decode ${Y}.`),Error(`Cannot render audio "${Y}": The audio could not be decoded by the browser.`),`Cannot decode ${Y}, falling back to <Html5Audio>`);return}if($0.type==="cannot-decode-alpha")throw Error(`Cannot decode alpha component for ${Y}, and 'disallowFallbackToHtml5Audio' was set. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`);if($0.type==="network-error"){e(Error(`Network error fetching ${Y}.`),Error(`Cannot render audio "${Y}": Network error while fetching the audio (possibly CORS).`),`Network error fetching ${Y}, falling back to <Html5Audio>`);return}let{audio:Y0,durationInSeconds:C0}=$0,B1=_Z({behavior:Q??"repeat",loop:W??!1,assetDurationInSeconds:C0??0,fps:x,frame:D,startsAt:E}),a0=L1.evaluateVolume({volume:$,frame:B1,mediaVolume:1});if(L1.warnAboutTooHighVolume(a0),Y0&&a0>0)VZ(Y0.data,a0),T({type:"inline-audio",id:s,audio:v.isClientSideRendering?Y0.data:Array.from(Y0.data),frame:w,timestamp:Y0.timestamp,duration:Y0.numberOfFrames/j8()*1e6,toneFrequency:R??1});k(t)}).catch(($0)=>{v5($0)}),()=>{k(t),C(s)}},[w,k,S,Z,K,N,v.isClientSideRendering,x,D,s,B,W,Q,X,J,T,Y,E,C,$,U,R,z,H,m,a,r,A,M,n]),m)return xQ(i9,{src:Y,playbackRate:J,muted:X,loop:W,volume:$,delayRenderRetries:Z,delayRenderTimeoutInMilliseconds:K,style:V,loopVolumeCurveBehavior:Q,audioStreamIndex:U,useWebAudioApi:j?.useWebAudioApi,onError:j?.onError,toneFrequency:R,acceptableTimeShiftInSeconds:j?.acceptableTimeShiftInSeconds,preservePitch:j?.preservePitch??!0,name:_,showInTimeline:q});return null},{validateMediaProps:yQ}=P6,SQ={...P6.baseSchema,volume:{type:"number",min:0,max:20,step:0.01,default:1,description:"Volume",hiddenFromList:!1},playbackRate:{type:"number",min:0.1,step:0.01,default:1,description:"Playback rate",hiddenFromList:!1,keyframable:!1},loop:{type:"boolean",default:!1,description:"Loop"}},hQ=($)=>{let{name:J,stack:Y,showInTimeline:X,controls:Q,from:Z,durationInFrames:K,freeze:G,hidden:W,...j}=$,U=K9(),[q]=P6.useMediaVolumeState(),V=P6.useMediaStartsAt(),_=G9(),N=Math.min(K??1/0,Math.max(0,_.durationInFrames-(Z??0))),R=P6.useBasicMediaInTimeline({src:$.src,volume:$.volume,playbackRate:$.playbackRate??1,trimBefore:$.trimBefore,trimAfter:$.trimAfter,sequenceDurationInFrames:N,mediaType:"audio",displayName:J??"<Audio>",mediaVolume:q,mediaStartsAt:V,loop:$.loop??!1}),[z,H]=X9(null),A=C5(()=>a5({loop:$.loop??!1,mediaDurationInSeconds:z,playbackRate:$.playbackRate??1,trimAfter:$.trimAfter,trimBefore:$.trimBefore,sequenceDurationInFrames:N,compFps:_.fps}),[$.loop,z,$.playbackRate,$.trimAfter,$.trimBefore,N,_.fps]),M=C5(()=>({type:"audio",data:R}),[R]);if(typeof $.src!=="string")throw TypeError(`The \`<Audio>\` tag requires a string for \`src\`, but got ${JSON.stringify($.src)} instead.`);if(yQ({playbackRate:$.playbackRate,volume:$.volume},"Audio"),N===0)return null;return W7(Q9,{layout:"none",from:Z??0,durationInFrames:R.duration,freeze:G,_remotionInternalStack:Y,_remotionInternalIsMedia:M,name:J??"<Audio>",_remotionInternalDocumentationLink:J===void 0?"https://www.remotion.dev/docs/media/audio":void 0,controls:Q,_remotionInternalLoopDisplay:A,showInTimeline:X??!0,hidden:W,children:U.isRendering?W7(IQ,{...j}):W7(UZ,{name:J,...j,stack:Y??null,setMediaDurationInSeconds:H})})},B7=Z9.withSchema({Component:hQ,componentName:"<Audio>",componentIdentity:"dev.remotion.media.Audio",schema:SQ,supportsEffects:!1});P6.addSequenceStackTraces(B7);var M7=new Map,oQ=($,J)=>{let{width:Y,height:X}=J;if(Y===0||X===0)return;let Q=M7.get($);if(!Q||Q.width!==Y||Q.height!==X)Q=new OffscreenCanvas(Y,X),M7.set($,Q);let Z=Q.getContext("2d");if(!Z)return;Z.clearRect(0,0,Y,X),Z.drawImage(J,0,0)},sQ=($)=>{return M7.get($)??null},rQ=/\bobject-(contain|cover|fill|none|scale-down)\b/,c5=!1,n5=!1,LZ=({style:$,className:J,logLevel:Y})=>{if(!c5&&$?.objectFit)c5=!0,d5.Log.warn({logLevel:Y,tag:"@remotion/media"},"Use the `objectFit` prop instead of the `style` prop.");if(!n5&&J&&rQ.test(J))n5=!0,d5.Log.warn({logLevel:Y,tag:"@remotion/media"},"Use the `objectFit` prop instead of `object-*` CSS class names.")},{useUnsafeVideoConfig:iQ,Timeline:aQ,SharedAudioContext:tQ,usePlayerMutedState:eQ,useMediaVolumeState:$K,useFrameForVolumeProp:JK,evaluateVolume:YK,warnAboutTooHighVolume:XK,usePreload:o5,SequenceContext:ZK,useEffectChainState:QK}=M1,KK=({src:$,style:J,playbackRate:Y,logLevel:X,className:Q,muted:Z,volume:K,loopVolumeCurveBehavior:G,onVideoFrame:W,showInTimeline:j,loop:U,trimAfter:q,trimBefore:V,stack:_,disallowFallbackToOffthreadVideo:N,fallbackOffthreadVideoProps:R,audioStreamIndex:z,debugOverlay:H,headless:A,onError:M,credentials:F,requestInit:O,objectFit:B,_experimentalInitiallyDrawCachedFrame:D,effects:w,setMediaDurationInSeconds:P,refForOutline:T,...C})=>{let E=o5($),v=F0(null),x=iQ(),S=AZ(),k=F0(null),m=F0(V),f=F0(q),n=F0(W),[o]=q7(O),[s,a]=q7(!1),[r,l]=q7(!1),[X0]=aQ.usePlayingState(),{playbackRate:N0}=M1.usePlaybackRate(),t=j7(tQ),$0=cQ(),e=p5((j0)=>{v.current=j0,T.current=j0},[T]),Y0=p5((j0)=>{T.current=j0},[T]),[C0]=eQ(),[B1]=$K(),a0=JK(G),E0=YK({frame:a0,volume:K,mediaVolume:B1});if(!x)throw Error("No video config found");XK(E0);let t0=QK(),D1=F0(w);D1.current=w;let n1=F0(t0);n1.current=t0;let w0=j7(ZK),e0=Boolean(w0?.premounting),P0=Boolean(w0?.postmounting),n0=(w0?.absoluteFrom??0)/x.fps,q8=S/x.fps,N8=F0(q8);N8.current=q8;let b0=o5(E),Q0=j7(M1.BufferingContextReact);if(!Q0)throw Error("useMediaPlayback must be used inside a <BufferingContext>");let A0=Z||C0||E0<=0,g0=M1.useIsPlayerBuffering(Q0),o1=F0(X0&&!g0),T6=F0(e0),v6=F0(P0),MJ=F0(N0),MZ=F0(Y),FZ=F0(A0),wZ=F0(x.durationInFrames),OZ=F0(n0),FJ=F0(!1),C7=F0(e0);C7.current=e0,V$(()=>{if(!D)return;let j0=v.current;if(!j0)return;let j1=sQ(E);if(!j1)return;j0.width=j1.width,j0.height=j1.height;let O0=j0.getContext("2d",{alpha:!0,desynchronized:!0});if(!O0)return;O0.drawImage(j1,0,0)},[D,E]),V$(()=>{if(!D)return;return()=>{let j0=v.current;if(!j0||!FJ.current||C7.current)return;oQ(E,j0)}},[D,E]),pQ(()=>{let j0=t?.audioContext&&t.gainNode?{audioContext:t.audioContext,gainNode:t.gainNode,audioSyncAnchor:t.audioSyncAnchor,scheduleAudioNode:t.scheduleAudioNode,unscheduleAudioNode:t.unscheduleAudioNode}:null;try{let j1=new O7({canvas:v.current,src:b0,logLevel:X,sharedAudioContext:j0,loop:U,trimAfter:f.current,trimBefore:m.current,fps:x.fps,playbackRate:MZ.current,audioStreamIndex:z,debugOverlay:H,bufferState:$0,isPremounting:T6.current,isPostmounting:v6.current,globalPlaybackRate:MJ.current,durationInFrames:wZ.current,onVideoFrameCallback:n.current??null,playing:o1.current,sequenceOffset:OZ.current,credentials:F,requestInit:o,tagType:"video",getEffects:()=>D1.current,getEffectChainState:(O0,$1)=>n1.current?.get(O0,$1)});k.current=j1,j1.initialize(N8.current,FZ.current).then((O0)=>{if(O0.type==="disposed")return;let $1=(x6,DZ)=>{let[CZ,EZ]=W8({onError:M,error:x6,disallowFallback:N,isClientSideRendering:!1,clientSideError:x6});if(CZ==="fail")throw EZ;M1.Log.warn({logLevel:X,tag:"@remotion/media"},DZ),l(!0)};if(O0.type==="unknown-container-format"){$1(Error(`Unknown container format ${b0}.`),`Unknown container format for ${b0} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <OffthreadVideo>`);return}if(O0.type==="network-error"){$1(Error(`Network error fetching ${b0}.`),`Network error fetching ${b0}, falling back to <OffthreadVideo>`);return}if(O0.type==="cannot-decode"){$1(Error(`Cannot decode ${b0}.`),`Cannot decode ${b0}, falling back to <OffthreadVideo>`);return}if(O0.type==="no-tracks"){$1(Error(`No video or audio tracks found for ${b0}.`),`No video or audio tracks found for ${b0}, falling back to <OffthreadVideo>`);return}if(O0.type==="success")a(!0),P(O0.durationInSeconds),FJ.current=!0}).catch((O0)=>{let[$1,x6]=W8({onError:M,error:O0,disallowFallback:N,isClientSideRendering:!1,clientSideError:O0});if($1==="fail")throw x6;M1.Log.error({logLevel:X,tag:"@remotion/media"},"[VideoForPreview] Failed to initialize MediaPlayer",x6),l(!0)})}catch(j1){let[O0,$1]=W8({error:j1,onError:M,disallowFallback:N,isClientSideRendering:!1,clientSideError:j1});if(O0==="fail")throw $1;M1.Log.error({logLevel:X,tag:"@remotion/media"},"[VideoForPreview] MediaPlayer initialization failed",$1),l(!0)}return()=>{if(k.current)M1.Log.trace({logLevel:X,tag:"@remotion/media"},"[VideoForPreview] Disposing MediaPlayer"),k.current.dispose(),k.current=null;a(!1),l(!1),FJ.current=!1}},[z,$0,H,N,X,U,b0,t,x.fps,M,F,o,P]),LZ({style:J,className:Q,logLevel:X});let BZ=L7(()=>{return[M1.OBJECTFIT_CONTAIN_CLASS_NAME,Q].filter(M1.truthy).join(" ")},[Q]);QZ({mediaPlayerRef:k,mediaPlayerReady:s,currentTimeRef:N8,playing:X0,isPlayerBuffering:g0,frame:S,trimBefore:V,trimAfter:q,effectiveMuted:A0,userPreferredVolume:E0,playbackRate:Y,globalPlaybackRate:N0,fps:x.fps,sequenceOffset:n0,loop:U,durationInFrames:x.durationInFrames,isPremounting:e0,isPostmounting:P0,currentTime:q8,logLevel:X,label:"VideoForPreview"}),V$(()=>{let j0=k.current;if(!j0||!s)return;j0.setDebugOverlay(H)},[H,s]),V$(()=>{let j0=k.current;if(!j0||!s)return;j0.setVideoFrameCallback(W??null)},[W,s]),V$(()=>{let j0=k.current;if(!j0||!s)return;j0.redrawVideoEffects().catch(()=>{})},[w,s,k]);let E7=L7(()=>{return{...J,objectFit:B}},[B,J]);if(r&&!N)return F7(dQ,{...C,ref:Y0,src:E,style:E7,className:Q,muted:Z,volume:K,trimAfter:q,trimBefore:V,playbackRate:Y,loopVolumeCurveBehavior:G,name:"<Html5Video> (fallback)",loop:U,showInTimeline:j,stack:_??void 0,...R});if(A)return null;return F7("canvas",{...C,ref:e,style:E7,className:BZ})},GK=($)=>{let J=AZ(),Y=nQ(),X=J/Y.fps;if(!L7(()=>{return A$({unloopedTimeInSeconds:X,playbackRate:$.playbackRate,loop:$.loop,trimBefore:$.trimBefore,trimAfter:$.trimAfter,mediaDurationInSeconds:1/0,fps:Y.fps,ifNoMediaDuration:"infinity",src:$.src})!==null},[X,$.loop,$.playbackRate,$.src,Y.fps,$.trimBefore,$.trimAfter]))return null;return F7(KK,{...$})},zK=({volume:$,playbackRate:J,src:Y,muted:X,loopVolumeCurveBehavior:Q,delayRenderRetries:Z,delayRenderTimeoutInMilliseconds:K,onVideoFrame:G,logLevel:W,loop:j,style:U,className:q,fallbackOffthreadVideoProps:V,audioStreamIndex:_,disallowFallbackToOffthreadVideo:N,stack:R,toneFrequency:z,trimAfterValue:H,trimBeforeValue:A,headless:M,onError:F,credentials:O,requestInit:B,objectFit:D,effects:w,...P})=>{if(!Y)throw TypeError("No `src` was passed to <Video>.");let T=NK(),C=y0.useTimelinePosition(),{fps:E}=HK(),{registerRenderAsset:v,unregisterRenderAsset:x}=s5(y0.RenderAssetManager),S=y0.useMediaStartsAt(),k=s5(y0.SequenceContext),m=N7(()=>`media-video-${qK(Y)}-${k?.cumulatedFrom}-${k?.relativeFrom}-${k?.durationInFrames}`,[Y,k?.cumulatedFrom,k?.relativeFrom,k?.durationInFrames]),f=_K(),{delayRender:n,continueRender:o,cancelRender:s}=VK(),a=WK(null),[r,l]=V7(!1),[X0]=V7(B),N0=y0.useAudioEnabled(),t=y0.useVideoEnabled(),$0=NZ(W),e=y0.useEffectChainState(),[Y0,C0]=V7(null);if(Y0)throw Y0;UK(()=>{if(!a.current&&!M)return;if(r)return;if(!a.current?.getContext&&!M)return C0(Error("Canvas does not have .getContext() method available. This could be because <Video> was mounted inside an <svg> tag."));let E0=T/E,t0=1/E,D1=n(`Extracting frame at time ${E0} from ${Y}`,{retries:Z??void 0,timeoutInMilliseconds:K??void 0}),n1=(()=>{if(!N0)return!1;if(X)return!1;return!0})();return RZ({src:Y,timeInSeconds:E0,durationInSeconds:t0,playbackRate:J,logLevel:W,includeAudio:n1,includeVideo:t,isClientSideRendering:f.isClientSideRendering,loop:j,audioStreamIndex:_,trimAfter:H,trimBefore:A,fps:E,maxCacheSize:$0,credentials:O,requestInit:X0}).then(async(w0)=>{let e0=(Q0,A0,g0,o1)=>{if(f.isClientSideRendering){s(A0);return}let[T6,v6]=W8({onError:F,error:Q0,disallowFallback:N,isClientSideRendering:f.isClientSideRendering,clientSideError:Q0});if(T6==="fail"){s(v6);return}if(window.remotion_isMainTab)y0.Log.warn({logLevel:W,tag:"@remotion/media"},g0);l({durationInSeconds:o1})};if(w0.type==="unknown-container-format"){e0(Error(`Unknown container format ${Y}.`),Error(`Cannot render video "${Y}": Unknown container format. See supported formats: https://www.remotion.dev/docs/mediabunny/formats`),`Unknown container format for ${Y} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <OffthreadVideo>`,null);return}if(w0.type==="cannot-decode"){e0(Error(`Cannot decode ${Y}.`),Error(`Cannot render video "${Y}": The video could not be decoded by the browser.`),`Cannot decode ${Y}, falling back to <OffthreadVideo>`,w0.durationInSeconds);return}if(w0.type==="cannot-decode-alpha"){e0(Error(`Cannot decode alpha component for ${Y}.`),Error(`Cannot render video "${Y}": The alpha channel could not be decoded by the browser.`),`Cannot decode alpha component for ${Y}, falling back to <OffthreadVideo>`,w0.durationInSeconds);return}if(w0.type==="network-error"){e0(Error(`Network error fetching ${Y}.`),Error(`Cannot render video "${Y}": Network error while fetching the video (possibly CORS).`),`Network error fetching ${Y} (no CORS?), falling back to <OffthreadVideo>`,null);return}let{frame:P0,audio:n0,durationInSeconds:q8}=w0;if(P0){G?.(P0);let Q0=a.current?.getContext("2d",{alpha:!0});if(Q0){if(Q0.canvas.width=P0.width,Q0.canvas.height=P0.height,Q0.canvas.style.aspectRatio=`${Q0.canvas.width} / ${Q0.canvas.height}`,Q0.drawImage(P0,0,0),w.length>0){if(!await y0.runEffectChain({state:e.get(P0.width,P0.height),source:Q0.canvas,effects:w,output:Q0.canvas,width:P0.width,height:P0.height})){P0.close();return}}}P0.close()}else if(t){let Q0=a.current?.getContext("2d",{alpha:!0});if(Q0)Q0.clearRect(0,0,Q0.canvas.width,Q0.canvas.height)}let N8=_Z({behavior:Q,loop:j,assetDurationInSeconds:q8??0,fps:E,frame:T,startsAt:S}),b0=y0.evaluateVolume({volume:$,frame:N8,mediaVolume:1});if(y0.warnAboutTooHighVolume(b0),n0&&b0>0)VZ(n0.data,b0),v({type:"inline-audio",id:m,audio:f.isClientSideRendering?n0.data:Array.from(n0.data),frame:C,timestamp:n0.timestamp,duration:n0.numberOfFrames/j8()*1e6,toneFrequency:z});o(D1)}).catch((w0)=>{s(w0)}),()=>{o(D1),x(m)}},[C,o,n,Z,K,f.isClientSideRendering,E,T,m,W,j,Q,X,G,J,v,Y,S,x,$,r,_,N,z,H,A,N0,t,$0,s,M,F,O,e,w,X0]),LZ({style:U,className:q,logLevel:W});let B1=N7(()=>{return[y0.OBJECTFIT_CONTAIN_CLASS_NAME,q].filter(y0.truthy).join(" ")},[q]),a0=N7(()=>{return{...U,objectFit:D}},[D,U]);if(r){let E0=_7(y0.InnerOffthreadVideo,{...P,src:Y,playbackRate:J??1,muted:X??!1,acceptableTimeShiftInSeconds:V?.acceptableTimeShiftInSeconds,loopVolumeCurveBehavior:Q??"repeat",delayRenderRetries:Z??void 0,delayRenderTimeoutInMilliseconds:K??void 0,name:"Fallback to <OffthreadVideo>",style:a0,allowAmplificationDuringRender:!0,transparent:V?.transparent??!0,toneMapped:V?.toneMapped??!0,audioStreamIndex:_??0,className:q,onVideoFrame:G,volume:$,id:m,onError:V?.onError,toneFrequency:z,showInTimeline:!1,crossOrigin:V?.crossOrigin,onAutoPlayError:V?.onAutoPlayError??null,pauseWhenBuffering:V?.pauseWhenBuffering??!1,trimAfter:H,trimBefore:A,useWebAudioApi:V?.useWebAudioApi??!1,preservePitch:V?.preservePitch??!0,startFrom:void 0,endAt:void 0,stack:R,_remotionInternalNativeLoopPassed:!1});if(j){if(!r.durationInSeconds){let t0=Error(`Cannot render video ${Y}: @remotion/media was unable to render, and fell back to <OffthreadVideo>. Also, "loop" was set, but <OffthreadVideo> does not support looping and @remotion/media could also not determine the duration of the video.`);throw s(t0),t0}return _7(jK,{layout:"none",durationInFrames:y0.calculateMediaDuration({trimAfter:H,mediaDurationInFrames:r.durationInSeconds*E,playbackRate:J,trimBefore:A}),children:E0})}return E0}if(M)return null;return _7("canvas",{...P,ref:a,style:a0,className:B1})},{validateMediaTrimProps:RK,resolveTrimProps:AK,validateMediaProps:LK}=w1,MK={...w1.baseSchema,volume:{type:"number",min:0,max:20,step:0.01,default:1,description:"Volume",hiddenFromList:!1},playbackRate:{type:"number",min:0.1,step:0.01,default:1,description:"Playback rate",hiddenFromList:!1,keyframable:!1},loop:{type:"boolean",default:!1,description:"Loop"},...w1.transformSchema},FK=({src:$,audioStreamIndex:J,className:Y,delayRenderRetries:X,delayRenderTimeoutInMilliseconds:Q,disallowFallbackToOffthreadVideo:Z,fallbackOffthreadVideoProps:K,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,onVideoFrame:q,playbackRate:V,style:_,trimAfter:N,trimBefore:R,volume:z,stack:H,toneFrequency:A,showInTimeline:M,debugOverlay:F,headless:O,onError:B,credentials:D,requestInit:w,controls:P,objectFit:T,_experimentalInitiallyDrawCachedFrame:C,effects:E,setMediaDurationInSeconds:v,refForOutline:x,...S})=>{let k=mQ();if(typeof $!=="string")throw TypeError(`The \`<Video>\` tag requires a string for \`src\`, but got ${JSON.stringify($)} instead.`);RK({startFrom:void 0,endAt:void 0,trimBefore:R,trimAfter:N});let{trimBeforeValue:m,trimAfterValue:f}=AK({startFrom:void 0,endAt:void 0,trimBefore:R,trimAfter:N});if(LK({playbackRate:V,volume:z},"Video"),k.isRendering)return AJ(zK,{...S,audioStreamIndex:J??0,className:Y,delayRenderRetries:X??null,delayRenderTimeoutInMilliseconds:Q??null,disallowFallbackToOffthreadVideo:Z??!1,fallbackOffthreadVideoProps:K,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,onVideoFrame:q,playbackRate:V,src:$,stack:H,style:_,volume:z,toneFrequency:A,trimAfterValue:f,trimBeforeValue:m,headless:O,onError:B,credentials:D,requestInit:w,objectFit:T,effects:E});return AJ(GK,{...S,setMediaDurationInSeconds:v,audioStreamIndex:J??0,className:Y,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,onVideoFrame:q,playbackRate:V,src:$,style:_,volume:z,showInTimeline:M,trimAfter:f,trimBefore:m,stack:H??null,disallowFallbackToOffthreadVideo:Z,fallbackOffthreadVideoProps:K,debugOverlay:F??!1,headless:O??!1,onError:B,credentials:D,requestInit:w,controls:P,objectFit:T,effects:E,_experimentalInitiallyDrawCachedFrame:C,refForOutline:x})},wK=({src:$,audioStreamIndex:J,className:Y,delayRenderRetries:X,delayRenderTimeoutInMilliseconds:Q,disallowFallbackToOffthreadVideo:Z,fallbackOffthreadVideoProps:K,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,name:q,onVideoFrame:V,playbackRate:_,showInTimeline:N,style:R,trimAfter:z,trimBefore:H,volume:A,stack:M,toneFrequency:F,debugOverlay:O,headless:B,onError:D,credentials:w,requestInit:P,controls:T,objectFit:C,_experimentalInitiallyDrawCachedFrame:E,effects:v,durationInFrames:x,from:S,freeze:k,hidden:m,...f})=>{let n=w1.useLogLevel(),[o]=w1.useMediaVolumeState(),s=w1.useMediaStartsAt(),a=lQ(),r=Math.min(x??1/0,Math.max(0,a.durationInFrames-(S??0))),l=w1.useBasicMediaInTimeline({src:$,volume:A,playbackRate:_??1,trimBefore:H,trimAfter:z,sequenceDurationInFrames:r,mediaType:"video",displayName:q??"<Video>",mediaVolume:o,mediaStartsAt:s,loop:W??!1}),[X0,N0]=gQ(null),t=l5(()=>a5({loop:W??!1,mediaDurationInSeconds:X0,playbackRate:_??1,trimAfter:z,trimBefore:H,sequenceDurationInFrames:r,compFps:a.fps}),[W,X0,_,z,H,r,a.fps]),$0=l5(()=>({type:"video",data:l}),[l]),e=w1.useMemoizedEffects({effects:v??[],overrideId:T?.overrideId??null}),Y0=w1.useMemoizedEffectDefinitions(v??[]),C0=fQ.useRef(null);if(r===0)return null;return AJ(uQ,{layout:"none",from:S??0,durationInFrames:l.duration,freeze:k,_remotionInternalStack:M,_remotionInternalIsMedia:$0,name:q??"<Video>",_remotionInternalDocumentationLink:q===void 0?"https://www.remotion.dev/docs/media/video":void 0,controls:T,_remotionInternalLoopDisplay:t,_remotionInternalEffects:Y0,outlineRef:C0,showInTimeline:N??!0,hidden:m,children:AJ(FK,{...f,audioStreamIndex:J??0,className:Y,delayRenderRetries:X??null,delayRenderTimeoutInMilliseconds:Q??null,disallowFallbackToOffthreadVideo:Z??!1,fallbackOffthreadVideoProps:K??{},logLevel:G??n,loop:W??!1,loopVolumeCurveBehavior:j??"repeat",muted:U??!1,onVideoFrame:V,playbackRate:_??1,showInTimeline:N??!0,src:$,style:R??{},trimAfter:z,trimBefore:H,volume:A??1,toneFrequency:F??1,stack:M,debugOverlay:O??!1,headless:B??!1,onError:D,credentials:w,requestInit:P,controls:T,objectFit:C??"contain",_experimentalInitiallyDrawCachedFrame:E??!1,effects:e,setMediaDurationInSeconds:N0,refForOutline:C0})})},D7=kQ.withSchema({Component:wK,componentName:"<Video>",componentIdentity:"dev.remotion.media.Video",schema:MK,supportsEffects:!0});w1.addSequenceStackTraces(D7);var OK=B7,BK=D7;var{Audio:s_,AudioForPreview:r_,Video:i_,experimental_Audio:a_,experimental_Video:t_,getTargetSampleRate:e_}=LJ;var JH=LJ;export{e_ as getTargetSampleRate,t_ as experimental_Video,a_ as experimental_Audio,JH as default,i_ as Video,r_ as AudioForPreview,s_ as Audio};
|
|
410
|
+
*/var C5=Symbol.for("mediabunny loaded");if(globalThis[C5])k._error(`[WARNING]
|
|
411
|
+
Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[C5]=!0;import{Internals as w9}from"remotion";import{Internals as L7}from"remotion";import{useContext as r9,useLayoutEffect as n0}from"react";import{Internals as b5}from"remotion";import{jsx as UZ}from"react/jsx-runtime";import{useContext as T5,useLayoutEffect as KQ,useMemo as GQ,useState as v5}from"react";import{cancelRender as x5,Html5Audio as WQ,Internals as E1,random as UQ,useCurrentFrame as jQ,useDelayRender as qQ,useRemotionEnvironment as NQ}from"remotion";import NZ from"react";import{cancelRender as I5,Internals as I6}from"remotion";import{Internals as y5}from"remotion";import{Internals as VZ}from"remotion";import{Internals as AQ}from"remotion";import{Internals as MQ}from"remotion";import{Internals as t1}from"remotion";import{Internals as MJ}from"remotion";import{Internals as gQ}from"remotion";import{jsx as cQ}from"react/jsx-runtime";import{jsx as wJ}from"react/jsx-runtime";import iQ,{useMemo as l5,useState as aQ}from"react";import{Freeze as tQ,Internals as G1,Interactive as L$,Sequence as eQ,useRemotionEnvironment as $K,useVideoConfig as JK}from"remotion";import{Internals as YK}from"remotion";import{useCallback as p5,useContext as H7,useEffect as ZK,useLayoutEffect as F$,useMemo as O7,useRef as b0,useState as z7}from"react";import{Html5Video as QK,Internals as P1,useBufferState as KK,useCurrentFrame as BZ,useVideoConfig as GK}from"remotion";import{Internals as d5}from"remotion";import{jsx as D7}from"react/jsx-runtime";import{useContext as o5,useLayoutEffect as DK,useMemo as R7,useRef as CK,useState as A7}from"react";import{Internals as l0,Loop as EK,random as PK,useCurrentFrame as bK,useDelayRender as TK,useRemotionEnvironment as vK,useVideoConfig as xK}from"remotion";import{jsx as M7}from"react/jsx-runtime";import{jsx as w$}from"react/jsx-runtime";var G9=Symbol.dispose||Symbol.for("Symbol.dispose"),W9=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),r5=($,J,Y)=>{if(J!=null){if(typeof J!=="object"&&typeof J!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var X;if(Y)X=J[W9];if(X===void 0)X=J[G9];if(typeof X!=="function")throw TypeError("Object not disposable");$.push([Y,X,J])}else if(Y)$.push([Y]);return J},i5=($,J,Y)=>{var X=typeof SuppressedError==="function"?SuppressedError:function(K,G,W,j){return j=Error(W),j.name="SuppressedError",j.error=K,j.suppressed=G,j},Q=(K)=>J=Y?new X(K,J,"An error was suppressed during disposal"):(Y=!0,K),Z=(K)=>{while(K=$.pop())try{var G=K[1]&&K[1].call(K[2]);if(K[0])return Promise.resolve(G).then(Z,(W)=>(Q(W),Z()))}catch(W){Q(W)}if(Y)throw J};return Z()},a5=({loop:$,mediaDurationInSeconds:J,playbackRate:Y,trimAfter:X,trimBefore:Q,sequenceDurationInFrames:Z,compFps:K})=>{if(!$||!J)return;let G=H9.calculateMediaDuration({mediaDurationInFrames:J*K,playbackRate:Y,trimAfter:X,trimBefore:Q});return{numberOfTimes:Z/G,startOffset:0,durationInFrames:G}},B$=({loop:$,mediaDurationInSeconds:J,unloopedTimeInSeconds:Y,src:X,trimAfter:Q,trimBefore:Z,fps:K,playbackRate:G,ifNoMediaDuration:W})=>{if(J===null&&$&&W==="fail")throw Error(`Could not determine duration of ${X}, but "loop" was set.`);let j=$?F7.calculateMediaDuration({trimAfter:Q,mediaDurationInFrames:J?J*K:1/0,playbackRate:1,trimBefore:Z}):1/0,U=$?Y*G*K%j/K:Y*G;if((Q??null)!==null&&!$){let q=(Q-(Z??0))/K;if(U>=q)return null}return U+(Z??0)/K},L9=({mediaDurationInSeconds:$,ifNoMediaDuration:J,src:Y,trimAfter:X,trimBefore:Q,fps:Z})=>{if($===null&&J==="fail")throw Error(`Could not determine duration of ${Y}, but "loop" was set.`);return F7.calculateMediaDuration({trimAfter:X,mediaDurationInFrames:$?$*Z:1/0,playbackRate:1,trimBefore:Q})/Z+(Q??0)/Z},O9=0.1,B9=({startFromSecond:$,iterator:J,unscheduleAudioNode:Y})=>{let X=!1,Q=[],Z=-1/0,K=()=>{for(let{node:W}of Q){Y(W);try{W.stop()}catch{}}Q.length=0};return{destroy:()=>{K(),X=!0,J.return().catch(()=>{return})},getNextFn:async()=>{let W=await J.next();if(W.value)Z=Math.max(Z,W.value.timelineTimestamp+W.value.sourceDurationInSeconds);return W},isDestroyed:()=>{return X},addQueuedAudioNode:(W)=>{Q.push(W)},guessNextTimestamp:()=>{return!Number.isFinite(Z)?$:Z},getQueuedPeriod:()=>{let W=-1/0,j=1/0;for(let U of Q)W=Math.max(W,U.timestamp+U.sourceDurationInSeconds),j=Math.min(j,U.timestamp);if(!Number.isFinite(j)||!Number.isFinite(W))return null;return{from:j,until:W}}}},D9=($,J)=>{if(!J)return!1;return $>=J.from&&$<J.until},e5=({mediaTimestamp:$,targetTime:J,currentTime:Y,sequenceStartTime:X})=>{let Z=$<X?X-$:0,K=J<0?-J:0,G=Z+K;return J+Y+G},C9=({sourceDurationInSeconds:$,sourceOffsetInSeconds:J,offset:Y})=>{return Math.max(0,$-(Y-J))},E9=({mediaTimestamp:$,targetTime:J,sequenceStartTime:Y,combinedPlaybackRate:X,sourceStartOffsetInSeconds:Q})=>{let K=$<Y?Y-$:0,G=J<0?-J*X:0;return Q+K+G};class C7 extends Error{constructor(){super("Waiter became stale before it got its turn");this.name="StaleWaiterError"}}var P9=1,e1=[],_7=0,M$=null,BJ=()=>{if(_7>=P9)if(M$?.waiter.getPriority()===null)M$.cancel();else return;let $=[];for(let G=e1.length-1;G>=0;G--)if(e1[G].getPriority()===null){let[W]=e1.splice(G,1);$.push(W)}for(let G of $)G.onError(new C7);if(e1.length===0)return;let J=0,Y=e1[0].getPriority();if(Y===null)throw Error("Stale waiter should have been removed");for(let G=1;G<e1.length;G++){let W=e1[G].getPriority();if(W===null)throw Error("Stale waiter should have been removed");if(W<Y)Y=W,J=G}if(Y>2)return;let[X]=e1.splice(J,1);_7++;let Q=!1,Z=!1,K={waiter:X,cancel:()=>{Z=!0,K.settle()},settle:()=>{if(Q)return;if(Q=!0,_7--,M$===K)M$=null}};M$=K,X.fn().then((G)=>{if(K.settle(),Z)return;X.onDone(G,BJ)},(G)=>{if(K.settle(),Z)return;X.onError(G)})},b9=({getPriority:$,fn:J,onDone:Y,onError:X})=>{e1.push({getPriority:$,fn:J,onDone:Y,onError:X}),BJ()},T9=0.5;async function*$Z({audioSink:$,timeToSeek:J,maximumTimestamp:Y}){let X=Math.max(0,J-T9),Q=$.buffers(X,Y);for await(let Z of Q){let K=Math.max(Z.timestamp,J),G=Math.min(Z.timestamp+Z.duration,Y);if(G<=K)continue;yield{buffer:Z,timelineTimestamp:K,sourceOffsetInSeconds:K-Z.timestamp,sourceDurationInSeconds:G-K}}}async function*v9({audioSink:$,seekTimeInSeconds:J,loopStartInSeconds:Y,segmentEndInSeconds:X,maximumContinuousTimestamp:Q}){if(X<=Y)throw Error(`Cannot loop audio over an empty range (${Y} to ${X})`);let Z=J,K=J;while(!0){let G=!1;for await(let W of $Z({audioSink:$,timeToSeek:Z,maximumTimestamp:X})){G=!0;let j=K+(W.timelineTimestamp-Z),U=Math.min(W.sourceDurationInSeconds,Q-j);if(U<=0)return;if(yield{...W,timelineTimestamp:j,sourceDurationInSeconds:U},j+U>=Q)return}if(!G)throw Error(`Audio loop pass from ${Z} to ${X} yielded no buffers`);K+=X-Z,Z=Y}}var x9=0.1,I9=($)=>{return $>=x9},JZ=({anchor:$,unloopedTimeInSeconds:J,playbackRate:Y})=>{return $.mediaStartInSeconds+(J-$.unloopedStartInSeconds)*Y},y9=({audioTrack:$,delayPlaybackHandleIfNotPremounting:J,sharedAudioContext:Y,getSequenceEndTimestamp:X,getSequenceDurationInSeconds:Q,getMediaEndTimestamp:Z,getStartTime:K,initialMuted:G,drawDebugOverlay:W,initialPlaybackRate:j,initialTrimBefore:U,initialTrimAfter:q,initialSequenceOffset:N,initialSequenceDurationInFrames:_,initialLoop:V,initialFps:z})=>{let R=G,H=1,A={time:-1,playbackRate:j,trimBefore:U,trimAfter:q,sequenceOffset:N,sequenceDurationInFrames:_,loop:V,fps:z},M=Y.audioContext.createGain();M.connect(Y.gainNode);let L=new VJ($),w=null,O=null,D=0,B=0,C=null,E=()=>{if(C)C.unblock(),C=null},P=[],v=()=>{for(let m=P.length-1;m>=0;m--){let c=P[m];if(c.remaining--,c.remaining<=0)c.resolve(),P.splice(m,1)}},T=(m)=>{if(m<=0)return Promise.resolve();return new Promise((c)=>{P.push({remaining:m,resolve:c})})},x=({buffer:m,mediaTimestamp:c,originalUnloopedMediaTimestamp:s,sourceOffsetInSeconds:X0,sourceDurationInSeconds:e,playbackRate:Q0,scheduleAudioNode:i,logLevel:j0})=>{if(!w)throw Error("Audio buffer iterator not found");if(R)return;let o=Y.audioContext.createBufferSource();o.buffer=m,o.playbackRate.value=Q0,o.connect(M);let G0=i(o,c,s,X0,e);if(G0.type==="not-started"){w9.Log.verbose({logLevel:j0,tag:"audio-scheduling"},"not started, disconnected: %s %s",c.toFixed(3),m.duration.toFixed(3)),o.disconnect();return}w.addQueuedAudioNode({node:o,timestamp:c,buffer:m,sourceDurationInSeconds:e,scheduledTime:G0.scheduledTime,playbackRate:Q0,scheduledAtAnchor:Y.audioSyncAnchor.value})},I=({buffer:m,playbackRate:c,scheduleAudioNode:s,logLevel:X0})=>{if(R)return;let e=K(),Q0=X();if(m.timelineTimestamp+m.sourceDurationInSeconds<=e)return;if(m.timelineTimestamp>=Q0)return;let i=Math.max(m.timelineTimestamp,e),j0=Math.min(m.timelineTimestamp+m.sourceDurationInSeconds,Q0);B+=Math.max(0,j0-i),x({buffer:m.buffer.buffer,mediaTimestamp:m.timelineTimestamp,playbackRate:c,scheduleAudioNode:s,logLevel:X0,originalUnloopedMediaTimestamp:m.buffer.timestamp,sourceOffsetInSeconds:m.sourceOffsetInSeconds,sourceDurationInSeconds:m.sourceDurationInSeconds}),W()},S=({iterator:m,nonce:c,getTargetTime:s,playbackRate:X0,scheduleAudioNode:e,onScheduled:Q0,onDestroyed:i,onDone:j0,logLevel:o,currentTime:G0,getAudioContextCurrentTimeMockedInTest:$0})=>{b9({getPriority:()=>{if(m.isDestroyed())return i(),null;let a=m.guessNextTimestamp(),J0=s(a,G0);if(J0===null)return null;return e5({mediaTimestamp:a,targetTime:J0,currentTime:G0,sequenceStartTime:K()})-$0()},fn:()=>m.getNextFn(),onDone:(a,J0)=>{if(m.isDestroyed()){J0(),i();return}if(!a.value){J0(),j0();return}Q0(a.value.sourceDurationInSeconds),v(),I({buffer:a.value,playbackRate:X0,scheduleAudioNode:e,logLevel:o}),S({iterator:m,nonce:c,getTargetTime:s,playbackRate:X0,scheduleAudioNode:e,onScheduled:Q0,onDestroyed:i,onDone:j0,logLevel:o,currentTime:G0,getAudioContextCurrentTimeMockedInTest:$0}),J0()},onError:(a)=>{if(a instanceof D0){i();return}if(a instanceof C7){i();return}throw a}})},u=({nonce:m,playbackRate:c,startFromSecond:s,unloopedStartFromSecond:X0,scheduleAudioNode:e,getTargetTime:Q0,logLevel:i,loop:j0,unscheduleAudioNode:o,getAudioContextCurrentTimeMockedInTest:G0})=>{if(R)return;let $0=Z();if(s>=$0)return;w?.destroy(),E();let a=J();C=a,O={unloopedStartInSeconds:X0,mediaStartInSeconds:s};let J0=s+Q()*c,I0=j0?v9({audioSink:L,seekTimeInSeconds:s,loopStartInSeconds:K(),segmentEndInSeconds:$0,maximumContinuousTimestamp:J0}):$Z({audioSink:L,timeToSeek:s,maximumTimestamp:$0}),p0=B9({startFromSecond:s,iterator:I0,unscheduleAudioNode:o});D++,w=p0;let H0=0,F0=!1,C0=()=>{if(F0)return;F0=!0,a.unblock()};S({iterator:p0,nonce:m,getTargetTime:Q0,playbackRate:c,scheduleAudioNode:e,onScheduled:(y0)=>{if(H0+=y0,I9(H0))C0()},onDestroyed:()=>{C0()},onDone:()=>{C0()},logLevel:i,currentTime:Y.audioContext.currentTime,getAudioContextCurrentTimeMockedInTest:G0})};return{startAudioIterator:u,getAudioBufferIterator:()=>w,getCurrentAnchor:()=>O,destroyIterator:()=>{w?.destroy(),w=null,O=null,E()},seek:({newTime:m,unloopedNewTime:c,nonce:s,playbackRate:X0,localPlaybackRate:e,scheduleAudioNode:Q0,getTargetTime:i,logLevel:j0,loop:o,trimBefore:G0,trimAfter:$0,sequenceOffset:a,sequenceDurationInFrames:J0,fps:I0,getAudioContextCurrentTimeMockedInTest:p0})=>{if(s.isStale())return;if(A.time===m&&A.playbackRate===X0&&A.trimBefore===G0&&A.trimAfter===$0&&A.sequenceOffset===a&&A.sequenceDurationInFrames===J0&&A.loop===o&&A.fps===I0)return;if(A={time:m,playbackRate:X0,trimBefore:G0,trimAfter:$0,sequenceOffset:a,sequenceDurationInFrames:J0,loop:o,fps:I0},R)return;if(w&&!w.isDestroyed()){let H0=o&&O?JZ({anchor:O,unloopedTimeInSeconds:c,playbackRate:e}):m,F0=w.getQueuedPeriod(),C0=F0?{from:F0.from-O9-Y.audioContext.baseLatency-Y.audioContext.outputLatency,until:F0.until}:null;if(D9(H0,C0)){BJ();return}let J1=w.guessNextTimestamp();if(J1<H0&&Math.abs(J1-H0)<1){BJ();return}}u({nonce:s,playbackRate:X0,startFromSecond:m,unloopedStartFromSecond:c,scheduleAudioNode:Q0,getTargetTime:i,logLevel:j0,loop:o,unscheduleAudioNode:Y.unscheduleAudioNode,getAudioContextCurrentTimeMockedInTest:p0})},getAudioIteratorsCreated:()=>D,getTotalAudioScheduledInSeconds:()=>B,setMuted:(m)=>{R=m,M.gain.value=R?0:H},setVolume:(m)=>{H=Math.max(0,m),M.gain.value=R?0:H},scheduleAudioChunk:x,waitForNScheduledNodes:T}},S9=({context:$,audioTime:J,audioContextState:Y,audioSyncAnchor:X,playing:Q,audioIteratorManager:Z,videoIteratorManager:K,playbackRate:G})=>{let W=X?.value??0,j=["Debug overlay",`Video iterators created: ${K?.getVideoIteratorsCreated()}`,`Audio iterators created: ${Z?.getAudioIteratorsCreated()}`,`Audio scheduled: ${(Z?.getTotalAudioScheduledInSeconds()??0).toFixed(3)}s`,`Frames rendered: ${K?.getFramesRendered()}`,`Audio context state: ${Y}`,J?`Audio time: ${((J-W)*G).toFixed(3)}s`:null].filter(Boolean);if(Z){let H=Z.getAudioBufferIterator()?.getQueuedPeriod();if(H){let A=J?` (${(H.until-(J-W)*G).toFixed(3)}s ahead)`:"";j.push(`Audio queued until ${H.until.toFixed(3)}s${A}`)}j.push(`Playing: ${Q}`)}let U=30,q=10,N=10,_=20,V=20,z=600,R=j.length*U+2*N;$.fillStyle="rgba(0, 0, 0, 1)",$.fillRect(_,V,z,R),$.fillStyle="white",$.font="24px sans-serif",$.textBaseline="top";for(let H=0;H<j.length;H++)$.fillText(j[H],_+q,V+N+H*U)},YZ=async($)=>{return await $.getDurationFromMetadata(void 0,{skipLiveWait:!0})??$.computeDuration(void 0,{skipLiveWait:!0})},h9=($)=>{if(!$)return;let J=[];if($ instanceof Headers)$.forEach((Y,X)=>{J.push([X.toLowerCase(),Y])});else if(Array.isArray($))for(let[Y,X]of $)J.push([Y.toLowerCase(),X]);else for(let[Y,X]of Object.entries($))J.push([Y.toLowerCase(),X]);return J.sort(([Y],[X])=>Y<X?-1:Y>X?1:0),J},y6=($)=>{if(!$)return;let J=h9($.headers),Y={...$.cache===void 0?null:{cache:$.cache},...$.credentials===void 0?null:{credentials:$.credentials},...J===void 0?null:{headers:J},...$.integrity===void 0?null:{integrity:$.integrity},...$.mode===void 0?null:{mode:$.mode},...$.redirect===void 0?null:{redirect:$.redirect},...$.referrer===void 0?null:{referrer:$.referrer},...$.referrerPolicy===void 0?null:{referrerPolicy:$.referrerPolicy}};return Object.keys(Y).length===0?void 0:Y},XZ=($)=>{let J=y6($);if(!J)return null;return[J.cache??null,J.credentials??null,J.integrity??null,J.mode??null,J.redirect??null,J.referrer??null,J.referrerPolicy??null,J.headers??null]},ZZ=({credentials:$,requestInit:J})=>{if($===void 0)return y6(J);return y6({credentials:$,...J})},DJ={},f9=({src:$,credentials:J,requestInit:Y})=>JSON.stringify([$,J??null,XZ(Y)]),g9=({src:$,credentials:J,requestInit:Y})=>{let X=y6(Y),Q=f9({src:$,credentials:J,requestInit:X}),Z=DJ[Q];if(Z)return Z.refCount++,{input:Z.input,cacheKey:Q};let K=ZZ({credentials:J,requestInit:X}),G=new C1({source:new m8($,K?{requestInit:K}:void 0),formats:j$});return DJ[Q]={input:G,refCount:1},{input:G,cacheKey:Q}},k9=($)=>{let J=DJ[$];if(!J)return;if(J.refCount--,J.refCount<=0)delete DJ[$],J.input.dispose()},QZ=async({videoTrack:$,audioTracks:J,audioStreamIndex:Y})=>{if(Y!==null)return J[Y]??null;if($)return await $.getPrimaryPairableAudioTrack()??null;return J[0]??null};function O$($){if($.message.includes("Failed to fetch")||$.message.includes("Load failed")||$.message.includes("NetworkError when attempting to fetch resource"))return!0;return!1}function u9($){return $.message.includes("Unsupported configuration")}var m9=()=>{let $=0;return{createAsyncOperation:()=>{$++;let Y=$;return{isStale:()=>$!==Y}}}};class KZ{isPremounting;isPostmounting;activeHandles=new Set;delayPlayback;constructor({bufferState:$,isPremounting:J,isPostmounting:Y}){this.delayPlayback=$.delayPlayback,this.isPremounting=J,this.isPostmounting=Y}shouldDelayPlayback(){return!this.isPremounting&&!this.isPostmounting}syncHandles(){for(let $ of this.activeHandles)if(this.shouldDelayPlayback())$.arm();else $.disarm()}setIsPremounting($){this.isPremounting=$,this.syncHandles()}setIsPostmounting($){this.isPostmounting=$,this.syncHandles()}createHandle(){let $=!1,J=null,Y=!1,X=()=>{if($||Y)return;J=this.delayPlayback().unblock,$=!0},Q=()=>{if(!$)return;J?.(),J=null,$=!1},Z={arm:X,disarm:Q,dispose:()=>{}};if(Z.dispose=()=>{if(Y)return;Y=!0,Q(),this.activeHandles.delete(Z)},this.activeHandles.add(Z),this.shouldDelayPlayback())X();return{unblock:Z.dispose,[Symbol.dispose]:Z.dispose}}}var _0=($)=>{return Math.round($*1000)/1000},l9=3,GZ=Symbol("releaseCanvas"),OJ=($)=>{$?.[GZ]?.()},p9=()=>{let $=[];return{makeStableFrame:(Y)=>{let{canvas:X}=Y,Q=$.pop()??new OffscreenCanvas(X.width,X.height);if(Q.width!==X.width)Q.width=X.width;if(Q.height!==X.height)Q.height=X.height;let Z=Q.getContext("2d");if(!Z)throw Error("Could not create canvas context");Z.clearRect(0,0,Q.width,Q.height),Z.drawImage(X,0,0);let K=!1;return{canvas:Q,duration:Y.duration,timestamp:Y.timestamp,[GZ]:()=>{if(K)return;K=!0,$.push(Q)}}}}},P5=($,J)=>{let Y=$.canvases(J),X=[],Q=!1,Z=!1,K=!1,G=null,W=p9(),j=(_)=>{return W.makeStableFrame(_)},U=()=>{if(Q||Z||K)return;if(X.length>=l9)return;Q=!0;let _={promise:Y.next(),resolved:null};X.push(_),G=_.promise.then((V)=>{if(Q=!1,G=null,V.done){_.resolved=V,Z=!0;return}if(K){_.resolved={done:!0,value:void 0};return}_.resolved={...V,value:j(V.value)},U()},()=>{Q=!1,G=null})};return U(),{next:()=>{let _=X.shift();if(U(),!_){if(Z||K)return{type:"ready",frame:null};let V=G;return{type:"pending",wait:async()=>{await V;let z=X.shift();if(U(),!z)return null;if(z.resolved)return z.resolved.done?null:z.resolved.value;let R=await z.promise;return R.done?null:j(R.value)}}}if(_.resolved){if(_.resolved.done)return{type:"ready",frame:null};return{type:"ready",frame:_.resolved.value}}return{type:"pending",wait:async()=>{let V=await _.promise;if(_.resolved)return _.resolved.done?null:_.resolved.value;return V.done?null:j(V.value)}}},closeIterator:async()=>{K=!0;for(let _ of X)if(_.resolved&&!_.resolved.done)OJ(_.resolved.value);X.length=0,await Y.return()}}},d9=($)=>{let J=new Map;return{prewarmIteratorForLooping:({timeToSeek:Z})=>{if(!J.has(Z))J.set(Z,P5($,Z))},makeIteratorOrUsePrewarmed:(Z)=>{let K=J.get(Z);if(K)return J.delete(Z),K;return P5($,Z)},destroy:()=>{for(let Z of J.values())Z.closeIterator();J.clear()}}},c9=async($,J)=>{let Y=!1,X=J.makeIteratorOrUsePrewarmed($),Q=!1,Z=X.next(),K=Z&&Z.type==="ready"?Z.frame:await Z.wait(),G=K,W=null,j=(H)=>{if(G!==H)OJ(G);G=H},U=(H)=>{if(W=H,W===null)Q=!0;return W},q=()=>{if(W)return{type:"ready",frame:W};if(Q)return{type:"ready",frame:null};let H=X.next();if(H.type==="ready")return{type:"ready",frame:U(H.frame)};return{type:"pending",wait:H.wait}},N=(H)=>{return H?_0(H.timestamp):1/0},_=async({pendingFrameBehavior:H,shouldContinue:A})=>{let M=q();if(M.type==="ready")return{type:"ready",timestamp:N(M.frame)};if(H==="restart-iterator")return{type:"pending"};if(!A())return{type:"cancelled"};let L=U(await M.wait());if(!A())return{type:"cancelled"};return{type:"ready",timestamp:N(L)}},V=()=>{if(W){let A=W;j(A);let M={type:"got-frame-or-end",frame:A};return W=null,M}let H=X.next();if(H.type==="pending")return{type:"need-to-wait-for-it",waitPromise:async()=>{let A=await H.wait();if(A)j(A);else Q=!0;return A}};if(H.frame)j(H.frame);else Q=!0;return{type:"got-frame-or-end",frame:H.frame??null}};return{destroy:()=>{if(Y=!0,OJ(G),W!==G)OJ(W);G=null,W=null,X.closeIterator().catch(()=>{return})},initialFrame:K,isDestroyed:()=>{return Y},tryToSatisfySeek:async(H,A)=>{if(!A.shouldContinue())return{type:"not-satisfied",reason:"seek was superseded"};let M=_0(H);if(G){let L=_0(G.timestamp);if(M<L){if(G===K&&_0(H)>=_0($))return{type:"satisfied",frame:G};return{type:"not-satisfied",reason:`iterator is too far, most recently returned ${L}`}}let w=await _({pendingFrameBehavior:A.pendingFrameBehavior,shouldContinue:A.shouldContinue});if(w.type==="cancelled")return{type:"not-satisfied",reason:"seek was superseded"};if(w.type==="pending")return{type:"not-satisfied",reason:"iterator did not have next frame ready"};if(L<=M&&w.timestamp>M)return{type:"satisfied",frame:G}}if(Q){if(G)return{type:"satisfied",frame:G};return{type:"not-satisfied",reason:"iterator ended"}}while(!0){if(!A.shouldContinue())return{type:"not-satisfied",reason:"seek was superseded"};let L=V();if(L.type==="need-to-wait-for-it")return{type:"not-satisfied",reason:"iterator did not have frame ready"};if(L.type==="got-frame-or-end"){if(L.frame===null){if(Q=!0,G)return{type:"satisfied",frame:G};return{type:"not-satisfied",reason:"iterator ended and did not have frame ready"}}let w=_0(L.frame.timestamp),O=await _({pendingFrameBehavior:A.pendingFrameBehavior,shouldContinue:A.shouldContinue});if(O.type==="cancelled")return{type:"not-satisfied",reason:"seek was superseded"};if(O.type==="pending")return{type:"not-satisfied",reason:"iterator did not have next frame ready"};if(w<=M&&O.timestamp>M)return{type:"satisfied",frame:L.frame};continue}throw Error("Unreachable")}}}},{runEffectChain:n9}=L7,s9=({previousTime:$,newTime:J,fps:Y,playbackRate:X,isPlaying:Q})=>{if(!Q||J<$)return!1;let Z=Math.abs(X)/Y;return _0(J-$)<=_0(Z)},o9=async({delayPlaybackHandleIfNotPremounting:$,canvas:J,context:Y,drawDebugOverlay:X,logLevel:Q,getOnVideoFrameCallback:Z,videoTrack:K,getLoopSegmentMediaEndTimestamp:G,getStartTime:W,getIsLooping:j,getEffects:U,getEffectChainState:q})=>{let N=0,_=null,V=0,z=null,R=null,H=null,A=()=>{R=null};if(J){let E=await K.getDisplayWidth(),P=await K.getDisplayHeight();if(J.width!==E||J.height!==P)J.width=E,J.height=P}let M=new NJ(K,{poolSize:3,fit:"contain",alpha:!0}),L=d9(M),w=async(E)=>{if(Y&&J){let P=U(),v=q(J.width,J.height);if(P.length>0&&v&&J instanceof HTMLCanvasElement)await n9({state:v,source:E.canvas,effects:P,output:J,width:J.width,height:J.height});else Y.clearRect(0,0,J.width,J.height),Y.drawImage(E.canvas,0,0)}},O=async(E)=>{await w(E),R=E,V++,X();let P=Z();if(P)P(E.canvas);L7.Log.trace({logLevel:Q,tag:"@remotion/media"},`[MediaPlayer] Drew frame ${E.timestamp.toFixed(3)}s`)},D=async()=>{if(!R)return;await w(R),X();let E=Z();if(E)E(R.canvas);L7.Log.trace({logLevel:Q,tag:"@remotion/media"},`[MediaPlayer] Redrew frame ${R.timestamp.toFixed(3)}s with updated effects`)},B=async(E,P)=>{let v=[];try{A(),_?.destroy(),z=r5(v,$(),0),H=E;let S=await c9(E,L);if(N++,_=S,S.isDestroyed())return;if(P.isStale())return;if(_.isDestroyed())return;if(!S.initialFrame)return;await O(S.initialFrame)}catch(I){var T=I,x=1}finally{i5(v,T,x)}};return{startVideoIterator:B,getVideoIteratorsCreated:()=>N,seek:async({newTime:E,nonce:P,fps:v,playbackRate:T,isPlaying:x})=>{if(!_)return;if(H!==null&&_0(H)===_0(E))return;let I=H;if(H=E,j()){if(G()-E<1)L.prewarmIteratorForLooping({timeToSeek:W()})}let S=I!==null&&s9({previousTime:I,newTime:E,fps:v,playbackRate:T,isPlaying:x})?"wait":"restart-iterator",u=await _.tryToSatisfySeek(E,{pendingFrameBehavior:S,shouldContinue:()=>!P.isStale()});if(u.type==="satisfied"){await O(u.frame);return}if(P.isStale())return;await B(E,P)},destroy:()=>{if(A(),L.destroy(),_?.destroy(),Y&&J)Y.clearRect(0,0,J.width,J.height);if(z)z.unblock(),z=null;_=null},getVideoFrameIterator:()=>_,drawFrame:O,redrawCurrentFrame:D,getFramesRendered:()=>V}};class E7{tagType;canvas;context;src;logLevel;playbackRate;globalPlaybackRate;audioStreamIndex;sharedAudioContext;audioIteratorManager=null;videoIteratorManager=null;playing=!1;loop=!1;fps;trimBefore;trimAfter;sequenceDurationInFrames;sequenceOffset;totalDuration;debugOverlay=!1;nonceManager;onVideoFrameCallback=null;getEffects;getEffectChainState;initializationPromise=null;premountAwareDelayPlayback;seekPromiseChain=Promise.resolve();constructor({canvas:$,src:J,logLevel:Y,sharedAudioContext:X,loop:Q,trimBefore:Z,trimAfter:K,playbackRate:G,globalPlaybackRate:W,audioStreamIndex:j,fps:U,debugOverlay:q,bufferState:N,isPremounting:_,isPostmounting:V,durationInFrames:z,onVideoFrameCallback:R,playing:H,sequenceOffset:A,credentials:M,requestInit:L,tagType:w,getEffects:O,getEffectChainState:D}){this.canvas=$??null,this.src=J,this.logLevel=Y,this.sharedAudioContext=X,this.playbackRate=G,this.globalPlaybackRate=W,this.loop=Q,this.trimBefore=Z,this.trimAfter=K,this.audioStreamIndex=j,this.fps=U,this.debugOverlay=q,this.premountAwareDelayPlayback=new KZ({bufferState:N,isPremounting:_,isPostmounting:V}),this.sequenceDurationInFrames=z,this.nonceManager=m9(),this.onVideoFrameCallback=R,this.playing=H,this.sequenceOffset=A;let{input:B,cacheKey:C}=g9({src:this.src,credentials:M,requestInit:L});if(this.input=B,this.inputCacheKey=C,this.tagType=w,this.getEffects=O,this.getEffectChainState=D,$){let E=$.getContext("2d",{alpha:!0,desynchronized:!0});if(!E)throw Error("Could not get 2D context from canvas");this.context=E}else this.context=null}input;inputCacheKey;disposed=!1;isDisposalError(){return this.disposed||this.input.disposed===!0}initialize($,J){let Y=this._initialize($,J);return this.initializationPromise=Y,this.seekPromiseChain=Y,Y}getStartTime(){return(this.trimBefore??0)/this.fps}getSequenceEndTimestamp(){return this.sequenceDurationInFrames/this.fps*this.playbackRate+this.getStartTime()}getSequenceDurationInSeconds(){return this.sequenceDurationInFrames/this.fps}getMediaEndTimestamp(){return L9({mediaDurationInSeconds:this.totalDuration,ifNoMediaDuration:"fail",src:this.src,trimAfter:this.trimAfter,trimBefore:this.trimBefore,fps:this.fps})}getLoopSegmentMediaEndTimestamp(){return Math.min(this.getMediaEndTimestamp(),this.getSequenceEndTimestamp())}async _initialize($,J){let Y=[];try{let Z=r5(Y,this.delayPlaybackHandleIfNotPremounting(),0);try{if(this.isDisposalError())return{type:"disposed"};try{await this.input.getFormat()}catch(N){if(this.isDisposalError())return{type:"disposed"};if(O$(N))throw N;return RJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Failed to recognize format for ${this.src}`,N),{type:"unknown-container-format"}}let[K,G,W]=await Promise.all([YZ(this.input),this.input.getPrimaryVideoTrack(),this.input.getAudioTracks()]);if(this.isDisposalError())return{type:"disposed"};this.totalDuration=K;let j=await QZ({videoTrack:G,audioTracks:W,audioStreamIndex:this.audioStreamIndex});if(!G&&!j)return{type:"no-tracks"};if(G&&this.tagType==="video"){if(await G.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+this.src);if(await G.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+this.src);if(!await G.canDecode()){if(G.codec==="prores")return{type:"cannot-decode-prores"};return{type:"cannot-decode"}}if(this.isDisposalError())return{type:"disposed"};this.videoIteratorManager=await o9({videoTrack:G,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,context:this.context,canvas:this.canvas,getOnVideoFrameCallback:()=>this.onVideoFrameCallback,logLevel:this.logLevel,drawDebugOverlay:this.drawDebugOverlay,getLoopSegmentMediaEndTimestamp:()=>this.getLoopSegmentMediaEndTimestamp(),getStartTime:()=>this.getStartTime(),getIsLooping:()=>this.loop,getEffects:this.getEffects,getEffectChainState:this.getEffectChainState})}let U=this.getTrimmedTime($);if(U===null)throw Error("should have asserted that the time is not null");if(j&&this.sharedAudioContext){if(await j.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+this.src);if(await j.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+this.src);if(!await j.canDecode())return{type:"cannot-decode"};if(this.isDisposalError())return{type:"disposed"};this.audioIteratorManager=y9({audioTrack:j,delayPlaybackHandleIfNotPremounting:this.delayPlaybackHandleIfNotPremounting,sharedAudioContext:this.sharedAudioContext,getMediaEndTimestamp:()=>this.getMediaEndTimestamp(),getSequenceEndTimestamp:()=>this.getSequenceEndTimestamp(),getStartTime:()=>this.getStartTime(),initialMuted:J,drawDebugOverlay:this.drawDebugOverlay,initialPlaybackRate:this.playbackRate*this.globalPlaybackRate,getSequenceDurationInSeconds:()=>this.getSequenceDurationInSeconds(),initialTrimBefore:this.trimBefore,initialTrimAfter:this.trimAfter,initialSequenceOffset:this.sequenceOffset,initialSequenceDurationInFrames:this.sequenceDurationInFrames,initialLoop:this.loop,initialFps:this.fps})}let q=this.nonceManager.createAsyncOperation();try{await Promise.all([this.audioIteratorManager?this.audioIteratorManager.startAudioIterator({nonce:q,playbackRate:this.playbackRate*this.globalPlaybackRate,startFromSecond:U,unloopedStartFromSecond:$,scheduleAudioNode:this.scheduleAudioNode,getTargetTime:this.getTargetTime,logLevel:this.logLevel,loop:this.loop,unscheduleAudioNode:this.sharedAudioContext.unscheduleAudioNode,getAudioContextCurrentTimeMockedInTest:()=>this.sharedAudioContext.audioContext.currentTime}):Promise.resolve(),this.videoIteratorManager?this.videoIteratorManager.startVideoIterator(U,q):Promise.resolve()])}catch(N){if(this.isDisposalError())return{type:"disposed"};RJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to start audio and video iterators",N)}return{type:"success",durationInSeconds:K}}catch(K){let G=K;if(O$(G))return RJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},`[MediaPlayer] Network/CORS error for ${this.src}`,G),{type:"network-error"};throw RJ.Log.error({logLevel:this.logLevel,tag:"@remotion/media"},"[MediaPlayer] Failed to initialize",K),K}}catch(Z){var X=Z,Q=1}finally{i5(Y,X,Q)}}seekToWithQueue=async($,J)=>{let Y=this.nonceManager.createAsyncOperation();await this.seekPromiseChain,this.seekPromiseChain=this.seekToDoNotCallDirectly($,J,Y),await this.seekPromiseChain};async seekTo($){let J=this.getTrimmedTime($);if(J===null)throw Error("should have asserted that the time is not null");await this.seekToWithQueue(J,$)}async seekToDoNotCallDirectly($,J,Y){if(Y.isStale())return;try{await Promise.all([this.videoIteratorManager?.seek({newTime:$,nonce:Y,fps:this.fps,playbackRate:this.playbackRate,isPlaying:this.playing}),this.audioIteratorManager?.seek({newTime:$,unloopedNewTime:J,nonce:Y,playbackRate:this.playbackRate*this.globalPlaybackRate,localPlaybackRate:this.playbackRate,getTargetTime:this.getTargetTime,logLevel:this.logLevel,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,sequenceOffset:this.sequenceOffset,sequenceDurationInFrames:this.sequenceDurationInFrames,fps:this.fps,scheduleAudioNode:this.scheduleAudioNode,getAudioContextCurrentTimeMockedInTest:()=>this.sharedAudioContext.audioContext.currentTime})])}catch(X){if(this.isDisposalError())return;throw X}}play(){if(this.playing)return;this.playing=!0,this.drawDebugOverlay()}delayPlaybackHandleIfNotPremounting=()=>{return this.premountAwareDelayPlayback.createHandle()};pause(){if(!this.playing)return;this.playing=!1,this.drawDebugOverlay()}setMuted($){this.audioIteratorManager?.setMuted($)}setVolume($){if(!this.audioIteratorManager)return;this.audioIteratorManager.setVolume($)}getTrimmedTime($){return B$({unloopedTimeInSeconds:$,playbackRate:this.playbackRate,loop:this.loop,trimBefore:this.trimBefore,trimAfter:this.trimAfter,mediaDurationInSeconds:this.totalDuration??null,fps:this.fps,ifNoMediaDuration:"infinity",src:this.src})}async setTrimBefore($,J){if(this.trimBefore!==$)this.trimBefore=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setTrimAfter($,J){if(this.trimAfter!==$)this.trimAfter=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}setDebugOverlay($){this.debugOverlay=$}async setPlaybackRate($,J){if(this.playbackRate!==$)this.playbackRate=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setGlobalPlaybackRate($,J){if(this.globalPlaybackRate!==$)this.globalPlaybackRate=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setFps($,J){if(this.fps!==$)this.fps=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}setIsPremounting($){this.premountAwareDelayPlayback.setIsPremounting($)}setIsPostmounting($){this.premountAwareDelayPlayback.setIsPostmounting($)}async setLoop($,J){if(this.loop!==$)this.loop=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setSequenceOffset($,J){if(this.sequenceOffset!==$)this.sequenceOffset=$,this.audioIteratorManager?.destroyIterator(),await this.seekTo(J)}async setSequenceDurationInFrames($,J){if(this.sequenceDurationInFrames!==$)this.sequenceDurationInFrames=$,await this.seekTo(J)}async dispose(){if(this.disposed)return;if(this.disposed=!0,this.initializationPromise)try{await this.initializationPromise}catch{}this.nonceManager.createAsyncOperation(),this.videoIteratorManager?.destroy(),this.audioIteratorManager?.destroyIterator(),k9(this.inputCacheKey)}getTargetTime=($,J)=>{if(!this.sharedAudioContext)throw Error("Shared audio context not found");let X=(J-this.sharedAudioContext.audioSyncAnchor.value)*this.globalPlaybackRate-this.sequenceOffset,Q=this.loop?this.audioIteratorManager?.getCurrentAnchor()??null:null,Z=Q?JZ({anchor:Q,unloopedTimeInSeconds:X,playbackRate:this.playbackRate}):this.getTrimmedTime(X);if(Z===null)return null;return($-Z)/(this.playbackRate*this.globalPlaybackRate)};scheduleAudioNode=($,J,Y,X,Q)=>{if(!this.sharedAudioContext)throw Error("Shared audio context not found");let Z=this.getTargetTime(J,this.sharedAudioContext.audioContext.currentTime),K=this.playbackRate*this.globalPlaybackRate;if(Z===null)return{type:"not-started",reason:"no target for"+J.toFixed(3)+","+this.sharedAudioContext.audioContext.currentTime.toFixed(3)};let G=this.getStartTime(),W=E9({mediaTimestamp:J,targetTime:Z,sequenceStartTime:G,combinedPlaybackRate:K,sourceStartOffsetInSeconds:X}),j=C9({sourceDurationInSeconds:Q,sourceOffsetInSeconds:X,offset:W}),U=e5({mediaTimestamp:J,targetTime:Z,sequenceStartTime:G,currentTime:this.sharedAudioContext.audioContext.currentTime});return this.sharedAudioContext.scheduleAudioNode({node:$,mediaTimestamp:J,sourceOffset:X,scheduledTime:U,duration:j,offset:W,originalUnloopedMediaTimestamp:Y})};setVideoFrameCallback($){this.onVideoFrameCallback=$}async redrawVideoEffects(){await this.videoIteratorManager?.redrawCurrentFrame()}drawDebugOverlay=()=>{if(!this.debugOverlay)return;if(this.context&&this.canvas)S9({context:this.context,audioTime:this.sharedAudioContext?.audioContext.currentTime??null,audioContextState:this.sharedAudioContext?.audioContext.state??null,audioSyncAnchor:this.sharedAudioContext?.audioSyncAnchor??null,audioIteratorManager:this.audioIteratorManager,playing:this.playing,videoIteratorManager:this.videoIteratorManager,playbackRate:this.playbackRate*this.globalPlaybackRate})};audioSyncAnchorChanged=()=>{if(!this.audioIteratorManager)return;this.audioIteratorManager.destroyIterator()}}var z8=({onError:$,error:J,disallowFallback:Y,isClientSideRendering:X,clientSideError:Q})=>{let Z=$?.(J);if(X)return["fail",Q];if(Z)return[Z,J];if(Y)return["fail",J];return["fallback",J]},WZ=({mediaPlayerRef:$,mediaPlayerReady:J,currentTimeRef:Y,playing:X,isPlayerBuffering:Q,frame:Z,trimBefore:K,trimAfter:G,effectiveMuted:W,userPreferredVolume:j,playbackRate:U,globalPlaybackRate:q,fps:N,sequenceOffset:_,loop:V,durationInFrames:z,isPremounting:R,isPostmounting:H,currentTime:A,logLevel:M,label:L})=>{let w=r9(b5.SharedAudioContext);n0(()=>{let O=$.current;if(!O)return;if(X&&!Q)O.play();else O.pause()},[Q,X,M,J,Z,$]),n0(()=>{if(!w)return;let{remove:O}=w.audioSyncAnchorEmitter.subscribe((D)=>{if(D==="changed")$.current?.audioSyncAnchorChanged()});return()=>{O()}},[w,$]),n0(()=>{let O=$.current;if(!O||!J)return;O.setTrimBefore(K,Y.current)},[K,J,$,Y]),n0(()=>{let O=$.current;if(!O||!J)return;O.setTrimAfter(G,Y.current)},[G,J,$,Y]),n0(()=>{let O=$.current;if(!O||!J)return;O.setMuted(W)},[W,J,$]),n0(()=>{let O=$.current;if(!O||!J)return;O.setVolume(j)},[j,J,$]),n0(()=>{let O=$.current;if(!O||!J)return;O.setPlaybackRate(U,Y.current)},[U,J,$,Y]),n0(()=>{let O=$.current;if(!O||!J)return;O.setGlobalPlaybackRate(q,Y.current)},[q,J,$,Y]),n0(()=>{let O=$.current;if(!O||!J)return;O.setLoop(V,Y.current)},[V,J,$,Y]),n0(()=>{let O=$.current;if(!O||!J)return;O.setSequenceDurationInFrames(z,Y.current)},[z,J,$,Y]),n0(()=>{let O=$.current;if(!O)return;O.setIsPremounting(R)},[R,J,$]),n0(()=>{let O=$.current;if(!O)return;O.setIsPostmounting(H)},[H,J,$]),n0(()=>{let O=$.current;if(!O||!J)return;O.setFps(N,Y.current)},[N,J,$,Y]),n0(()=>{let O=$.current;if(!O||!J)return;O.setSequenceOffset(_,Y.current)},[_,J,$,Y]),n0(()=>{let O=$.current;if(!O||!J)return;O.seekTo(A).catch(()=>{}),b5.Log.trace({logLevel:M,tag:"@remotion/media"},`[${L}] Updating target time to ${A.toFixed(3)}s`)},[A,M,J,L,$])},{useUnsafeVideoConfig:i9,Timeline:a9,SharedAudioContext:t9,usePlayerMutedState:e9,useMediaVolumeState:$Q,useFrameForVolumeProp:JQ,evaluateVolume:YQ,warnAboutTooHighVolume:XQ,usePreload:jZ,SequenceContext:ZQ}=b1,QQ=({src:$,playbackRate:J,logLevel:Y,muted:X,volume:Q,loopVolumeCurveBehavior:Z,loop:K,trimAfter:G,trimBefore:W,name:j,showInTimeline:U,_remotionInternalStack:q,disallowFallbackToHtml5Audio:N,toneFrequency:_,audioStreamIndex:V,fallbackHtml5AudioProps:z,onError:R,credentials:H,requestInit:A,setMediaDurationInSeconds:M,style:L})=>{let w=i9(),O=t5(),D=K1(null),B=K1(W),C=K1(G),[E]=V7(A),[P,v]=V7(!1),[T,x]=V7(!1),[I]=a9.usePlayingState(),{playbackRate:S}=b1.usePlaybackRate(),u=N7(t9),r=M9(),[m]=e9(),[c]=$Q(),s=JQ(Z??"repeat"),X0=YQ({frame:s,volume:Q,mediaVolume:c});if(XQ(X0),!w)throw Error("No video config found");if(!$)throw TypeError("No `src` was passed to <NewAudioForPreview>.");let e=O/w.fps,Q0=K1(e);Q0.current=e;let i=jZ($),j0=N7(ZQ),o=Boolean(j0?.premounting),G0=Boolean(j0?.postmounting),$0=(j0?.absoluteFrom??0)/w.fps,a=N7(b1.BufferingContextReact);if(!a)throw Error("useMediaPlayback must be used inside a <BufferingContext>");let J0=X||m||X0<=0,I0=b1.useIsPlayerBuffering(a),p0=K1(I&&!I0),H0=K1(o),F0=K1(G0),C0=K1(S),y0=K1(J),J1=K1(J0),z0=K1(w.durationInFrames),s0=K1($0);if(WZ({mediaPlayerRef:D,mediaPlayerReady:P,currentTimeRef:Q0,playing:I,isPlayerBuffering:I0,frame:O,trimBefore:W,trimAfter:G,effectiveMuted:J0,userPreferredVolume:X0,playbackRate:J,globalPlaybackRate:S,fps:w.fps,sequenceOffset:$0,loop:K,durationInFrames:w.durationInFrames,isPremounting:o,isPostmounting:G0,currentTime:e,logLevel:Y,label:"AudioForPreview"}),z9(()=>{if(!u)return;if(!u.audioContext)return;let{audioContext:T0,gainNode:o0,audioSyncAnchor:v1,scheduleAudioNode:x1,unscheduleAudioNode:E0}=u;if(!o0)return;try{let Y0=new E7({src:i,logLevel:Y,sharedAudioContext:{audioContext:T0,gainNode:o0,audioSyncAnchor:v1,scheduleAudioNode:x1,unscheduleAudioNode:E0},loop:K,trimAfter:C.current,trimBefore:B.current,fps:w.fps,canvas:null,playbackRate:y0.current,audioStreamIndex:V??null,debugOverlay:!1,bufferState:r,isPostmounting:F0.current,isPremounting:H0.current,globalPlaybackRate:C0.current,durationInFrames:z0.current,onVideoFrameCallback:null,playing:p0.current,sequenceOffset:s0.current,credentials:H,requestInit:E,tagType:"audio",getEffects:()=>[],getEffectChainState:()=>null});D.current=Y0,Y0.initialize(Q0.current,J1.current).then((R0)=>{if(R0.type==="disposed")return;let g0=($8,h6)=>{let[f6,PJ]=z8({onError:R,error:$8,disallowFallback:N,isClientSideRendering:!1,clientSideError:$8});if(f6==="fail")throw PJ;else b1.Log.warn({logLevel:Y,tag:"@remotion/media"},h6),x(!0)};if(R0.type==="unknown-container-format"){g0(Error(`Unknown container format ${i}.`),`Unknown container format for ${i} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <Html5Audio>`);return}if(R0.type==="network-error"){g0(Error(`Network error fetching ${i}.`),`Network error fetching ${i}, falling back to <Html5Audio>`);return}if(R0.type==="cannot-decode"){g0(Error(`Cannot decode ${i}.`),`Cannot decode ${i}, falling back to <Html5Audio>`);return}if(R0.type==="no-tracks"){g0(Error(`No video or audio tracks found for ${i}.`),`No video or audio tracks found for ${i}, falling back to <Html5Audio>`);return}if(R0.type==="cannot-decode-prores")throw Error(`Encountered ProRes media for ${i}. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`);if(R0.type==="success")v(!0),M(R0.durationInSeconds),b1.Log.trace({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialized successfully")}).catch((R0)=>{let[g0,$8]=z8({onError:R,error:R0,disallowFallback:N,isClientSideRendering:!1,clientSideError:R0});if(g0==="fail")throw $8;else b1.Log.error({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] Failed to initialize MediaPlayer",R0),x(!0)})}catch(Y0){let[R0,g0]=z8({error:Y0,onError:R,disallowFallback:N,isClientSideRendering:!1,clientSideError:Y0});if(R0==="fail")throw g0;b1.Log.error({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] MediaPlayer initialization failed",g0),x(!0)}return()=>{if(D.current)b1.Log.trace({logLevel:Y,tag:"@remotion/media"},"[AudioForPreview] Disposing MediaPlayer"),D.current.dispose(),D.current=null;v(!1),x(!1)}},[i,Y,u,K,w.fps,V,N,r,R,H,E,M]),T&&!N)return UZ(A9,{src:$,muted:X,volume:Q,startFrom:W,endAt:G,playbackRate:J,loopVolumeCurveBehavior:Z,name:j,loop:K,showInTimeline:U,style:L??void 0,_remotionInternalStack:q??void 0,toneFrequency:_,audioStreamIndex:V,pauseWhenBuffering:z?.pauseWhenBuffering,crossOrigin:z?.crossOrigin,...z});return null},qZ=({loop:$=!1,src:J,logLevel:Y,muted:X,name:Q,volume:Z,loopVolumeCurveBehavior:K,playbackRate:G=1,trimAfter:W,trimBefore:j,showInTimeline:U,_remotionInternalStack:q,disallowFallbackToHtml5Audio:N,toneFrequency:_,audioStreamIndex:V,fallbackHtml5AudioProps:z,onError:R,credentials:H,requestInit:A,setMediaDurationInSeconds:M,style:L})=>{let w=jZ(J),O=b1.useLogLevel(),D=t5(),B=F9(),C=D/B.fps;if(!R9(()=>{return B$({unloopedTimeInSeconds:C,playbackRate:G,loop:$,trimBefore:j,trimAfter:W,mediaDurationInSeconds:1/0,fps:B.fps,ifNoMediaDuration:"infinity",src:J})!==null},[C,G,J,W,j,B.fps,$]))return null;if(!M)throw Error("setMediaDurationInSeconds is required");return UZ(QQ,{audioStreamIndex:V,src:w,playbackRate:G,logLevel:Y??O,muted:X??!1,volume:Z??1,loopVolumeCurveBehavior:K??"repeat",loop:$,trimAfter:W,trimBefore:j,name:Q,showInTimeline:U??!0,_remotionInternalStack:q,disallowFallbackToHtml5Audio:N??!1,toneFrequency:_,onError:R,credentials:H,requestInit:A,fallbackHtml5AudioProps:z,setMediaDurationInSeconds:M,style:L})},VQ=()=>{let $=[],J={};return{addFrame:(j)=>{$.push(j.timestamp),J[j.timestamp]=j},clearBeforeThreshold:(j)=>{for(let U of $.slice())if(U+J[U].duration<j){if(U===$[$.length-1])continue;J[U].close(),delete J[U],$.splice($.indexOf(U),1)}},deleteAll:()=>{for(let j of $)J[j].close(),delete J[j];$.length=0},getSamples:(j,U)=>{let q=[];for(let N=0;N<$.length;N++){let _=$[N],V=J[_];if(V.timestamp+V.duration-0.0000000001<=j)continue;if(V.timestamp>=j+U-0.0000000001)break;q.push(V)}return q},getOldestTimestamp:()=>{return $[0]},getNewestTimestamp:()=>{if($.length===0)return null;let j=J[$[$.length-1]];return j.timestamp+j.duration},getOpenTimestamps:()=>{return $}}},_Q=1.5,S5=0.2,h5={},HQ=($,J)=>{if(h5[$])return;h5[$]=!0,VZ.Log.warn({logLevel:J,tag:"@remotion/media"},`Audio from ${$} will need to be read from the beginning. https://www.remotion.dev/docs/media/support#matroska-limitation`)},zQ=({audioSampleSink:$,isMatroska:J,startTimestamp:Y,src:X,actualMatroskaTimestamps:Q,logLevel:Z})=>{let K=$.samples(J?0:Math.max(0,Y-_Q));if(J)HQ(X,Z);let G=null,W=VQ(),j=Date.now(),U=async()=>{j=Date.now();let{value:H,done:A}=await K.next();if(A)return G=W.getNewestTimestamp(),null;let M=Q.getRealTimestamp(H.timestamp);if(M!==null&&M!==H.timestamp)H.setTimestamp(M);return Q.observeTimestamp(H.timestamp),Q.observeTimestamp(H.timestamp+H.duration),W.addFrame(H),H},q=async(H,A)=>{if(j=Date.now(),G!==null&&H>G)return W.clearBeforeThreshold(G-S5),[];let M=W.getSamples(H,A),L=W.getNewestTimestamp();if(L!==null){if(L>=H+A-0.0000000001)return M}while(!0){let w=await U(),O=G===null?H:Math.min(H,G);if(W.clearBeforeThreshold(O-S5),w===null)break;if(w.timestamp+w.duration-0.0000000001<=H)continue;if(w.timestamp>=H+A-0.0000000001)break;M.push(w)}return M},N=()=>{let H=W.getOpenTimestamps();if(H.length>0){let A=H[0],M=H[H.length-1];VZ.Log.verbose({logLevel:Z,tag:"@remotion/media"},"Open audio samples for src",X,`${A.toFixed(3)}...${M.toFixed(3)}`)}},_=()=>{return{count:W.getOpenTimestamps().length,size:W.getOpenTimestamps().reduce((H,A)=>H+A,0)}},V=(H)=>{let A=W.getOldestTimestamp()??Y;if(G!==null&&H>G)return!0;return A<H&&Math.abs(A-H)<10},z=()=>{W.deleteAll(),K.return().then((H)=>{if(H.value)H.value.close()}),G=null},R=Promise.resolve([]);return{src:X,getSamples:(H,A)=>{return R=R.then(()=>q(H,A)),R},waitForCompletion:async()=>{return await R,!0},canSatisfyRequestedTime:V,logOpenFrames:N,getCacheStats:_,getLastUsed:()=>j,prepareForDeletion:z,startTimestamp:Y,clearBeforeThreshold:W.clearBeforeThreshold,getOldestTimestamp:W.getOldestTimestamp,getNewestTimestamp:W.getNewestTimestamp}},RQ=({getTotalCacheStats:$})=>{let J=[],Y=!1,X=({timeInSeconds:_,src:V,audioSampleSink:z,isMatroska:R,actualMatroskaTimestamps:H,logLevel:A})=>{let M=zQ({audioSampleSink:z,isMatroska:R,startTimestamp:_,src:V,actualMatroskaTimestamps:H,logLevel:A});return J.push(M),M},Q=()=>{let _=null,V=null;for(let z of J){let R=z.getLastUsed();if(_===null||R<_)_=R,V=z}return V},Z=()=>{let _=Q();if(_)_.prepareForDeletion(),J.splice(J.indexOf(_),1)},K=(_)=>{let V=new Set;for(let z=0;z<J.length;z++){let R=J[z],H=`${R.src}-${R.getOldestTimestamp()}-${R.getNewestTimestamp()}`;if(V.has(H))R.prepareForDeletion(),J.splice(J.indexOf(R),1),y5.Log.verbose({logLevel:_,tag:"@remotion/media"},`Deleted duplicate iterator for ${R.src}`);V.add(H)}},G=async({src:_,timeInSeconds:V,audioSampleSink:z,isMatroska:R,actualMatroskaTimestamps:H,logLevel:A,maxCacheSize:M})=>{if(Y)throw Error("Media cache has already been disposed");let L=0,w=3;while((await $()).totalSize>M&&L<w)Z(),L++;if((await $()).totalSize>M&&L>=w)y5.Log.warn({logLevel:A,tag:"@remotion/media"},`Audio cache: Exceeded max cache size after ${w} attempts. Still ${(await $()).totalSize} bytes used, target was ${M} bytes.`);for(let O of J)if(O.src===_&&await O.waitForCompletion()&&O.canSatisfyRequestedTime(V))return O;for(let O=0;O<J.length;O++){let D=J[O];if(D.src===_&&D.startTimestamp===V)D.prepareForDeletion(),J.splice(J.indexOf(D),1)}if(K(A),Y)throw Error("Media cache has already been disposed");return X({src:_,timeInSeconds:V,audioSampleSink:z,isMatroska:R,actualMatroskaTimestamps:H,logLevel:A})},W=()=>{let _=0,V=0;for(let z of J){let{count:R,size:H}=z.getCacheStats();_+=R,V+=H}return{count:_,totalSize:V}},j=()=>{for(let _ of J)_.logOpenFrames()},U=()=>{for(let _ of J)_.prepareForDeletion();J.length=0},q=()=>{if(Y)return;Y=!0,U()},N=Promise.resolve(void 0);return{getIterator:({src:_,timeInSeconds:V,audioSampleSink:z,isMatroska:R,actualMatroskaTimestamps:H,logLevel:A,maxCacheSize:M})=>{return N=N.then(()=>G({src:_,timeInSeconds:V,audioSampleSink:z,isMatroska:R,actualMatroskaTimestamps:H,logLevel:A,maxCacheSize:M})),N},getCacheStats:W,getIteratorMostInThePast:Q,logOpenFrames:j,deleteDuplicateIterators:K,clearAll:U,dispose:q}},AJ=null,FQ=()=>{return new OffscreenCanvas(1,1).getContext("webgl2")!==null},LQ=()=>{if(AJ!==null)return AJ;return AJ=FQ(),AJ},wQ=($)=>{let J=[];return{observeTimestamp:(Q)=>{if(!$)return;J.push(Q)},getRealTimestamp:(Q)=>{if(!$)return Q;return J.find((Z)=>Math.abs(Q-Z)<0.001)??null}}},OQ=()=>{return null},BQ=async($)=>{try{return await $.getFormat()}catch(J){if(O$(J))return"network-error";return null}},DQ=($,J,Y,X)=>{let Q=ZZ({credentials:Y,requestInit:X}),Z=new C1({formats:j$,source:new m8($,{getRetryDelay:OQ,...Q?{requestInit:Q}:void 0})});return{promise:(async()=>{let G=await BQ(Z),W=G===QJ||G===KJ,j=async()=>{if(G==="network-error")return"network-error";if(G===null)return"unknown-container-format";let z=await Z.getPrimaryVideoTrack();if(!z)return"no-video-track";if(await z.isLive())throw Error("Live streams are not currently supported by Remotion. Sorry! Source: "+$);if(await z.isRelativeToUnixEpoch())throw Error("Streams with UNIX timestamps are not currently supported by Remotion. Sorry! Source: "+$);if(!await z.canDecode()){if(z.codec==="prores")return"cannot-decode-prores";return"cannot-decode"}let H=new C6(z);if((await new a1(z).getFirstPacket({verifyKeyPackets:!0}))?.sideData.alpha&&!LQ())MQ.Log.warn({logLevel:J,tag:"@remotion/media"},`WebGL2 is not available, using the non-fast CPU path to decode alpha for ${$}.`);return{sampleSink:H}},U=null,q=()=>{if(U)return U;return U=j(),U},N={},_=async(z)=>{if(G===null)return"unknown-container-format";if(G==="network-error")return"network-error";let[R,H]=await Promise.all([Z.getPrimaryVideoTrack(),Z.getAudioTracks()]),A=await QZ({videoTrack:R,audioTracks:H,audioStreamIndex:z});if(!A)return"no-audio-track";if(!await A.canDecode())return"cannot-decode-audio";return{sampleSink:new E6(A)}},V=(z)=>{let R=z===null?-1:z;if(N[R])return N[R];return N[R]=_(z),N[R]};return{getVideo:()=>q(),getAudio:(z)=>V(z),actualMatroskaTimestamps:wQ(W),isMatroska:W,getDuration:()=>{return YZ(Z)}}})(),dispose:()=>Z.dispose()}},CQ=({src:$,credentials:J,requestInit:Y})=>JSON.stringify([$,J,XZ(Y)]),EQ=()=>{let $={},J={},Y=!1;return{getSink:(X,Q,Z,K)=>{if(Y)return Promise.reject(Error("Media cache has already been disposed"));let G=y6(K),W=CQ({src:X,credentials:Z,requestInit:G}),j=$[W];if(!j){AQ.Log.verbose({logLevel:Q,tag:"@remotion/media"},`Sink for ${X} was not found, creating new sink`);let U=DQ(X,Q,Z,G);j=U.promise,$[W]=j,J[W]=U.dispose}return j},dispose:()=>{if(Y)return;Y=!0;let X=null;for(let Q of Object.keys(J))try{J[Q]()}catch(Z){X??=Z}finally{delete J[Q],delete $[Q]}if(X!==null)throw X}}},w7=($)=>{if($.length===0)return"(none)";if($.length===1)return $[0].toFixed(3);return`${$[0].toFixed(3)}...${$[$.length-1].toFixed(3)}`},PQ=3,f5=($)=>{if($.format===null)return $.codedHeight*$.codedWidth*PQ;return $.allocationSize()},bQ=3,g5=async({logLevel:$,src:J,videoSampleSink:Y,initialTimestampRequest:X})=>{let Q=Y.samples(_0(X)),Z={},K=[],G=!1,W=Date.now(),j=0,U=(T)=>{let x=K.indexOf(T);if(x===-1)throw Error(`Frame ${T} not found`);let I=K[x+1];if(I===void 0)return null;return I-T},q=(T)=>{let x=U(T);if(x!==null)return x;if(!G)return null;return Z[T].duration??0},N=(T)=>{return U(T)??Z[T].duration??0},_=(T)=>{j-=f5(Z[T]),K.splice(K.indexOf(T),1),Z[T].close(),delete Z[T]},V=({logLevel:T,timestampInSeconds:x})=>{let I=[];for(let S of K.slice()){if(G){if(S===K[K.length-1])continue}if(!Z[S])continue;let u=q(S);if(u===null)continue;if(S+u<x)_(S),I.push(S)}if(I.length>0)MJ.Log.verbose({logLevel:T,tag:"@remotion/media"},`Deleted ${I.length} frame${I.length===1?"":"s"} ${w7(I)} for src ${J} because it is lower than ${x}. Remaining: ${w7(K)}`)},z=(T)=>{let x=K[K.length-1];if(x===void 0)return!1;if(!Z[x])return!0;if(_0(x)>=_0(T))return!0;let S=q(x);if(S===null)return!1;return _0(x+S)>_0(T)},R=(T,x)=>{if(Z[T.timestamp])_(T.timestamp);Z[T.timestamp]=T,K.push(T.timestamp),j+=f5(T),W=Date.now(),MJ.Log.trace({logLevel:x,tag:"@remotion/media"},`Added frame at ${T.timestamp}sec to bank`)},H=async(T,x,I)=>{while(!z(T)){let S=await Q.next();if(S.value)R(S.value,x);if(S.done){G=!0;break}V({logLevel:$,timestampInSeconds:T-_Z(I)})}W=Date.now()},A=async(T,x)=>{W=Date.now();let I=T;if(G&&_0(I)>_0(K[K.length-1]))I=K[K.length-1];await H(I,$,x);for(let S=K.length-1;S>=0;S--){let u=Z[K[S]];if(!u)return null;if(_0(u.timestamp)<=_0(I)||Math.abs(u.timestamp-I)<=0.001)return u}return Z[K[0]]??null},M=async(T,x)=>{return await A(T,x)!==null},L=()=>{return{size:j,timestamps:K}},w=()=>{return W},O=Promise.resolve(void 0),D=await Q.next();if(!D.value)throw Error("No first frame found");let B=D.value.timestamp;MJ.Log.verbose({logLevel:$,tag:"@remotion/media"},`Creating keyframe bank from ${B}sec`),R(D.value,$);let C=()=>{if(K.length===0)return null;let T=K[0],x=K[K.length-1],I=N(x);return{firstTimestamp:T,lastTimestamp:x+I}};return{getFrameFromTimestamp:(T,x)=>{return O=O.then(()=>A(T,x)),O},prepareForDeletion:(T,x)=>{let I=C();if(I)MJ.Log.verbose({logLevel:T,tag:"@remotion/media"},`Preparing for deletion (${x}) of keyframe bank from ${I?.firstTimestamp}sec to ${I?.lastTimestamp}sec`);let S=0;for(let u of K.slice()){if(!Z[u])continue;_(u),S++}return Q.return(),K.length=0,{framesDeleted:S}},hasTimestampInSecond:(T,x)=>{return O=O.then(()=>M(T,x)),O},addFrame:R,deleteFramesBeforeTimestamp:V,src:J,getOpenFrameCount:L,getLastUsed:w,canSatisfyTimestamp:(T)=>{if(K.length===0)return!1;let x=_0(T),I=_0(K[0]),S=C();if(!S)return!1;let u=_0(K[K.length-1]),r=_0(S.lastTimestamp);if(G&&x>u)return!0;if(x<I)return I===B&&x>=X;if(x-bQ>r)return!1;return!0},getRangeOfTimestamps:C}},TQ=({getTotalCacheStats:$})=>{let J={},Y=!1,X=({src:z,bank:R,logLevel:H})=>{if(Y)return R.prepareForDeletion(H,"media cache was disposed"),!1;return J[z]=J[z]??[],J[z].push(R),!0},Q=(z)=>{let R=0,H=0;for(let A in J)for(let M of J[A]){let{size:L,timestamps:w}=M.getOpenFrameCount();if(R+=w.length,H+=L,L===0)continue;t1.Log.verbose({logLevel:z,tag:"@remotion/media"},`Open frames for src ${A}: ${w7(w)}`)}t1.Log.verbose({logLevel:z,tag:"@remotion/media"},`Video cache stats: ${R} open frames, ${H} bytes`)},Z=()=>{let z=0,R=0;for(let H in J)for(let A of J[H]){let{timestamps:M,size:L}=A.getOpenFrameCount();if(z+=M.length,R+=L,L===0)continue}return{count:z,totalSize:R}},K=()=>{let z=null,R=null,H=0;for(let A in J)for(let M of J[A]){let L=J[A].indexOf(M),w=M.getLastUsed();if(z===null||w<z)z=w,R={src:A,bank:M,index:L};H++}if(!R)throw Error("No keyframe bank found");return{mostInThePastBank:R,numberOfBanks:H}},G=(z)=>{let{mostInThePastBank:{bank:R,src:H,index:A},numberOfBanks:M}=K();if(M<2)return{finish:!0};if(R){let L=R.getRangeOfTimestamps(),{framesDeleted:w}=R.prepareForDeletion(z,"deleted oldest keyframe bank to stay under max cache size");if(J[H].splice(A,1),L)t1.Log.verbose({logLevel:z,tag:"@remotion/media"},`Deleted ${w} frames for src ${H} from ${L?.firstTimestamp}sec to ${L?.lastTimestamp}sec to free up memory.`)}return{finish:!1}},W=(z,R)=>{let H=$(),A=0,M=3;while(H.totalSize>R&&A<M){let{finish:L}=G(z);if(L)break;t1.Log.verbose({logLevel:z,tag:"@remotion/media"},"Deleted oldest keyframe bank to stay under max cache size",(H.totalSize/1024/1024).toFixed(1),"out of",(R/1024/1024).toFixed(1)),H=$(),A++}if(H.totalSize>R&&A>=M)t1.Log.warn({logLevel:z,tag:"@remotion/media"},`Exceeded max cache size after ${M} attempts. Remaining cache size: ${(H.totalSize/1024/1024).toFixed(1)} MB, target was ${(R/1024/1024).toFixed(1)} MB.`)},j=({timestampInSeconds:z,src:R,logLevel:H,fps:A})=>{let M=z-_Z(A);if(!J[R])return;let L=J[R];for(let w of L){let O=w.getRangeOfTimestamps();if(!O)continue;if(O.lastTimestamp<M){w.prepareForDeletion(H,"cleared before threshold "+M),t1.Log.verbose({logLevel:H,tag:"@remotion/media"},`[Video] Cleared frames for src ${R} from ${O.firstTimestamp}sec to ${O.lastTimestamp}sec`);let D=L.indexOf(w);delete J[R][D]}else w.deleteFramesBeforeTimestamp({timestampInSeconds:M,logLevel:H})}J[R]=J[R].filter((w)=>w!==void 0),Q(H)},U=async({timestamp:z,videoSampleSink:R,src:H,logLevel:A})=>{let L=(J[H]??[])?.find((O)=>O.canSatisfyTimestamp(z));if(!L){t1.Log.trace({logLevel:A,tag:"@remotion/media"},`Creating new keyframe bank for src ${H} at timestamp ${z}`);let O=await g5({videoSampleSink:R,logLevel:A,src:H,initialTimestampRequest:z});if(!X({src:H,bank:O,logLevel:A}))return null;return O}if(L.canSatisfyTimestamp(z))return t1.Log.trace({logLevel:A,tag:"@remotion/media"},`Keyframe bank exists and satisfies timestamp ${z}`),L;t1.Log.verbose({logLevel:A,tag:"@remotion/media"},`Keyframe bank exists but frame at time ${z} does not exist anymore.`),L.prepareForDeletion(A,"already existed but evicted"),J[H]=J[H].filter((O)=>O!==L);let w=await g5({videoSampleSink:R,initialTimestampRequest:z,logLevel:A,src:H});if(!X({src:H,bank:w,logLevel:A}))return null;return w},q=async({timestamp:z,videoSampleSink:R,src:H,logLevel:A,maxCacheSize:M,fps:L})=>{if(Y)return null;return W(A,M),j({timestampInSeconds:z,src:H,logLevel:A,fps:L}),await U({timestamp:z,videoSampleSink:R,src:H,logLevel:A})},N=(z)=>{let R=Object.keys(J);for(let H of R){let A=J[H];for(let M of A)M.prepareForDeletion(z,"clearAll");J[H]=[]}J={}},_=(z)=>{if(Y)return;Y=!0,N(z)},V=Promise.resolve(void 0);return{requestKeyframeBank:({timestamp:z,videoSampleSink:R,src:H,logLevel:A,maxCacheSize:M,fps:L})=>{return V=V.then(()=>q({timestamp:z,videoSampleSink:R,src:H,logLevel:A,maxCacheSize:M,fps:L})),V},getCacheStats:Z,clearAll:N,dispose:_}},_Z=($)=>6/$,HZ=()=>{let $=EQ(),J={keyframe:null,audio:null},Y=()=>{let{keyframe:W,audio:j}=J;if(W===null||j===null)throw Error("Media cache managers have not been initialized");let U=W.getCacheStats(),q=j.getCacheStats();return{count:U.count+q.count,totalSize:U.totalSize+q.totalSize}},X=TQ({getTotalCacheStats:Y}),Q=RQ({getTotalCacheStats:Y});J.keyframe=X,J.audio=Q;let Z=Promise.resolve(void 0),K=Promise.resolve(void 0),G=!1;return{sinkManager:$,keyframeManager:X,audioManager:Q,getTotalCacheStats:Y,isDisposed:()=>G,queueFrameExtraction:(W)=>{let j=Z.then(W);return Z=j.catch(()=>{return}),j},queueAudioExtraction:(W)=>{let j=K.then(W);return K=j.catch(()=>{return}),j},dispose:(W)=>{if(G)return;G=!0;try{X.dispose(W)}finally{try{Q.dispose()}finally{$.dispose()}}}}},zZ=HZ(),RZ=($)=>{let J=NZ.useContext(I6.RenderResourceManagerContext);if(J===null)return zZ;return J.getOrCreateResource({key:"@remotion/media/cache",create:()=>{let Y=HZ();return{resource:Y,dispose:()=>Y.dispose($)}}})},vQ=($)=>{if(typeof window<"u"&&window.remotion_mediaCacheSizeInBytes!==void 0&&window.remotion_mediaCacheSizeInBytes!==null){if(window.remotion_mediaCacheSizeInBytes<251658240)I5(Error(`The minimum value for the "mediaCacheSizeInBytes" prop is 240MB (251658240), got: ${window.remotion_mediaCacheSizeInBytes}`));if(window.remotion_mediaCacheSizeInBytes>20971520000)I5(Error(`The maximum value for the "mediaCacheSizeInBytes" prop is 20GB (20971520000), got: ${window.remotion_mediaCacheSizeInBytes}`));return I6.Log.verbose({logLevel:$,tag:"@remotion/media"},`Using cache size set using "mediaCacheSizeInBytes": ${(window.remotion_mediaCacheSizeInBytes/1024/1024).toFixed(1)} MB`),window.remotion_mediaCacheSizeInBytes}if(typeof window<"u"&&window.remotion_initialMemoryAvailable!==void 0&&window.remotion_initialMemoryAvailable!==null){let J=window.remotion_initialMemoryAvailable/2;if(J<524288000)return I6.Log.verbose({logLevel:$,tag:"@remotion/media"},"Using cache size set based on minimum value of 500MB (which is more than half of the available system memory!)"),524288000;if(J>20971520000)return I6.Log.verbose({logLevel:$,tag:"@remotion/media"},"Using cache size set based on maximum value of 20GB (which is less than half of the available system memory)"),20971520000;return I6.Log.verbose({logLevel:$,tag:"@remotion/media"},`Using cache size set based on available memory (50% of available memory): ${(J/1024/1024).toFixed(1)} MB`),J}return 1e9},FJ=null,xQ=($)=>{if(FJ!==null)return FJ;return FJ=vQ($),FJ},AZ=($)=>{let J=NZ.useContext(I6.MaxMediaCacheSizeContext);if(J===null)return xQ($);return J},MZ=($,J)=>{if(J===1)return;for(let Y=0;Y<$.length;Y++){let X=$[Y]*J;if(X<-32768)$[Y]=-32768;else if(X>32767)$[Y]=32767;else $[Y]=X}},S6=2,R8=()=>{if(typeof window<"u"&&window.remotion_sampleRate)return window.remotion_sampleRate;return 48000},k5=($)=>{if($%1<0.0000001)return Math.floor($);if($%1>0.9999999)return Math.ceil($);return $},IQ=({srcNumberOfChannels:$,sourceChannels:J,destination:Y,targetFrames:X,chunkSize:Q})=>{let Z=(K,G,W)=>{let j=k5(K),U=k5(G),q=Math.floor(j),N=Math.ceil(j),_=j-q,V=U-Math.floor(U),z=Math.floor(U),R=0,H=0;if(_>0){let M=J[q*$+W];R+=M*(1-_),H+=1-_}for(let M=N;M<z;M++){let L=J[M*$+W];R+=L,H+=1}if(V>0){let M=J[z*$+W];R+=M*V,H+=V}return R/H};for(let K=0;K<X;K++){let G=K*Q,W=G+Q;if(S6===$)for(let j=0;j<$;j++)Y[K*$+j]=Z(G,W,j);if($===1){let j=Z(G,W,0);Y[K*2+0]=j,Y[K*2+1]=j}else if($===4){let j=Z(G,W,0),U=Z(G,W,1),q=Z(G,W,2),N=Z(G,W,3),_=0.5*(j+q),V=0.5*(U+N);Y[K*2+0]=_,Y[K*2+1]=V}else if($===6){let j=Z(G,W,0),U=Z(G,W,1),q=Z(G,W,2),N=Z(G,W,3),_=Z(G,W,4),V=Math.sqrt(0.5),z=j+V*(q+N),R=U+V*(q+_);Y[K*2+0]=z,Y[K*2+1]=R}else for(let j=0;j<$;j++)Y[K*S6+j]=Z(G,W,j)}},FZ=({behavior:$,loop:J,assetDurationInSeconds:Y,fps:X,frame:Q,startsAt:Z})=>{if(!J)return Q+Z;if($==="extend")return Q+Z;let K=Math.floor(Y*X)-Z;return Q%K+Z},u5="s16",T1=($)=>{let J=Math.abs($%1);if(J<0.0000001)return $<0?Math.ceil($):Math.floor($);if(J>0.9999999)return $<0?Math.floor($):Math.ceil($);return $},m5=($)=>{let J=T1($);return Math.ceil(J)},yQ=({audioData:$,trimStartInSeconds:J,trimEndInSeconds:Y,playbackRate:X,audioDataTimestamp:Q,isLast:Z})=>{let{numberOfChannels:K,sampleRate:G,numberOfFrames:W}=$,j=G/R8(),U=Math.floor(T1(J*$.sampleRate)),q=W-Y*$.sampleRate-U,N=Z?m5(q):Math.round(q),_=Z?m5(q/j/X):Math.round(q/j/X);if(_===0)throw Error("Cannot resample - the given sample rate would result in less than 1 sample");let V=new Int16Array(K*N);if($.format==="f32"||$.format==="f32-planar"){let L=N*4,w=new ArrayBuffer(K*L);for(let D=0;D<K;D++)$.copyTo(new Float32Array(w,D*L,N),{planeIndex:D,frameOffset:U,frameCount:N,format:"f32-planar"});let O=new AudioData({format:"f32-planar",sampleRate:G,numberOfFrames:N,numberOfChannels:K,timestamp:$.timestamp,data:w});O.copyTo(V,{planeIndex:0,format:u5,frameOffset:0,frameCount:N}),O.close()}else $.copyTo(V,{planeIndex:0,format:u5,frameOffset:U,frameCount:N});let R=new Int16Array(_*S6),H=N/_,A=U/$.sampleRate*1e6;if(_===N&&S6===K&&X===1)return{data:V,numberOfFrames:_,timestamp:Q*1e6+T1(A),durationInMicroSeconds:T1(_/R8()*1e6)};return IQ({srcNumberOfChannels:K,sourceChannels:V,destination:R,targetFrames:_,chunkSize:H}),{data:R,numberOfFrames:_,timestamp:Q*1e6+T1(A),durationInMicroSeconds:T1(_/R8()*1e6)}},SQ=($)=>{let J=0,Y=0,{timestamp:X}=$[0];for(let K of $)J+=K.numberOfFrames,Y+=K.durationInMicroSeconds;let Q=new Int16Array(J*S6),Z=0;for(let K of $)Q.set(K.data,Z),Z+=K.data.length;return{data:Q,numberOfFrames:J,timestamp:T1(X),durationInMicroSeconds:T1(Y)}},hQ=async({src:$,timeInSeconds:J,durationInSeconds:Y,logLevel:X,loop:Q,playbackRate:Z,audioStreamIndex:K,trimBefore:G,trimAfter:W,fps:j,maxCacheSize:U,credentials:q,requestInit:N,mediaCache:_})=>{let{getAudio:V,actualMatroskaTimestamps:z,isMatroska:R,getDuration:H}=await _.sinkManager.getSink($,X,q,N),A=null;if(Q)A=await H();let M=await V(K);if(M==="network-error")return"network-error";if(M==="no-audio-track")return{data:null,durationInSeconds:null};if(M==="cannot-decode-audio")return"cannot-decode";if(M==="unknown-container-format")return"unknown-container-format";let L=B$({loop:Q,mediaDurationInSeconds:A,unloopedTimeInSeconds:J,src:$,trimAfter:W,playbackRate:Z,trimBefore:G,fps:j,ifNoMediaDuration:"fail"});if(L===null)return{data:null,durationInSeconds:A};try{let w=await _.audioManager.getIterator({src:$,timeInSeconds:L,audioSampleSink:M.sampleSink,isMatroska:R,actualMatroskaTimestamps:z,logLevel:X,maxCacheSize:U}),O=Y*Z,D=await w.getSamples(L,O);_.audioManager.logOpenFrames();let B=[];for(let E=0;E<D.length;E++){let P=D[E];if(Math.abs(P.timestamp-(L+O))*P.sampleRate<1)continue;if(P.timestamp+P.duration<=L)continue;let v=E===0,T=E===D.length-1,x=P.toAudioData(),I=0,S=0,u=null;if(v){if(I=T1(L-P.timestamp),I<0){let m=Math.ceil(T1(-I*R8()));u={data:new Int16Array(m*S6),numberOfFrames:m,timestamp:L*1e6,durationInMicroSeconds:m/R8()*1e6},I=0}}if(T)S=Math.max(0,P.timestamp+P.duration-(L+O));let r=yQ({audioData:x,trimStartInSeconds:I,trimEndInSeconds:S,playbackRate:Z,audioDataTimestamp:P.timestamp,isLast:T});if(x.close(),r.numberOfFrames===0)continue;if(u)B.push(u);B.push(r)}if(B.length===0)return{data:null,durationInSeconds:A};return{data:SQ(B),durationInSeconds:A}}catch(w){let O=w;if(O$(O))return"network-error";if(u9(O))return"cannot-decode";throw w}},fQ=($)=>{return $.mediaCache.queueAudioExtraction(()=>hQ($))},kQ=async({src:$,timeInSeconds:J,logLevel:Y,loop:X,trimAfter:Q,trimBefore:Z,playbackRate:K,fps:G,maxCacheSize:W,credentials:j,requestInit:U,mediaCache:q})=>{let N=await q.sinkManager.getSink($,Y,j,U),[_,V]=await Promise.all([N.getVideo(),X?N.getDuration():Promise.resolve(null)]),z=X?V:null;if(_==="no-video-track")throw Error(`No video track found for ${$}`);if(_==="cannot-decode")return{type:"cannot-decode",durationInSeconds:z};if(_==="cannot-decode-prores")return{type:"cannot-decode-prores",durationInSeconds:z};if(_==="unknown-container-format")return{type:"unknown-container-format"};if(_==="network-error")return{type:"network-error"};if(_==="cannot-decode-alpha")return{type:"cannot-decode-alpha",durationInSeconds:z};let R=B$({loop:X,mediaDurationInSeconds:z,unloopedTimeInSeconds:J,src:$,trimAfter:Q,playbackRate:K,trimBefore:Z,fps:G,ifNoMediaDuration:"fail"});if(R===null)return{type:"success",frame:null,rotation:0,durationInSeconds:await N.getDuration()};try{let H=await q.keyframeManager.requestKeyframeBank({videoSampleSink:_.sampleSink,timestamp:R,src:$,logLevel:Y,maxCacheSize:W,fps:G});if(!H)return{type:"success",frame:null,rotation:0,durationInSeconds:await N.getDuration()};let A=await H.getFrameFromTimestamp(R,G),M=A?.rotation??0;return{type:"success",frame:A?.toVideoFrame()??null,rotation:M,durationInSeconds:await N.getDuration()}}catch(H){return gQ.Log.info({logLevel:Y,tag:"@remotion/media"},`Error decoding ${$} at time ${R}: ${H}`,H),{type:"cannot-decode",durationInSeconds:z}}},uQ=($)=>{return $.mediaCache.queueFrameExtraction(()=>kQ($))},mQ=async({frame:$,rotation:J})=>{if(J===0){let G=await createImageBitmap($);return $.close(),G}let Y=J===90||J===270?$.displayHeight:$.displayWidth,X=J===90||J===270?$.displayWidth:$.displayHeight,Q=new OffscreenCanvas(Y,X),Z=Q.getContext("2d");if(!Z)throw Error("Could not get 2d context");if(Q.width=Y,Q.height=X,J===90)Z.translate(Y,0);else if(J===180)Z.translate(Y,X);else if(J===270)Z.translate(0,X);Z.rotate(J*(Math.PI/180)),Z.drawImage($,0,0);let K=await createImageBitmap(Q);return $.close(),K},LZ=async({src:$,timeInSeconds:J,logLevel:Y,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,loop:G,audioStreamIndex:W,trimAfter:j,trimBefore:U,fps:q,maxCacheSize:N,credentials:_,requestInit:V,mediaCache:z})=>{try{let[R,H]=await Promise.all([K?uQ({src:$,timeInSeconds:J,logLevel:Y,loop:G,trimAfter:j,playbackRate:Q,trimBefore:U,fps:q,maxCacheSize:N,credentials:_,requestInit:V,mediaCache:z}):null,Z?fQ({src:$,timeInSeconds:J,durationInSeconds:X,logLevel:Y,loop:G,playbackRate:Q,audioStreamIndex:W,trimAfter:j,fps:q,trimBefore:U,maxCacheSize:N,credentials:_,requestInit:V,mediaCache:z}):null]);if(R?.type==="cannot-decode")return{type:"cannot-decode",durationInSeconds:R.durationInSeconds};if(R?.type==="cannot-decode-prores")return{type:"cannot-decode-prores",durationInSeconds:R.durationInSeconds};if(R?.type==="unknown-container-format")return{type:"unknown-container-format"};if(R?.type==="cannot-decode-alpha")return{type:"cannot-decode-alpha",durationInSeconds:R.durationInSeconds};if(R?.type==="network-error")return{type:"network-error"};if(H==="unknown-container-format")return{type:"unknown-container-format"};if(H==="network-error")return{type:"network-error"};if(H==="cannot-decode")return{type:"cannot-decode",durationInSeconds:R?.type==="success"?R.durationInSeconds:null};return{type:"success",frame:R?.frame?await mQ({frame:R.frame,rotation:R.rotation}):null,audio:H?.data??null,durationInSeconds:H?.durationInSeconds??null}}catch(R){if(O$(R))return{type:"network-error"};throw R}},lQ=($)=>{$.postMessage({type:"main-tab-ready"}),setInterval(()=>{$.postMessage({type:"main-tab-ready"})},300)},pQ=()=>{if(!(typeof window<"u"&&window.remotion_broadcastChannel&&window.remotion_isMainTab))return;window.remotion_broadcastChannel.addEventListener("message",async($)=>{let J=$.data;if(J.type==="request")try{let Y=await LZ({src:J.src,timeInSeconds:J.timeInSeconds,logLevel:J.logLevel,durationInSeconds:J.durationInSeconds,playbackRate:J.playbackRate,includeAudio:J.includeAudio,includeVideo:J.includeVideo,loop:J.loop,audioStreamIndex:J.audioStreamIndex,trimAfter:J.trimAfter,trimBefore:J.trimBefore,fps:J.fps,maxCacheSize:J.maxCacheSize,credentials:J.credentials,requestInit:J.requestInit,mediaCache:zZ});if(Y.type==="cannot-decode"){let W={type:"response-cannot-decode",id:J.id,durationInSeconds:Y.durationInSeconds};window.remotion_broadcastChannel.postMessage(W);return}if(Y.type==="cannot-decode-prores"){let W={type:"response-cannot-decode-prores",id:J.id,durationInSeconds:Y.durationInSeconds};window.remotion_broadcastChannel.postMessage(W);return}if(Y.type==="cannot-decode-alpha"){let W={type:"response-cannot-decode-alpha",id:J.id,durationInSeconds:Y.durationInSeconds};window.remotion_broadcastChannel.postMessage(W);return}if(Y.type==="network-error"){let W={type:"response-network-error",id:J.id};window.remotion_broadcastChannel.postMessage(W);return}if(Y.type==="unknown-container-format"){let W={type:"response-unknown-container-format",id:J.id};window.remotion_broadcastChannel.postMessage(W);return}let{frame:X,audio:Q,durationInSeconds:Z}=Y,K=X?await createImageBitmap(X):null;if(X)X.close();let G={type:"response-success",id:J.id,frame:K,audio:Q,durationInSeconds:Z??null};window.remotion_broadcastChannel.postMessage(G)}catch(Y){let X={type:"response-error",id:J.id,errorStack:Y.stack??"No stack trace"};window.remotion_broadcastChannel.postMessage(X)}else if(J.type==="main-tab-ready");else throw Error("Invalid message: "+JSON.stringify(J))}),lQ(window.remotion_broadcastChannel)},LJ=null,dQ=($)=>{if(LJ)return LJ;return LJ=new Promise((J)=>{let Y=(X)=>{if(X.data.type==="main-tab-ready")J(),$.removeEventListener("message",Y)};$.addEventListener("message",Y)}),LJ};pQ();var wZ=async({src:$,timeInSeconds:J,logLevel:Y,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,isClientSideRendering:G,loop:W,audioStreamIndex:j,trimAfter:U,trimBefore:q,fps:N,maxCacheSize:_,credentials:V,requestInit:z,mediaCache:R})=>{if(G||window.remotion_isMainTab)return LZ({logLevel:Y,src:$,timeInSeconds:J,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,loop:W,audioStreamIndex:j,trimAfter:U,trimBefore:q,fps:N,maxCacheSize:_,credentials:V,requestInit:z,mediaCache:R});await dQ(window.remotion_broadcastChannel);let H=crypto.randomUUID(),A=new Promise((w,O)=>{let D=(B)=>{let C=B.data;if(!C)return;if(C.type==="main-tab-ready")return;if(C.id!==H)return;if(C.type==="response-success"){w({type:"success",frame:C.frame?C.frame:null,audio:C.audio?C.audio:null,durationInSeconds:C.durationInSeconds?C.durationInSeconds:null}),window.remotion_broadcastChannel.removeEventListener("message",D);return}if(C.type==="response-error"){O(C.errorStack),window.remotion_broadcastChannel.removeEventListener("message",D);return}if(C.type==="response-cannot-decode"){w({type:"cannot-decode",durationInSeconds:C.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",D);return}if(C.type==="response-cannot-decode-prores"){w({type:"cannot-decode-prores",durationInSeconds:C.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",D);return}if(C.type==="response-network-error"){w({type:"network-error"}),window.remotion_broadcastChannel.removeEventListener("message",D);return}if(C.type==="response-unknown-container-format"){w({type:"unknown-container-format"}),window.remotion_broadcastChannel.removeEventListener("message",D);return}if(C.type==="response-cannot-decode-alpha"){w({type:"cannot-decode-alpha",durationInSeconds:C.durationInSeconds}),window.remotion_broadcastChannel.removeEventListener("message",D);return}throw Error(`Invalid message: ${JSON.stringify(C)}`)};window.remotion_broadcastChannel.addEventListener("message",D)}),M={type:"request",src:$,timeInSeconds:J,id:H,logLevel:Y,durationInSeconds:X,playbackRate:Q,includeAudio:Z,includeVideo:K,loop:W,audioStreamIndex:j,trimAfter:U,trimBefore:q,fps:N,maxCacheSize:_,credentials:V,requestInit:y6(z)};window.remotion_broadcastChannel.postMessage(M);let L;return Promise.race([A.then((w)=>{return clearTimeout(L),w}),new Promise((w,O)=>{L=setTimeout(()=>{O(Error(`Timeout while extracting frame at time ${J}sec from ${$}`))},Math.max(3000,window.remotion_puppeteerTimeout-5000))})])},nQ=({volume:$,playbackRate:J,src:Y,muted:X,loopVolumeCurveBehavior:Q,delayRenderRetries:Z,delayRenderTimeoutInMilliseconds:K,logLevel:G,loop:W,fallbackHtml5AudioProps:j,audioStreamIndex:U,showInTimeline:q,style:N,name:_,disallowFallbackToHtml5Audio:V,toneFrequency:z,trimAfter:R,trimBefore:H,onError:A,credentials:M,requestInit:L})=>{let w=E1.useLogLevel(),O=G??w,D=jQ(),B=E1.useTimelinePosition(),C=E1.useUnsafeVideoConfig(),{registerRenderAsset:E,unregisterRenderAsset:P}=T5(E1.RenderAssetManager),v=E1.useMediaStartsAt(),T=NQ();if(!C)throw Error("No video config found");if(!Y)throw TypeError("No `src` was passed to <Audio>.");let{fps:x}=C,{delayRender:I,continueRender:S}=qQ(),[u,r]=v5(!1),[m]=v5(L),c=T5(E1.SequenceContext),s=GQ(()=>`media-audio-${UQ(Y)}-${c?.cumulatedFrom}-${c?.relativeFrom}-${c?.durationInFrames}`,[Y,c?.cumulatedFrom,c?.relativeFrom,c?.durationInFrames]),X0=AZ(O),e=RZ(O),Q0=E1.useAudioEnabled();if(KQ(()=>{let i=D/x,j0=1/x,o=(()=>{if(!Q0)return!1;if(X)return!1;return!0})();if(!o)return;if(u)return;let G0=I(`Extracting audio for frame ${D}`,{retries:Z??void 0,timeoutInMilliseconds:K??void 0});return wZ({src:Y,timeInSeconds:i,durationInSeconds:j0,playbackRate:J??1,logLevel:O,includeAudio:o,includeVideo:!1,isClientSideRendering:T.isClientSideRendering,loop:W??!1,audioStreamIndex:U??null,trimAfter:R,trimBefore:H,fps:x,maxCacheSize:X0,credentials:M,requestInit:m,mediaCache:e}).then(($0)=>{if(e.isDisposed())return;let a=(F0,C0,y0)=>{let[J1,z0]=z8({onError:A,error:F0,disallowFallback:V??!1,isClientSideRendering:T.isClientSideRendering,clientSideError:C0});if(J1==="fail")x5(z0);E1.Log.warn({logLevel:O,tag:"@remotion/media"},y0),r(!0)};if($0.type==="unknown-container-format"){a(Error(`Unknown container format ${Y}.`),Error(`Cannot render audio "${Y}": Unknown container format. See supported formats: https://www.remotion.dev/docs/mediabunny/formats`),`Unknown container format for ${Y} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <Html5Audio>`);return}if($0.type==="cannot-decode"){a(Error(`Cannot decode ${Y}.`),Error(`Cannot render audio "${Y}": The audio could not be decoded by the browser.`),`Cannot decode ${Y}, falling back to <Html5Audio>`);return}if($0.type==="cannot-decode-alpha")throw Error(`Cannot decode alpha component for ${Y}, and 'disallowFallbackToHtml5Audio' was set. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`);if($0.type==="cannot-decode-prores")throw Error(`Encountered ProRes media for ${Y}. But this should never happen, since you used the <Audio> tag. Please report this as a bug.`);if($0.type==="network-error"){a(Error(`Network error fetching ${Y}.`),Error(`Cannot render audio "${Y}": Network error while fetching the audio (possibly CORS).`),`Network error fetching ${Y}, falling back to <Html5Audio>`);return}let{audio:J0,durationInSeconds:I0}=$0,p0=FZ({behavior:Q??"repeat",loop:W??!1,assetDurationInSeconds:I0??0,fps:x,frame:D,startsAt:v}),H0=E1.evaluateVolume({volume:$,frame:p0,mediaVolume:1});if(E1.warnAboutTooHighVolume(H0),J0&&H0>0)MZ(J0.data,H0),E({type:"inline-audio",id:s,audio:T.isClientSideRendering?J0.data:Array.from(J0.data),frame:B,timestamp:J0.timestamp,duration:J0.numberOfFrames/R8()*1e6,toneFrequency:z??1});S(G0)}).catch(($0)=>{if(e.isDisposed())return;x5($0)}),()=>{S(G0),P(s)}},[B,S,I,Z,K,V,T.isClientSideRendering,x,D,s,O,W,Q,X,J,E,Y,v,P,$,U,z,R,H,u,X0,Q0,A,M,m,e]),u)return cQ(WQ,{src:Y,playbackRate:J,muted:X,loop:W,volume:$,delayRenderRetries:Z,delayRenderTimeoutInMilliseconds:K,style:N,loopVolumeCurveBehavior:Q,audioStreamIndex:U,useWebAudioApi:j?.useWebAudioApi,onError:j?.onError,toneFrequency:z,acceptableTimeShiftInSeconds:j?.acceptableTimeShiftInSeconds,preservePitch:j?.preservePitch??!0,name:_,showInTimeline:q});return null},{validateMediaProps:sQ}=H8,oQ={src:{type:"asset",default:void 0,description:"Source",keyframable:!1},...H8.baseSchema,...H8.premountSchema,volume:{type:"number",min:0,max:20,step:0.01,default:1,description:"Volume",hiddenFromList:!1},playbackRate:{type:"number",min:0.1,step:0.01,default:1,description:"Playback rate",hiddenFromList:!1,keyframable:!1},loop:{type:"boolean",default:!1,description:"Loop"}},rQ=($)=>{let{name:J,showInTimeline:Y,controls:X,from:Q,durationInFrames:Z,freeze:K,hidden:G,style:W,premountFor:j,postmountFor:U,...q}=$,N=V9(),_=X?H8.getStackForControls(X):null,[V]=H8.useMediaVolumeState(),z=H8.useMediaStartsAt(),R=_9(),H=Math.min(Z??1/0,Math.max(0,R.durationInFrames-(Q??0))),A=H8.useBasicMediaInTimeline({src:$.src,volume:$.volume,playbackRate:$.playbackRate??1,trimBefore:$.trimBefore,trimAfter:$.trimAfter,sequenceDurationInFrames:H,mediaType:"audio",displayName:J??"<Audio>",mediaVolume:V,mediaStartsAt:z,loop:$.loop??!1}),[M,L]=U9(null),w=E5(()=>a5({loop:$.loop??!1,mediaDurationInSeconds:M,playbackRate:$.playbackRate??1,trimAfter:$.trimAfter,trimBefore:$.trimBefore,sequenceDurationInFrames:H,compFps:R.fps}),[$.loop,M,$.playbackRate,$.trimAfter,$.trimBefore,H,R.fps]),O=E5(()=>({type:"audio",data:A}),[A]),{effectivePostmountFor:D,effectivePremountFor:B,freezeFrame:C,isPremountingOrPostmounting:E,postmountingActive:P,premountingActive:v,premountingStyle:T}=H8.usePremounting({from:Q??0,durationInFrames:A.duration,premountFor:j??null,postmountFor:U??null,style:W??null,styleWhilePremounted:null,styleWhilePostmounted:null,hideWhilePremounted:"display-none"});if(typeof $.src!=="string")throw TypeError(`The \`<Audio>\` tag requires a string for \`src\`, but got ${JSON.stringify($.src)} instead.`);if(sQ({playbackRate:$.playbackRate,volume:$.volume},"Audio"),H===0)return null;return wJ(j9,{frame:C,active:E,children:wJ(N9,{layout:"none",from:Q??0,durationInFrames:A.duration,freeze:K,_remotionInternalIsMedia:O,_remotionInternalPremountDisplay:B||null,_remotionInternalPostmountDisplay:D||null,_remotionInternalIsPremounting:v,_remotionInternalIsPostmounting:P,name:J??"<Audio>",_remotionInternalDocumentationLink:J===void 0?"https://www.remotion.dev/docs/media/audio":void 0,controls:X,_remotionInternalLoopDisplay:w,showInTimeline:Y??!0,hidden:G,children:N.isRendering?wJ(nQ,{...q,style:T??void 0}):wJ(qZ,{name:J,...q,style:T,_remotionInternalStack:_,setMediaDurationInSeconds:L})})})},OZ=q9.withSchema({Component:rQ,componentName:"<Audio>",componentIdentity:"dev.remotion.media.Audio",schema:oQ,supportsEffects:!1}),XK=({durationInFrames:$,loop:J,playbackRate:Y,trimAfter:X,trimBefore:Q})=>{if(J||X===void 0)return $;let Z=YK.calculateMediaDuration({trimAfter:X,trimBefore:Q,playbackRate:Y,mediaDurationInFrames:1/0});return Math.min($??1/0,Z)},WK="https://www.remotion.dev/docs/videos/prores",UK=($)=>{return`Cannot decode "${$}": it is encoded with Apple ProRes, which WebCodecs does not support natively. ProRes decoding is not enabled by default. Register the ProRes decoder by calling registerProresDecoder() from "@mediabunny/prores" in your entry point, before registerRoot(). See ${WK}.`};class CJ extends Error{constructor($){super(UK($));this.name="ProResDecoderNotEnabledError"}}var B7=new Map,jK=($,J)=>{let{width:Y,height:X}=J;if(Y===0||X===0)return;let Q=B7.get($);if(!Q||Q.width!==Y||Q.height!==X)Q=new OffscreenCanvas(Y,X),B7.set($,Q);let Z=Q.getContext("2d");if(!Z)return;Z.clearRect(0,0,Y,X),Z.drawImage(J,0,0)},qK=($)=>{return B7.get($)??null},NK=/\bobject-(contain|cover|fill|none|scale-down)\b/,c5=!1,n5=!1,DZ=({style:$,className:J,logLevel:Y})=>{if(!c5&&$?.objectFit)c5=!0,d5.Log.warn({logLevel:Y,tag:"@remotion/media"},"Use the `objectFit` prop instead of the `style` prop.");if(!n5&&J&&NK.test(J))n5=!0,d5.Log.warn({logLevel:Y,tag:"@remotion/media"},"Use the `objectFit` prop instead of `object-*` CSS class names.")},{useUnsafeVideoConfig:VK,Timeline:_K,SharedAudioContext:HK,usePlayerMutedState:zK,useMediaVolumeState:RK,useFrameForVolumeProp:AK,evaluateVolume:MK,warnAboutTooHighVolume:FK,usePreload:s5,SequenceContext:LK,useEffectChainState:wK}=P1,OK=({src:$,style:J,playbackRate:Y,logLevel:X,className:Q,muted:Z,volume:K,loopVolumeCurveBehavior:G,onVideoFrame:W,showInTimeline:j,loop:U,trimAfter:q,trimBefore:N,_remotionInternalStack:_,disallowFallbackToOffthreadVideo:V,fallbackOffthreadVideoProps:z,audioStreamIndex:R,debugOverlay:H,headless:A,onError:M,credentials:L,requestInit:w,objectFit:O,_experimentalInitiallyDrawCachedFrame:D,effects:B,setMediaDurationInSeconds:C,refForOutline:E,...P})=>{let v=s5($),T=b0(null),x=VK(),I=BZ(),S=b0(null),u=b0(N),r=b0(q),m=b0(W),[c]=z7(w),[s,X0]=z7(!1),[e,Q0]=z7(!1),[i]=_K.usePlayingState(),{playbackRate:j0}=P1.usePlaybackRate(),o=H7(HK),G0=KK(),$0=p5((V0)=>{T.current=V0,E.current=V0},[E]),a=p5((V0)=>{E.current=V0},[E]),[J0]=zK(),[I0]=RK(),p0=AK(G),H0=MK({frame:p0,volume:K,mediaVolume:I0});if(!x)throw Error("No video config found");FK(H0);let F0=wK(),C0=b0(B);C0.current=B;let y0=b0(M);y0.current=M;let J1=b0(F0);J1.current=F0;let z0=H7(LK),s0=Boolean(z0?.premounting),T0=Boolean(z0?.postmounting),o0=(z0?.absoluteFrom??0)/x.fps,v1=I/x.fps,x1=b0(v1);x1.current=v1;let E0=s5(v),Y0=H7(P1.BufferingContextReact);if(!Y0)throw Error("useMediaPlayback must be used inside a <BufferingContext>");let R0=Z||J0||H0<=0,g0=P1.useIsPlayerBuffering(Y0),$8=b0(i&&!g0),h6=b0(s0),f6=b0(T0),PJ=b0(j0),EZ=b0(Y),PZ=b0(R0),bZ=b0(x.durationInFrames),TZ=b0(o0),bJ=b0(!1),P7=b0(s0);P7.current=s0,F$(()=>{if(!D)return;let V0=T.current;if(!V0)return;let A1=qK(v);if(!A1)return;V0.width=A1.width,V0.height=A1.height;let L0=V0.getContext("2d",{alpha:!0,desynchronized:!0});if(!L0)return;L0.drawImage(A1,0,0)},[D,v]),F$(()=>{if(!D)return;return()=>{let V0=T.current;if(!V0||!bJ.current||P7.current)return;jK(v,V0)}},[D,v]),ZK(()=>{let V0=o?.audioContext&&o.gainNode?{audioContext:o.audioContext,gainNode:o.gainNode,audioSyncAnchor:o.audioSyncAnchor,scheduleAudioNode:o.scheduleAudioNode,unscheduleAudioNode:o.unscheduleAudioNode}:null;try{let A1=new E7({canvas:T.current,src:E0,logLevel:X,sharedAudioContext:V0,loop:U,trimAfter:r.current,trimBefore:u.current,fps:x.fps,playbackRate:EZ.current,audioStreamIndex:R,debugOverlay:H,bufferState:G0,isPremounting:h6.current,isPostmounting:f6.current,globalPlaybackRate:PJ.current,durationInFrames:bZ.current,onVideoFrameCallback:m.current??null,playing:$8.current,sequenceOffset:TZ.current,credentials:L,requestInit:c,tagType:"video",getEffects:()=>C0.current,getEffectChainState:(L0,W1)=>J1.current?.get(L0,W1)});S.current=A1,A1.initialize(x1.current,PZ.current).then((L0)=>{if(L0.type==="disposed")return;let W1=(g6,xZ)=>{let[IZ,yZ]=z8({onError:y0.current,error:g6,disallowFallback:V,isClientSideRendering:!1,clientSideError:g6});if(IZ==="fail")throw yZ;P1.Log.warn({logLevel:X,tag:"@remotion/media"},xZ),Q0(!0)};if(L0.type==="unknown-container-format"){W1(Error(`Unknown container format ${E0}.`),`Unknown container format for ${E0} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <OffthreadVideo>`);return}if(L0.type==="network-error"){W1(Error(`Network error fetching ${E0}.`),`Network error fetching ${E0}, falling back to <OffthreadVideo>`);return}if(L0.type==="cannot-decode"){W1(Error(`Cannot decode ${E0}.`),`Cannot decode ${E0}, falling back to <OffthreadVideo>`);return}if(L0.type==="cannot-decode-prores")throw new CJ(E0);if(L0.type==="no-tracks"){W1(Error(`No video or audio tracks found for ${E0}.`),`No video or audio tracks found for ${E0}, falling back to <OffthreadVideo>`);return}if(L0.type==="success")X0(!0),C(L0.durationInSeconds),bJ.current=!0}).catch((L0)=>{if(L0 instanceof CJ)throw y0.current?.(L0),L0;let[W1,g6]=z8({onError:y0.current,error:L0,disallowFallback:V,isClientSideRendering:!1,clientSideError:L0});if(W1==="fail")throw g6;P1.Log.error({logLevel:X,tag:"@remotion/media"},"[VideoForPreview] Failed to initialize MediaPlayer",g6),Q0(!0)})}catch(A1){let[L0,W1]=z8({error:A1,onError:y0.current,disallowFallback:V,isClientSideRendering:!1,clientSideError:A1});if(L0==="fail")throw W1;P1.Log.error({logLevel:X,tag:"@remotion/media"},"[VideoForPreview] MediaPlayer initialization failed",W1),Q0(!0)}return()=>{if(S.current)P1.Log.trace({logLevel:X,tag:"@remotion/media"},"[VideoForPreview] Disposing MediaPlayer"),S.current.dispose(),S.current=null;X0(!1),Q0(!1),bJ.current=!1}},[R,G0,H,V,X,U,E0,o,x.fps,L,c,C]),DZ({style:J,className:Q,logLevel:X});let vZ=O7(()=>{return[P1.OBJECTFIT_CONTAIN_CLASS_NAME,Q].filter(P1.truthy).join(" ")},[Q]);WZ({mediaPlayerRef:S,mediaPlayerReady:s,currentTimeRef:x1,playing:i,isPlayerBuffering:g0,frame:I,trimBefore:N,trimAfter:q,effectiveMuted:R0,userPreferredVolume:H0,playbackRate:Y,globalPlaybackRate:j0,fps:x.fps,sequenceOffset:o0,loop:U,durationInFrames:x.durationInFrames,isPremounting:s0,isPostmounting:T0,currentTime:v1,logLevel:X,label:"VideoForPreview"}),F$(()=>{let V0=S.current;if(!V0||!s)return;V0.setDebugOverlay(H)},[H,s]),F$(()=>{let V0=S.current;if(!V0||!s)return;V0.setVideoFrameCallback(W??null)},[W,s]),F$(()=>{let V0=S.current;if(!V0||!s)return;V0.redrawVideoEffects().catch(()=>{})},[B,s,S]);let b7=O7(()=>{return{...J,objectFit:O}},[O,J]);if(e&&!V)return D7(QK,{...P,ref:a,src:v,style:b7,className:Q,muted:Z,volume:K,trimAfter:q,trimBefore:N,playbackRate:Y,loopVolumeCurveBehavior:G,name:"<Html5Video> (fallback)",loop:U,showInTimeline:j,_remotionInternalStack:_??void 0,...z});if(A)return null;return D7("canvas",{...P,ref:$0,style:b7,className:vZ})},BK=($)=>{let J=BZ(),Y=GK(),X=J/Y.fps;if(!O7(()=>{return B$({unloopedTimeInSeconds:X,playbackRate:$.playbackRate,loop:$.loop,trimBefore:$.trimBefore,trimAfter:$.trimAfter,mediaDurationInSeconds:1/0,fps:Y.fps,ifNoMediaDuration:"infinity",src:$.src})!==null},[X,$.loop,$.playbackRate,$.src,Y.fps,$.trimBefore,$.trimAfter]))return null;return D7(OK,{...$})},IK=({volume:$,playbackRate:J,src:Y,muted:X,loopVolumeCurveBehavior:Q,delayRenderRetries:Z,delayRenderTimeoutInMilliseconds:K,onVideoFrame:G,logLevel:W,loop:j,style:U,className:q,fallbackOffthreadVideoProps:N,audioStreamIndex:_,disallowFallbackToOffthreadVideo:V,_remotionInternalStack:z,toneFrequency:R,trimAfterValue:H,trimBeforeValue:A,headless:M,onError:L,credentials:w,requestInit:O,objectFit:D,effects:B,...C})=>{if(!Y)throw TypeError("No `src` was passed to <Video>.");let E=bK(),P=l0.useTimelinePosition(),{fps:v}=xK(),{registerRenderAsset:T,unregisterRenderAsset:x}=o5(l0.RenderAssetManager),I=l0.useMediaStartsAt(),S=o5(l0.SequenceContext),u=R7(()=>`media-video-${PK(Y)}-${S?.cumulatedFrom}-${S?.relativeFrom}-${S?.durationInFrames}`,[Y,S?.cumulatedFrom,S?.relativeFrom,S?.durationInFrames]),r=vK(),{delayRender:m,continueRender:c,cancelRender:s}=TK(),X0=CK(null),[e,Q0]=A7(!1),[i]=A7(O),j0=l0.useAudioEnabled(),o=l0.useVideoEnabled(),G0=AZ(W),$0=RZ(W),a=l0.useEffectChainState(),[J0,I0]=A7(null);if(J0)throw J0;DK(()=>{if(!X0.current&&!M)return;if(e)return;if(!X0.current?.getContext&&!M)return I0(Error("Canvas does not have .getContext() method available. This could be because <Video> was mounted inside an <svg> tag."));let F0=E/v,C0=1/v,y0=m(`Extracting frame at time ${F0} from ${Y}`,{retries:Z??void 0,timeoutInMilliseconds:K??void 0}),J1=(()=>{if(!j0)return!1;if(X)return!1;return!0})();return wZ({src:Y,timeInSeconds:F0,durationInSeconds:C0,playbackRate:J,logLevel:W,includeAudio:J1,includeVideo:o,isClientSideRendering:r.isClientSideRendering,loop:j,audioStreamIndex:_,trimAfter:H,trimBefore:A,fps:v,maxCacheSize:G0,credentials:w,requestInit:i,mediaCache:$0}).then(async(z0)=>{if($0.isDisposed()){if(z0.type==="success")z0.frame?.close();return}let s0=(Y0,R0,g0,$8)=>{if(r.isClientSideRendering){s(R0);return}let[h6,f6]=z8({onError:L,error:Y0,disallowFallback:V,isClientSideRendering:r.isClientSideRendering,clientSideError:Y0});if(h6==="fail"){s(f6);return}if(window.remotion_isMainTab)l0.Log.warn({logLevel:W,tag:"@remotion/media"},g0);Q0({durationInSeconds:$8})};if(z0.type==="unknown-container-format"){s0(Error(`Unknown container format ${Y}.`),Error(`Cannot render video "${Y}": Unknown container format. See supported formats: https://www.remotion.dev/docs/mediabunny/formats`),`Unknown container format for ${Y} (Supported formats: https://www.remotion.dev/docs/mediabunny/formats), falling back to <OffthreadVideo>`,null);return}if(z0.type==="cannot-decode"){s0(Error(`Cannot decode ${Y}.`),Error(`Cannot render video "${Y}": The video could not be decoded by the browser.`),`Cannot decode ${Y}, falling back to <OffthreadVideo>`,z0.durationInSeconds);return}if(z0.type==="cannot-decode-prores"){let Y0=new CJ(Y);L?.(Y0),s(Y0);return}if(z0.type==="cannot-decode-alpha"){s0(Error(`Cannot decode alpha component for ${Y}.`),Error(`Cannot render video "${Y}": The alpha channel could not be decoded by the browser.`),`Cannot decode alpha component for ${Y}, falling back to <OffthreadVideo>`,z0.durationInSeconds);return}if(z0.type==="network-error"){s0(Error(`Network error fetching ${Y}.`),Error(`Cannot render video "${Y}": Network error while fetching the video (possibly CORS).`),`Network error fetching ${Y} (no CORS?), falling back to <OffthreadVideo>`,null);return}let{frame:T0,audio:o0,durationInSeconds:v1}=z0;if(T0){G?.(T0);let Y0=X0.current?.getContext("2d",{alpha:!0});if(Y0){if(Y0.canvas.width=T0.width,Y0.canvas.height=T0.height,Y0.canvas.style.aspectRatio=`${Y0.canvas.width} / ${Y0.canvas.height}`,Y0.drawImage(T0,0,0),B.length>0){if(!await l0.runEffectChain({state:a.get(T0.width,T0.height),source:Y0.canvas,effects:B,output:Y0.canvas,width:T0.width,height:T0.height})||$0.isDisposed()){T0.close();return}}}T0.close()}else if(o){let Y0=X0.current?.getContext("2d",{alpha:!0});if(Y0)Y0.clearRect(0,0,Y0.canvas.width,Y0.canvas.height)}let x1=FZ({behavior:Q,loop:j,assetDurationInSeconds:v1??0,fps:v,frame:E,startsAt:I}),E0=l0.evaluateVolume({volume:$,frame:x1,mediaVolume:1});if(l0.warnAboutTooHighVolume(E0),o0&&E0>0)MZ(o0.data,E0),T({type:"inline-audio",id:u,audio:r.isClientSideRendering?o0.data:Array.from(o0.data),frame:P,timestamp:o0.timestamp,duration:o0.numberOfFrames/R8()*1e6,toneFrequency:R});c(y0)}).catch((z0)=>{if($0.isDisposed())return;s(z0)}),()=>{c(y0),x(u)}},[P,c,m,Z,K,r.isClientSideRendering,v,E,u,W,j,Q,X,G,J,T,Y,I,x,$,e,_,V,R,H,A,j0,o,G0,s,M,L,w,a,B,i,$0]),DZ({style:U,className:q,logLevel:W});let p0=R7(()=>{return[l0.OBJECTFIT_CONTAIN_CLASS_NAME,q].filter(l0.truthy).join(" ")},[q]),H0=R7(()=>{return{...U,objectFit:D}},[D,U]);if(e){let F0=M7(l0.InnerOffthreadVideo,{...C,src:Y,playbackRate:J??1,muted:X??!1,acceptableTimeShiftInSeconds:N?.acceptableTimeShiftInSeconds,loopVolumeCurveBehavior:Q??"repeat",delayRenderRetries:Z??void 0,delayRenderTimeoutInMilliseconds:K??void 0,name:"Fallback to <OffthreadVideo>",style:H0,allowAmplificationDuringRender:!0,transparent:N?.transparent??!0,toneMapped:N?.toneMapped??!0,audioStreamIndex:_??0,className:q,onVideoFrame:G,volume:$,id:u,onError:N?.onError,toneFrequency:R,showInTimeline:!1,crossOrigin:N?.crossOrigin,onAutoPlayError:N?.onAutoPlayError??null,pauseWhenBuffering:N?.pauseWhenBuffering??!1,trimAfter:H,trimBefore:A,useWebAudioApi:N?.useWebAudioApi??!1,preservePitch:N?.preservePitch??!0,startFrom:void 0,endAt:void 0,_remotionInternalStack:z,_remotionInternalNativeLoopPassed:!1});if(j){if(!e.durationInSeconds){let C0=Error(`Cannot render video ${Y}: @remotion/media was unable to render, and fell back to <OffthreadVideo>. Also, "loop" was set, but <OffthreadVideo> does not support looping and @remotion/media could also not determine the duration of the video.`);throw s(C0),C0}return M7(EK,{layout:"none",durationInFrames:l0.calculateMediaDuration({trimAfter:H,mediaDurationInFrames:e.durationInSeconds*v,playbackRate:J,trimBefore:A}),children:F0})}return F0}if(M)return null;return M7("canvas",{...C,ref:X0,style:H0,className:p0})},{validateMediaTrimProps:yK,resolveTrimProps:SK,validateMediaProps:hK,useCropStyle:fK}=G1,gK={src:{type:"asset",default:void 0,description:"Source",keyframable:!1},...G1.baseSchema,...G1.premountSchema,volume:{type:"number",min:0,max:20,step:0.01,default:1,description:"Volume",hiddenFromList:!1},playbackRate:{type:"number",min:0.1,step:0.01,default:1,description:"Playback rate",hiddenFromList:!1,keyframable:!1},muted:{type:"boolean",default:!1,description:"Muted"},loop:{type:"boolean",default:!1,description:"Loop"},...G1.transformSchema,...L$.backgroundSchema,...L$.borderSchema,...L$.borderRadiusSchema,...L$.cropSchema},kK=({src:$,audioStreamIndex:J,className:Y,delayRenderRetries:X,delayRenderTimeoutInMilliseconds:Q,disallowFallbackToOffthreadVideo:Z,fallbackOffthreadVideoProps:K,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,onVideoFrame:q,playbackRate:N,style:_,trimAfter:V,trimBefore:z,volume:R,_remotionInternalStack:H,toneFrequency:A,showInTimeline:M,debugOverlay:L,headless:w,onError:O,credentials:D,requestInit:B,controls:C,objectFit:E,_experimentalInitiallyDrawCachedFrame:P,effects:v,setMediaDurationInSeconds:T,refForOutline:x,...I})=>{let S=$K();if(typeof $!=="string")throw TypeError(`The \`<Video>\` tag requires a string for \`src\`, but got ${JSON.stringify($)} instead.`);yK({startFrom:void 0,endAt:void 0,trimBefore:z,trimAfter:V});let{trimBeforeValue:u,trimAfterValue:r}=SK({startFrom:void 0,endAt:void 0,trimBefore:z,trimAfter:V});if(hK({playbackRate:N,volume:R},"Video"),S.isRendering)return w$(IK,{...I,audioStreamIndex:J??0,className:Y,delayRenderRetries:X??null,delayRenderTimeoutInMilliseconds:Q??null,disallowFallbackToOffthreadVideo:Z??!1,fallbackOffthreadVideoProps:K,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,onVideoFrame:q,playbackRate:N,src:$,_remotionInternalStack:H,style:_,volume:R,toneFrequency:A,trimAfterValue:r,trimBeforeValue:u,headless:w,onError:O,credentials:D,requestInit:B,objectFit:E,effects:v});return w$(BK,{...I,setMediaDurationInSeconds:T,audioStreamIndex:J??0,className:Y,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,onVideoFrame:q,playbackRate:N,src:$,style:_,volume:R,showInTimeline:M,trimAfter:r,trimBefore:u,_remotionInternalStack:H??null,disallowFallbackToOffthreadVideo:Z,fallbackOffthreadVideoProps:K,debugOverlay:L??!1,headless:w??!1,onError:O,credentials:D,requestInit:B,controls:C,objectFit:E,effects:v,_experimentalInitiallyDrawCachedFrame:P,refForOutline:x})},uK=({src:$,audioStreamIndex:J,className:Y,delayRenderRetries:X,delayRenderTimeoutInMilliseconds:Q,disallowFallbackToOffthreadVideo:Z,fallbackOffthreadVideoProps:K,logLevel:G,loop:W,loopVolumeCurveBehavior:j,muted:U,name:q,onVideoFrame:N,playbackRate:_,showInTimeline:V,style:z,trimAfter:R,trimBefore:H,volume:A,toneFrequency:M,debugOverlay:L,headless:w,onError:O,credentials:D,requestInit:B,controls:C,objectFit:E,_experimentalInitiallyDrawCachedFrame:P,effects:v,durationInFrames:T,from:x,freeze:I,hidden:S,premountFor:u,postmountFor:r,styleWhilePremounted:m,styleWhilePostmounted:c,cropLeft:s,cropRight:X0,cropTop:e,cropBottom:Q0,...i})=>{let j0=C?G1.getStackForControls(C)??void 0:void 0,o=G1.useLogLevel(),[G0]=G1.useMediaVolumeState(),$0=G1.useMediaStartsAt(),a=JK(),J0=Math.min(T??1/0,Math.max(0,a.durationInFrames-(x??0))),I0=XK({durationInFrames:T,loop:W??!1,playbackRate:_??1,trimAfter:R,trimBefore:H}),p0=G1.useBasicMediaInTimeline({src:$,volume:A,playbackRate:_??1,trimBefore:H,trimAfter:R,sequenceDurationInFrames:J0,mediaType:"video",displayName:q??"<Video>",mediaVolume:G0,mediaStartsAt:$0,loop:W??!1}),[H0,F0]=aQ(null),C0=l5(()=>a5({loop:W??!1,mediaDurationInSeconds:H0,playbackRate:_??1,trimAfter:R,trimBefore:H,sequenceDurationInFrames:J0,compFps:a.fps}),[W,H0,_,R,H,J0,a.fps]),y0=l5(()=>({type:"video",data:p0}),[p0]),J1=G1.useMemoizedEffects({effects:v??[],overrideId:C?.overrideId??null}),z0=G1.useMemoizedEffectDefinitions(v??[]),s0=iQ.useRef(null),{effectivePostmountFor:T0,effectivePremountFor:o0,freezeFrame:v1,isPremountingOrPostmounting:x1,postmountingActive:E0,premountingActive:Y0,premountingStyle:R0}=G1.usePremounting({from:x??0,durationInFrames:I0??1/0,premountFor:u??null,postmountFor:r??null,style:z??null,styleWhilePremounted:m??null,styleWhilePostmounted:c??null,hideWhilePremounted:"display-none"}),g0=fK({cropLeft:s,cropRight:X0,cropTop:e,cropBottom:Q0,style:R0,componentName:"<Video />"});if(J0===0)return null;return w$(tQ,{frame:v1,active:x1,children:w$(eQ,{layout:"none",from:x??0,durationInFrames:I0,freeze:I,_remotionInternalIsMedia:y0,_remotionInternalPremountDisplay:o0||null,_remotionInternalPostmountDisplay:T0||null,_remotionInternalIsPremounting:Y0,_remotionInternalIsPostmounting:E0,name:q??"<Video>",_remotionInternalDocumentationLink:q===void 0?"https://www.remotion.dev/docs/media/video":void 0,controls:C,_remotionInternalLoopDisplay:C0,_remotionInternalEffects:z0,outlineRef:s0,showInTimeline:V??!0,hidden:S,children:w$(kK,{...i,audioStreamIndex:J??0,className:Y,delayRenderRetries:X??null,delayRenderTimeoutInMilliseconds:Q??null,disallowFallbackToOffthreadVideo:Z??!1,fallbackOffthreadVideoProps:K??{},logLevel:G??o,loop:W??!1,loopVolumeCurveBehavior:j??"repeat",muted:U??!1,onVideoFrame:N,playbackRate:_??1,showInTimeline:V??!0,src:$,style:g0??{},trimAfter:R,trimBefore:H,volume:A??1,toneFrequency:M??1,_remotionInternalStack:j0,debugOverlay:L??!1,headless:w??!1,onError:O,credentials:D,requestInit:B,controls:C,objectFit:E??"contain",_experimentalInitiallyDrawCachedFrame:P??!1,effects:J1,setMediaDurationInSeconds:F0,refForOutline:s0})})})},CZ=L$.withSchema({Component:uK,componentName:"<Video>",componentIdentity:"dev.remotion.media.Video",schema:gK,supportsEffects:!0}),mK=OZ,lK=CZ;var{Audio:yH,AudioForPreview:SH,Video:hH,experimental_Audio:fH,experimental_Video:gH,getTargetSampleRate:kH}=EJ;var mH=EJ;export{kH as getTargetSampleRate,gH as experimental_Video,fH as experimental_Audio,mH as default,hH as Video,SH as AudioForPreview,yH as Audio};
|