@1agh/maude 0.39.1 → 0.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/apps/studio/ai-banner.tsx +2 -2
- package/apps/studio/annotations-context-toolbar.tsx +44 -1
- package/apps/studio/annotations-layer.tsx +306 -5
- package/apps/studio/annotations-model.ts +107 -6
- package/apps/studio/api.ts +1316 -67
- package/apps/studio/artboard-marquee.tsx +1 -1
- package/apps/studio/bin/_canvas-rects-playwright.mjs +55 -0
- package/apps/studio/bin/_canvas-rects-static.mjs +166 -0
- package/apps/studio/bin/_fetch-asset.mjs +556 -0
- package/apps/studio/bin/_html-playwright.mjs +9 -1
- package/apps/studio/bin/_pdf-playwright.mjs +8 -1
- package/apps/studio/bin/_png-playwright.mjs +8 -1
- package/apps/studio/bin/_pw-launch.mjs +54 -0
- package/apps/studio/bin/_svg-playwright.mjs +8 -1
- package/apps/studio/bin/_video-playwright.mjs +452 -0
- package/apps/studio/bin/annotate.mjs +576 -34
- package/apps/studio/bin/canvas-rects.sh +152 -0
- package/apps/studio/bin/fetch-asset.sh +34 -0
- package/apps/studio/bin/prep.sh +8 -1
- package/apps/studio/bin/read-annotations.mjs +138 -7
- package/apps/studio/bin/smoke.sh +42 -6
- package/apps/studio/build.ts +21 -0
- package/apps/studio/canvas-comment-mount.tsx +138 -4
- package/apps/studio/canvas-edit.ts +2625 -111
- package/apps/studio/canvas-lib.tsx +238 -2
- package/apps/studio/canvas-list-watch.ts +6 -2
- package/apps/studio/canvas-shell.tsx +514 -20
- package/apps/studio/client/app.jsx +2480 -52
- package/apps/studio/client/comments-overlay.css +130 -126
- package/apps/studio/client/github.js +15 -0
- package/apps/studio/client/panels/TimelinePanel.jsx +860 -0
- package/apps/studio/client/panels/timeline-parse.js +229 -0
- package/apps/studio/client/panels/timeline-snap.js +55 -0
- package/apps/studio/client/styles/3-shell-maude.css +155 -0
- package/apps/studio/comments-overlay.tsx +148 -41
- package/apps/studio/config.schema.json +14 -0
- package/apps/studio/context-menu.tsx +16 -6
- package/apps/studio/context.ts +113 -1
- package/apps/studio/contextual-toolbar.tsx +262 -4
- package/apps/studio/cursors-overlay.tsx +4 -4
- package/apps/studio/dist/client.bundle.js +89 -17
- package/apps/studio/dist/comment-mount.js +59 -1
- package/apps/studio/dist/runtime/.min-sizes.json +11 -1
- package/apps/studio/dist/runtime/@remotion_media.js +491 -0
- package/apps/studio/dist/runtime/@remotion_player.js +56 -0
- package/apps/studio/dist/runtime/@remotion_transitions.js +300 -0
- package/apps/studio/dist/runtime/@remotion_transitions_clock-wipe.js +1 -0
- package/apps/studio/dist/runtime/@remotion_transitions_fade.js +1 -0
- package/apps/studio/dist/runtime/@remotion_transitions_flip.js +1 -0
- package/apps/studio/dist/runtime/@remotion_transitions_none.js +1 -0
- package/apps/studio/dist/runtime/@remotion_transitions_slide.js +1 -0
- package/apps/studio/dist/runtime/@remotion_transitions_wipe.js +1 -0
- package/apps/studio/dist/runtime/REMOTION-LICENSE.md +28 -0
- package/apps/studio/dist/runtime/remotion.js +42 -0
- package/apps/studio/dist/styles.css +1 -1
- package/apps/studio/dom-selection.ts +127 -1
- package/apps/studio/drag-state.ts +24 -0
- package/apps/studio/equal-spacing-detector.ts +205 -0
- package/apps/studio/export-dialog.tsx +1 -1
- package/apps/studio/exporters/_browser-bundles.ts +117 -0
- package/apps/studio/exporters/_runtime.ts +69 -0
- package/apps/studio/exporters/html.ts +4 -3
- package/apps/studio/exporters/index.ts +28 -2
- package/apps/studio/exporters/pdf.ts +4 -3
- package/apps/studio/exporters/png.ts +5 -3
- package/apps/studio/exporters/pptx.ts +6 -4
- package/apps/studio/exporters/svg.ts +9 -5
- package/apps/studio/exporters/video-encode-lib.ts +200 -0
- package/apps/studio/exporters/video-render-lib.ts +108 -0
- package/apps/studio/exporters/video.ts +184 -0
- package/apps/studio/history.ts +47 -1
- package/apps/studio/http.ts +758 -27
- package/apps/studio/input-router.tsx +19 -1
- package/apps/studio/marquee-overlay.tsx +1 -1
- package/apps/studio/measure-overlay.tsx +241 -0
- package/apps/studio/participants-chrome.tsx +3 -3
- package/apps/studio/runtime-bundle.ts +30 -0
- package/apps/studio/server.ts +34 -9
- package/apps/studio/sizing-mode.ts +117 -0
- package/apps/studio/spacing-handles.ts +166 -0
- package/apps/studio/test/annotate-write.test.ts +890 -0
- package/apps/studio/test/annotations-roundtrip.test.ts +47 -0
- package/apps/studio/test/camera-reveal.test.tsx +173 -0
- package/apps/studio/test/canvas-create-api.test.ts +76 -0
- package/apps/studio/test/canvas-edit.test.ts +140 -0
- package/apps/studio/test/canvas-list-watch.test.ts +49 -0
- package/apps/studio/test/canvas-media-drop.test.ts +30 -1
- package/apps/studio/test/canvas-origin-gate.test.ts +54 -0
- package/apps/studio/test/canvas-rects.test.ts +198 -0
- package/apps/studio/test/clip-addressing.test.ts +732 -0
- package/apps/studio/test/comments-overlay.test.ts +117 -0
- package/apps/studio/test/config-reload.test.ts +230 -0
- package/apps/studio/test/dns-rebinding-guard.test.ts +74 -0
- package/apps/studio/test/dom-selection.test.ts +130 -0
- package/apps/studio/test/edit-css-occurrence.test.ts +81 -0
- package/apps/studio/test/edit-persistence.test.ts +91 -0
- package/apps/studio/test/edit-scope-api.test.ts +115 -0
- package/apps/studio/test/element-resize.test.ts +136 -0
- package/apps/studio/test/element-structural-api.test.ts +360 -0
- package/apps/studio/test/element-structural-edit.test.ts +233 -0
- package/apps/studio/test/equal-spacing-detector.test.ts +165 -1
- package/apps/studio/test/exporters/runtime.test.ts +59 -0
- package/apps/studio/test/file-lock.test.ts +84 -0
- package/apps/studio/test/fixtures/video-comp-fixture.tsx +82 -0
- package/apps/studio/test/history-rollback.test.ts +26 -0
- package/apps/studio/test/knob-props-authored.test.ts +87 -0
- package/apps/studio/test/read-annotations.test.ts +154 -0
- package/apps/studio/test/sizing-mode.test.ts +102 -0
- package/apps/studio/test/spacing-handles.test.ts +138 -0
- package/apps/studio/test/specimen-select.test.ts +88 -0
- package/apps/studio/test/timeline-parse.test.ts +127 -0
- package/apps/studio/test/timeline-snap.test.ts +85 -0
- package/apps/studio/test/tool-palette-insert-anchor.test.ts +84 -0
- package/apps/studio/test/undo-sequence-byte-compare.test.ts +211 -0
- package/apps/studio/test/video-asset.test.ts +163 -0
- package/apps/studio/test/video-comp-fixture.test.ts +50 -0
- package/apps/studio/test/video-comp.test.ts +168 -0
- package/apps/studio/test/video-render-bridge.test.ts +149 -0
- package/apps/studio/tool-palette.tsx +122 -2
- package/apps/studio/undo-hud.tsx +2 -2
- package/apps/studio/use-annotation-resize.tsx +6 -3
- package/apps/studio/use-canvas-media-drop.tsx +66 -4
- package/apps/studio/use-element-resize.tsx +732 -0
- package/apps/studio/use-keyboard-discipline.tsx +205 -15
- package/apps/studio/use-selection-set.tsx +14 -0
- package/apps/studio/use-spacing-handles.tsx +388 -0
- package/apps/studio/video-comp.tsx +444 -0
- package/apps/studio/whats-new.json +55 -0
- package/apps/studio/ws.ts +5 -0
- package/cli/commands/design.mjs +6 -1
- package/cli/commands/design.test.mjs +49 -1
- package/cli/lib/fetch-asset.test.mjs +213 -0
- package/package.json +8 -8
- package/plugins/design/dependencies.json +10 -2
- package/plugins/design/templates/_shell.html +25 -2
- package/plugins/design/templates/design-system-inspiration/_MAPPING.md +1 -1
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
var PZ=Object.defineProperty;var bZ=($,J)=>{for(var Y in J)PZ($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:(X)=>J[Y]=()=>X})};var LJ={};bZ(LJ,{getTargetSampleRate:()=>j8,experimental_Video:()=>BK,experimental_Audio:()=>OK,Video:()=>D7,AudioForPreview:()=>UZ,Audio:()=>B7});import{useMemo as C5,useState as X9}from"react";import{Internals as P6,Interactive as Z9,Sequence as Q9,useRemotionEnvironment as K9,useVideoConfig as G9}from"remotion";import{Internals as U9}from"remotion";import{useContext as Z7,useEffect as W9,useMemo as j9,useRef as i0,useState as Q7}from"react";import{Internals as F1,Audio as q9,useBufferState as N9,useCurrentFrame as t5,useVideoConfig as V9}from"remotion";import{Internals as H7}from"remotion";/*!
|
|
2
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
3
|
+
*
|
|
4
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
5
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
|
+
*/function L($){if(!$)throw Error("Assertion failed.")}var s1=($)=>{let J=($%360+360)%360;if(J===0||J===90||J===180||J===270)return J;else throw Error(`Invalid rotation ${$}.`)},K0=($)=>{return $&&$[$.length-1]};var y=($)=>{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)},q1=($)=>{let J=y($);return(J&1)===0?-(J>>1):J+1>>1};var _0=($)=>{if($.constructor===Uint8Array)return $;else if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);else return new Uint8Array($)},u=($)=>{if($.constructor===DataView)return $;else if(ArrayBuffer.isView($))return new DataView($.buffer,$.byteOffset,$.byteLength);else return new DataView($)},H0=new TextDecoder;var CJ=($)=>{return Object.fromEntries(Object.entries($).map(([J,Y])=>[Y,J]))},V8={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},_8=CJ(V8),H8={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},z8=CJ(H8),R8={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},A8=CJ(R8);var I6=($)=>{return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)};class o0{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 P7=/^[0-9a-fA-F]+$/,r1=($)=>{return[...$].map((J)=>J.toString(16).padStart(2,"0")).join("")},b7=($)=>{L($.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},EJ=($)=>{return $=$>>1&1431655765|($&1431655765)<<1,$=$>>2&858993459|($&858993459)<<2,$=$>>4&252645135|($&252645135)<<4,$=$>>8&16711935|($&16711935)<<8,$=$>>16&65535|($&65535)<<16,$>>>0},C1=($,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},PJ=($,J,Y)=>{let X=p($,Y(J),Y);$.splice(X+1,0,J)},U0=()=>{let $,J;return{promise:new Promise((X,Q)=>{$=X,J=Q}),resolve:$,reject:J}},T7=($,J)=>{let Y=$.indexOf(J);if(Y!==-1)$.splice(Y,1)},bJ=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return $[Y];return},L8=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return Y;return-1},v7=async function*($){if(Symbol.iterator in $)yield*$[Symbol.iterator]();else yield*$[Symbol.asyncIterator]()},x7=($)=>{if(!(Symbol.iterator in $)&&!(Symbol.asyncIterator in $))throw TypeError("Argument must be an iterable or async iterable.")},T0=($)=>{throw Error(`Unexpected value: ${$}`)},M8=($,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},I7=($,J,Y)=>{return M8($,J,Y)<<8>>8},M$=($,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 y6=($,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}}},s0=($,J,Y)=>{return Math.max(J,Math.min(Y,$))},Z0="und",E1=($)=>{let J=Math.round($);if(Math.abs($/J-1)<10*Number.EPSILON)return J;else return $},S6=($,J)=>{return Math.round($/J)*J},d8=($,J)=>{return Math.round($*J)/J},F$=($,J)=>{return Math.floor($/J)*J};var y7=($)=>{let J=0;while($)J++,$>>=1;return J},TZ=/^[a-z]{3}$/,c8=($)=>{return TZ.test($)},N1=1e6*(1+Number.EPSILON),S7=($,J)=>{let Y={...$,...J};if($.headers||J.headers){let X=$.headers?L$($.headers):{},Q=J.headers?L$(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},L$=($)=>{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 $},h7=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(console.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 k6(1000*G);if(Q())throw K}};class n8{constructor(){this.currentPromise=Promise.resolve()}call($){return this.currentPromise=this.currentPromise.then($)}}var wJ=null,F8=()=>{if(wJ!==null)return wJ;return wJ=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))},OJ=null,o8=()=>{if(OJ!==null)return OJ;return OJ=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox")},BJ=null,h6=()=>{if(BJ!==null)return BJ;return BJ=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))},DJ=null,f7=()=>{if(DJ!==null)return DJ;if(typeof navigator>"u")return null;let $=/\bChrome\/(\d+)/.exec(navigator.userAgent);if(!$)return null;return DJ=Number($[1])},w8=($,J)=>{return $!==-1?$:J},w$=($,J,Y,X)=>{return $<=X&&Y<=J};var f6=($)=>{let J=atob($),Y=new Uint8Array(J.length);for(let X=0;X<J.length;X++)Y[X]=J.charCodeAt(X);return Y};var TJ=($,J)=>{if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if($[Y]!==J[Y])return!1;return!0},s8=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},g6=($)=>{return typeof $==="number"&&!Number.isNaN($)},J1=($,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("/")},O8=($,J)=>{let Y=0;for(let X=0;X<$.length;X++)if(J($[X]))Y++;return Y},r8=($,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=($)=>{L(Number.isInteger($.num)),L(Number.isInteger($.den)),L($.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}},vJ=($,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 k6=($)=>{return new Promise((J)=>setTimeout(J,$))};class i1{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
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
9
|
+
*
|
|
10
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
11
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
12
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
13
|
+
*/class P1{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 u6{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 M0={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};/*!
|
|
14
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
15
|
+
*
|
|
16
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
17
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
18
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
19
|
+
*/class c{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 c(this.bytes);return $.pos=this.pos,$}}/*!
|
|
20
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
21
|
+
*
|
|
22
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
23
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
24
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
25
|
+
*/var b1=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],D8=[-1,1,2,3,4,5,6,8],C8=($)=>{if(!$||$.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let J=new c($),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<b1.length)Q=b1[X];let Z=J.readBits(4),K=null;if(Z>=1&&Z<=7)K=D8[Z];return{objectType:Y,frequencyIndex:X,sampleRate:Q,channelConfiguration:Z,numberOfChannels:K}};/*!
|
|
26
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
27
|
+
*
|
|
28
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
29
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
30
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
31
|
+
*/var T1=["avc","hevc","vp9","av1","vp8"],B0=["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"],O$=["aac","opus","mp3","vorbis","flac","ac3","eac3"],v1=[...O$,...B0];var xJ=[{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 E8=[{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 g7=".01.01.01.01.00",k7=".0.110.01.01.01.0";var i8=($)=>{let{codec:J,codecDescription:Y,colorSpace:X,avcCodecInfo:Q,hevcCodecInfo:Z,vp9CodecInfo:K,av1CodecInfo:G}=$;if(J==="avc"){if(L($.avcType!==null),Q){let W=new Uint8Array([Q.avcProfileIndication,Q.profileCompatibility,Q.avcLevelIndication]);return`avc${$.avcType}.${r1(W)}`}if(!Y||Y.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${$.avcType}.${r1(Y.subarray(1,4))}`}else if(J==="hevc"){let W,j,U,q,V,_;if(Z)W=Z.generalProfileSpace,j=Z.generalProfileIdc,U=EJ(Z.generalProfileCompatibilityFlags),q=Z.generalTierFlag,V=Z.generalLevelIdc,_=[...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=u(Y),z=R.getUint8(1);W=z>>6&3,j=z&31,U=EJ(R.getUint32(2)),q=z>>5&1,V=R.getUint8(12),_=[];for(let H=0;H<6;H++)_.push(R.getUint8(6+H))}let N="hev1.";N+=["","A","B","C"][W]+j,N+=".",N+=U.toString(16).toUpperCase(),N+=".",N+=q===0?"L":"H",N+=V;while(_.length>0&&_[_.length-1]===0)_.pop();if(_.length>0)N+=".",N+=_.map((R)=>R.toString(16).toUpperCase()).join(".");return N}else if(J==="vp8")return"vp8";else if(J==="vp9"){if(!K){let H=$.width*$.height,A=K0(E8).level;for(let M of E8)if(H<=M.maxPictureSize){A=M.level;break}return`vp09.00.${A.toString().padStart(2,"0")}.08`}let W=K.profile.toString().padStart(2,"0"),j=K.level.toString().padStart(2,"0"),U=K.bitDepth.toString().padStart(2,"0"),q=K.chromaSubsampling.toString().padStart(2,"0"),V=K.colourPrimaries.toString().padStart(2,"0"),_=K.transferCharacteristics.toString().padStart(2,"0"),N=K.matrixCoefficients.toString().padStart(2,"0"),R=K.videoFullRangeFlag.toString().padStart(2,"0"),z=`vp09.${W}.${j}.${U}.${q}`;if(z+=`.${V}.${_}.${N}.${R}`,z.endsWith(g7))z=z.slice(0,-g7.length);return z}else if(J==="av1"){if(!G){let M=$.width*$.height,F=K0(E8).level;for(let O of E8)if(M<=O.maxPictureSize){F=O.level;break}return`av01.0.${F.toString().padStart(2,"0")}M.08`}let W=G.profile,j=G.level.toString().padStart(2,"0"),U=G.tier?"H":"M",q=G.bitDepth.toString().padStart(2,"0"),V=G.monochrome?"1":"0",_=100*G.chromaSubsamplingX+10*G.chromaSubsamplingY+1*(G.chromaSubsamplingX&&G.chromaSubsamplingY?G.chromaSamplePosition:0),N=X?.primaries?V8[X.primaries]:1,R=X?.transfer?H8[X.transfer]:1,z=X?.matrix?R8[X.matrix]:1,H=X?.fullRange?1:0,A=`av01.${W}.${j}${U}.${q}`;if(A+=`.${V}.${_.toString().padStart(3,"0")}`,A+=`.${N.toString().padStart(2,"0")}`,A+=`.${R.toString().padStart(2,"0")}`,A+=`.${z.toString().padStart(2,"0")}`,A+=`.${H}`,A.endsWith(k7))A=A.slice(0,-k7.length);return A}throw TypeError(`Unhandled codec '${J}'.`)};var a8=($)=>{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=C8(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&&B0.includes(J))return J;throw TypeError(`Unhandled codec '${J}'.`)};var x1=48000,u7=/^pcm-([usf])(\d+)(be)?$/,I1=($)=>{if(L(B0.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=u7.exec($);L(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}},a1=($)=>{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";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(u7.test($))return $;if($==="webvtt")return"webvtt";return null};/*!
|
|
32
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
33
|
+
*
|
|
34
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
35
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
36
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
37
|
+
*/var V1=4,xZ=[44100,48000,32000],m7=[-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],e8=1483304551,m6=1231971951,l7=($,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},p7=($,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},$6=($,J)=>{return $===3?J===3?21:36:J===3?13:21},J6=($,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,V=Q>>1&1,_=Z>>6&3,N=Z>>4&3,R=Z>>3&1,z=Z>>2&1,H=Z&3,A=m7[K*16*4+j*16+U];if(A===-1)return{header:null,bytesAdvanced:1};let M=A*1000,F=xZ[q]>>K+G,O=l7(K,j,M,F,V);if(J!==null&&J<O)return{header:null,bytesAdvanced:1};let B;if(W===3)B=j===3?384:1152;else if(j===3)B=384;else if(j===2)B=1152;else B=576;return{header:{totalSize:O,mpegVersionId:W,lowSamplingFrequency:K,layer:j,bitrate:M,frequencyIndex:q,sampleRate:F,channel:_,modeExtension:N,copyright:R,original:z,emphasis:H,audioSamplesInFrame:B},bytesAdvanced:1}};var B$=($)=>{let J=2130706432,Y=0;while(J!==0)Y>>=1,Y|=$&J,J>>=8;return Y},t8;(function($){$[$.FrameCount=1]="FrameCount",$[$.FileSize=2]="FileSize",$[$.Toc=4]="Toc"})(t8||(t8={}));var t1=($)=>{return $===3?1:2};/*!
|
|
38
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
39
|
+
*
|
|
40
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
41
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
42
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
43
|
+
*/var P8=[48000,44100,32000],IJ=[24000,22050,16000];/*!
|
|
44
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
45
|
+
*
|
|
46
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
47
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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};/*!
|
|
50
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
51
|
+
*
|
|
52
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
53
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
54
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
55
|
+
*/class L0{constructor($){this.input=$}dispose(){}}/*!
|
|
56
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
57
|
+
*
|
|
58
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
59
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
60
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
61
|
+
*/var V0=new Uint8Array(0);class i{constructor($,J,Y,X,Q=-1,Z,K){if(this.data=$,this.type=J,this.timestamp=Y,this.duration=X,this.sequenceNumber=Q,$===V0&&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===V0}get microsecondTimestamp(){return Math.trunc(N1*this.timestamp)}get microsecondDuration(){return Math.trunc(N1*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 i(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 i($?.data??this.data,$?.type??this.type,$?.timestamp??this.timestamp,$?.duration??this.duration,$?.sequenceNumber??this.sequenceNumber,this.byteLength,$?.sideData??this.sideData)}}/*!
|
|
62
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
63
|
+
*
|
|
64
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
65
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
66
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
67
|
+
*/var cJ=($)=>{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},v$=($)=>{let J=u($),Y=0,X=J.getUint8(Y);Y+=1,Y+=3;let Q=r1($.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(r1($.subarray(Y,Y+16))),Y+=16}}let K=J.getUint32(Y);return Y+=4,{systemId:Q,keyIds:Z,data:$.slice(Y,Y+K)}},x$=($,J)=>$.systemId===J.systemId&&TJ($.data,J.data);/*!
|
|
68
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
69
|
+
*
|
|
70
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
71
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
72
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
73
|
+
*/var e1=8,v8=16,S1=($)=>{let J=I($),Y=J0($,4),X=8;if(J===1)J=k0($),X=16;let Z=J-X;if(Z<0)return null;return{name:Y,totalSize:J,headerSize:X,contentSize:Z}},$8=($)=>{return h1($)/65536},I$=($)=>{return h1($)/1073741824},y$=($)=>{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},Y1=($)=>{let J=G0($);return $.skip(2),J=Math.min(J,$.remainingLength),H0.decode(h($,J))},$X=($)=>{let J=S1($);if(!J||J.name!=="data")return null;if($.remainingLength<8)return null;let Y=I($);$.skip(4);let X=h($,J.contentSize-8);switch(Y){case 1:return H0.decode(X);case 2:return new TextDecoder("utf-16be").decode(X);case 13:return new P1(X,"image/jpeg");case 14:return new P1(X,"image/png");case 27:return new P1(X,"image/bmp");default:return X}};/*!
|
|
74
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
75
|
+
*
|
|
76
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
77
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
78
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
79
|
+
*/var X1=16,f1=new Uint32Array(256),Z6=new Uint32Array(256),Q6=new Uint32Array(256),K6=new Uint32Array(256),G6=new Uint32Array(256),D0=new Uint32Array(256),JX=new Uint32Array(10),YX=!1,pZ=()=>{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);f1[Z]=K<<24|K<<16|K<<8|K,D0[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),V=W<<24|j<<16|U<<8|q;Z6[Z]=V,Q6[Z]=V>>>8|V<<24,K6[Z]=V>>>16|V<<16,G6[Z]=V>>>24|V<<8}let Q=1;for(let Z=0;Z<10;Z++)JX[Z]=Q<<24,Q=Q<<1^(Q&128?283:0);YX=!0};class S${constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(X1/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(X1),this.out=new Uint8Array(X1),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:$,iv:J}){if(L($.byteLength===16),L(J.byteLength===16),!YX)pZ();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]^f1[Z>>>16&255]&4278190080^f1[Z>>>8&255]&16711680^f1[Z>>>0&255]&65280^f1[Z>>>24&255]&255^JX[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]=Z6[f1[K>>>24&255]&255]^Q6[f1[K>>>16&255]&255]^K6[f1[K>>>8&255]&255]^G6[f1[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 z=1;z<10;z++){let H=z*4;W=Z6[$>>>24]^Q6[X>>>16&255]^K6[Y>>>8&255]^G6[J&255]^this.roundkey[H],j=Z6[J>>>24]^Q6[$>>>16&255]^K6[X>>>8&255]^G6[Y&255]^this.roundkey[H+1],U=Z6[Y>>>24]^Q6[J>>>16&255]^K6[$>>>8&255]^G6[X&255]^this.roundkey[H+2],q=Z6[X>>>24]^Q6[Y>>>16&255]^K6[J>>>8&255]^G6[$&255]^this.roundkey[H+3],$=W,J=j,Y=U,X=q}let V=D0[$>>>24&255]&4278190080^D0[X>>>16&255]&16711680^D0[Y>>>8&255]&65280^D0[J>>>0&255]&255^this.roundkey[40],_=D0[J>>>24&255]&4278190080^D0[$>>>16&255]&16711680^D0[X>>>8&255]&65280^D0[Y>>>0&255]&255^this.roundkey[41],N=D0[Y>>>24&255]&4278190080^D0[J>>>16&255]&16711680^D0[$>>>8&255]&65280^D0[X>>>0&255]&255^this.roundkey[42],R=D0[X>>>24&255]&4278190080^D0[Y>>>16&255]&16711680^D0[J>>>8&255]&65280^D0[$>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,V^this.iv[0],!1),this.outView.setUint32(4,_^this.iv[1],!1),this.outView.setUint32(8,N^this.iv[2],!1),this.outView.setUint32(12,R^this.iv[3],!1),this.iv[0]=Q,this.iv[1]=Z,this.iv[2]=K,this.iv[3]=G}}var XX=($,J,Y)=>{let X=!1,Q=0,Z=65536,K=16,G=new S$;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 V=q===j?q-K:q,_=h(U,V),N=new Uint8Array(V);for(let R=0;R<V;R+=16)G.in.set(_.subarray(R,R+16)),G.decrypt(),N.set(G.out,R);if(V<q)W.enqueue(N),Q+=V;else{let R=N[V-1];if(R===0||R>16)throw Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let z=N.subarray(0,V-R);W.enqueue(z),W.close(),Y()}},cancel:()=>{Y()}})};/*!
|
|
80
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
81
|
+
*
|
|
82
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
83
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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};/*!
|
|
86
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
87
|
+
*
|
|
88
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
89
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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.")}/*!
|
|
92
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
93
|
+
*
|
|
94
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
95
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
96
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
97
|
+
*/var JY=($)=>{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};/*!
|
|
98
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
99
|
+
*
|
|
100
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
101
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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}}}/*!
|
|
104
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
105
|
+
*
|
|
106
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
107
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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};/*!
|
|
110
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
111
|
+
*
|
|
112
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
113
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
114
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
115
|
+
*/class QY extends L0{constructor($){super($);this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new o0,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 HX(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)while(!0){let K=this.reader.requestSlice(this.lastLoadedPos,d0);if(K instanceof Promise)K=await K;if(!K){this.lastSampleLoaded=!0;return}let G=G1(K);if(!G)break;this.lastLoadedPos=K.filePos+G.size}let $=await t6(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=$6(J.mpegVersionId,J.channel),X=this.reader.requestSlice($.startPos+Y,4);if(X instanceof Promise)X=await X;if(X){let K=I(X);if(K===e8||K===m6){if(!this.xingData){let W=this.reader.requestSlice($.startPos+Y+4,12);if(W instanceof Promise)W=await W;if(W){let j=h(W,12),U=u(j),q=U.getUint32(0,!1);this.xingData={frameCount:q&t8.FrameCount?U.getUint32(4,!1):null,fileSize:q&t8.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,d0);if(X instanceof Promise)X=await X;if(!X)break;let Q=G1(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;q6(Z,Q,this.metadataTags),J=X.filePos+Q.size}if(!Y&&this.reader.fileSize!==null&&this.reader.fileSize>=e6){let X=this.reader.requestSlice(this.reader.fileSize-e6,e6);if(X instanceof Promise)X=await X;if(L(X),J0(X,3)==="TAG")zX(X,this.metadataTags)}return this.metadataTags}finally{$()}}}class HX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return L(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let $=this.demuxer;if(L($.firstFrameHeader!==null),L($.firstFrameHeaderPos!==null),$.xingData){if($.xingData.frameCount!==null)return $.xingData.frameCount*$.firstFrameHeader.audioSamplesInFrame/$.firstFrameHeader.sampleRate}else if($.reader.fileSize!==null){let J=p7($.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 Z0}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return L(this.demuxer.firstFrameHeader),t1(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return L(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...M0}}async getDecoderConfig(){return L(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:t1(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=V0;else{let Q=this.demuxer.reader.requestSlice(Y.dataStart,Y.dataSize);if(Q instanceof Promise)Q=await Q;if(!Q)return null;X=h(Q,Y.dataSize)}return new i(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=C1(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)}}/*!
|
|
116
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
117
|
+
*
|
|
118
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
119
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
120
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
121
|
+
*/var l$=1399285583,aZ=79764919,RX=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let Y=0;Y<8;Y++)J=J&2147483648?J<<1^aZ:J<<1;RX[$]=J>>>0&4294967295}var KY=($)=>{let J=u($),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^RX[X>>>24^Z])>>>0}return J.setUint32(22,Y,!0),X},GY=($,J,Y)=>{let X=0,Q=null;if($.length>0){if(J.codec==="vorbis"){L(J.vorbisInfo);let Z=J.vorbisInfo.modeBlockflags.length,G=(1<<y7(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,V=$[0]&q?1:0;j=J.vorbisInfo.blocksizes[V]}X=j!==null?j+Q>>2:0}else if(J.codec==="opus")X=i7($).durationInSamples}return{durationInSamples:X,vorbisBlockSize:Q}},UY=($)=>{let J="audio/ogg";if($.codecStrings){let Y=[...new Set($.codecStrings)];J+=`; codecs="${Y.join(", ")}"`}return J};/*!
|
|
122
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
123
|
+
*
|
|
124
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
125
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
126
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
127
|
+
*/var Y8=27,I8=282,WY=I8+65025,N6=($)=>{let J=$.filePos;if(x8($)!==l$)return null;$.skip(1);let X=g($),Q=LX($),Z=x8($),K=x8($),G=x8($),W=g($),j=new Uint8Array(W);for(let _=0;_<W;_++)j[_]=g($);let U=27+W,q=j.reduce((_,N)=>_+N,0),V=U+q;return{headerStartPos:J,totalSize:V,dataStartPos:J+U,dataSize:q,headerType:X,granulePosition:Q,serialNumber:Z,sequenceNumber:K,checksum:G,lacingValues:j}},AX=($,J)=>{while($.filePos<J-3){let Y=x8($),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===l$)return!0;$.skip(1)}return!1};/*!
|
|
128
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
129
|
+
*
|
|
130
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
131
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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}};/*!
|
|
134
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
135
|
+
*
|
|
136
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
137
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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)}}/*!
|
|
140
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
141
|
+
*
|
|
142
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
143
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
144
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
145
|
+
*/var y8=7,U1=9,z1=($)=>{let J=$.filePos,Y=h($,9),X=new c(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 V=null;if(K===1)$.filePos-=2;else V=X.readBits(16);return{objectType:G,samplingFrequencyIndex:W,channelConfiguration:j,frameLength:U,numberOfAacFrames:q,crcCheck:V,startPos:J}};/*!
|
|
146
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
147
|
+
*
|
|
148
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
149
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
150
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
151
|
+
*/var $$=1024;class VY extends L0{constructor($){super($);this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new o0,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();L(this.firstFrameHeader),this.trackBackings=[new BX(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)while(!0){let Z=this.reader.requestSlice(this.lastLoadedPos,d0);if(Z instanceof Promise)Z=await Z;if(!Z){this.lastSampleLoaded=!0;return}let K=G1(Z);if(!K)break;this.lastLoadedPos=Z.filePos+K.size}let $=this.reader.requestSliceRange(this.lastLoadedPos,y8,U1);if($ instanceof Promise)$=await $;if(!$){this.lastSampleLoaded=!0;return}let J=z1($);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=b1[J.samplingFrequencyIndex];L(Y!==void 0);let X=$$/Y,Q={timestamp:this.nextTimestampInSamples/Y,duration:X,dataStart:J.startPos,dataSize:J.frameLength};this.loadedSamples.push(Q),this.nextTimestampInSamples+=$$,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,d0);if(Y instanceof Promise)Y=await Y;if(!Y)break;let X=G1(Y);if(!X)break;let Q=this.reader.requestSlice(Y.filePos,X.size);if(Q instanceof Promise)Q=await Q;if(!Q)break;q6(Q,X,this.metadataTags),J=Y.filePos+X.size}return this.metadataTags}finally{$()}}}class BX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/$$}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Z0}getCodec(){return"aac"}getInternalCodecId(){return L(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){L(this.demuxer.firstFrameHeader);let $=D8[this.demuxer.firstFrameHeader.channelConfiguration];return L($!==void 0),$}getSampleRate(){L(this.demuxer.firstFrameHeader);let $=b1[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return L($!==void 0),$}getDisposition(){return{...M0}}async getDecoderConfig(){return L(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=V0;else{let Q=this.demuxer.reader.requestSlice(Y.dataStart,Y.dataSize);if(Q instanceof Promise)Q=await Q;if(!Q)return null;X=h(Q,Y.dataSize)}return new i(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=C1(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)}}/*!
|
|
152
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
153
|
+
*
|
|
154
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
155
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
156
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
157
|
+
*/var _Y=($)=>{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},DX=($,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}},HY=($)=>{let J=0,Y=new c(h($,1));while(Y.readBits(1)===1)J++;if(J===0)return Y.readBits(7);let X=[],Q=J-1,Z=new c(h($,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)},zY=($,J)=>{if(J==="uncommon-u16")return G0($)+1;else if(J==="uncommon-u8")return g($)+1;else if(typeof J==="number")return J;else T0(J),L(!1)},CX=($,J)=>{if(J==="uncommon-u16")return G0($);if(J==="uncommon-u16-10")return G0($)*10;if(J==="uncommon-u8")return g($);if(typeof J==="number")return J;return null},EX=($)=>{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};/*!
|
|
158
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
159
|
+
*
|
|
160
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
161
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
162
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
163
|
+
*/class RY extends L0{constructor($){super($);this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new o0,this.lastSampleLoaded=!1,this.reader=$._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),L(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){let $=4;return this.metadataPromise??=(async()=>{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.`);L(J);let Y=g(J),X=Z1(J),Q=(Y&128)!==0;switch(Y&127){case _1.STREAMINFO:{let K=this.reader.requestSlice($,X);if(K instanceof Promise)K=await K;if(L(K),K===null)throw Error(`StreamInfo block at position ${$} is too small! Corrupted file.`);let G=h(K,34),W=new c(G),j=W.readBits(16),U=W.readBits(16),q=W.readBits(24),V=W.readBits(24),_=W.readBits(20),N=W.readBits(3)+1;W.readBits(5);let R=W.readBits(36);W.skipBits(128);let z=new Uint8Array(42);z.set(new Uint8Array([102,76,97,67]),0),z.set(new Uint8Array([128,0,0,34]),4),z.set(G,8),this.audioInfo={numberOfChannels:N,sampleRate:_,totalSamples:R,minimumBlockSize:j,maximumBlockSize:U,minimumFrameSize:q,maximumFrameSize:V,description:z},this.trackBacking=new PX(this);break}case _1.VORBIS_COMMENT:{let K=this.reader.requestSlice($,X);if(K instanceof Promise)K=await K;L(K),o6(h(K,X),this.metadataTags);break}case _1.PICTURE:{let K=this.reader.requestSlice($,X);if(K instanceof Promise)K=await K;L(K);let G=I(K),W=I(K),j=H0.decode(h(K,W)),U=I(K),q=H0.decode(h(K,U));K.skip(16);let V=I(K),_=h(K,V);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}){L(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 V=j.filePos,_=g(j),N=this.blockingBit===1?249:248;if(_!==N){j.filePos=V;continue}j.skip(-2);let R=j.filePos-$,z=this.readFlacFrameHeader({slice:j,isFirstPacket:!1});if(!z){j.filePos=V;continue}if(this.blockingBit===0){if(z.num-U.num!==1){j.filePos=V;continue}}else if(z.num-U.num!==U.blockSize){j.filePos=V;continue}return{num:U.num,blockSize:U.blockSize,sampleRate:U.sampleRate,size:R,isLastFrame:!1}}}}readFlacFrameHeader({slice:$,isFirstPacket:J}){let Y=$.filePos,X=h($,4),Q=new c(X);if(Q.readBits(15)!==32764)return null;if(this.blockingBit===null){L(J);let R=Q.readBits(1);this.blockingBit=R}else if(this.blockingBit===1){if(L(!J),Q.readBits(1)!==1)return null}else if(this.blockingBit===0){if(L(!J),Q.readBits(1)!==0)return null}else throw Error("Invalid blocking bit");let K=_Y(Q.readBits(4));if(!K)return null;L(this.audioInfo);let G=DX(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=HY($),U=zY($,K),q=CX($,G);if(q===null)return null;if(q!==this.audioInfo.sampleRate)return null;let V=$.filePos-Y,_=g($);$.skip(-V),$.skip(-1);let N=EX(h($,V));if(_!==N)return null;return{num:j,blockSize:U,sampleRate:q}}async advanceReader(){await this.readMetadata(),L(this.lastLoadedPos!==null),L(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 PX{constructor($){this.demuxer=$}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return L(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return L(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Z0}getTimeResolution(){return L(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){if(L(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{...M0}}async getDecoderConfig(){return L(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket($,J){if(L(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=V0;else{let K=this.demuxer.reader.requestSlice(Y.byteOffset,Y.byteSize);if(K instanceof Promise)K=await K;if(!K)return null;X=h(K,Y.byteSize)}L(this.demuxer.audioInfo);let Q=Y.blockOffset/this.demuxer.audioInfo.sampleRate,Z=Y.blockSize/this.demuxer.audioInfo.sampleRate;return new i(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,$)}}/*!
|
|
164
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
165
|
+
*
|
|
166
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
167
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
168
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
169
|
+
*/var W1=90000,I0=188,AY=($)=>{let J="video/MP2T",Y=[...new Set($.filter(Boolean))];if(Y.length>0)J+=`; codecs="${Y.join(", ")}"`;return J};/*!
|
|
170
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
171
|
+
*
|
|
172
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
173
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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}}/*!
|
|
176
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
177
|
+
*
|
|
178
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
179
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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)}}/*!
|
|
182
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
183
|
+
*
|
|
184
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
185
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
186
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
187
|
+
*/class IY{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 getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let $=[];if(this.trackDeclarations){for(let J of this.trackDeclarations)if(J.type==="video"){let Y=O8($,(X)=>X.getType()==="video")+1;$.push(new vY(this,J,Y))}else if(J.type==="audio"){let Y=O8($,(X)=>X.getType()==="audio")+1;$.push(new xY(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=O8($,(Z)=>Z.getType()==="video")+1;$.push(new vY(this,{id:$.length+1,type:"video"},Q))}else if(X.type==="audio"){let Q=O8($,(Z)=>Z.getType()==="audio")+1;$.push(new xY(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 yY{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(),L(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch}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){L($.sequenceNumber>=0),L(this.segmentedInput.firstSegment);let X=await this.segmentedInput.getMediaOffset(J,Y.input),Q=J.timestamp-this.segmentedInput.firstSegment.timestamp,Z=$.clone({timestamp:d8($.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(),L(this.segmentedInput.firstSegment),L(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 vY extends yY{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 xY extends yY{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 J4=(()=>({}));/*!
|
|
188
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
189
|
+
*
|
|
190
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
191
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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()}}/*!
|
|
194
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
195
|
+
*
|
|
196
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
197
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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}}/*!
|
|
200
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
201
|
+
*
|
|
202
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
203
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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};/*!
|
|
206
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
207
|
+
*
|
|
208
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
209
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
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.`)}};/*!
|
|
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
|
+
*//*!
|
|
218
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
219
|
+
*
|
|
220
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
221
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
222
|
+
* 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)}}};/*!
|
|
224
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
225
|
+
*
|
|
226
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
227
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
228
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
229
|
+
*//*!
|
|
230
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
231
|
+
*
|
|
232
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
233
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
234
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
235
|
+
*/var Z$=[],Q$=[];/*!
|
|
236
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
237
|
+
*
|
|
238
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
239
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
240
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
241
|
+
*/var K5=($)=>{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 G5=($)=>{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
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
243
|
+
*
|
|
244
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
245
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
246
|
+
* 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))}}/*!
|
|
270
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
271
|
+
*
|
|
272
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
273
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
274
|
+
* 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)};/*!
|
|
276
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
277
|
+
*
|
|
278
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
279
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
280
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
281
|
+
*/s8();var F2=1,uX=2;class A1 extends i1{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 c0)))throw TypeError("options.formats must be an array of InputFormat.");if(!($.source instanceof r0||$.source instanceof A6))throw TypeError("options.source must be a Source or SourceRef.");if($.source instanceof r0&&$.source._disposed)throw TypeError("options.source must not be a disposed Source.");if($.initInput!==void 0&&!($.initInput instanceof A1))throw TypeError("options.initInput, when provided, must be an Input.");if($.formatOptions!==void 0)tX($.formatOptions,"formatOptions");if(this._formats=$.formats,this._initInput=$.initInput??null,this._formatOptions=$.formatOptions??{},$.source instanceof r0)this._rootRef=$.source.ref();else this._rootRef=$.source;this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached($){L(this._rootSource instanceof R1);let J=await this._rootSource._resolveRequest($);return this._emit("source",{source:J.source,request:$,isRoot:$.isRoot}),J}_getSourceCached($,J=F2){let Y=this._sourceCache.find((Z)=>Z.cacheGroup===J&&fY(Z.request,$));if(Y)return Y.age++,Promise.resolve(Y.sourceRef.source.ref());let X=this._sourceCachePromises.find((Z)=>Z.cacheGroup===J&&fY(Z.request,$));if(X)return X.promise.then((Z)=>Z.sourceRef.source.ref());let Q=(async()=>{let Z=await this._getSourceUncached($),K=4;if(O8(this._sourceCache,(U)=>U.cacheGroup===J&&U.sourceRef.source._refCount===1)>=4){let U=r8(this._sourceCache,(V)=>V.cacheGroup===J&&V.sourceRef.source._refCount===1?V.age:1/0);L(U!==-1);let q=this._sourceCache[U];this._sourceCache.splice(U,1),q.sourceRef.free(),T7(this._sourceRefs,q.sourceRef)}this._sourceRefs.push(Z);let W=this._sourceCachePromises.findIndex((U)=>U.request===$);return L(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 f8(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 qJ})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),L(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch($){if($ instanceof qJ)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($){$&&=w6($);let Y=(await this._getTrackBackings()).map((X)=>this._wrapBackingAsTrack(X));return jJ(Y,$)}async getVideoTracks($){$&&=w6($);let Y=(await this.getTracks()).filter((X)=>X.isVideoTrack());return jJ(Y,$)}async getAudioTracks($){$&&=w6($);let Y=(await this.getTracks()).filter((X)=>X.isAudioTrack());return jJ(Y,$)}async getPrimaryVideoTrack($){$&&=w6($);let J=G8($,{sortBy:async(X)=>[l8((await X.getDisposition()).default),l8(await X.hasPairableAudioTrack()),l8(!await X.hasOnlyKeyPackets()),WJ(await X.getBitrate())]});return(await this.getVideoTracks(J))[0]??null}async getPrimaryAudioTrack($){$&&=w6($);let J=await this.getPrimaryVideoTrack(),Y=G8($,{sortBy:async(Q)=>[l8(!J||Q.canBePairedWith(J)),l8((await Q.getDisposition()).default),WJ(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 K8(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 qJ extends Error{constructor($="Input has an unsupported or unrecognizable format."){super($);this.name="UnsupportedInputFormatError"}}class R0 extends Error{constructor($="Input has been disposed."){super($);this.name="InputDisposedError"}}/*!
|
|
282
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
283
|
+
*
|
|
284
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
285
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
286
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
287
|
+
*/class f8{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 R0;if($<0)return null;if(this.fileSizeNonStrict!==null&&$+J>this.fileSizeNonStrict)return null;if(J===0){let Q=new Uint8Array(0);return new x0(Q,u(Q),0,$,$)}let Y=$+J,X=this.source._read($,Y,SY,hY);if(X instanceof Promise)return X.then((Q)=>{if(!Q)return null;return new x0(Q.bytes,Q.view,Q.offset,$,Y)});else{if(!X)return null;return new x0(X.bytes,X.view,X.offset,$,Y)}}requestSliceRange($,J,Y){if(this.source._disposed)throw new R0;if($<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice($,s0(this.fileSizeNonStrict-$,J,Y));else{let X=this.requestSlice($,Y),Q=(Z)=>{if(Z)return Z;return L(this.fileSizeNonStrict!==null),this.requestSlice($,s0(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=h(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 x0(X,u(X),0,0,Y)})()}}class x0{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 x0($,u($),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 x0(this.bytes,this.view,this.offset,$,$+J)}}var p0=($,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.`)},h=($,J)=>{p0($,J);let Y=$.bytes.subarray($.bufferPos,$.bufferPos+J);return $.bufferPos+=J,Y},g=($)=>{return p0($,1),$.view.getUint8($.bufferPos++)},_6=($,J)=>{p0($,2);let Y=$.view.getUint16($.bufferPos,J);return $.bufferPos+=2,Y},G0=($)=>{p0($,2);let J=$.view.getUint16($.bufferPos,!1);return $.bufferPos+=2,J},Z1=($)=>{p0($,3);let J=M8($.view,$.bufferPos,!1);return $.bufferPos+=3,J},r6=($)=>{p0($,2);let J=$.view.getInt16($.bufferPos,!1);return $.bufferPos+=2,J},u1=($,J)=>{p0($,4);let Y=$.view.getUint32($.bufferPos,J);return $.bufferPos+=4,Y},I=($)=>{p0($,4);let J=$.view.getUint32($.bufferPos,!1);return $.bufferPos+=4,J},x8=($)=>{p0($,4);let J=$.view.getUint32($.bufferPos,!0);return $.bufferPos+=4,J},h1=($)=>{p0($,4);let J=$.view.getInt32($.bufferPos,!1);return $.bufferPos+=4,J},w2=($)=>{p0($,4);let J=$.view.getInt32($.bufferPos,!0);return $.bufferPos+=4,J},qY=($,J)=>{let Y,X;if(J)Y=u1($,!0),X=u1($,!0);else X=u1($,!1),Y=u1($,!1);return X*4294967296+Y},k0=($)=>{let J=I($),Y=I($);return J*4294967296+Y},WX=($)=>{let J=h1($),Y=I($);return J*4294967296+Y},LX=($)=>{let J=x8($);return w2($)*4294967296+J},qX=($)=>{p0($,4);let J=$.view.getFloat32($.bufferPos,!1);return $.bufferPos+=4,J},f$=($)=>{p0($,8);let J=$.view.getFloat64($.bufferPos,!1);return $.bufferPos+=8,J},J0=($,J)=>{p0($,J);let Y="";for(let X=0;X<J;X++)Y+=String.fromCharCode($.bytes[$.bufferPos++]);return Y},r$=($,J,Y)=>{return H0.decode(h($,J)).split(`
|
|
288
|
+
`).map((Z)=>Z.trim()).filter((Z)=>Z.length>0&&!Y?.ignore?.(Z))};/*!
|
|
289
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
290
|
+
*
|
|
291
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
292
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
293
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
294
|
+
*/var B6;(function($){$[$.Unsynchronisation=128]="Unsynchronisation",$[$.ExtendedHeader=64]="ExtendedHeader",$[$.ExperimentalIndicator=32]="ExperimentalIndicator",$[$.Footer=16]="Footer"})(B6||(B6={}));var D6;(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"})(D6||(D6={}));var e6=128,d0=10,C6=["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"],zX=($,J)=>{let Y=$.filePos;J.raw??={},J.raw.TAG??=h($,e6-3),$.filePos=Y;let X=O6($,30);if(X)J.title??=X;let Q=O6($,30);if(Q)J.artist??=Q;let Z=O6($,30);if(Z)J.album??=Z;let K=O6($,4),G=Number.parseInt(K,10);if(Number.isInteger(G)&&G>0)J.date??=new Date(String(G));let W=h($,30),j;if(W[28]===0&&W[29]!==0){let q=W[29];if(q>0)J.trackNumber??=q;$.skip(-30),j=O6($,28),$.skip(2)}else $.skip(-30),j=O6($,30);if(j)J.comment??=j;let U=g($);if(U<C6.length)J.genre??=C6[U]},O6=($,J)=>{let Y=h($,J),X=w8(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()},G1=($)=>{let J=$.filePos,Y=J0($,3),X=g($),Q=g($),Z=g($),K=I($);if(Y!=="ID3"||X===255||Q===255||(K&2155905152)!==0)return $.filePos=J,null;let G=B$(K);return{majorVersion:X,revision:Q,flags:Z,size:G}},q6=($,J,Y)=>{if(![2,3,4].includes(J.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${J.majorVersion}`);return}let X=h($,J.size),Q=new V5(J,X);if(J.flags&B6.Footer)Q.removeFooter();if(J.flags&B6.Unsynchronisation&&J.majorVersion===3)Q.ununsynchronizeAll();if(J.flags&B6.ExtendedHeader){let Z=Q.readU32();if(J.majorVersion===3)Q.pos+=Z;else Q.pos+=Z-4}while(Q.pos<=Q.bytes.length-Q.frameHeaderSize()){let Z=Q.readId3V2Frame();if(!Z)break;let K=Q.pos,G=Q.pos+Z.size,W=!1,j=!1,U=!1;if(J.majorVersion===3)W=!!(Z.flags&64),j=!!(Z.flags&128);else if(J.majorVersion===4)W=!!(Z.flags&4),j=!!(Z.flags&8),U=!!(Z.flags&2)||!!(J.flags&B6.Unsynchronisation);if(W){console.warn(`Skipping encrypted ID3v2 frame ${Z.id}`),Q.pos=G;continue}if(j){console.warn(`Skipping compressed ID3v2 frame ${Z.id}`),Q.pos=G;continue}if(U)Q.ununsynchronizeRegion(Q.pos,G);if(Y.raw??={},Z.id==="TXXX"){let q=Y.raw.TXXX??={},V=Q.readId3V2TextEncoding(),_=Q.readId3V2Text(V,G),N=Q.readId3V2Text(V,G);q[_]??=N}else if(Z.id[0]==="T")Y.raw[Z.id]??=Q.readId3V2EncodingAndText(G);else Y.raw[Z.id]??=Q.readBytes(Z.size);switch(Q.pos=K,Z.id){case"TIT2":case"TT2":Y.title??=Q.readId3V2EncodingAndText(G);break;case"TIT3":case"TT3":Y.description??=Q.readId3V2EncodingAndText(G);break;case"TPE1":case"TP1":Y.artist??=Q.readId3V2EncodingAndText(G);break;case"TALB":case"TAL":Y.album??=Q.readId3V2EncodingAndText(G);break;case"TPE2":case"TP2":Y.albumArtist??=Q.readId3V2EncodingAndText(G);break;case"TRCK":case"TRK":{let V=Q.readId3V2EncodingAndText(G).split("/"),_=Number.parseInt(V[0],10),N=V[1]&&Number.parseInt(V[1],10);if(Number.isInteger(_)&&_>0)Y.trackNumber??=_;if(N&&Number.isInteger(N)&&N>0)Y.tracksTotal??=N}break;case"TPOS":case"TPA":{let V=Q.readId3V2EncodingAndText(G).split("/"),_=Number.parseInt(V[0],10),N=V[1]&&Number.parseInt(V[1],10);if(Number.isInteger(_)&&_>0)Y.discNumber??=_;if(N&&Number.isInteger(N)&&N>0)Y.discsTotal??=N}break;case"TCON":case"TCO":{let q=Q.readId3V2EncodingAndText(G),V=/^\((\d+)\)/.exec(q);if(V){let _=Number.parseInt(V[1]);if(C6[_]!==void 0){Y.genre??=C6[_];break}}if(V=/^\d+$/.exec(q),V){let _=Number.parseInt(V[0]);if(C6[_]!==void 0){Y.genre??=C6[_];break}}Y.genre??=q}break;case"TDRC":case"TDAT":{let q=Q.readId3V2EncodingAndText(G),V=new Date(q);if(!Number.isNaN(V.getTime()))Y.date??=V}break;case"TYER":case"TYE":{let q=Q.readId3V2EncodingAndText(G),V=Number.parseInt(q,10);if(Number.isInteger(V))Y.date??=new Date(String(V))}break;case"USLT":case"ULT":{let q=Q.readU8();Q.pos+=3,Q.readId3V2Text(q,G),Y.lyrics??=Q.readId3V2Text(q,G)}break;case"COMM":case"COM":{let q=Q.readU8();Q.pos+=3,Q.readId3V2Text(q,G),Y.comment??=Q.readId3V2Text(q,G)}break;case"APIC":case"PIC":{let q=Q.readId3V2TextEncoding(),V;if(J.majorVersion===2){let z=Q.readAscii(3);V=z==="PNG"?"image/png":z==="JPG"?"image/jpeg":"image/*"}else V=Q.readId3V2Text(q,G);let _=Q.readU8(),N=Q.readId3V2Text(q,G).trimEnd(),R=G-Q.pos;if(R>=0){let z=Q.readBytes(R);if(!Y.images)Y.images=[];Y.images.push({data:z,mimeType:V,kind:_===3?"coverFront":_===4?"coverBack":"unknown",description:N})}}break;default:Q.pos+=Z.size;break}Q.pos=G}};class V5{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)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-d0),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?B$(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:B$(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 D6.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 D6.UTF_16_WITH_BOM:if(X[0]===255&&X[1]===254){let Q=new TextDecoder("utf-16le"),Z=w8(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=w8(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=w8(X.findIndex((Z)=>Z===0),X.length);return this.pos=Y+Math.min(Q+1,X.length),H0.decode(X.subarray(0,Q))}case D6.UTF_16_BE_NO_BOM:{let Q=new TextDecoder("utf-16be"),Z=w8(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 D6.UTF_8:{let Q=w8(X.findIndex((Z)=>Z===0),X.length);return this.pos=Y+Math.min(Q+1,X.length),H0.decode(X.subarray(0,Q))}}}readId3V2EncodingAndText($){if(this.pos>=$)return"";let J=this.readId3V2TextEncoding();return this.readId3V2Text(J,$)}}/*!
|
|
295
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
296
|
+
*
|
|
297
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
298
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
299
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
300
|
+
*//*!
|
|
301
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
302
|
+
*
|
|
303
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
304
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
305
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
306
|
+
*//*!
|
|
307
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
308
|
+
*
|
|
309
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
310
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
311
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
312
|
+
*//*!
|
|
313
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
314
|
+
*
|
|
315
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
316
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
317
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
318
|
+
*//*!
|
|
319
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
320
|
+
*
|
|
321
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
322
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
323
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
324
|
+
*/var T2=new Uint8Array(8),HW=new DataView(T2.buffer);/*!
|
|
325
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
326
|
+
*
|
|
327
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
328
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
329
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
330
|
+
*/var wW=(()=>({}));/*!
|
|
331
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
332
|
+
*
|
|
333
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
334
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
335
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
336
|
+
*//*!
|
|
337
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
338
|
+
*
|
|
339
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
340
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
341
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
342
|
+
*//*!
|
|
343
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
344
|
+
*
|
|
345
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
346
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
347
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
348
|
+
*//*!
|
|
349
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
350
|
+
*
|
|
351
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
352
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
353
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
354
|
+
*//*!
|
|
355
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
356
|
+
*
|
|
357
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
358
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
359
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
360
|
+
*//*!
|
|
361
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
362
|
+
*
|
|
363
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
364
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
365
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
366
|
+
*//*!
|
|
367
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
368
|
+
*
|
|
369
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
370
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
371
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
372
|
+
*/var f2=4096;var ij=new Uint8Array([9,240]),aj=new Uint8Array([70,1]);var g2=79764919,R5=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let Y=0;Y<8;Y++)J=J&2147483648?J<<1^g2:J<<1;R5[$]=J>>>0&4294967295}var k2=($)=>{let J=4294967295;for(let Y=0;Y<$.length;Y++){let X=$[Y];J=(J<<8^R5[J>>>24^X])>>>0}return J},E6=new Uint8Array(16);{let $=u(E6);E6[0]=0,$.setUint16(1,45069,!1),$.setUint16(3,1,!1),E6[5]=193,E6[6]=0,E6[7]=0,$.setUint16(8,1,!1),$.setUint16(10,57344|f2&8191,!1),$.setUint32(12,k2(E6.subarray(0,12)),!1)}/*!
|
|
373
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
374
|
+
*
|
|
375
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
376
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
377
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
378
|
+
*//*!
|
|
379
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
380
|
+
*
|
|
381
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
382
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
383
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
384
|
+
*//*!
|
|
385
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
386
|
+
*
|
|
387
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
388
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
389
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
390
|
+
*//*!
|
|
391
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
392
|
+
*
|
|
393
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
394
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
395
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
396
|
+
*/var A5=!1;class X7{constructor($,J){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let Y=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement==="function";if(!X7.forceCpu&&Y&&!A5)try{if(typeof OffscreenCanvas<"u")this.canvas=new OffscreenCanvas($,J);else this.canvas=document.createElement("canvas"),this.canvas.width=$,this.canvas.height=J;let X=this.canvas.getContext("webgl2",{alpha:!0});if(!X)throw Error("Couldn't acquire WebGL 2 context.");this.gl=X,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(X){this.gl=null,this.canvas=null,A5=!0,console.warn("Falling back to CPU for color/alpha splitting.",X)}}async update($){if(this.gl)return this.updateGpu($);else return this.updateCpu($)}updateGpu($){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.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,$);let J=this.runColorProgram($),Y=this.runAlphaProgram($);return $.close(),{colorFrame:J,alphaFrame:Y}}createVertexShader(){return L(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
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}}};/*!
|
|
461
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
462
|
+
*
|
|
463
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
464
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
465
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
466
|
+
*//*!
|
|
467
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
468
|
+
*
|
|
469
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
470
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
471
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
472
|
+
*//*!
|
|
473
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
474
|
+
*
|
|
475
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
476
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
477
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
478
|
+
*//*!
|
|
479
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
480
|
+
*
|
|
481
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
482
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
483
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
484
|
+
*//*!
|
|
485
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
486
|
+
*
|
|
487
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
488
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
489
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
490
|
+
*/var D5=Symbol.for("mediabunny loaded");if(globalThis[D5])console.error(`[WARNING]
|
|
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};
|