agentroam-runtime-darwin-arm64 0.2.0-preview.81 → 0.2.0-preview.82
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/manifest.json +2 -2
- package/package.json +1 -1
- package/runtime/.next/BUILD_ID +1 -1
- package/runtime/.next/app-build-manifest.json +8 -8
- package/runtime/.next/app-path-routes-manifest.json +1 -1
- package/runtime/.next/build-manifest.json +5 -5
- package/runtime/.next/prerender-manifest.json +1 -1
- package/runtime/.next/required-server-files.json +1 -1
- package/runtime/.next/server/app/_not-found/page.js +1 -1
- package/runtime/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app/_not-found.html +1 -1
- package/runtime/.next/server/app/_not-found.rsc +1 -1
- package/runtime/.next/server/app/api/agent/abort/route.js +1 -1
- package/runtime/.next/server/app/api/agent/answer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/codex-sharing/route.js +1 -1
- package/runtime/.next/server/app/api/agent/composer/route.js +1 -0
- package/runtime/.next/server/app/api/agent/composer/route.js.nft.json +1 -0
- package/runtime/.next/server/app/api/agent/harness/status/route.js +1 -1
- package/runtime/.next/server/app/api/agent/model/route.js +1 -1
- package/runtime/.next/server/app/api/agent/models/route.js +1 -1
- package/runtime/.next/server/app/api/agent/run/route.js +1 -1
- package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
- package/runtime/.next/server/app/api/agent/steer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/stream/route.js +2 -2
- package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/agent-workspaces/route.js +1 -1
- package/runtime/.next/server/app/api/auth/verify/route.js +1 -1
- package/runtime/.next/server/app/api/business/route.js +1 -1
- package/runtime/.next/server/app/api/calendar/route.js +2 -2
- package/runtime/.next/server/app/api/client-logs/route.js +1 -1
- package/runtime/.next/server/app/api/collaboration/route.js +2 -2
- package/runtime/.next/server/app/api/engine-threads/route.js +1 -1
- package/runtime/.next/server/app/api/engine-threads.body +1 -1
- package/runtime/.next/server/app/api/flow/v1/catalog/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/cancel/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/events/route.js +2 -2
- package/runtime/.next/server/app/api/flow/v1/runs/route.js +1 -1
- package/runtime/.next/server/app/api/flow-studio/config/route.js +1 -1
- package/runtime/.next/server/app/api/internal/todo-bootstrap/route.js +1 -1
- package/runtime/.next/server/app/api/internal/todo-mcp/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/connect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/disconnect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/servers/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/servers.body +1 -1
- package/runtime/.next/server/app/api/memory/[key]/route.js +1 -1
- package/runtime/.next/server/app/api/memory/route.js +1 -1
- package/runtime/.next/server/app/api/messaging/route.js +1 -1
- package/runtime/.next/server/app/api/notifications/[id]/ack/route.js +1 -1
- package/runtime/.next/server/app/api/notifications/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/notifications/route.js +1 -1
- package/runtime/.next/server/app/api/notifications/stream/route.js +2 -2
- package/runtime/.next/server/app/api/plugins/load/route.js +1 -1
- package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/projects/check/route.js +1 -1
- package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
- package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
- package/runtime/.next/server/app/api/projects/route.js +1 -1
- package/runtime/.next/server/app/api/push/subscribe/route.js +2 -2
- package/runtime/.next/server/app/api/push/unsubscribe/route.js +2 -2
- package/runtime/.next/server/app/api/push/vapid/route.js +2 -2
- package/runtime/.next/server/app/api/push/vapid.body +1 -1
- package/runtime/.next/server/app/api/remote-tools/register/route.js +1 -1
- package/runtime/.next/server/app/api/session-images/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/session-views/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/[jobId]/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/[jobId]/stop/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/background-jobs/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +2 -2
- package/runtime/.next/server/app/api/sessions/[id]/engine-switches/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork-at/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/native-goal/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/release/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/switch-engine/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/thread-goal/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/thread-history/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/tool-result/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/parallel/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/settings/route.js +1 -1
- package/runtime/.next/server/app/api/skills/route.js +1 -1
- package/runtime/.next/server/app/api/todos/[id]/commands/route.js +1 -1
- package/runtime/.next/server/app/api/todos/[id]/executions/route.js +1 -1
- package/runtime/.next/server/app/api/todos/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/todos/route.js +1 -1
- package/runtime/.next/server/app/api/tool-policies/[policyId]/route.js +1 -1
- package/runtime/.next/server/app/api/tool-policies/route.js +1 -1
- package/runtime/.next/server/app/api/tools/route.js +1 -1
- package/runtime/.next/server/app/api/update/check/route.js +1 -1
- package/runtime/.next/server/app/api/update/install/route.js +1 -1
- package/runtime/.next/server/app/api/update/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/computer-settings/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/computers/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
- package/runtime/.next/server/app/api/workspace-changes/route.js +1 -1
- package/runtime/.next/server/app/web/page.js +4 -4
- package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app-paths-manifest.json +34 -33
- package/runtime/.next/server/chunks/1298.js +1 -1
- package/runtime/.next/server/chunks/5303.js +2 -2
- package/runtime/.next/server/chunks/5801.js +1 -1
- package/runtime/.next/server/chunks/6703.js +1 -1
- package/runtime/.next/server/chunks/9119.js +3 -3
- package/runtime/.next/server/chunks/9457.js +1 -1
- package/runtime/.next/server/middleware-build-manifest.js +1 -1
- package/runtime/.next/server/pages/404.html +1 -1
- package/runtime/.next/server/pages/500.html +1 -1
- package/runtime/.next/server/server-reference-manifest.json +1 -1
- package/runtime/.next/static/chunks/app/web/error-828d278147a0619d.js +1 -0
- package/runtime/.next/static/chunks/app/web/layout-1127176e7e88e395.js +1 -0
- package/runtime/.next/static/chunks/app/web/{page-b0da5ef19349a66b.js → page-f008ab6dfeab7ce7.js} +1 -1
- package/runtime/.next/static/chunks/{main-68faabab5d101471.js → main-9c08f7656f9692e6.js} +1 -1
- package/runtime/.next/static/chunks/main-app-07d67f2d4e96ecb8.js +1 -0
- package/runtime/lib/remote-control/application/paced-video-sender.mjs +20 -1
- package/runtime/lib/remote-control/application/remote-video-session.mjs +18 -4
- package/runtime/lib/remote-control/infrastructure/native-video-encoder.mjs +15 -2
- package/runtime/lib/remote-control/infrastructure/werift-video-transport.mjs +3 -1
- package/runtime/lib/remote-control/remote-authorization.mjs +2 -2
- package/runtime/lib/remote-control/remote-video-signal.mjs +2 -0
- package/runtime/lib/todo-completion-worker.mjs +45 -0
- package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/MacOS/agentroam-remote-desktop +0 -0
- package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/Resources/agentroam-component.json +1 -1
- package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/_CodeSignature/CodeResources +2 -2
- package/runtime/node_modules/.package-lock.json +129 -129
- package/runtime/node_modules/@agent/core/dist/index.js +286 -68
- package/runtime/node_modules/@agent/native-runtime/dist/index.js +444 -127
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs +75 -79
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js +52 -52
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-2g5j09ba.mjs +16 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-59ydwk0g.mjs +17 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-q4cwy1ja.mjs → core-664d5mmy.mjs} +2 -2
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-zn1abzvs.mjs → core-70sfhqm6.mjs} +2 -2
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-95gcz3n1.mjs +38 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-ew5sfvfe.mjs +39 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-gjhs7gf6.mjs +20 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-kvdt1szx.mjs +18 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-p654hjkr.mjs +22 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-q9bjbxkv.mjs +19 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-samdvsjh.mjs +33 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-x6bt758j.mjs +17 -0
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core.mjs +12 -12
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.json +22 -22
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json +26 -26
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/package.json +22 -23
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs +84 -83
- package/runtime/node_modules/caniuse-lite/package.json +1 -1
- package/runtime/node_modules/mediabunny/README.md +4 -0
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.cjs +185 -127
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.min.cjs +11 -11
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.min.mjs +12 -12
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.mjs +185 -127
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs +185 -127
- package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.worker.js +8 -0
- package/runtime/node_modules/mediabunny/dist/modules/src/adts/adts-demuxer.js +4 -0
- package/runtime/node_modules/mediabunny/dist/modules/src/aes.js +6 -4
- package/runtime/node_modules/mediabunny/dist/modules/src/hls/hls-demuxer.js +6 -0
- package/runtime/node_modules/mediabunny/dist/modules/src/hls/hls-segmented-input.js +17 -5
- package/runtime/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-boxes.js +2 -1
- package/runtime/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-demuxer.js +12 -1
- package/runtime/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-muxer.js +34 -18
- package/runtime/node_modules/mediabunny/dist/modules/src/matroska/matroska-demuxer.js +3 -0
- package/runtime/node_modules/mediabunny/dist/modules/src/media-sink.js +3 -8
- package/runtime/node_modules/mediabunny/dist/modules/src/media-source.js +5 -12
- package/runtime/node_modules/mediabunny/dist/modules/src/misc.js +19 -5
- package/runtime/node_modules/mediabunny/dist/modules/src/mp3/mp3-demuxer.js +4 -0
- package/runtime/node_modules/mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-demuxer.js +22 -13
- package/runtime/node_modules/mediabunny/dist/modules/src/mpeg-ts/mpeg-ts-muxer.js +2 -2
- package/runtime/node_modules/mediabunny/dist/modules/src/segmented-input.js +70 -65
- package/runtime/node_modules/mediabunny/dist/modules/src/tsconfig.tsbuildinfo +1 -1
- package/runtime/node_modules/mediabunny/dist/modules/src/version.js +1 -1
- package/runtime/node_modules/mediabunny/dist/modules/src/worker.js +26 -0
- package/runtime/node_modules/mediabunny/package.json +1 -1
- package/runtime/node_modules/mediabunny/src/adts/adts-demuxer.ts +5 -0
- package/runtime/node_modules/mediabunny/src/aes.ts +7 -4
- package/runtime/node_modules/mediabunny/src/hls/hls-demuxer.ts +7 -0
- package/runtime/node_modules/mediabunny/src/hls/hls-segmented-input.ts +19 -6
- package/runtime/node_modules/mediabunny/src/isobmff/isobmff-boxes.ts +2 -1
- package/runtime/node_modules/mediabunny/src/isobmff/isobmff-demuxer.ts +15 -1
- package/runtime/node_modules/mediabunny/src/isobmff/isobmff-muxer.ts +37 -19
- package/runtime/node_modules/mediabunny/src/matroska/matroska-demuxer.ts +4 -0
- package/runtime/node_modules/mediabunny/src/media-sink.ts +3 -12
- package/runtime/node_modules/mediabunny/src/media-source.ts +5 -20
- package/runtime/node_modules/mediabunny/src/misc.ts +26 -5
- package/runtime/node_modules/mediabunny/src/mp3/mp3-demuxer.ts +5 -0
- package/runtime/node_modules/mediabunny/src/mpeg-ts/mpeg-ts-demuxer.ts +30 -19
- package/runtime/node_modules/mediabunny/src/mpeg-ts/mpeg-ts-muxer.ts +2 -2
- package/runtime/node_modules/mediabunny/src/segmented-input.ts +76 -79
- package/runtime/node_modules/mediabunny/src/version.ts +1 -1
- package/runtime/node_modules/mediabunny/src/worker.ts +28 -0
- package/runtime/package-lock.json +162 -162
- package/runtime/server.js +1 -1
- package/runtime/webapp/dist/assets/AIHubView-CNKanNZa.js +1 -0
- package/runtime/webapp/dist/assets/{AgentManager-dXI31b0a.js → AgentManager-B8TTqJaL.js} +2 -2
- package/runtime/webapp/dist/assets/AiHubPane-Coyn3P-J.js +1 -0
- package/runtime/webapp/dist/assets/App-BGIGpBp3.js +68 -0
- package/runtime/webapp/dist/assets/BrowserLivePanel-DnzJOz5w.js +61 -0
- package/runtime/webapp/dist/assets/CalendarPage-D0oaq2_l.js +1 -0
- package/runtime/webapp/dist/assets/{CalendarView-QfbrlL9X.js → CalendarView-QXZbXnXA.js} +3 -3
- package/runtime/webapp/dist/assets/CollaborationCreateDialog-CE8OML-A.js +1 -0
- package/runtime/webapp/dist/assets/CollaborationDashboard-CV18iiBO.js +1 -0
- package/runtime/webapp/dist/assets/{CollaborationPage-B1tiqgnG.js → CollaborationPage-B2mIAc-h.js} +2 -2
- package/runtime/webapp/dist/assets/{FilePreview-CPY6dP8Q.js → FilePreview-BCEiERA1.js} +9 -9
- package/runtime/webapp/dist/assets/{FileTree-BBgrOian.js → FileTree-CMbs1Gj3.js} +2 -2
- package/runtime/webapp/dist/assets/FileWorkspaceDrawer-BxFS-0sF.js +1 -0
- package/runtime/webapp/dist/assets/FlowStudioPane-CVP0Q6zR.js +5 -0
- package/runtime/webapp/dist/assets/HostProjectPicker-DUUgM2Cm.js +1 -0
- package/runtime/webapp/dist/assets/{LSPServerList-B-R7HDSP.js → LSPServerList-COMVmsvb.js} +1 -1
- package/runtime/webapp/dist/assets/{MCPServerList-CTc0iAwT.js → MCPServerList-C_juD6B4.js} +1 -1
- package/runtime/webapp/dist/assets/{MemoryViewer-Dzh_miRv.js → MemoryViewer-Et2vysSN.js} +1 -1
- package/runtime/webapp/dist/assets/NewSessionWindow-DwJhkRJd.js +1 -0
- package/runtime/webapp/dist/assets/RemoteDesktopPage-Cqsea4X7.js +1 -0
- package/runtime/webapp/dist/assets/{RemoteDesktopTabBridge-BA_HQv3V.js → RemoteDesktopTabBridge-BFzNwpUn.js} +1 -1
- package/runtime/webapp/dist/assets/{RunningSessionsIcon-BvFSI9OF.js → RunningSessionsIcon-D_cOqmmk.js} +1 -1
- package/runtime/webapp/dist/assets/{SessionDashboard-DcPPoXe2.js → SessionDashboard-yjdEKypJ.js} +2 -2
- package/runtime/webapp/dist/assets/{SessionDashboardBridge-CjoeUy-v.js → SessionDashboardBridge-Kc_1Et9r.js} +1 -1
- package/runtime/webapp/dist/assets/{SettingsPanel-DmdXDQUm.js → SettingsPanel-t26XhKHP.js} +2 -2
- package/runtime/webapp/dist/assets/{SkillManager-CS_skFZj.js → SkillManager-nZU7b1sc.js} +1 -1
- package/runtime/webapp/dist/assets/{TaskPaneTerminal-BFHDRCb9.js → TaskPaneTerminal-BPaCKman.js} +1 -1
- package/runtime/webapp/dist/assets/{TerminalPane-Dr_nY9pI.js → TerminalPane-CiIpI1Id.js} +1 -1
- package/runtime/webapp/dist/assets/TodoPage-CG__S6_l.js +1 -0
- package/runtime/webapp/dist/assets/{abnfDiagram-VCTEODGH-FEEApB15.js → abnfDiagram-VCTEODGH-DmKjGVfG.js} +1 -1
- package/runtime/webapp/dist/assets/{arc-CycwMc2c.js → arc-D6bpvBke.js} +1 -1
- package/runtime/webapp/dist/assets/{architectureDiagram-5GKGNRK7-BFq9JapX.js → architectureDiagram-5GKGNRK7-NEKc2BYf.js} +1 -1
- package/runtime/webapp/dist/assets/{blockDiagram-I7D4REHJ-DkOJ55Ag.js → blockDiagram-I7D4REHJ-V6G00twZ.js} +1 -1
- package/runtime/webapp/dist/assets/{c4Diagram-7LVT6UL2-CRvi_3RM.js → c4Diagram-7LVT6UL2-CojA33V5.js} +1 -1
- package/runtime/webapp/dist/assets/{calendar-days-CLwKstxM.js → calendar-days-DXE_2mLa.js} +1 -1
- package/runtime/webapp/dist/assets/channel-D66Qxmo0.js +1 -0
- package/runtime/webapp/dist/assets/{check-8EVJMrTV.js → check-UipgMBET.js} +1 -1
- package/runtime/webapp/dist/assets/{chevron-down-ChNxfI2x.js → chevron-down-Dvinwg2S.js} +1 -1
- package/runtime/webapp/dist/assets/{chevron-right-Cbkc_d70.js → chevron-right-BGU3tcLA.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-2Q5K7J3B-Cklzvs8u.js → chunk-2Q5K7J3B-DObpPEgk.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-5VM5RSS4-NxozE5UP.js → chunk-5VM5RSS4-PaTzAg6w.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-F27PBJKO-Dyb8E7YM.js → chunk-F27PBJKO-Pn4gut94.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-IMKFNOWR-BqbMMc1n.js → chunk-IMKFNOWR-nRaVFzK9.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-JWPE2WC7-do0R2H6U.js → chunk-JWPE2WC7-CxssjKKN.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-POPQ4Y6H-B2HIaynf.js → chunk-POPQ4Y6H-CweDXr-B.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-SVP7TREG-C_zmjkwn.js → chunk-SVP7TREG-C7T3FGE-.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-TICWLB2K-Dh2bZgM1.js → chunk-TICWLB2K-Nc0H-0_V.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-XXDRQBXY-CnqciVDz.js → chunk-XXDRQBXY-D_GQGF5g.js} +1 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-BAX0-S6b.js +1 -0
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-BAX0-S6b.js +1 -0
- package/runtime/webapp/dist/assets/{client-I0ZVCjOI.js → client-Bb0hpbIR.js} +1 -1
- package/runtime/webapp/dist/assets/{codeSyntax-C8n4_KZS.js → codeSyntax-DHonp3tF.js} +3 -3
- package/runtime/webapp/dist/assets/{collaboration-lVxWL5ce.js → collaboration-e_iziKU1.js} +1 -1
- package/runtime/webapp/dist/assets/composer-file-routing-CWyT7leB.js +6 -0
- package/runtime/webapp/dist/assets/{cose-bilkent-JH36ORCC-CulKVUkj.js → cose-bilkent-JH36ORCC-Ac_FBan4.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefin-OW5HDTMX-C1LUI1_G.js → cynefin-OW5HDTMX-vr6c389q.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefinDiagram-5FMLGOSQ-D3Ymzw_P.js → cynefinDiagram-5FMLGOSQ-sXmUCrp_.js} +1 -1
- package/runtime/webapp/dist/assets/{dagre-GXQ25YYZ-DRaL0cGu.js → dagre-GXQ25YYZ-B0DmGxDv.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-S7CK7UJ4-D8gLHoZo.js → diagram-S7CK7UJ4-Dn-2jJ6S.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-UQ7AKVKN-CaVU0aQT.js → diagram-UQ7AKVKN-BcasYsju.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-VSXAHHWV-LFAKRvZz.js → diagram-VSXAHHWV-DCgGkc82.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-VX7I27RA-DXpxUERc.js → diagram-VX7I27RA-Cjs0Ny4i.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-Z3DM3KII-vAiik55G.js → diagram-Z3DM3KII-0nyddp0v.js} +1 -1
- package/runtime/webapp/dist/assets/{ebnfDiagram-PWID7BFC-MaFL7Kgb.js → ebnfDiagram-PWID7BFC-By7gCUsz.js} +1 -1
- package/runtime/webapp/dist/assets/{erDiagram-RLTQ6QDP-DuEu79B3.js → erDiagram-RLTQ6QDP-DdwBp45A.js} +1 -1
- package/runtime/webapp/dist/assets/{file-types-ZVLWtslN.js → file-types-nujx8XUw.js} +1 -1
- package/runtime/webapp/dist/assets/{flowDiagram-HODETNUW-BAQ6nP2D.js → flowDiagram-HODETNUW-DbOwRaT9.js} +1 -1
- package/runtime/webapp/dist/assets/{ganttDiagram-EL5Y4UJY-C48VBnPy.js → ganttDiagram-EL5Y4UJY-CG8obc7O.js} +3 -3
- package/runtime/webapp/dist/assets/{gitGraphDiagram-WWUBYQGX-BfWAh9Kr.js → gitGraphDiagram-WWUBYQGX-ru6aSu_g.js} +1 -1
- package/runtime/webapp/dist/assets/{history-D4E3D_aM.js → history-DaBh5_SJ.js} +1 -1
- package/runtime/webapp/dist/assets/{image-plus-DQV_EEAN.js → image-plus-Cm9jq1yo.js} +1 -1
- package/runtime/webapp/dist/assets/index-BAGzBXQc.css +1 -0
- package/runtime/webapp/dist/assets/index-YrEOkxAg.js +500 -0
- package/runtime/webapp/dist/assets/{infoDiagram-27XIBGKW-BM7P_-u_.js → infoDiagram-27XIBGKW-Crx1iSbW.js} +1 -1
- package/runtime/webapp/dist/assets/{ishikawaDiagram-5VMMS53U-Cwd8XR-p.js → ishikawaDiagram-5VMMS53U-ClQPMEk5.js} +1 -1
- package/runtime/webapp/dist/assets/{journeyDiagram-3NMN7TZE-MOgiksTh.js → journeyDiagram-3NMN7TZE-DHso2Xht.js} +1 -1
- package/runtime/webapp/dist/assets/{kanban-definition-UXKFOSKX-DulC5OLL.js → kanban-definition-UXKFOSKX-D6psIAhv.js} +1 -1
- package/runtime/webapp/dist/assets/{layout-Dku9sXQ7.js → layout-B6AVZ9v9.js} +1 -1
- package/runtime/webapp/dist/assets/{linear-B3-dddD7.js → linear-CEZOUjlB.js} +1 -1
- package/runtime/webapp/dist/assets/{list-todo-Bik5IY2r.js → list-todo-D9ChIz0f.js} +1 -1
- package/runtime/webapp/dist/assets/{loader-circle-C5C-IzGK.js → loader-circle-CAHZbD5s.js} +1 -1
- package/runtime/webapp/dist/assets/{locate-fixed-CHkezEEh.js → locate-fixed-2R48MVg_.js} +1 -1
- package/runtime/webapp/dist/assets/{mermaid.core-CRRXKysA.js → mermaid.core-DH0df9xk.js} +5 -5
- package/runtime/webapp/dist/assets/{mindmap-definition-YA3MSWOX-CaaP-nEb.js → mindmap-definition-YA3MSWOX-QWt8leZC.js} +1 -1
- package/runtime/webapp/dist/assets/{mobileViewport-CekmYKqS.js → mobileViewport-CKvpvxYc.js} +1 -1
- package/runtime/webapp/dist/assets/new-session-window-CiRwM3Od.js +191 -0
- package/runtime/webapp/dist/assets/{new-session-window-BfDMd-h3.css → new-session-window-DIU2v1uh.css} +1 -1
- package/runtime/webapp/dist/assets/{page-_fFyRId-.js → page-Cd9ci9uo.js} +6 -6
- package/runtime/webapp/dist/assets/{pause-BsmUCuwZ.js → pause-ddt7BLlm.js} +1 -1
- package/runtime/webapp/dist/assets/{pegDiagram-XKGWAZYB-BqybPEwk.js → pegDiagram-XKGWAZYB-JNBt0nDx.js} +1 -1
- package/runtime/webapp/dist/assets/{pieDiagram-E7YTZNPT-BX1H2lh2.js → pieDiagram-E7YTZNPT-g0hnDqNp.js} +1 -1
- package/runtime/webapp/dist/assets/{pin-BsEEYq8M.js → pin-BTP5lC_c.js} +1 -1
- package/runtime/webapp/dist/assets/{quadrantDiagram-AXDQQJYC-Btnywv1k.js → quadrantDiagram-AXDQQJYC-mLZASjSm.js} +1 -1
- package/runtime/webapp/dist/assets/{railroadDiagram-O6MQD6OU-Da_TV1ER.js → railroadDiagram-O6MQD6OU-CAXNAZhB.js} +1 -1
- package/runtime/webapp/dist/assets/{requirementDiagram-BXWQKSXE-5V1Aow9h.js → requirementDiagram-BXWQKSXE-BC8y1ZXE.js} +1 -1
- package/runtime/webapp/dist/assets/{rotate-ccw-BbSby0GQ.js → rotate-ccw-CHFTy38a.js} +1 -1
- package/runtime/webapp/dist/assets/{rotate-cw-BMdX-ln4.js → rotate-cw-CFCtRFDl.js} +1 -1
- package/runtime/webapp/dist/assets/{sankeyDiagram-P5KCCOFB-D_OIVihV.js → sankeyDiagram-P5KCCOFB-Boi5NPjT.js} +1 -1
- package/runtime/webapp/dist/assets/{send-Cb7EWSJF.js → send-CzCncLlt.js} +1 -1
- package/runtime/webapp/dist/assets/{sequenceDiagram-WJ2MYXX4-LKeF5Mri.js → sequenceDiagram-WJ2MYXX4-D4ccoVEB.js} +1 -1
- package/runtime/webapp/dist/assets/{session-dashboard-BFqNDCc8.js → session-dashboard-C0KfSCDl.js} +1 -1
- package/runtime/webapp/dist/assets/{session-tree-BK_qaCnb.js → session-tree-CTzXmV6R.js} +1 -1
- package/runtime/webapp/dist/assets/{shield-check-C-r87aMq.js → shield-check-Da6EGdIt.js} +1 -1
- package/runtime/webapp/dist/assets/{sizeCapture-INFHLROL-B6j7Q_MN.js → sizeCapture-INFHLROL-Cd5jIVgK.js} +1 -1
- package/runtime/webapp/dist/assets/{stateDiagram-D77RDMKH-zhPFqHdQ.js → stateDiagram-D77RDMKH-DXlmaNwu.js} +1 -1
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-Dh6coc1l.js +1 -0
- package/runtime/webapp/dist/assets/{swimlanes-42K2YHIH-C_FCENx1.js → swimlanes-42K2YHIH-DyhRB_e0.js} +1 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-BzriATjP.js +8 -0
- package/runtime/webapp/dist/assets/{timeline-definition-24CTP7MA-C3DBXjDU.js → timeline-definition-24CTP7MA-Bkfs9Mi-.js} +1 -1
- package/runtime/webapp/dist/assets/{trash-2-DjggJGbw.js → trash-2-C682LDDA.js} +1 -1
- package/runtime/webapp/dist/assets/{types-BQCEWNQz.js → types-CfOuS-6l.js} +1 -1
- package/runtime/webapp/dist/assets/{use-session-activity-BbTXGW7Z.js → use-session-activity-C9Cn92Hj.js} +1 -1
- package/runtime/webapp/dist/assets/{vennDiagram-4TSXK5OY-CssdTIB0.js → vennDiagram-4TSXK5OY-APWT64sw.js} +1 -1
- package/runtime/webapp/dist/assets/{wardleyDiagram-VM6X3IG4-C58K2vVU.js → wardleyDiagram-VM6X3IG4-H7xLoxwM.js} +1 -1
- package/runtime/webapp/dist/assets/{web-B4y8vdRZ.js → web-CT8e03DV.js} +1 -1
- package/runtime/webapp/dist/assets/{web-D9rJZXHW.js → web-DG022HwJ.js} +1 -1
- package/runtime/webapp/dist/assets/{xychartDiagram-S5SC5T6Z-CQi8bD6A.js → xychartDiagram-S5SC5T6Z-DIrxZ4UJ.js} +1 -1
- package/runtime/webapp/dist/assets/{zoom-out-iMMWRXJs.js → zoom-out-CRN76HNZ.js} +1 -1
- package/runtime/webapp/dist/index.html +2 -2
- package/runtime/ws-server.mjs +5 -0
- package/runtime/.next/static/chunks/app/web/error-30cea9cffce0ebc2.js +0 -1
- package/runtime/.next/static/chunks/app/web/layout-d8a4f4131e7f2330.js +0 -1
- package/runtime/.next/static/chunks/main-app-30a478479a347a9e.js +0 -1
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-0e6mn0ck.mjs +0 -17
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-0ssqfy51.mjs +0 -18
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-82ghff97.mjs +0 -39
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-82yhcz2x.mjs +0 -17
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-b8jr1m8m.mjs +0 -23
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-cj0jh226.mjs +0 -17
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-ebtbxtjf.mjs +0 -28
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-pb4erfqh.mjs +0 -42
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-rs058s2g.mjs +0 -16
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-w6pv4szb.mjs +0 -18
- package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-wjeh40nr.mjs +0 -20
- package/runtime/webapp/dist/assets/AIHubView-CM6ugXG3.js +0 -1
- package/runtime/webapp/dist/assets/AiHubPane-DFzC3nbd.js +0 -1
- package/runtime/webapp/dist/assets/App-mF6ELC07.js +0 -68
- package/runtime/webapp/dist/assets/BrowserLivePanel-CamAULwS.js +0 -61
- package/runtime/webapp/dist/assets/CalendarPage-BbYdGYWn.js +0 -1
- package/runtime/webapp/dist/assets/CollaborationCreateDialog-CWhmFQtA.js +0 -1
- package/runtime/webapp/dist/assets/CollaborationDashboard-XL5SnFOu.js +0 -1
- package/runtime/webapp/dist/assets/FileWorkspaceDrawer-BXDuKlrL.js +0 -1
- package/runtime/webapp/dist/assets/FlowStudioPane-lnjLcd9c.js +0 -5
- package/runtime/webapp/dist/assets/HostProjectPicker-DN_vGqQb.js +0 -1
- package/runtime/webapp/dist/assets/NewSessionWindow-zjqAUfKb.js +0 -1
- package/runtime/webapp/dist/assets/RemoteDesktopPage-9AhztqA2.js +0 -1
- package/runtime/webapp/dist/assets/TodoPage-guIvBCW0.js +0 -1
- package/runtime/webapp/dist/assets/artifact-links-B0ApmgK6.js +0 -2
- package/runtime/webapp/dist/assets/channel-BwDuyJO4.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-BfyV8P0w.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-BfyV8P0w.js +0 -1
- package/runtime/webapp/dist/assets/composer-file-routing-qSvJpT-v.js +0 -6
- package/runtime/webapp/dist/assets/download-BE31-Qm0.js +0 -6
- package/runtime/webapp/dist/assets/index-DSgLFE4Q.js +0 -489
- package/runtime/webapp/dist/assets/index-zQk0NCEB.css +0 -1
- package/runtime/webapp/dist/assets/new-session-window-Dgl7UWPR.js +0 -190
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-DWnBZAiI.js +0 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-DOZCbCJP.js +0 -8
- package/runtime/webapp/dist/assets/x-BYUglEo9.js +0 -6
- /package/runtime/.next/static/{5rv6PMhU7yq1sI1ClFWRU → _rMvYWpbWkNWrFkCQx3rK}/_buildManifest.js +0 -0
- /package/runtime/.next/static/{5rv6PMhU7yq1sI1ClFWRU → _rMvYWpbWkNWrFkCQx3rK}/_ssgManifest.js +0 -0
|
@@ -5,18 +5,18 @@
|
|
|
5
5
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
6
|
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
7
|
*/
|
|
8
|
-
"use strict";var Mediabunny=(()=>{var Jp=Object.create;var As=Object.defineProperty;var eh=Object.getOwnPropertyDescriptor;var th=Object.getOwnPropertyNames;var rh=Object.getPrototypeOf,ih=Object.prototype.hasOwnProperty;var kd=(i,t)=>(t=Symbol[i])?t:Symbol.for("Symbol."+i),Td=i=>{throw TypeError(i)};var nh=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),ah=(i,t)=>{for(var e in t)As(i,e,{get:t[e],enumerable:!0})},wd=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of th(t))!ih.call(i,n)&&n!==e&&As(i,n,{get:()=>t[n],enumerable:!(r=eh(t,n))||r.enumerable});return i};var Sd=(i,t,e)=>(e=i!=null?Jp(rh(i)):{},wd(t||!i||!i.__esModule?As(e,"default",{value:i,enumerable:!0}):e,i)),sh=i=>wd(As({},"__esModule",{value:!0}),i);var yt=(i,t,e)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&Td("Object expected");var r,n;e&&(r=t[kd("asyncDispose")]),r===void 0&&(r=t[kd("dispose")],e&&(n=r)),typeof r!="function"&&Td("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(a){return Promise.reject(a)}}),i.push([e,r,t])}else e&&i.push([e]);return t},kt=(i,t,e)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(s,o,c,l){return l=Error(c),l.name="SuppressedError",l.error=s,l.suppressed=o,l},n=s=>t=e?new r(s,t,"An error was suppressed during disposal"):(e=!0,s),a=s=>{for(;s=i.pop();)try{var o=s[1]&&s[1].call(s[2]);if(s[0])return Promise.resolve(o).then(a,c=>(n(c),a()))}catch(c){n(c)}if(e)throw t};return a()};var Mu=nh(()=>{});var my={};ah(my,{ADTS:()=>Pc,ALL_FORMATS:()=>rp,ALL_TRACK_TYPES:()=>dl,AUDIO_CODECS:()=>pe,AdtsInputFormat:()=>cs,AdtsOutputFormat:()=>sl,AppendOnlyStreamTarget:()=>Kc,AttachedFile:()=>Lr,AudioBufferSink:()=>_c,AudioBufferSource:()=>Oc,AudioSample:()=>Ce,AudioSampleResource:()=>Gr,AudioSampleSink:()=>sn,AudioSampleSource:()=>aa,AudioSource:()=>vr,BaseMediaSampleSink:()=>ra,BlobSource:()=>pc,BufferSource:()=>fc,BufferTarget:()=>Bi,CanvasSink:()=>vc,CanvasSource:()=>Mc,CmafOutputFormat:()=>mn,ConcurrentRunner:()=>Cs,Conversion:()=>pl,ConversionCanceledError:()=>bn,CustomAudioDecoder:()=>Da,CustomAudioEncoder:()=>Ua,CustomPathedSource:()=>Zn,CustomSource:()=>Jn,CustomVideoDecoder:()=>Oa,CustomVideoEncoder:()=>Va,EncodedAudioPacketSource:()=>ii,EncodedPacket:()=>ee,EncodedPacketSink:()=>ut,EncodedVideoPacketSource:()=>ri,EventEmitter:()=>st,FLAC:()=>Wu,FilePathSource:()=>gc,FilePathTarget:()=>Gc,FlacInputFormat:()=>os,FlacOutputFormat:()=>ol,HLS:()=>Ic,HLS_FORMATS:()=>ip,HlsInputFormat:()=>nn,HlsOutputFormat:()=>ll,Input:()=>vi,InputAudioTrack:()=>Er,InputDisposedError:()=>ge,InputFormat:()=>nt,InputTrack:()=>Ri,InputVideoTrack:()=>Pr,IsobmffInputFormat:()=>ea,IsobmffOutputFormat:()=>hn,LogLevel:()=>Fl,Logging:()=>O,MATROSKA:()=>zu,MP3:()=>Cc,MP4:()=>Ac,MPEG_TS:()=>Ec,MatroskaInputFormat:()=>ta,MediaSource:()=>on,MediaStreamAudioTrackSource:()=>Dc,MediaStreamVideoTrackSource:()=>Bc,MkvOutputFormat:()=>la,MovOutputFormat:()=>fn,Mp3InputFormat:()=>ns,Mp3OutputFormat:()=>il,Mp4InputFormat:()=>ts,Mp4OutputFormat:()=>ys,MpegTsInputFormat:()=>ls,MpegTsOutputFormat:()=>cl,NON_PCM_AUDIO_CODECS:()=>Jt,NullTarget:()=>Oi,OGG:()=>Hu,OggInputFormat:()=>ss,OggOutputFormat:()=>al,Output:()=>Or,OutputAudioTrack:()=>Ts,OutputFormat:()=>Ne,OutputSubtitleTrack:()=>ws,OutputTrack:()=>gn,OutputTrackGroup:()=>pt,OutputVideoTrack:()=>ks,PCM_AUDIO_CODECS:()=>se,PathedSource:()=>it,PathedTarget:()=>ft,QTFF:()=>xc,QUALITY_HIGH:()=>Qm,QUALITY_LOW:()=>Km,QUALITY_MEDIUM:()=>Gm,QUALITY_VERY_HIGH:()=>jm,QUALITY_VERY_LOW:()=>qm,Quality:()=>ue,QuickTimeInputFormat:()=>rs,RangedSource:()=>Ja,RangedTarget:()=>bs,ReadableStreamSource:()=>rn,RichImageData:()=>At,SUBTITLE_CODECS:()=>qe,Source:()=>Qe,SourceRef:()=>Ei,StreamSource:()=>$f,StreamTarget:()=>ca,SubtitleSource:()=>ln,Target:()=>Oe,TextSubtitleSource:()=>Vc,UnsupportedInputFormatError:()=>na,UrlSource:()=>hc,VIDEO_CODECS:()=>le,VIDEO_SAMPLE_PIXEL_FORMATS:()=>_a,VideoSample:()=>$e,VideoSampleColorSpace:()=>Xi,VideoSampleResource:()=>jt,VideoSampleSink:()=>_i,VideoSampleSource:()=>cn,VideoSource:()=>Ir,WAVE:()=>Lu,WEBM:()=>Nu,WavOutputFormat:()=>nl,WaveInputFormat:()=>as,WebMInputFormat:()=>is,WebMOutputFormat:()=>ir,asc:()=>lp,canDecode:()=>xm,canDecodeAudio:()=>mo,canDecodeVideo:()=>uo,canEncode:()=>Xm,canEncodeAudio:()=>Ma,canEncodeSubtitles:()=>Ba,canEncodeVideo:()=>Fa,desc:()=>ds,getDecodableAudioCodecs:()=>ql,getDecodableCodecs:()=>Pm,getDecodableVideoCodecs:()=>Wl,getEncodableAudioCodecs:()=>Mn,getEncodableCodecs:()=>$m,getEncodableSubtitleCodecs:()=>Zl,getEncodableVideoCodecs:()=>Yl,getFirstEncodableAudioCodec:()=>Ym,getFirstEncodableSubtitleCodec:()=>Zm,getFirstEncodableVideoCodec:()=>To,prefer:()=>Mi,registerDecoder:()=>ef,registerEncoder:()=>tf,registerVideoSampleTransformer:()=>Om});function b(i){if(!i)throw new Error("Assertion failed.")}var wl=Math.PI/180,Ps=180/Math.PI,ai=i=>{let t=(i%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw new Error(`Invalid rotation ${i}.`)},si=[1,0,0,0,1,0,0,0,1],Es=(i,t,e)=>{let[r,n,,a,s]=i,o=Math.abs(r)*t+Math.abs(a)*e,c=Math.abs(n)*t+Math.abs(s)*e;return sr(sr(Ad(-t/2,-e/2),i),Ad(o/2,c/2))},Di=i=>{let[t,e]=i,r=Math.atan2(e,Sl(i)?-t:t);return ai(Fs(r*Ps,90))},Sl=i=>{let[t,e,,r,n]=i;return t*n-e*r<0},Tn=i=>{let t=i*wl,e=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[e,r,0,-r,e,0,0,0,1]},Ad=(i,t)=>[1,0,0,0,1,0,i,t,1],Is=(i,t)=>[i,0,0,0,t,0,0,0,1],sr=(i,t)=>{let e=new Array(9);for(let r=0;r<3;r++)for(let n=0;n<3;n++)e[3*r+n]=i[3*r]*t[n]+i[3*r+1]*t[3+n]+i[3*r+2]*t[6+n];return e},vs=(i,t,e,r)=>({rotation:ai(i+(t?-e:e)),flip:t!==r}),J=i=>i&&i[i.length-1],or=i=>i>=0&&i<2**32,Al=i=>i>=-(2**31)&&i<2**31,V=i=>{let t=0;for(;i.readBits(1)===0&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return 2**t-1+i.readBits(t)},Vi=(i,t)=>{let e=t+1,r=Math.floor(Math.log2(e));i.writeBits(r,0),i.writeBits(1,1),i.writeBits(r,e-2**r)},cr=i=>{let t=V(i);return t%2===0?-(t/2):(t+1)/2},G=i=>i.constructor===Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i),N=i=>i.constructor===DataView?i:ArrayBuffer.isView(i)?new DataView(i.buffer,i.byteOffset,i.byteLength):new DataView(i),oh=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(t=""){let e=new Uint8Array(3*t.length),r=0;for(let n=0;n<t.length;n++){let a=t.charCodeAt(n);if(a<128)e[r++]=a;else if(a<2048)e[r++]=192|a>>6,e[r++]=128|a&63;else if(a<55296||a>57343)e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|a&63;else{let s=n+1<t.length?t.charCodeAt(n+1):0;a<56320&&s>=56320&&s<=57343?(a=65536+(a-55296<<10)+(s-56320),n++,e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|a&63):(e[r++]=239,e[r++]=191,e[r++]=189)}}return e.slice(0,r)}},oi=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(t="utf-8"){let e=t.trim().toLowerCase();if(e==="utf-8"||e==="utf8"||e==="unicode-1-1-utf-8")this.encoding="utf-8";else if(e==="utf-16le"||e==="utf-16")this.encoding="utf-16le";else if(e==="utf-16be")this.encoding="utf-16be";else throw new RangeError(`The encoding label provided ('${t}') is invalid.`)}decode(t){let e=t?G(t):new Uint8Array(0),r=[];if(this.encoding==="utf-8"){let a=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?3:0;for(;a<e.length;){let s=e[a];if(s<128){r.push(s),a++;continue}let o,c;if(s>=194&&s<224)o=1,c=s&31;else if(s>=224&&s<240)o=2,c=s&15;else if(s>=240&&s<245)o=3,c=s&7;else{r.push(65533),a++;continue}let l=s===224?160:s===240?144:128,u=s===237?159:s===244?143:191,d=1;for(;d<=o;d++){let m=a+d<e.length?e[a+d]:0;if(m<l||m>u)break;c=c<<6|m&63,l=128,u=191}a+=d,d<=o?r.push(65533):c>=65536?(c-=65536,r.push(55296|c>>10,56320|c&1023)):r.push(c)}}else{let a=this.encoding==="utf-16le",s=a?255:254,o=a?254:255,c=e.length>=2&&e[0]===s&&e[1]===o?2:0;for(;c+1<e.length;){let l=a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1];if(c+=2,l>=55296&&l<=56319){let u=c+1<e.length?a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1]:-1;u>=56320&&u<=57343?(r.push(l,u),c+=2):(r.push(65533),c+1===e.length&&c++)}else l>=56320&&l<=57343?r.push(65533):r.push(l)}c<e.length&&r.push(65533)}let n="";for(let a=0;a<r.length;a+=8192)n+=String.fromCharCode(...r.slice(a,a+8192));return n}},be=new oi,Cd=new oi("utf-8",{fatal:!0}),Y=new oh,Ht=i=>{for(let t=0;t<i.length;t++)if(i.charCodeAt(t)>255)return!1;return!0},xl=i=>Object.fromEntries(Object.entries(i).map(([t,e])=>[e,t])),_t={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Tt=xl(_t),Rt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},wt=xl(Rt),Ft={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},St=xl(Ft),wn=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!=null,_s=i=>!i||i.primaries==null&&i.transfer==null&&i.matrix==null&&i.fullRange==null,Rs={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Dr=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),Ee=class{constructor(){this.currentPromise=Promise.resolve();this.pending=0}async acquire(){let t,e=new Promise(n=>{let a=!1;t=()=>{a||(n(),this.pending--,a=!0)}}),r=this.currentPromise;return this.currentPromise=e,this.pending++,await r,t}},Pd=/^[0-9a-fA-F]+$/,ci=i=>[...i].map(t=>t.toString(16).padStart(2,"0")).join(""),Ed=i=>{b(i.length%2===0);let t=new Uint8Array(i.length/2);for(let e=0;e<i.length;e+=2)t[e/2]=parseInt(i.slice(e,e+2),16);return t},Cl=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),Vr=(i,t,e)=>{let r=0,n=i.length-1,a=-1;for(;r<=n;){let s=r+n>>1,o=e(i[s]);o===t?(a=s,n=s-1):o<t?r=s+1:n=s-1}return a},j=(i,t,e)=>{let r=0,n=i.length-1,a=-1;for(;r<=n;){let s=r+(n-r+1)/2|0;e(i[s])<=t?(a=s,r=s+1):n=s-1}return a},Pl=(i,t,e)=>{let r=j(i,e(t),e);i.splice(r+1,0,t)},te=()=>{let i,t;return{promise:new Promise((r,n)=>{i=r,t=n}),resolve:i,reject:t}},Sn=(i,t)=>{let e=i.indexOf(t);e!==-1&&i.splice(e,1)},El=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return i[e]},lr=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1},Id=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},vd=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},Z=i=>{throw new Error(`Unexpected value: ${i}`)},Ui=(i,t,e)=>{let r=i.getUint8(t),n=i.getUint8(t+1),a=i.getUint8(t+2);return e?r|n<<8|a<<16:r<<16|n<<8|a},_d=(i,t,e)=>Ui(i,t,e)<<8>>8,zi=(i,t,e,r)=>{e=e>>>0,e=e&16777215,r?(i.setUint8(t,e&255),i.setUint8(t+1,e>>>8&255),i.setUint8(t+2,e>>>16&255)):(i.setUint8(t,e>>>16&255),i.setUint8(t+1,e>>>8&255),i.setUint8(t+2,e&255))},Rd=(i,t,e,r)=>{e=ne(e,-8388608,8388607),e<0&&(e=e+16777216&16777215),zi(i,t,e,r)},Fd=(i,t,e,r)=>{e=Math.trunc(e),r?(i.setUint32(t+0,e,!0),i.setInt32(t+4,Math.floor(e/2**32),!0)):(i.setInt32(t+0,Math.floor(e/2**32),!1),i.setUint32(t+4,e,!1))},da=(i,t)=>({async next(){let e=await i.next();if(e.done)return{value:void 0,done:!0};try{return{value:t(e.value),done:!1}}catch(r){throw await i.return(),r}},return(){return i.return()},throw(e){return i.throw(e)},[Symbol.asyncIterator](){return this}}),ne=(i,t,e)=>Math.max(t,Math.min(e,i)),Md=(i,t,e)=>i+(t-i)*e,Il=(i,t)=>i-Math.floor(i/t)*t,ce="und",Fe=i=>{let t=Math.round(i);return Math.abs(i/t-1)<10*Number.EPSILON?t:i},Fs=(i,t)=>Math.round(i/t)*t,Mt=(i,t)=>Math.round(i*t)/t,An=(i,t)=>Math.floor(i/t)*t,vl=(i,t)=>Math.floor(i*t)/t,Bd=i=>{let t=0;for(;i;)t++,i>>=1;return t},Ms=i=>{let t=0;for(;i!==0;)i&=i-1,t++;return t},ch=/^[a-z]{3}$/,Ur=i=>ch.test(i),ur=1e6*(1+Number.EPSILON),Bs=(i,t)=>{let e={...i,...t};if(i.headers||t.headers){let r=i.headers?xs(i.headers):{},n=t.headers?xs(t.headers):{},a={...r};Object.entries(n).forEach(([s,o])=>{let c=Object.keys(a).find(l=>l.toLowerCase()===s.toLowerCase());c&&delete a[c],a[s]=o}),e.headers=a}return e},xs=i=>{if(i instanceof Headers){let t={};return i.forEach((e,r)=>{t[r]=e}),t}if(Array.isArray(i)){let t={};return i.forEach(([e,r])=>{t[e]=r}),t}return i},_l=async(i,t,e,r,n)=>{let a=0;for(;;)try{return await i(t,e)}catch(s){if(n())throw s;a++;let o=r(a,s,t);if(o===null)throw s;if(O._error("Retrying failed fetch. Error:",s),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Nr(1e3*o),n())throw s}},Od=(i,t)=>{let e=i<0?-1:1;i=Math.abs(i);let r=0,n=1,a=1,s=0,o=i;for(;;){let c=Math.floor(o),l=c*a+r,u=c*s+n;if(u>t)return{num:e*a,den:s};if(r=a,n=s,a=l,s=u,o=1/(o-c),!isFinite(o))break}return{num:e*a,den:s}},ni=class{constructor(){this.currentPromise=Promise.resolve()}call(t){let e=this.currentPromise.then(t);return this.currentPromise=e.catch(()=>{}),e}},gl=null,et=()=>gl!==null?gl:gl=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),bl=null,Wt=()=>bl!==null?bl:bl=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),yl=null,Ni=()=>yl!==null?yl:yl=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),kl=null,Dd=()=>{if(kl!==null)return kl;if(typeof navigator>"u")return null;let i=/\bChrome\/(\d+)/.exec(navigator.userAgent);return i?kl=Number(i[1]):null},Tl=null,Vd=()=>Tl!==null?Tl:Tl=typeof navigator<"u"&&/Android/.test(navigator.userAgent),xn=i=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${i} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${i} is not available in this environment.`,Ud=i=>i instanceof DOMException&&i.name==="QuotaExceededError"&&/reclaimed/i.test(i.message),lh=(async()=>{})().constructor,R=i=>i instanceof lh||i instanceof Promise?!0:typeof i?.then=="function",Li=(i,t)=>i!==-1?i:t,Os=(i,t,e,r)=>i<=r&&e<=t,qt=function*(i){for(let t in i){let e=i[t];e!==void 0&&(yield{key:t,value:e})}},zd=i=>{switch(i.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},Hi=i=>{let t;try{t=atob(i)}catch{throw new Error("Invalid base64 string.")}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e},Nd=i=>{let t="";for(let e=0;e<i.length;e++)t+=String.fromCharCode(i[e]);return btoa(t)},Ds=(i,t)=>{if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++)if(i[e]!==t[e])return!1;return!0},Cn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Ie=i=>typeof i=="number"&&!Number.isNaN(i),ve=(i,t)=>{if(/^(?:[a-z][a-z0-9+.-]*:\/\/|(?:data|blob):)/i.test(t))return t;if(i.includes("://")){let l=i.search(/[?#]/);l!==-1&&(i=i.slice(0,l))}let e=t.search(/[?#]/),r=e===-1?"":t.slice(e);e!==-1&&(t=t.slice(0,e));let n;if(t==="")n=i;else if(t.startsWith("/")){let l=i.indexOf("://");if(l===-1)n=t;else if(t.startsWith("//"))n=i.slice(0,l+1)+t;else{let u=i.indexOf("/",l+3);u===-1?n=i+t:n=i.slice(0,u)+t}}else{let l=i.indexOf("://"),u=i.lastIndexOf("/");l!==-1&&u===l+2?n=i+"/"+t:u===-1?n=t:n=i.slice(0,u+1)+t}let a="",s=n.indexOf("://");if(s!==-1){let l=n.indexOf("/",s+3);l!==-1&&(a=n.slice(0,l),n=n.slice(l))}let o=n.split("/"),c=[];for(let l of o)l===".."?c.length===0||c[c.length-1]===".."?c.push(".."):(c.length!==1||c[0]!=="")&&c.pop():l!=="."&&c.push(l);return a+c.join("/")+r},Ld=(i,t)=>{let e=i.indexOf("#"),r=e===-1?i:i.slice(0,e),n=r.indexOf("?");return n===-1?null:new URLSearchParams(r.slice(n+1)).get(t)},Wi=(i,t)=>{let e=0;for(let r=0;r<i.length;r++)t(i[r])&&e++;return e},li=(i,t)=>{let e=-1,r=1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);(e===-1||a<r)&&(r=a,e=n)}return e},Hd=(i,t)=>{let e=-1,r=-1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);(e===-1||a>r)&&(r=a,e=n)}return e},zr=i=>{b(Number.isInteger(i.num)),b(Number.isInteger(i.den)),b(i.den!==0);let t=Math.abs(i.num),e=Math.abs(i.den);for(;e!==0;){let n=t%e;t=e,e=n}let r=t||1;return{num:i.num/r,den:i.den/r}},Wd=(i,t)=>{if(typeof i!="object"||!i)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},ua,uh=1,xd=new Map,Rl=new Map,qd=()=>typeof window>"u",dh=()=>{let i=new Map,t=new Map;self.onmessage=e=>{let r=e.data;switch(r.type){case"set-timeout":{let n=setTimeout(()=>{i.delete(r.timerId),self.postMessage({type:"fire",timerId:r.timerId})},r.delay);i.set(r.timerId,n)}break;case"set-interval":{let n=setInterval(()=>{self.postMessage({type:"fire",timerId:r.timerId})},r.delay);t.set(r.timerId,n)}break;case"clear-timeout":{let n=i.get(r.timerId);n!==void 0&&(clearTimeout(n),i.delete(r.timerId))}break;case"clear-interval":{let n=t.get(r.timerId);n!==void 0&&(clearInterval(n),t.delete(r.timerId))}break}}},Kd=()=>{if(ua)return ua;let i=`(${dh.toString()})();`,t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));return ua=new Worker(t),URL.revokeObjectURL(t),ua.onmessage=e=>{let r=e.data,n=xd.get(r.timerId);if(n){xd.delete(r.timerId),n();return}let a=Rl.get(r.timerId);a&&a()},ua};var Gd=(i,t)=>{if(qd())return{id:setInterval(i,t)};let e=uh++;return Rl.set(e,()=>{i()}),Kd().postMessage({type:"set-interval",timerId:e,delay:t}),{id:e}},Qd=i=>{if(qd()){clearInterval(i.id);return}b(typeof i.id=="number"),Rl.delete(i.id),Kd().postMessage({type:"clear-interval",timerId:i.id})},Nr=i=>new Promise(t=>setTimeout(t,i));var Bt=i=>Array.isArray(i)?i:[i],st=class{constructor(){this._listeners=new Map}on(t,e,r){this._listeners.has(t)||this._listeners.set(t,new Set);let n={fn:e,once:r?.once??!1};return this._listeners.get(t).add(n),()=>{this._listeners.get(t)?.delete(n)}}_emit(...t){let[e,r]=t,n=this._listeners.get(e);if(n){for(let a of[...n])if(n.has(a)){a.once&&n.delete(a);try{a.fn(r)}catch(s){console.error(s)}}}}},qi=i=>Math.ceil(i/2)*2,Cs=class{constructor(t){this._queue=[];this._errored=!1;this.parallelism=t}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(t){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);let e=t();this._queue.push(e),e.then(()=>Sn(this._queue,e)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}},Vs=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(t=>typeof t=="string"),Pn=(i,t=0,e=1)=>{let r=new Date(0);return r.setUTCFullYear(i,t,e),r},mh=/^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:[T ](\d{2})(?::(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?)?)?)?(?:Z|([+-])(\d{2})(?::?(\d{2}))?)?$/,Kt=i=>{let t=mh.exec(i);if(!t)return null;let[,e,r="01",n="01",a="00",s="00",o="00",c="",l="+",u="00",d="00"]=t,m=`${e}-${r}-${n}T${a}:${s}:${o}`,f=new Date(`${m}.${c.padEnd(3,"0").slice(0,3)}Z`);if(Number.isNaN(f.getTime())||!f.toISOString().startsWith(m)||Number(u)>23||Number(d)>59)return null;let p=(l==="-"?-1:1)*(60*Number(u)+Number(d));return f.setTime(f.getTime()-6e4*p),f};var Fl=(n=>(n[n.Silent=0]="Silent",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.Info=3]="Info",n))(Fl||{}),ot=class ot{constructor(){}static get level(){return ot._level}static set level(t){if(t!==0&&t!==1&&t!==2&&t!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ot._level=t}static get _emitter(){return ot._emitterInstance??=new st}static on(t,e,r){return ot._emitter.on(t,e,r)}static _error(...t){ot._emitter._emit("error",t),ot._level>=1&&console.error(...t)}static _warn(...t){ot._emitter._emit("warn",t),ot._level>=2&&console.warn(...t)}static _info(...t){ot._emitter._emit("info",t),ot._level>=3&&console.info(...t)}};ot._level=3,ot._emitterInstance=null;var O=ot;var At=class{constructor(t,e){this.data=t;this.mimeType=e;if(!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof e!="string")throw new TypeError("mimeType must be a string.")}},Lr=class{constructor(t,e,r,n){this.data=t;this.mimeType=e;this.name=r;this.description=n;if(!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!==void 0&&typeof e!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}},ma=i=>{if(!i||typeof i!="object")throw new TypeError("tags must be an object.");if(i.title!==void 0&&typeof i.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(i.description!==void 0&&typeof i.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(i.artist!==void 0&&typeof i.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(i.album!==void 0&&typeof i.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(i.albumArtist!==void 0&&typeof i.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(i.trackNumber!==void 0&&(!Number.isInteger(i.trackNumber)||i.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(i.tracksTotal!==void 0&&(!Number.isInteger(i.tracksTotal)||i.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(i.discNumber!==void 0&&(!Number.isInteger(i.discNumber)||i.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(i.discsTotal!==void 0&&(!Number.isInteger(i.discsTotal)||i.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(i.genre!==void 0&&typeof i.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(i.date!==void 0&&(!(i.date instanceof Date)||Number.isNaN(i.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(i.creationTime!==void 0&&i.creationTime!==null&&(!(i.creationTime instanceof Date)||Number.isNaN(i.creationTime.getTime())))throw new TypeError("tags.creationTime, when provided, must be a valid Date or null.");if(i.beatsPerMinute!==void 0&&(!Number.isInteger(i.beatsPerMinute)||i.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(i.lyrics!==void 0&&typeof i.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(i.images!==void 0){if(!Array.isArray(i.images))throw new TypeError("tags.images, when provided, must be an array.");for(let t of i.images){if(!t||typeof t!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof t.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("Each image.name, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("Each image.description, when provided, must be a string.")}}if(i.comment!==void 0&&typeof i.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(i.raw!==void 0){if(!i.raw||typeof i.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let t of Object.values(i.raw))if(t!==null&&typeof t!="string"&&!(Array.isArray(t)&&t.every(e=>typeof e=="string"))&&!(t instanceof Uint8Array)&&!(Array.isArray(t)&&t.every(e=>e instanceof Uint8Array))&&!(t instanceof At)&&!(t instanceof Lr)&&!Vs(t))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, Uint8Array array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Hr=i=>i.title===void 0&&i.description===void 0&&i.artist===void 0&&i.album===void 0&&i.albumArtist===void 0&&i.trackNumber===void 0&&i.tracksTotal===void 0&&i.discNumber===void 0&&i.discsTotal===void 0&&i.genre===void 0&&i.beatsPerMinute===void 0&&i.date===void 0&&i.lyrics===void 0&&(!i.images||i.images.length===0)&&i.comment===void 0&&(i.raw===void 0||Object.keys(i.raw).length===0),Ve={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},jd=i=>{if(!i||typeof i!="object")throw new TypeError("disposition must be an object.");if(i.default!==void 0&&typeof i.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(i.primary!==void 0&&typeof i.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(i.forced!==void 0&&typeof i.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(i.original!==void 0&&typeof i.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(i.commentary!==void 0&&typeof i.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(i.hearingImpaired!==void 0&&typeof i.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(i.visuallyImpaired!==void 0&&typeof i.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var K=class i{constructor(t){this.bytes=t;this.pos=0}seekToByte(t){this.pos=8*t}readBit(){let t=Math.floor(this.pos/8),e=this.bytes[t]??0,r=7-(this.pos&7),n=(e&1<<r)>>r;return this.pos++,n}readBits(t){if(t===1)return this.readBit();let e=0;for(let r=0;r<t;r++)e=2*e+this.readBit();return e}writeBits(t,e){let r=this.pos+t;for(let n=this.pos;n<r;n++){let a=Math.floor(n/8),s=this.bytes[a],o=7-(n&7),c=Math.floor(e/2**(r-n-1))&1;s&=~(1<<o),s|=c<<o,this.bytes[a]=s}this.pos=r}copyBits(t,e){let r=0;for(r;r<t-7;r+=8)this.writeBits(8,e.readBits(8));let n=t-r;n>0&&this.writeBits(n,e.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new i(this.bytes);return t.pos=this.pos,t}};var Xe=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],dr=[-1,1,2,3,4,5,6,8],fh=[1,2,3,4,6,7,17,19,20,21,22],xt=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let t=new K(i),e=Ml(t),{frequencyIndex:r,sampleRate:n}=Bl(t),a=t.readBits(4),s=null;a>=1&&a<=7&&(s=dr[a]);let o=e,c=!1,l=n;(e===5||e===29)&&(c=e===29,l=Bl(t).sampleRate,o=Ml(t),o===22&&t.skipBits(4));let u=1024,d=null;if(fh.includes(o)&&(u=t.readBits(1)?960:1024,a===0&&(t.readBits(1)&&t.skipBits(14),t.skipBits(1),d=Jd(t),s=Wr(d))),e!==5&&e!==29)for(;t.getBitsLeft()>15;){let m=t.pos;if(t.readBits(11)!==695){t.pos=m+1;continue}Ml(t)===5&&t.readBits(1)&&(l=Bl(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return s!==null&&s>1&&(c=!1),{objectType:e,coreObjectType:o,frequencyIndex:r,channelConfiguration:a,coreSampleRate:n,outputSampleRate:l,outputNumberOfChannels:c&&s===1?2:s,frameLength:u,programConfigElement:d}},Ml=i=>{let t=i.readBits(5);return t===31?32+i.readBits(6):t},Bl=i=>{let t=i.readBits(4);return t===15?{frequencyIndex:t,sampleRate:i.readBits(24)}:{frequencyIndex:t,sampleRate:t<Xe.length?Xe[t]:null}},ui=i=>{let t=i.objectType===5||i.objectType===29,e=i.objectType===29,r=t?i.outputSampleRate/2:i.outputSampleRate,n=e?1:i.outputNumberOfChannels,a=i.programConfigElement?0:dr.indexOf(n);if(a===-1)throw new TypeError(`Unsupported number of channels: ${i.outputNumberOfChannels}`);let s=16;i.objectType>=32&&(s+=6),Ol(r)===15&&(s+=24),t&&(s+=9,Ol(i.outputSampleRate)===15&&(s+=24));let o=Math.ceil(s/8)+(i.programConfigElement?Yd(i.programConfigElement):0),c=new Uint8Array(o),l=new K(c);return Xd(l,i.objectType),$d(l,r),l.writeBits(4,a),t&&($d(l,i.outputSampleRate),Xd(l,2)),l.writeBits(3,0),i.programConfigElement&&Zd(l,i.programConfigElement),c.subarray(0,Math.ceil(l.pos/8))},Xd=(i,t)=>{t<32?i.writeBits(5,t):(i.writeBits(5,31),i.writeBits(6,t-32))},$d=(i,t)=>{let e=Ol(t);i.writeBits(4,e),e===15&&i.writeBits(24,t)},Ol=i=>{let t=Xe.indexOf(i);return t===-1?15:t},Us=i=>{let{coreObjectType:t,frequencyIndex:e,frameLength:r}=i,{channelConfiguration:n,programConfigElement:a}=i;if(t<1||t>4)throw new Error(`AAC object type ${t} can't be stored in ADTS.`);if(e>=Xe.length)throw new Error(`AAC sampling frequency index ${e} can't be stored in ADTS.`);if(n===11||n===12){let l={isCpe:!0,tagSelect:1};a={elementInstanceTag:0,objectType:t-1,samplingFrequencyIndex:e,frontElements:[{isCpe:!1,tagSelect:0},{isCpe:!0,tagSelect:0}],sideElements:n===12?[l]:[],backElements:n===11?[l,{isCpe:!1,tagSelect:1}]:[{isCpe:!0,tagSelect:2}],lfeElementTags:[0],assocDataElementTags:[],ccElements:[],monoMixdownElementNumber:null,stereoMixdownElementNumber:null,matrixMixdown:null,comment:new Uint8Array(0)},n=0}if(n>7)throw new Error(`AAC channel configuration ${n} can't be stored in ADTS.`);if(r!==1024)throw new Error(`AAC frame length ${r} can't be stored in ADTS.`);let s=new Uint8Array(7+(a?Yd(a):0)),o=new K(s),c=t-1;return o.writeBits(12,4095),o.writeBits(1,0),o.writeBits(2,0),o.writeBits(1,1),o.writeBits(2,c),o.writeBits(4,e),o.writeBits(1,0),o.writeBits(3,n),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(1,0),o.skipBits(13),o.writeBits(11,2047),o.writeBits(2,0),a&&(o.pos=8*7,o.writeBits(3,5),Zd(o,a),s=s.subarray(0,o.pos/8)),{header:s,bitstream:o}},Yd=i=>64+i.comment.byteLength,Zd=(i,t)=>{i.writeBits(4,t.elementInstanceTag),i.writeBits(2,t.objectType),i.writeBits(4,t.samplingFrequencyIndex),i.writeBits(4,t.frontElements.length),i.writeBits(4,t.sideElements.length),i.writeBits(4,t.backElements.length),i.writeBits(2,t.lfeElementTags.length),i.writeBits(3,t.assocDataElementTags.length),i.writeBits(4,t.ccElements.length),i.writeBits(1,+(t.monoMixdownElementNumber!==null)),t.monoMixdownElementNumber!==null&&i.writeBits(4,t.monoMixdownElementNumber),i.writeBits(1,+(t.stereoMixdownElementNumber!==null)),t.stereoMixdownElementNumber!==null&&i.writeBits(4,t.stereoMixdownElementNumber),i.writeBits(1,+(t.matrixMixdown!==null)),t.matrixMixdown&&(i.writeBits(2,t.matrixMixdown.index),i.writeBits(1,+t.matrixMixdown.pseudoSurroundEnabled));for(let e of[...t.frontElements,...t.sideElements,...t.backElements])i.writeBits(1,+e.isCpe),i.writeBits(4,e.tagSelect);for(let e of[...t.lfeElementTags,...t.assocDataElementTags])i.writeBits(4,e);for(let e of t.ccElements)i.writeBits(1,+e.isIndependentlySwitched),i.writeBits(4,e.tagSelect);i.pos=8*Math.ceil(i.pos/8),i.writeBits(8,t.comment.byteLength),i.bytes.set(t.comment,i.pos/8),i.pos+=8*t.comment.byteLength},zs=(i,t)=>{if(t>=2**13)throw new Error(`AAC frame too large for ADTS (${t} bytes, at most ${2**13-1} allowed).`);i.pos=30,i.writeBits(13,t)},mr=i=>{let t=new K(i);if(t.readBits(3)!==5)return null;let e=Jd(t),r=t.pos/8;if(r>i.byteLength)throw new Error("Invalid ADTS frame: its program config element extends past the end of the frame.");return{programConfigElement:e,size:r}},Jd=i=>{let t=i.readBits(4),e=i.readBits(2),r=i.readBits(4),n=i.readBits(4),a=i.readBits(4),s=i.readBits(4),o=i.readBits(2),c=i.readBits(3),l=i.readBits(4),u=i.readBits(1)?i.readBits(4):null,d=i.readBits(1)?i.readBits(4):null,m=i.readBits(1)?{index:i.readBits(2),pseudoSurroundEnabled:!!i.readBits(1)}:null,f=A=>Array.from({length:A},()=>({isCpe:!!i.readBits(1),tagSelect:i.readBits(4)})),p=f(n),g=f(a),h=f(s),y=Array.from({length:o},()=>i.readBits(4)),k=Array.from({length:c},()=>i.readBits(4)),T=Array.from({length:l},()=>({isIndependentlySwitched:!!i.readBits(1),tagSelect:i.readBits(4)}));i.pos=8*Math.ceil(i.pos/8);let S=i.readBits(8),w=i.bytes.slice(i.pos/8,i.pos/8+S);return i.pos+=8*S,{elementInstanceTag:t,objectType:e,samplingFrequencyIndex:r,frontElements:p,sideElements:g,backElements:h,lfeElementTags:y,assocDataElementTags:k,ccElements:T,monoMixdownElementNumber:u,stereoMixdownElementNumber:d,matrixMixdown:m,comment:w}},Wr=i=>[...i.frontElements,...i.sideElements,...i.backElements].reduce((e,r)=>e+(r.isCpe?2:1),i.lfeElementTags.length);var Dl=[44100,48e3,32e3],Ns=[-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],qr=1483304551,di=1231971951,em=1447187017,Ls=(i,t,e,r,n)=>t===0?0:t===1?Math.floor(144*e/(r<<i))+n:t===2?Math.floor(144*e/r)+n:(Math.floor(12*e/r)+n)*4,tm=(i,t,e,r)=>t===0?0:t===1?144*e/(r<<i):t===2?144*e/r:12*e/r*4,mi=(i,t)=>i===3?t===3?21:36:t===3?13:21,fr=(i,t)=>{let e=i>>>24,r=i>>>16&255,n=i>>>8&255,a=i&255;if(e!==255&&r!==255&&n!==255&&a!==255)return{header:null,bytesAdvanced:4};if(e!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let s=0,o=0;r&16?s=r&8?0:1:(s=1,o=1);let c=r>>3&3,l=r>>1&3,u=n>>4&15,d=n>>2&3;if(c===1||d===3)return{header:null,bytesAdvanced:1};let m=n>>1&1,f=a>>6&3,p=a>>4&3,g=a>>3&1,h=a>>2&1,y=a&3,k=Ns[s*16*4+l*16+u];if(k===-1)return{header:null,bytesAdvanced:1};let T=k*1e3,S=Dl[d]>>s+o,w=Ls(s,l,T,S,m);if(t!==null&&t<w)return{header:null,bytesAdvanced:1};let A;return c===3?A=l===3?384:1152:l===3?A=384:l===2?A=1152:A=576,{header:{totalSize:w,mpegVersionId:c,lowSamplingFrequency:s,layer:l,bitrate:T,frequencyIndex:d,sampleRate:S,channel:f,modeExtension:p,copyright:g,original:h,emphasis:y,audioSamplesInFrame:A},bytesAdvanced:1}},rm=i=>{let t=127,e=0,r=i;for(;(t^2147483647)!==0;)e=r&~t,e<<=1,e|=r&t,t=(t+1<<8)-1,r=e;return e},fa=i=>{let t=2130706432,e=0;for(;t!==0;)e>>=1,e|=i&t,t>>=8;return e};var fi=i=>i===3?1:2;var Ki=[48e3,44100,32e3],Vl=[24e3,22050,16e3];var ph="1.66.2",Kr=`Mediabunny v${ph}`;var pi=function*(i){let t=0,e=-1;for(;t<i.length-2;){let r=i.indexOf(0,t);if(r===-1||r>=i.length-2)break;t=r;let n=0;if(t+3<i.length&&i[t+1]===0&&i[t+2]===0&&i[t+3]===1?n=4:i[t+1]===0&&i[t+2]===1&&(n=3),n===0){t++;continue}e!==-1&&t>e&&(yield{offset:e,length:t-e}),e=t+n,t=e}e!==-1&&e<i.length&&(yield{offset:e,length:i.length-e})},Ws=function*(i,t){let e=0,r=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;e+t<=i.length;){let n;t===1?n=r.getUint8(e):t===2?n=r.getUint16(e,!1):t===3?n=Ui(r,e,!1):(b(t===4),n=r.getUint32(e,!1)),e+=t,yield{offset:e,length:n},e+=n}},zl=(i,t)=>{if(t.description){let n=(G(t.description)[4]&3)+1;return Ws(i,n)}else return pi(i)},pr=i=>i&31,qs=i=>{let t=new Uint8Array(i.length),e=i.length,r=0;for(let n=0;n<e;n++)n+2<e&&i[n]===0&&i[n+1]===0&&i[n+2]===3?(t[r++]=0,t[r++]=0,n+=2):t[r++]=i[n];return t.subarray(0,r)},hh=i=>{let t=[],e=0;for(let r of i)e===2&&r<=3&&(t.push(3),e=0),t.push(r),e=r===0?e+1:0;return new Uint8Array(t)},Ul=new Uint8Array([0,0,0,1]),ga=i=>{let t=i.reduce((n,a)=>n+Ul.byteLength+a.byteLength,0),e=new Uint8Array(t),r=0;for(let n of i)e.set(Ul,r),r+=Ul.byteLength,e.set(n,r),r+=n.byteLength;return e},Ks=(i,t)=>{let e=i.reduce((a,s)=>a+t+s.byteLength,0),r=new Uint8Array(e),n=0;for(let a of i){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:s.setUint8(n,a.byteLength);break;case 2:s.setUint16(n,a.byteLength,!1);break;case 3:zi(s,n,a.byteLength,!1);break;case 4:s.setUint32(n,a.byteLength,!1);break}n+=t,r.set(a,n),n+=a.byteLength}return r},sm=(i,t)=>{if(t.description){let n=(G(t.description)[4]&3)+1;return Ks(i,n)}else return ga(i)},hr=i=>{try{let t=[],e=[],r=[];for(let o of pi(i)){let c=i.subarray(o.offset,o.offset+o.length),l=pr(c[0]);l===7&&t.length<31?t.push(c):l===8&&e.length<255?e.push(c):l===13&&r.length<255&&r.push(c)}if(t.length===0||e.length===0)return null;let n=t[0],a=Gt(n);if(!a)return null;let s=Nl(a.profileIdc);return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:e,chromaFormat:s?a.chromaFormatIdc:null,bitDepthLumaMinus8:s?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:s?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:s?r:null}}catch(t){return O._error("Error building AVC Decoder Configuration Record:",t),null}},En=i=>{let t=[];t.push(i.configurationVersion),t.push(i.avcProfileIndication),t.push(i.profileCompatibility),t.push(i.avcLevelIndication),t.push(252|i.lengthSizeMinusOne&3),t.push(224|i.sequenceParameterSets.length&31);for(let e of i.sequenceParameterSets){let r=e.byteLength;t.push(r>>8),t.push(r&255);for(let n=0;n<r;n++)t.push(e[n])}t.push(i.pictureParameterSets.length);for(let e of i.pictureParameterSets){let r=e.byteLength;t.push(r>>8),t.push(r&255);for(let n=0;n<r;n++)t.push(e[n])}if(Nl(i.avcProfileIndication)&&i.chromaFormat!==null){b(i.bitDepthLumaMinus8!==null),b(i.bitDepthChromaMinus8!==null),b(i.sequenceParameterSetExt!==null),t.push(252|i.chromaFormat&3),t.push(248|i.bitDepthLumaMinus8&7),t.push(248|i.bitDepthChromaMinus8&7),t.push(i.sequenceParameterSetExt.length);for(let e of i.sequenceParameterSetExt){let r=e.byteLength;t.push(r>>8),t.push(r&255);for(let n=0;n<r;n++)t.push(e[n])}}return new Uint8Array(t)},gr=i=>{try{let t=N(i),e=0,r=t.getUint8(e++),n=t.getUint8(e++),a=t.getUint8(e++),s=t.getUint8(e++),o=t.getUint8(e++)&3,c=t.getUint8(e++)&31,l=[];for(let f=0;f<c;f++){let p=t.getUint16(e,!1);e+=2,l.push(i.subarray(e,e+p)),e+=p}let u=t.getUint8(e++),d=[];for(let f=0;f<u;f++){let p=t.getUint16(e,!1);e+=2,d.push(i.subarray(e,e+p)),e+=p}let m={configurationVersion:r,avcProfileIndication:n,profileCompatibility:a,avcLevelIndication:s,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(Nl(n)&&e+4<=i.length){let f=t.getUint8(e++)&3,p=t.getUint8(e++)&7,g=t.getUint8(e++)&7,h=t.getUint8(e++);m.chromaFormat=f,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=g;let y=[];for(let k=0;k<h;k++){let T=t.getUint16(e,!1);e+=2,y.push(i.subarray(e,e+T)),e+=T}m.sequenceParameterSetExt=y}return m}catch(t){return O._error("Error deserializing AVC Decoder Configuration Record:",t),null}},Nl=i=>i!==66&&i!==77&&i!==88,om={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}},Gt=i=>{try{let t=qs(i),e=new K(t);if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),a=e.readAlignedByte(),s=e.readAlignedByte();V(e);let o=1,c=0,l=0,u=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128||n===138||n===139||n===134||n===135||n===144)&&(o=V(e),o===3&&(u=e.readBits(1)),c=V(e),l=V(e),e.skipBits(1),e.readBits(1))){for(let z=0;z<(o!==3?8:12);z++)if(e.readBits(1)){let fe=z<6?16:64,ye=8,we=8;for(let Ze=0;Ze<fe;Ze++){if(we!==0){let at=cr(e);we=(ye+at+256)%256}ye=we===0?ye:we}}}V(e);let d=V(e);if(d===0)V(e);else if(d===1){e.skipBits(1),cr(e),cr(e);let L=V(e);for(let z=0;z<L;z++)cr(e)}let m=V(e);e.skipBits(1);let f=V(e),p=V(e),g=e.readBits(1);g||e.skipBits(1);let h=16*(f+1),y=16*(2-g)*(p+1),k=h,T=y;if(e.skipBits(1),e.readBits(1)){let L=V(e),z=V(e),$=V(e),fe=V(e),ye,we;if((u===0?o:0)===0)ye=1,we=2-g;else{let at=o===3?1:2,Le=o===1?2:1;ye=at,we=Le*(2-g)}k-=ye*(L+z),T-=we*($+fe)}if(k<=0||T<=0)return null;let w=2,A=2,C=2,E=0,I={num:1,den:1},x=null,P=null,v=null,_=null,M=e.pos;if(e.readBits(1)){if(e.readBits(1)){let at=e.readBits(8);if(at===255)I={num:e.readBits(16),den:e.readBits(16)};else{let Le=om[at];Le&&(I=Le)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),E=e.readBits(1),e.readBits(1)&&(w=e.readBits(8),A=e.readBits(8),C=e.readBits(8))),e.readBits(1)&&(V(e),V(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let we=e.readBits(1);we&&im(e);let Ze=e.readBits(1);Ze&&im(e),(we||Ze)&&e.skipBits(1),e.skipBits(1),v=e.pos,_=e.readBits(1),_&&(e.skipBits(1),V(e),V(e),V(e),V(e),x=Math.min(V(e),16),P=Math.min(V(e),16))}if(x===null){b(P===null);let L=a&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&L)x=0,P=0;else{let z=f+1,$=p+1,fe=(2-g)*$,ye=s===11&&L&&(n===66||n===77||n===88),we=ha.find(at=>at.level>=(ye?10:s))??J(ha),Ze=Math.min(Math.floor(we.maxDpbMbs/(z*fe)),16);x=Ze,P=Math.min(Math.max(Ze,m),16)}}return b(P!==null),{emulationUnpreventedBytes:t,profileIdc:n,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:g,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:h,codedHeight:y,displayWidth:k,displayHeight:T,pixelAspectRatio:I,colourPrimaries:w,matrixCoefficients:C,transferCharacteristics:A,fullRangeFlag:E,numReorderFrames:x,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:M,bitstreamRestrictionFlagBitOffset:v,bitstreamRestrictionFlag:_}}catch(t){return O._error("Error parsing AVC SPS:",t),null}},im=i=>{let t=V(i);i.skipBits(4),i.skipBits(4);for(let e=0;e<=t;e++)V(i),V(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},Ll=i=>{b(i.bitstreamRestrictionFlag!==1);let t=new Uint8Array(i.emulationUnpreventedBytes.byteLength+64),e=new K(i.emulationUnpreventedBytes),r=new K(t);i.bitstreamRestrictionFlag===null?(r.copyBits(i.vuiParametersFlagBitOffset,e),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(b(i.bitstreamRestrictionFlagBitOffset!==null),r.copyBits(i.bitstreamRestrictionFlagBitOffset,e)),r.writeBits(1,1),r.writeBits(1,1),Vi(r,2),Vi(r,1),Vi(r,16),Vi(r,16),Vi(r,i.numReorderFrames),Vi(r,i.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);let n=r.pos/8;return b(Number.isInteger(n)),hh(t.subarray(0,n))},gh=(i,t)=>{if(t.description){let n=(G(t.description)[21]&3)+1;return Ks(i,n)}else return ga(i)},pa=(i,t)=>{if(t.description){let n=(G(t.description)[21]&3)+1;return Ws(i,n)}else return pi(i)},Qt=i=>i>>1&63,Qi=i=>{try{let t=new K(qs(i));t.skipBits(16),t.readBits(4);let e=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:a,general_profile_idc:s,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=bh(t,e);V(t);let u=V(t),d=0;u===3&&(d=t.readBits(1));let m=V(t),f=V(t),p=m,g=f;if(t.readBits(1)){let _=V(t),M=V(t),D=V(t),L=V(t),z=1,$=1,fe=d===0?u:0;fe===1?(z=2,$=2):fe===2&&(z=2,$=1),p-=(_+M)*z,g-=(D+L)*$}if(p<=0||g<=0)return null;let h=V(t),y=V(t),k=V(t),S=t.readBits(1)?0:e,w=0;for(let _=S;_<=e;_++)V(t),w=V(t),V(t);V(t),V(t),V(t),V(t),V(t),V(t),t.readBits(1)&&t.readBits(1)&&yh(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),V(t),V(t),t.skipBits(1));let A=V(t);if(kh(t,A),t.readBits(1)){let _=V(t);for(let M=0;M<_;M++)t.skipBits(k+4),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let C=2,E=2,I=2,x=0,P=0,v={num:1,den:1};if(t.readBits(1)){let _=wh(t,e);v=_.pixelAspectRatio,C=_.colourPrimaries,E=_.transferCharacteristics,I=_.matrixCoefficients,x=_.fullRangeFlag,P=_.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:v,colourPrimaries:C,transferCharacteristics:E,matrixCoefficients:I,fullRangeFlag:x,maxDecFrameBuffering:Math.min(w+1,16),spsMaxSubLayersMinus1:e,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:s,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:h,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:P}}catch(t){return O._error("Error parsing HEVC SPS:",t),null}},br=i=>{try{let t=[],e=[],r=[],n=[],a=[];for(let d of pi(i)){let m=i.subarray(d.offset,d.offset+d.length),f=Qt(m[0]);f===32&&t.length<65535?t.push(m):f===33&&e.length<65535?e.push(m):f===34&&r.length<65535?r.push(m):f===39&&n.length<65535?n.push(m):f===40&&a.length<65535&&a.push(m)}if(e.length===0||r.length===0)return null;let o=Qi(e[0]);if(!o)return null;let c=0;if(r.length>0){let d=r[0],m=new K(qs(d));m.skipBits(16),V(m),V(m),m.skipBits(1),m.skipBits(1),m.skipBits(3),m.skipBits(1),m.skipBits(1),V(m),V(m),cr(m),m.skipBits(1),m.skipBits(1),m.readBits(1)&&V(m),cr(m),cr(m),m.skipBits(1),m.skipBits(1),m.skipBits(1),m.skipBits(1);let f=m.readBits(1),p=m.readBits(1);!f&&!p?c=0:f&&!p?c=2:!f&&p?c=3:c=0}let l=[...t.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:t}]:[],...e.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:r}]:[],...n.length?[{arrayCompleteness:0,nalUnitType:39,nalUnits:n}]:[],...a.length?[{arrayCompleteness:0,nalUnitType:40,nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(t){return O._error("Error building HEVC Decoder Configuration Record:",t),null}},bh=(i,t)=>{let e=i.readBits(2),r=i.readBits(1),n=i.readBits(5),a=0;for(let u=0;u<32;u++)a=a<<1|i.readBits(1);let s=new Uint8Array(6);for(let u=0;u<6;u++)s[u]=i.readBits(8);let o=i.readBits(8),c=[],l=[];for(let u=0;u<t;u++)c.push(i.readBits(1)),l.push(i.readBits(1));if(t>0)for(let u=t;u<8;u++)i.skipBits(2);for(let u=0;u<t;u++)c[u]&&i.skipBits(88),l[u]&&i.skipBits(8);return{general_profile_space:e,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:a,general_constraint_indicator_flags:s,general_level_idc:o}},yh=i=>{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(!i.readBits(1))V(i);else{let n=Math.min(64,1<<4+(t<<1));t>1&&cr(i);for(let a=0;a<n;a++)cr(i)}},kh=(i,t)=>{let e=[];for(let r=0;r<t;r++)e[r]=Th(i,r,t,e)},Th=(i,t,e,r)=>{let n=0,a=0,s=0;if(t!==0&&(a=i.readBits(1)),a){if(t===e){let c=V(i);s=t-(c+1)}else s=t-1;i.readBits(1),V(i);let o=r[s]??0;for(let c=0;c<=o;c++)(i.readBits(1)||i.readBits(1))&&n++}else{let o=V(i),c=V(i);for(let l=0;l<o;l++)V(i),i.readBits(1);for(let l=0;l<c;l++)V(i),i.readBits(1);n=o+c}return n},wh=(i,t)=>{let e=2,r=2,n=2,a=0,s=0,o={num:1,den:1};if(i.readBits(1)){let c=i.readBits(8);if(c===255)o={num:i.readBits(16),den:i.readBits(16)};else{let l=om[c];l&&(o=l)}}return i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),a=i.readBits(1),i.readBits(1)&&(e=i.readBits(8),r=i.readBits(8),n=i.readBits(8))),i.readBits(1)&&(V(i),V(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(V(i),V(i),V(i),V(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&V(i),i.readBits(1)&&Sh(i,!0,t)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),s=V(i),V(i),V(i),V(i),V(i)),{pixelAspectRatio:o,colourPrimaries:e,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:a,minSpatialSegmentationIdc:s}},Sh=(i,t,e)=>{let r=!1,n=!1,a=!1;t&&(r=i.readBits(1)===1,n=i.readBits(1)===1,(r||n)&&(a=i.readBits(1)===1,a&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),a&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let s=0;s<=e;s++){let o=i.readBits(1)===1,c=!0;o||(c=i.readBits(1)===1);let l=!1;c?V(i):l=i.readBits(1)===1;let u=1;l||(u=V(i)+1),r&&nm(i,u,a),n&&nm(i,u,a)}},nm=(i,t,e)=>{for(let r=0;r<t;r++)V(i),V(i),e&&(V(i),V(i)),i.readBits(1)},cm=i=>{let t=[];t.push(i.configurationVersion),t.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),t.push(i.generalProfileCompatibilityFlags>>>24&255),t.push(i.generalProfileCompatibilityFlags>>>16&255),t.push(i.generalProfileCompatibilityFlags>>>8&255),t.push(i.generalProfileCompatibilityFlags&255),t.push(...i.generalConstraintIndicatorFlags),t.push(i.generalLevelIdc&255),t.push(240|i.minSpatialSegmentationIdc>>8&15),t.push(i.minSpatialSegmentationIdc&255),t.push(252|i.parallelismType&3),t.push(252|i.chromaFormatIdc&3),t.push(248|i.bitDepthLumaMinus8&7),t.push(248|i.bitDepthChromaMinus8&7),t.push(i.avgFrameRate>>8&255),t.push(i.avgFrameRate&255),t.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),t.push(i.arrays.length&255);for(let e of i.arrays){t.push((e.arrayCompleteness&1)<<7|0|e.nalUnitType&63),t.push(e.nalUnits.length>>8&255),t.push(e.nalUnits.length&255);for(let r of e.nalUnits){t.push(r.length>>8&255),t.push(r.length&255);for(let n=0;n<r.length;n++)t.push(r[n])}}return new Uint8Array(t)},In=i=>{try{let t=N(i),e=0,r=t.getUint8(e++),n=t.getUint8(e++),a=n>>6&3,s=n>>5&1,o=n&31,c=t.getUint32(e,!1);e+=4;let l=i.subarray(e,e+6);e+=6;let u=t.getUint8(e++),d=(t.getUint8(e++)&15)<<8|t.getUint8(e++),m=t.getUint8(e++)&3,f=t.getUint8(e++)&3,p=t.getUint8(e++)&7,g=t.getUint8(e++)&7,h=t.getUint16(e,!1);e+=2;let y=t.getUint8(e++),k=y>>6&3,T=y>>3&7,S=y>>2&1,w=y&3,A=t.getUint8(e++),C=[];for(let E=0;E<A;E++){let I=t.getUint8(e++),x=I>>7&1,P=I&63,v=t.getUint16(e,!1);e+=2;let _=[];for(let M=0;M<v;M++){let D=t.getUint16(e,!1);e+=2,_.push(i.subarray(e,e+D)),e+=D}C.push({arrayCompleteness:x,nalUnitType:P,nalUnits:_})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:m,chromaFormatIdc:f,bitDepthLumaMinus8:p,bitDepthChromaMinus8:g,avgFrameRate:h,constantFrameRate:k,numTemporalLayers:T,temporalIdNested:S,lengthSizeMinusOne:w,arrays:C}}catch(t){return O._error("Error deserializing HEVC Decoder Configuration Record:",t),null}};var lm=(i,t)=>{let e=new Set,r=0;for(let a of pa(i,t)){if(r===4){e.add(a.offset);continue}let s=Qt(i[a.offset]);if(r===3&&s!==37){e.add(a.offset);continue}let o=!1;s===35?r>0?o=!0:r=1:s<=31?r>2?o=!0:r=2:s===36?r!==2?o=!0:r=3:s===37?r<2?o=!0:r=4:s===32||s===33||s===34||s===39||s>=41&&s<=44||s>=48&&s<=55?r>1?o=!0:r=1:(s===38||s===40||s>=45&&s<=47||s>=56&&s<=63)&&r<2&&(o=!0),o&&e.add(a.offset)}if(e.size===0)return null;let n=[];for(let a of pa(i,t))e.has(a.offset)||n.push(i.subarray(a.offset,a.offset+a.length));return gh(n,t)},Ah={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},vn=i=>{let t=new K(i);if(t.readBits(2)!==2)return null;let r=t.readBits(1),a=(t.readBits(1)<<1)+r;if(a===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let l=8;a>=2&&(l=t.readBits(1)?12:10);let u=t.readBits(3),d=0,m=0;if(u!==7)if(m=t.readBits(1),a===1||a===3){let E=t.readBits(1),I=t.readBits(1);d=!E&&!I?3:E&&!I?2:1,t.skipBits(1)}else d=1;else d=3,m=1,(a===1||a===3)&&t.skipBits(1);let f=t.readBits(16),p=t.readBits(16),g=f+1,h=p+1,y=g*h,k=J(Gi).level;for(let C of Gi)if(y<=C.maxPictureSize){k=C.level;break}let T=Ah[u],S=T?.colourPrimaries??2,w=T?.transferCharacteristics??2,A=T?.matrixCoefficients??2;return{profile:a,level:k,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:S,transferCharacteristics:w,matrixCoefficients:A}},um=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,dm=function*(i){let t=new K(i),e=()=>{let r=0;for(let n=0;n<8;n++){let a=t.readAlignedByte();if(r+=(a&127)*2**(n*7),!(a&128))break;if(n===7&&a&128)return null}return r>2**32-1?null:r};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),n=t.readBits(1),a=t.readBits(1);t.skipBits(1),n&&t.skipBits(8);let s;if(a){let o=e();if(o===null)return;s=o}else s=Math.floor(t.getBitsLeft()/8);b(t.pos%8===0),yield{type:r,data:i.subarray(t.pos/8,t.pos/8+s)},t.skipBits(s*8)}},hi=i=>{for(let{type:t,data:e}of dm(i)){if(t!==1)continue;let r=new K(e),n=r.readBits(3),a=r.readBits(1),s=r.readBits(1),o=0,c=0,l=0;if(s)o=r.readBits(5);else{let x=r.readBits(1),P=0;if(x){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let D=0;for(;D<32&&!r.readBits(1);)D++;D<32&&r.skipBits(D)}P=r.readBits(1),P&&(l=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}let v=r.readBits(1),_=r.readBits(5);for(let M=0;M<=_;M++){r.skipBits(12);let D=r.readBits(5);if(M===0&&(o=D),D>7){let L=r.readBits(1);M===0&&(c=L)}if(P&&r.readBits(1)){let z=l+1;r.skipBits(z),r.skipBits(z),r.skipBits(1)}v&&r.readBits(1)&&r.skipBits(4)}}let u=r.readBits(4),d=r.readBits(4),m=u+1;r.skipBits(m);let f=d+1;r.skipBits(f);let p=0;if(s?p=0:p=r.readBits(1),p&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let x=r.readBits(1);x&&(r.skipBits(1),r.skipBits(1));let P=r.readBits(1),v=0;P?v=2:v=r.readBits(1),v>0&&(r.readBits(1)||r.skipBits(1)),x&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);let g=r.readBits(1),h=8;n===2&&g?h=r.readBits(1)?12:10:n<=2&&(h=g?10:8);let y=0;n!==1&&(y=r.readBits(1));let k=2,T=2,S=2;r.readBits(1)&&(k=r.readBits(8),T=r.readBits(8),S=r.readBits(8));let A=0,C=1,E=1,I=0;return y?A=r.readBits(1):k===1&&T===13&&S===0?(A=1,C=0,E=0):(A=r.readBits(1),n===0?(C=1,E=1):n===1?(C=0,E=0):h===12?(C=r.readBits(1),E=C?r.readBits(1):0):(C=1,E=0),C&&E&&(I=r.readBits(2))),{profile:n,level:o,tier:c,bitDepth:h,monochrome:y,chromaSubsamplingX:C,chromaSubsamplingY:E,chromaSamplePosition:I,videoFullRangeFlag:A,colourPrimaries:k,transferCharacteristics:T,matrixCoefficients:S}}return null},Gs=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,Qs=i=>{if(i.length<28)return null;let e=N(i);return e.getUint32(4)!==1768124518||e.getUint16(8)<20?null:{fullRange:!1,colourPrimaries:e.getUint8(22),transferCharacteristics:e.getUint8(23),matrixCoefficients:e.getUint8(24)}},yr=i=>{if(i.byteLength<19)throw new Error("Invalid Opus identification header: too short.");let t=N(i),e=t.getUint8(9),r=t.getUint16(10,!0),n=t.getUint32(12,!0),a=t.getInt16(16,!0),s=t.getUint8(18),o=null;return s&&(o=i.subarray(19)),{outputChannelCount:e,preSkip:r,inputSampleRate:n,outputGain:a,channelMappingFamily:s,channelMappingTable:o}},xh=[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],js=i=>{let t=i[0]>>3,e=i[0]&3,r;return e===0?r=1:e===1||e===2?r=2:r=i[1]&63,{durationInSamples:xh[t]*r}},Xs=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let e=i.length,r=new Uint8Array(e);for(let d=0;d<e;d++)r[d]=i[e-1-d];let n=new K(r),a=0;for(;n.getBitsLeft()>97;)if(n.readBits(1)===1){a=n.pos;break}if(a===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,o=!1,c=0;for(;n.getBitsLeft()>=97;){let d=n.pos,m=n.readBits(8),f=n.readBits(16),p=n.readBits(16);if(m>63||f!==0||p!==0){n.pos=d;break}if(n.skipBits(1),s++,s>64)break;n.clone().readBits(6)+1===s&&(o=!0,c=s)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;n.pos=0,n.skipBits(a);let u=Array(l).fill(0);for(let d=l-1;d>=0;d--)n.skipBits(40),u[d]=n.readBits(1);return{modeBlockflags:u}},gi=(i,t,e)=>{switch(i){case"avc":{for(let r of zl(e,t)){let n=e[r.offset],a=pr(n);if(a>=1&&a<=4)return"delta";if(a===5)return"key";if(a===6&&!Ni()){let s=e.subarray(r.offset,r.offset+r.length),o=qs(s),c=1;do{let l=0;for(;;){let m=o[c++];if(m===void 0||(l+=m,m<255))break}let u=0;for(;;){let m=o[c++];if(m===void 0||(u+=m,m<255))break}if(l===6){let m=new K(o);m.pos=8*c;let f=-1;try{f=V(m)}catch{}let p=m.readBits(1);if(f===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(let r of pa(e,t)){let n=Qt(e[r.offset]);if(n<16)return"delta";if(n<=23)return"key"}return"delta"}case"vp8":return(e[0]&1)===0?"key":"delta";case"vp9":{let r=new K(e);if(r.readBits(2)!==2)return null;let n=r.readBits(1);return(r.readBits(1)<<1)+n===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(let{type:n,data:a}of dm(e))if(n===1){let s=new K(a);s.skipBits(4),r=!!s.readBits(1)}else if(n===3||n===6||n===7){if(r)return"key";let s=new K(a);if(s.readBits(1))return null;let c=s.readBits(2),l=s.readBits(1);return c===0&&l===1?"key":"delta"}return null}case"prores":return"key";default:Z(i),b(!1)}},mm=(i,t)=>{if(i==="vp8")return t[0]>>4&1;if(i==="vp9"){let e=n=>{let a=new K(n);a.skipBits(2);let s=a.readBits(1),o=a.readBits(1);return s===1&&o===1&&a.skipBits(1),a.readBits(1)===1?!0:(a.skipBits(1),a.readBits(1)===1)},r=t[t.length-1];if((r&224)===192){let n=(r&7)+1,a=(r>>3&3)+1,s=t.length-(2+n*a);if(t[s]===r){let o=0,c=0;for(let l=0;l<n;l++){let u=0;for(let d=0;d<a;d++)u+=t[s+1+l*a+d]*2**(8*d);e(t.subarray(c,c+u))&&o++,c+=u}return o}}return e(t)?1:0}return 1},_n=(i,t)=>i==="truehd"?(t.byteLength>=8?N(t).getUint32(4):null)===4168249274?"key":"delta":"key";var ba=(i,t)=>{let e=N(i),r=0;if(i.length<4)return;let n=e.getUint32(r,!0);r+=4;let a=be.decode(i.subarray(r,r+n));if(r+=n,n>0&&(t.raw??={},t.raw.vendor??=a),r+4>i.length)return;let s=e.getUint32(r,!0);r+=4;for(let o=0;o<s&&!(r+4>i.length);o++){let c=e.getUint32(r,!0);r+=4;let l=be.decode(i.subarray(r,r+c));r+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),m=l.slice(u+1);switch(t.raw??={},Array.isArray(t.raw[d])?t.raw[d].push(m):typeof t.raw[d]=="string"?t.raw[d]=[t.raw[d],m]:t.raw[d]??=m,d){case"TITLE":t.title??=m;break;case"DESCRIPTION":t.description??=m;break;case"ARTIST":t.artist??=m;break;case"ALBUM":t.album??=m;break;case"ALBUMARTIST":t.albumArtist??=m;break;case"COMMENT":t.comment??=m;break;case"LYRICS":t.lyrics??=m;break;case"TRACKNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(t.tracksTotal??=g)}break;case"TRACKTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.tracksTotal??=f)}break;case"DISCNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.discNumber??=p),g&&Number.isInteger(g)&&g>0&&(t.discsTotal??=g)}break;case"DISCTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.discsTotal??=f)}break;case"DATE":{let f=Kt(m);f&&(t.date??=f)}break;case"BPM":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.beatsPerMinute??=f)}break;case"GENRE":t.genre??=m;break;case"METADATA_BLOCK_PICTURE":try{let f=Hi(m),p=N(f),g=p.getUint32(0,!1),h=p.getUint32(4,!1),y=be.decode(f.subarray(8,8+h)),k=p.getUint32(8+h,!1),T=be.decode(f.subarray(12+h,12+h+k)),S=p.getUint32(h+k+28),w=f.subarray(h+k+32,h+k+32+S);t.images??=[],t.images.push({data:w,mimeType:y,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:T||void 0})}catch{}break}}},ya=(i,t,e)=>{let r=[i],n=Y.encode(Kr),a=new Uint8Array(4+n.length),s=new DataView(a.buffer);s.setUint32(0,n.length,!0),a.set(n,4),r.push(a);let o=[],c=(f,p)=>{let g=`${f}=${p}`,h=Y.encode(g);a=new Uint8Array(4+h.length),s=new DataView(a.buffer),s.setUint32(0,h.length,!0),a.set(h,4),r.push(a),o.push(f)};for(let{key:f,value:p}of qt(t))switch(f){case"title":c("TITLE",p);break;case"description":c("DESCRIPTION",p);break;case"artist":c("ARTIST",p);break;case"album":c("ALBUM",p);break;case"albumArtist":c("ALBUMARTIST",p);break;case"genre":c("GENRE",p);break;case"date":c("DATE",p.toISOString().slice(0,10));break;case"comment":c("COMMENT",p);break;case"lyrics":c("LYRICS",p);break;case"trackNumber":c("TRACKNUMBER",p.toString());break;case"tracksTotal":c("TRACKTOTAL",p.toString());break;case"discNumber":c("DISCNUMBER",p.toString());break;case"discsTotal":c("DISCTOTAL",p.toString());break;case"beatsPerMinute":c("BPM",p.toString());break;case"images":{if(!e)break;for(let g of p){let h=g.kind==="coverFront"?3:g.kind==="coverBack"?4:0,y=new Uint8Array(g.mimeType.length);for(let A=0;A<g.mimeType.length;A++)y[A]=g.mimeType.charCodeAt(A);let k=Y.encode(g.description??""),T=new Uint8Array(8+y.length+4+k.length+16+4+g.data.length),S=N(T);S.setUint32(0,h,!1),S.setUint32(4,y.length,!1),T.set(y,8),S.setUint32(8+y.length,k.length,!1),T.set(k,12+y.length),S.setUint32(28+y.length+k.length,g.data.length,!1),T.set(g.data,32+y.length+k.length);let w=Nd(T);c("METADATA_BLOCK_PICTURE",w)}}break;case"raw":break;case"creationTime":break;default:Z(f)}if(t.raw)for(let f in t.raw){let p=t.raw[f]??t.raw[f.toLowerCase()];if(!(f==="vendor"||p==null||o.includes(f))&&!(f==="METADATA_BLOCK_PICTURE"&&!e&&(t.images?.length??0)>0)){if(typeof p=="string")c(f,p);else if(Array.isArray(p)&&p.every(h=>typeof h=="string"))for(let h of p)c(f,h)}}let l=new Uint8Array(4);N(l).setUint32(0,o.length,!0),r.splice(2,0,l);let u=r.reduce((f,p)=>f+p.length,0),d=new Uint8Array(u),m=0;for(let f of r)d.set(f,m),m+=f.length;return d},ka=[2,1,2,3,3,4,4,5],$s=i=>{if(i.length<7||i[0]!==11||i[1]!==119)return null;let t=new K(i);t.skipBits(16),t.skipBits(16);let e=t.readBits(2);if(e===3)return null;let r=t.readBits(6),n=t.readBits(5);if(n>8)return null;let a=t.readBits(3),s=t.readBits(3);(s&1)!==0&&s!==1&&t.skipBits(2),(s&4)!==0&&t.skipBits(2),s===2&&t.skipBits(2);let o=t.readBits(1),c=Math.floor(r/2);return{fscod:e,bsid:n,bsmod:a,acmod:s,lfeon:o,bitRateCode:c}},fm=[64*2,69*2,96*2,64*2,70*2,96*2,80*2,87*2,120*2,80*2,88*2,120*2,96*2,104*2,144*2,96*2,105*2,144*2,112*2,121*2,168*2,112*2,122*2,168*2,128*2,139*2,192*2,128*2,140*2,192*2,160*2,174*2,240*2,160*2,175*2,240*2,192*2,208*2,288*2,192*2,209*2,288*2,224*2,243*2,336*2,224*2,244*2,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],pm=1536,Ta=new Uint8Array([5,4,65,67,45,51]),wa=new Uint8Array([5,4,69,65,67,51]),Ys=[1,2,3,6],Zs=i=>{if(i.length<6||i[0]!==11||i[1]!==119)return null;let t=new K(i);t.skipBits(16);let e=t.readBits(2);if(t.skipBits(3),e!==0&&e!==2)return null;let r=t.readBits(11),n=t.readBits(2),a=0,s;n===3?(a=t.readBits(2),s=3):s=t.readBits(2);let o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=Ys[s],d;n<3?d=Ki[n]/1e3:d=Vl[a]/1e3;let m=Math.round((r+1)*d/(u*16)),f=0,p=0,g=0,h=2*(r+1);for(;h+2<=i.length&&(t.seekToByte(h),!(t.readBits(16)!==2935||t.readBits(2)!==1));){t.skipBits(3);let k=t.readBits(11);t.skipBits(4);let T=t.readBits(3);if(t.skipBits(11),t.readBits(1)&&t.skipBits(8),T===0&&(t.skipBits(5),t.readBits(1)&&t.skipBits(8)),t.readBits(1)){let S=t.readBits(16);for(let w=0;w<8;w++)S&1<<10-w&&(g|=1<<w);S&2&&(g|=256)}p++,h+=2*(k+1)}return{dataRate:m,substreams:[{fscod:n,fscod2:a,bsid:l,bsmod:f,acmod:o,lfeon:c,numDepSub:p,chanLoc:g}]}},Js=i=>{let t=[],e=0;for(;e<i.length;){if(e+6>i.length||i[e]!==11||i[e+1]!==119)return null;let r=i[e+2]>>6,n=(i[e+2]&7)<<8|i[e+3],s=i[e+4]>>6===3?3:i[e+4]>>4&3,o=i[e+5]>>3,c=2*(n+1);if(o<=10||e+c>i.length)return null;if(r===1){let l=J(t);if(!l)return null;l.size+=c}else t.push({offset:e,size:c,blockCount:Ys[s]});e+=c}return t},hm=i=>{if(i.length<2)return null;let t=new K(i),e=t.readBits(13),r=t.readBits(3),n=[];for(let a=0;a<=r&&!(Math.ceil(t.pos/8)+3>i.length);a++){let s=t.readBits(2),o=t.readBits(5);t.skipBits(1),t.skipBits(1);let c=t.readBits(3),l=t.readBits(3),u=t.readBits(1);t.skipBits(3);let d=t.readBits(4),m=0;d>0?m=t.readBits(9):t.skipBits(1),n.push({fscod:s,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:m})}return n.length===0?null:{dataRate:e,substreams:n}},eo=i=>{let t=i.substreams[0];return b(t),t.fscod<3?Ki[t.fscod]:t.fscod2!==null&&t.fscod2<3?Vl[t.fscod2]:null},to=i=>{let t=i.substreams[0];b(t);let e=ka[t.acmod]+t.lfeon;if(t.numDepSub>0){let r=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)t.chanLoc&1<<n&&(e+=r[n])}return e};var Ch=1683496997,Sa=18,ro=10,gm=4096,am=32,io=20,Ph=8,Eh=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Ih=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],vh=[16,16,20,20,0,24,24,0],Hs=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],_h=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Rh=8,Fh=44646,Mh=[32e3,44100,48e3,0],Bh=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],bm=[512,1024,2048,4096],Aa=i=>{let t=Hl(i),e=N(i),r=t?Math.ceil(t.frameSize/4)*4:0,n=null;for(;r+4<=i.length&&e.getUint32(r)===Ch;){let s=xa(i.subarray(r));if(!s)break;n??=s,r+=s.frameSize}if(t)return{frameSize:n?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:n!==null};if(!n?.asset)return null;let{asset:a}=n;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},no=i=>{let t=Aa(i);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Hl=i=>{if(i.length<Sa||i[0]!==127||i[1]!==254||i[2]!==128||i[3]!==1)return null;let t=new K(i);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==am-1)return null;let e=t.readBits(1),r=t.readBits(7)+1;if(r%Ph!==0)return null;let n=t.readBits(14)+1;if(n<96)return null;let a=t.readBits(6);if(a>=Hs.length)return null;let s=Eh[t.readBits(4)];if(s===0)return null;let o=Ih[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4);let c=t.readBits(3),l=t.readBits(1);t.skipBits(1);let u=t.readBits(2);if(u===3)return null;t.skipBits(1),e&&t.skipBits(16),t.skipBits(7);let d=vh[t.readBits(3)];if(d===0)return null;let m=u!==0;return{frameSize:n,sampleRate:s,numberOfChannels:Hs[a]+(m?1:0),sampleCount:r*am,channelLayout:_h[a]|(m?Rh:0),amode:a,lfePresent:m,bitRate:o,pcmResolution:d,extAudioId:l?c:null}},xa=i=>{if(i.length<ro||i[0]!==100||i[1]!==88||i[2]!==32||i[3]!==37)return null;let t=new K(i);t.skipBits(32),t.skipBits(8);let e=t.readBits(2),r=t.readBits(1),n=8+4*r,a=16+4*r;t.skipBits(n);let s=t.readBits(a)+1,o={frameSize:s,asset:null};if(!t.readBits(1))return o;let c=Mh[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,m=[];for(let y=0;y<u;y++)m.push(t.readBits(e+1));for(let y of m)t.skipBits(8*Ms(y));if(t.readBits(1)){t.skipBits(2);let y=t.readBits(2)+1<<2,k=t.readBits(2)+1;t.skipBits(k*y)}for(let y=0;y<d;y++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let f=t.readBits(5)+1,p=Bh[t.readBits(4)],g=t.readBits(8)+1,h=0;if(t.readBits(1)&&(g>2&&t.skipBits(1),g>6&&t.skipBits(1),t.readBits(1))){let y=t.readBits(2)+1<<2;h=t.readBits(y)}return c===0||t.getBitsLeft()<0?o:{frameSize:s,asset:{sampleRate:p,numberOfChannels:g,sampleCount:Math.round(l*p/c),channelLayout:h,pcmResolution:f}}},ym=i=>{if(i.length<io)return null;let t=N(i),e=t.getUint32(0);if(e===0)return null;let r=new K(i);r.seekToByte(13);let n=r.readBits(2);r.skipBits(5);let a=r.readBits(1),s=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let o=r.readBits(16),c=null;return o!==0?c=Dh(o):s<Hs.length&&(c=Hs[s]+a),{sampleRate:e,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:i[12],sampleCount:bm[n],channelLayout:o,numberOfChannels:c}},Oh={0:2,2:4,6:3},km=i=>{let t=new Uint8Array(io),e=N(t);e.setUint32(0,i.sampleRate),e.setUint32(4,i.bitRate),e.setUint32(8,i.bitRate),t[12]=i.pcmResolution;let r=0;if(i.core&&!i.hasExtensions){let{extAudioId:a}=i.core;r=a===null?1:Oh[a]??0}let n=new K(t);return n.seekToByte(13),n.writeBits(2,Math.max(bm.indexOf(i.sampleCount),0)),n.writeBits(5,r),n.writeBits(1,i.core?.lfePresent?1:0),n.writeBits(6,i.core?.amode??0),n.writeBits(14,i.core?i.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,i.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),t},Dh=i=>Ms(i)+Ms(i&Fh);var Ca=/(?:(.+?)\n)?((?:\d{2,}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2,}:)?\d{2}:\d{2}.\d{3})/g,Vh=/^WEBVTT(.|\n)*?\n{2}/,Rn=/<(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})>/g,ao=class{constructor(t){this.preambleText=null;this.preambleEmitted=!1;this.options=t}parse(t){t=t.replaceAll(`\r
|
|
8
|
+
"use strict";var Mediabunny=(()=>{var Jp=Object.create;var xs=Object.defineProperty;var eh=Object.getOwnPropertyDescriptor;var th=Object.getOwnPropertyNames;var rh=Object.getPrototypeOf,ih=Object.prototype.hasOwnProperty;var yd=(i,t)=>(t=Symbol[i])?t:Symbol.for("Symbol."+i),kd=i=>{throw TypeError(i)};var nh=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),ah=(i,t)=>{for(var e in t)xs(i,e,{get:t[e],enumerable:!0})},Td=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of th(t))!ih.call(i,n)&&n!==e&&xs(i,n,{get:()=>t[n],enumerable:!(r=eh(t,n))||r.enumerable});return i};var wd=(i,t,e)=>(e=i!=null?Jp(rh(i)):{},Td(t||!i||!i.__esModule?xs(e,"default",{value:i,enumerable:!0}):e,i)),sh=i=>Td(xs({},"__esModule",{value:!0}),i);var yt=(i,t,e)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&kd("Object expected");var r,n;e&&(r=t[yd("asyncDispose")]),r===void 0&&(r=t[yd("dispose")],e&&(n=r)),typeof r!="function"&&kd("Object not disposable"),n&&(r=function(){try{n.call(this)}catch(a){return Promise.reject(a)}}),i.push([e,r,t])}else e&&i.push([e]);return t},kt=(i,t,e)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(s,o,c,l){return l=Error(c),l.name="SuppressedError",l.error=s,l.suppressed=o,l},n=s=>t=e?new r(s,t,"An error was suppressed during disposal"):(e=!0,s),a=s=>{for(;s=i.pop();)try{var o=s[1]&&s[1].call(s[2]);if(s[0])return Promise.resolve(o).then(a,c=>(n(c),a()))}catch(c){n(c)}if(e)throw t};return a()};var Bu=nh(()=>{});var my={};ah(my,{ADTS:()=>Ec,ALL_FORMATS:()=>rp,ALL_TRACK_TYPES:()=>ml,AUDIO_CODECS:()=>pe,AdtsInputFormat:()=>ls,AdtsOutputFormat:()=>ol,AppendOnlyStreamTarget:()=>Gc,AttachedFile:()=>Lr,AudioBufferSink:()=>Rc,AudioBufferSource:()=>Dc,AudioSample:()=>Ce,AudioSampleResource:()=>Gr,AudioSampleSink:()=>sn,AudioSampleSource:()=>sa,AudioSource:()=>vr,BaseMediaSampleSink:()=>ia,BlobSource:()=>hc,BufferSource:()=>pc,BufferTarget:()=>Bi,CanvasSink:()=>_c,CanvasSource:()=>Bc,CmafOutputFormat:()=>mn,ConcurrentRunner:()=>Ps,Conversion:()=>hl,ConversionCanceledError:()=>bn,CustomAudioDecoder:()=>Va,CustomAudioEncoder:()=>za,CustomPathedSource:()=>Jn,CustomSource:()=>ea,CustomVideoDecoder:()=>Da,CustomVideoEncoder:()=>Ua,EncodedAudioPacketSource:()=>ii,EncodedPacket:()=>ee,EncodedPacketSink:()=>ut,EncodedVideoPacketSource:()=>ri,EventEmitter:()=>st,FLAC:()=>qu,FilePathSource:()=>bc,FilePathTarget:()=>Qc,FlacInputFormat:()=>cs,FlacOutputFormat:()=>cl,HLS:()=>vc,HLS_FORMATS:()=>ip,HlsInputFormat:()=>nn,HlsOutputFormat:()=>ul,Input:()=>vi,InputAudioTrack:()=>Er,InputDisposedError:()=>ge,InputFormat:()=>nt,InputTrack:()=>Ri,InputVideoTrack:()=>Pr,IsobmffInputFormat:()=>ta,IsobmffOutputFormat:()=>hn,LogLevel:()=>Ml,Logging:()=>O,MATROSKA:()=>Nu,MP3:()=>Pc,MP4:()=>xc,MPEG_TS:()=>Ic,MatroskaInputFormat:()=>ra,MediaSource:()=>on,MediaStreamAudioTrackSource:()=>Vc,MediaStreamVideoTrackSource:()=>Oc,MkvOutputFormat:()=>ua,MovOutputFormat:()=>fn,Mp3InputFormat:()=>as,Mp3OutputFormat:()=>nl,Mp4InputFormat:()=>rs,Mp4OutputFormat:()=>ks,MpegTsInputFormat:()=>us,MpegTsOutputFormat:()=>ll,NON_PCM_AUDIO_CODECS:()=>Jt,NullTarget:()=>Oi,OGG:()=>Wu,OggInputFormat:()=>os,OggOutputFormat:()=>sl,Output:()=>Or,OutputAudioTrack:()=>ws,OutputFormat:()=>Ne,OutputSubtitleTrack:()=>Ss,OutputTrack:()=>gn,OutputTrackGroup:()=>pt,OutputVideoTrack:()=>Ts,PCM_AUDIO_CODECS:()=>se,PathedSource:()=>it,PathedTarget:()=>ft,QTFF:()=>Cc,QUALITY_HIGH:()=>Qm,QUALITY_LOW:()=>Km,QUALITY_MEDIUM:()=>Gm,QUALITY_VERY_HIGH:()=>jm,QUALITY_VERY_LOW:()=>qm,Quality:()=>de,QuickTimeInputFormat:()=>is,RangedSource:()=>es,RangedTarget:()=>ys,ReadableStreamSource:()=>rn,RichImageData:()=>At,SUBTITLE_CODECS:()=>qe,Source:()=>Qe,SourceRef:()=>Ei,StreamSource:()=>$f,StreamTarget:()=>la,SubtitleSource:()=>ln,Target:()=>Oe,TextSubtitleSource:()=>Uc,UnsupportedInputFormatError:()=>aa,UrlSource:()=>gc,VIDEO_CODECS:()=>ue,VIDEO_SAMPLE_PIXEL_FORMATS:()=>Ra,VideoSample:()=>$e,VideoSampleColorSpace:()=>Xi,VideoSampleResource:()=>jt,VideoSampleSink:()=>_i,VideoSampleSource:()=>cn,VideoSource:()=>Ir,WAVE:()=>Hu,WEBM:()=>Lu,WavOutputFormat:()=>al,WaveInputFormat:()=>ss,WebMInputFormat:()=>ns,WebMOutputFormat:()=>ir,asc:()=>lp,canDecode:()=>xm,canDecodeAudio:()=>fo,canDecodeVideo:()=>mo,canEncode:()=>Xm,canEncodeAudio:()=>Ba,canEncodeSubtitles:()=>Oa,canEncodeVideo:()=>Ma,desc:()=>ms,getDecodableAudioCodecs:()=>Kl,getDecodableCodecs:()=>Pm,getDecodableVideoCodecs:()=>ql,getEncodableAudioCodecs:()=>Bn,getEncodableCodecs:()=>$m,getEncodableSubtitleCodecs:()=>Jl,getEncodableVideoCodecs:()=>Zl,getFirstEncodableAudioCodec:()=>Ym,getFirstEncodableSubtitleCodec:()=>Zm,getFirstEncodableVideoCodec:()=>wo,prefer:()=>Mi,registerDecoder:()=>ef,registerEncoder:()=>tf,registerVideoSampleTransformer:()=>Om});function b(i){if(!i)throw new Error("Assertion failed.")}var Sl=Math.PI/180,Es=180/Math.PI,ai=i=>{let t=(i%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw new Error(`Invalid rotation ${i}.`)},si=[1,0,0,0,1,0,0,0,1],Is=(i,t,e)=>{let[r,n,,a,s]=i,o=Math.abs(r)*t+Math.abs(a)*e,c=Math.abs(n)*t+Math.abs(s)*e;return sr(sr(Sd(-t/2,-e/2),i),Sd(o/2,c/2))},Di=i=>{let[t,e]=i,r=Math.atan2(e,Al(i)?-t:t);return ai(Ms(r*Es,90))},Al=i=>{let[t,e,,r,n]=i;return t*n-e*r<0},Tn=i=>{let t=i*Sl,e=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[e,r,0,-r,e,0,0,0,1]},Sd=(i,t)=>[1,0,0,0,1,0,i,t,1],vs=(i,t)=>[i,0,0,0,t,0,0,0,1],sr=(i,t)=>{let e=new Array(9);for(let r=0;r<3;r++)for(let n=0;n<3;n++)e[3*r+n]=i[3*r]*t[n]+i[3*r+1]*t[3+n]+i[3*r+2]*t[6+n];return e},_s=(i,t,e,r)=>({rotation:ai(i+(t?-e:e)),flip:t!==r}),J=i=>i&&i[i.length-1],or=i=>i>=0&&i<2**32,xl=i=>i>=-(2**31)&&i<2**31,D=i=>{let t=0;for(;i.readBits(1)===0&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return 2**t-1+i.readBits(t)},Vi=(i,t)=>{let e=t+1,r=Math.floor(Math.log2(e));i.writeBits(r,0),i.writeBits(1,1),i.writeBits(r,e-2**r)},cr=i=>{let t=D(i);return t%2===0?-(t/2):(t+1)/2},Q=i=>i.constructor===Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i),z=i=>i.constructor===DataView?i:ArrayBuffer.isView(i)?new DataView(i.buffer,i.byteOffset,i.byteLength):new DataView(i),oh=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(t=""){let e=new Uint8Array(3*t.length),r=0;for(let n=0;n<t.length;n++){let a=t.charCodeAt(n);if(a<128)e[r++]=a;else if(a<2048)e[r++]=192|a>>6,e[r++]=128|a&63;else if(a<55296||a>57343)e[r++]=224|a>>12,e[r++]=128|a>>6&63,e[r++]=128|a&63;else{let s=n+1<t.length?t.charCodeAt(n+1):0;a<56320&&s>=56320&&s<=57343?(a=65536+(a-55296<<10)+(s-56320),n++,e[r++]=240|a>>18,e[r++]=128|a>>12&63,e[r++]=128|a>>6&63,e[r++]=128|a&63):(e[r++]=239,e[r++]=191,e[r++]=189)}}return e.slice(0,r)}},oi=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(t="utf-8"){let e=t.trim().toLowerCase();if(e==="utf-8"||e==="utf8"||e==="unicode-1-1-utf-8")this.encoding="utf-8";else if(e==="utf-16le"||e==="utf-16")this.encoding="utf-16le";else if(e==="utf-16be")this.encoding="utf-16be";else throw new RangeError(`The encoding label provided ('${t}') is invalid.`)}decode(t){let e=t?Q(t):new Uint8Array(0),r=[];if(this.encoding==="utf-8"){let a=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191?3:0;for(;a<e.length;){let s=e[a];if(s<128){r.push(s),a++;continue}let o,c;if(s>=194&&s<224)o=1,c=s&31;else if(s>=224&&s<240)o=2,c=s&15;else if(s>=240&&s<245)o=3,c=s&7;else{r.push(65533),a++;continue}let l=s===224?160:s===240?144:128,u=s===237?159:s===244?143:191,d=1;for(;d<=o;d++){let m=a+d<e.length?e[a+d]:0;if(m<l||m>u)break;c=c<<6|m&63,l=128,u=191}a+=d,d<=o?r.push(65533):c>=65536?(c-=65536,r.push(55296|c>>10,56320|c&1023)):r.push(c)}}else{let a=this.encoding==="utf-16le",s=a?255:254,o=a?254:255,c=e.length>=2&&e[0]===s&&e[1]===o?2:0;for(;c+1<e.length;){let l=a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1];if(c+=2,l>=55296&&l<=56319){let u=c+1<e.length?a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1]:-1;u>=56320&&u<=57343?(r.push(l,u),c+=2):(r.push(65533),c+1===e.length&&c++)}else l>=56320&&l<=57343?r.push(65533):r.push(l)}c<e.length&&r.push(65533)}let n="";for(let a=0;a<r.length;a+=8192)n+=String.fromCharCode(...r.slice(a,a+8192));return n}},be=new oi,Cd=new oi("utf-8",{fatal:!0}),Y=new oh,Ht=i=>{for(let t=0;t<i.length;t++)if(i.charCodeAt(t)>255)return!1;return!0},Cl=i=>Object.fromEntries(Object.entries(i).map(([t,e])=>[e,t])),_t={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Tt=Cl(_t),Rt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},wt=Cl(Rt),Ft={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},St=Cl(Ft),wn=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!=null,Rs=i=>!i||i.primaries==null&&i.transfer==null&&i.matrix==null&&i.fullRange==null,Fs={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Dr=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),Ee=class{constructor(){this.currentPromise=Promise.resolve();this.pending=0}async acquire(){let t,e=new Promise(n=>{let a=!1;t=()=>{a||(n(),this.pending--,a=!0)}}),r=this.currentPromise;return this.currentPromise=e,this.pending++,await r,t}},Pd=/^[0-9a-fA-F]+$/,ci=i=>[...i].map(t=>t.toString(16).padStart(2,"0")).join(""),Ed=i=>{b(i.length%2===0);let t=new Uint8Array(i.length/2);for(let e=0;e<i.length;e+=2)t[e/2]=parseInt(i.slice(e,e+2),16);return t},Pl=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),Vr=(i,t,e)=>{let r=0,n=i.length-1,a=-1;for(;r<=n;){let s=r+n>>1,o=e(i[s]);o===t?(a=s,n=s-1):o<t?r=s+1:n=s-1}return a},X=(i,t,e)=>{let r=0,n=i.length-1,a=-1;for(;r<=n;){let s=r+(n-r+1)/2|0;e(i[s])<=t?(a=s,r=s+1):n=s-1}return a},El=(i,t,e)=>{let r=X(i,e(t),e);i.splice(r+1,0,t)},te=()=>{let i,t;return{promise:new Promise((r,n)=>{i=r,t=n}),resolve:i,reject:t}},Sn=(i,t)=>{let e=i.indexOf(t);e!==-1&&i.splice(e,1)},Il=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return i[e]},lr=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1},Id=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},vd=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},Z=i=>{throw new Error(`Unexpected value: ${i}`)},Ui=(i,t,e)=>{let r=i.getUint8(t),n=i.getUint8(t+1),a=i.getUint8(t+2);return e?r|n<<8|a<<16:r<<16|n<<8|a},_d=(i,t,e)=>Ui(i,t,e)<<8>>8,zi=(i,t,e,r)=>{e=e>>>0,e=e&16777215,r?(i.setUint8(t,e&255),i.setUint8(t+1,e>>>8&255),i.setUint8(t+2,e>>>16&255)):(i.setUint8(t,e>>>16&255),i.setUint8(t+1,e>>>8&255),i.setUint8(t+2,e&255))},Rd=(i,t,e,r)=>{e=ne(e,-8388608,8388607),e<0&&(e=e+16777216&16777215),zi(i,t,e,r)},Fd=(i,t,e,r)=>{e=Math.trunc(e),r?(i.setUint32(t+0,e,!0),i.setInt32(t+4,Math.floor(e/2**32),!0)):(i.setInt32(t+0,Math.floor(e/2**32),!1),i.setUint32(t+4,e,!1))},ma=(i,t)=>({async next(){let e=await i.next();if(e.done)return{value:void 0,done:!0};try{return{value:t(e.value),done:!1}}catch(r){throw await i.return(),r}},return(){return i.return()},throw(e){return i.throw(e)},[Symbol.asyncIterator](){return this}}),ne=(i,t,e)=>Math.max(t,Math.min(e,i)),Md=(i,t,e)=>i+(t-i)*e,vl=(i,t)=>i-Math.floor(i/t)*t,le="und",Fe=i=>{let t=Math.round(i);return Math.abs(i/t-1)<10*Number.EPSILON?t:i},Ms=(i,t)=>Math.round(i/t)*t,Mt=(i,t)=>Math.round(i*t)/t,An=(i,t)=>Math.floor(i/t)*t,_l=(i,t)=>Math.floor(i*t)/t,Bd=i=>{let t=0;for(;i;)t++,i>>=1;return t},Bs=i=>{let t=0;for(;i!==0;)i&=i-1,t++;return t},ch=/^[a-z]{3}$/,Ur=i=>ch.test(i),ur=1e6*(1+Number.EPSILON),Os=(i,t)=>{let e={...i,...t};if(i.headers||t.headers){let r=i.headers?Cs(i.headers):{},n=t.headers?Cs(t.headers):{},a={...r};Object.entries(n).forEach(([s,o])=>{let c=Object.keys(a).find(l=>l.toLowerCase()===s.toLowerCase());c&&delete a[c],a[s]=o}),e.headers=a}return e},Cs=i=>{if(i instanceof Headers){let t={};return i.forEach((e,r)=>{t[r]=e}),t}if(Array.isArray(i)){let t={};return i.forEach(([e,r])=>{t[e]=r}),t}return i},Rl=async(i,t,e,r,n)=>{let a=0;for(;;)try{return await i(t,e)}catch(s){if(n())throw s;a++;let o=r(a,s,t);if(o===null)throw s;if(O._error("Retrying failed fetch. Error:",s),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Nr(1e3*o),n())throw s}},Od=(i,t)=>{let e=i<0?-1:1;i=Math.abs(i);let r=0,n=1,a=1,s=0,o=i;for(;;){let c=Math.floor(o),l=c*a+r,u=c*s+n;if(u>t)return{num:e*a,den:s};if(r=a,n=s,a=l,s=u,o=1/(o-c),!isFinite(o))break}return{num:e*a,den:s}},ni=class{constructor(){this.currentPromise=Promise.resolve()}call(t){let e=this.currentPromise.then(t);return this.currentPromise=e.catch(()=>{}),e}},bl=null,et=()=>bl!==null?bl:bl=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),yl=null,Wt=()=>yl!==null?yl:yl=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),kl=null,Ni=()=>kl!==null?kl:kl=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Tl=null,Dd=()=>{if(Tl!==null)return Tl;if(typeof navigator>"u")return null;let i=/\bChrome\/(\d+)/.exec(navigator.userAgent);return i?Tl=Number(i[1]):null},wl=null,Vd=()=>wl!==null?wl:wl=typeof navigator<"u"&&/Android/.test(navigator.userAgent),xn=i=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${i} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`:`${i} is not available in this environment.`,Ud=i=>i instanceof DOMException&&i.name==="QuotaExceededError"&&/reclaimed/i.test(i.message),lh=(async()=>{})().constructor,R=i=>i instanceof lh||i instanceof Promise?!0:typeof i?.then=="function",Li=(i,t)=>i!==-1?i:t,Ds=(i,t,e,r)=>i<=r&&e<=t,qt=function*(i){for(let t in i){let e=i[t];e!==void 0&&(yield{key:t,value:e})}},zd=i=>{switch(i.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},Hi=i=>{let t;try{t=atob(i)}catch{throw new Error("Invalid base64 string.")}let e=new Uint8Array(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e},Nd=i=>{let t="";for(let e=0;e<i.length;e++)t+=String.fromCharCode(i[e]);return btoa(t)},Vs=(i,t)=>{if(i.length!==t.length)return!1;for(let e=0;e<i.length;e++)if(i[e]!==t[e])return!1;return!0},Cn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Ie=i=>typeof i=="number"&&!Number.isNaN(i),ve=(i,t)=>{if(/^(?:[a-z][a-z0-9+.-]*:\/\/|(?:data|blob):)/i.test(t))return t;if(i.includes("://")){let l=i.search(/[?#]/);l!==-1&&(i=i.slice(0,l))}let e=t.search(/[?#]/),r=e===-1?"":t.slice(e);e!==-1&&(t=t.slice(0,e));let n;if(t==="")n=i;else if(t.startsWith("/")){let l=i.indexOf("://");if(l===-1)n=t;else if(t.startsWith("//"))n=i.slice(0,l+1)+t;else{let u=i.indexOf("/",l+3);u===-1?n=i+t:n=i.slice(0,u)+t}}else{let l=i.indexOf("://"),u=i.lastIndexOf("/");l!==-1&&u===l+2?n=i+"/"+t:u===-1?n=t:n=i.slice(0,u+1)+t}let a="",s=n.indexOf("://");if(s!==-1){let l=n.indexOf("/",s+3);l!==-1&&(a=n.slice(0,l),n=n.slice(l))}let o=n.split("/"),c=[];for(let l of o)l===".."?c.length===0||c[c.length-1]===".."?c.push(".."):(c.length!==1||c[0]!=="")&&c.pop():l!=="."&&c.push(l);return a+c.join("/")+r},Ld=(i,t)=>{let e=i.indexOf("#"),r=e===-1?i:i.slice(0,e),n=r.indexOf("?");return n===-1?null:new URLSearchParams(r.slice(n+1)).get(t)},Wi=(i,t)=>{let e=0;for(let r=0;r<i.length;r++)t(i[r])&&e++;return e},li=(i,t)=>{let e=-1,r=1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);(e===-1||a<r)&&(r=a,e=n)}return e},Hd=(i,t)=>{let e=-1,r=-1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);(e===-1||a>r)&&(r=a,e=n)}return e},zr=i=>{b(Number.isInteger(i.num)),b(Number.isInteger(i.den)),b(i.den!==0);let t=Math.abs(i.num),e=Math.abs(i.den);for(;e!==0;){let n=t%e;t=e,e=n}let r=t||1;return{num:i.num/r,den:i.den/r}},Wd=(i,t)=>{if(typeof i!="object"||!i)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},da,uh=1,Ad=new Map,Fl=new Map,qd=()=>typeof window>"u",dh=()=>{let i=new Map,t=new Map;self.onmessage=e=>{let r=e.data;switch(r.type){case"set-timeout":{let n=setTimeout(()=>{i.delete(r.timerId),self.postMessage({type:"fire",timerId:r.timerId})},r.delay);i.set(r.timerId,n)}break;case"set-interval":{let n=setInterval(()=>{self.postMessage({type:"fire",timerId:r.timerId})},r.delay);t.set(r.timerId,n)}break;case"clear-timeout":{let n=i.get(r.timerId);n!==void 0&&(clearTimeout(n),i.delete(r.timerId))}break;case"clear-interval":{let n=t.get(r.timerId);n!==void 0&&(clearInterval(n),t.delete(r.timerId))}break}}},Kd=()=>da||(da=Pn("unthrottled-timer",dh),da.onmessage=i=>{let t=i.data,e=Ad.get(t.timerId);if(e){Ad.delete(t.timerId),e();return}let r=Fl.get(t.timerId);r&&r()},da),xd=new Map,Pn=(i,t)=>{let e=globalThis[Symbol.for("mediabunny:workerUrl")];if(e!==void 0&&typeof e!="string"&&!(e instanceof URL))throw new TypeError("globalThis[Symbol.for('mediabunny:workerUrl')], when provided, must be a string or URL.");if(e!==void 0)return new Worker(e,{name:i});let r=xd.get(t);return r||(r=URL.createObjectURL(new Blob([`(${t.toString()})();`],{type:"text/javascript"})),xd.set(t,r)),new Worker(r,{name:i})};var Gd=(i,t)=>{if(qd())return{id:setInterval(i,t)};let e=uh++;return Fl.set(e,()=>{i()}),Kd().postMessage({type:"set-interval",timerId:e,delay:t}),{id:e}},Qd=i=>{if(qd()){clearInterval(i.id);return}b(typeof i.id=="number"),Fl.delete(i.id),Kd().postMessage({type:"clear-interval",timerId:i.id})},Nr=i=>new Promise(t=>setTimeout(t,i));var Bt=i=>Array.isArray(i)?i:[i],st=class{constructor(){this._listeners=new Map}on(t,e,r){this._listeners.has(t)||this._listeners.set(t,new Set);let n={fn:e,once:r?.once??!1};return this._listeners.get(t).add(n),()=>{this._listeners.get(t)?.delete(n)}}_emit(...t){let[e,r]=t,n=this._listeners.get(e);if(n){for(let a of[...n])if(n.has(a)){a.once&&n.delete(a);try{a.fn(r)}catch(s){console.error(s)}}}}},qi=i=>Math.ceil(i/2)*2,Ps=class{constructor(t){this._queue=[];this._errored=!1;this.parallelism=t}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(t){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);let e=t();this._queue.push(e),e.then(()=>Sn(this._queue,e)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}},Us=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(t=>typeof t=="string"),En=(i,t=0,e=1)=>{let r=new Date(0);return r.setUTCFullYear(i,t,e),r},mh=/^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:[T ](\d{2})(?::(\d{2})(?::(\d{2})(?:\.(\d+))?)?)?)?)?)?(?:Z|([+-])(\d{2})(?::?(\d{2}))?)?$/,Kt=i=>{let t=mh.exec(i);if(!t)return null;let[,e,r="01",n="01",a="00",s="00",o="00",c="",l="+",u="00",d="00"]=t,m=`${e}-${r}-${n}T${a}:${s}:${o}`,f=new Date(`${m}.${c.padEnd(3,"0").slice(0,3)}Z`);if(Number.isNaN(f.getTime())||!f.toISOString().startsWith(m)||Number(u)>23||Number(d)>59)return null;let p=(l==="-"?-1:1)*(60*Number(u)+Number(d));return f.setTime(f.getTime()-6e4*p),f};var Ml=(n=>(n[n.Silent=0]="Silent",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.Info=3]="Info",n))(Ml||{}),ot=class ot{constructor(){}static get level(){return ot._level}static set level(t){if(t!==0&&t!==1&&t!==2&&t!==3)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ot._level=t}static get _emitter(){return ot._emitterInstance??=new st}static on(t,e,r){return ot._emitter.on(t,e,r)}static _error(...t){ot._emitter._emit("error",t),ot._level>=1&&console.error(...t)}static _warn(...t){ot._emitter._emit("warn",t),ot._level>=2&&console.warn(...t)}static _info(...t){ot._emitter._emit("info",t),ot._level>=3&&console.info(...t)}};ot._level=3,ot._emitterInstance=null;var O=ot;var At=class{constructor(t,e){this.data=t;this.mimeType=e;if(!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof e!="string")throw new TypeError("mimeType must be a string.")}},Lr=class{constructor(t,e,r,n){this.data=t;this.mimeType=e;this.name=r;this.description=n;if(!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!==void 0&&typeof e!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(n!==void 0&&typeof n!="string")throw new TypeError("description, when provided, must be a string.")}},fa=i=>{if(!i||typeof i!="object")throw new TypeError("tags must be an object.");if(i.title!==void 0&&typeof i.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(i.description!==void 0&&typeof i.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(i.artist!==void 0&&typeof i.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(i.album!==void 0&&typeof i.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(i.albumArtist!==void 0&&typeof i.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(i.trackNumber!==void 0&&(!Number.isInteger(i.trackNumber)||i.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(i.tracksTotal!==void 0&&(!Number.isInteger(i.tracksTotal)||i.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(i.discNumber!==void 0&&(!Number.isInteger(i.discNumber)||i.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(i.discsTotal!==void 0&&(!Number.isInteger(i.discsTotal)||i.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(i.genre!==void 0&&typeof i.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(i.date!==void 0&&(!(i.date instanceof Date)||Number.isNaN(i.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(i.creationTime!==void 0&&i.creationTime!==null&&(!(i.creationTime instanceof Date)||Number.isNaN(i.creationTime.getTime())))throw new TypeError("tags.creationTime, when provided, must be a valid Date or null.");if(i.beatsPerMinute!==void 0&&(!Number.isInteger(i.beatsPerMinute)||i.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");if(i.lyrics!==void 0&&typeof i.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(i.images!==void 0){if(!Array.isArray(i.images))throw new TypeError("tags.images, when provided, must be an array.");for(let t of i.images){if(!t||typeof t!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof t.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.");if(t.name!==void 0&&typeof t.name!="string")throw new TypeError("Each image.name, when provided, must be a string.");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("Each image.description, when provided, must be a string.")}}if(i.comment!==void 0&&typeof i.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(i.raw!==void 0){if(!i.raw||typeof i.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(let t of Object.values(i.raw))if(t!==null&&typeof t!="string"&&!(Array.isArray(t)&&t.every(e=>typeof e=="string"))&&!(t instanceof Uint8Array)&&!(Array.isArray(t)&&t.every(e=>e instanceof Uint8Array))&&!(t instanceof At)&&!(t instanceof Lr)&&!Us(t))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, Uint8Array array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Hr=i=>i.title===void 0&&i.description===void 0&&i.artist===void 0&&i.album===void 0&&i.albumArtist===void 0&&i.trackNumber===void 0&&i.tracksTotal===void 0&&i.discNumber===void 0&&i.discsTotal===void 0&&i.genre===void 0&&i.beatsPerMinute===void 0&&i.date===void 0&&i.lyrics===void 0&&(!i.images||i.images.length===0)&&i.comment===void 0&&(i.raw===void 0||Object.keys(i.raw).length===0),Ve={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},jd=i=>{if(!i||typeof i!="object")throw new TypeError("disposition must be an object.");if(i.default!==void 0&&typeof i.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(i.primary!==void 0&&typeof i.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(i.forced!==void 0&&typeof i.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(i.original!==void 0&&typeof i.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(i.commentary!==void 0&&typeof i.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(i.hearingImpaired!==void 0&&typeof i.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(i.visuallyImpaired!==void 0&&typeof i.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};var K=class i{constructor(t){this.bytes=t;this.pos=0}seekToByte(t){this.pos=8*t}readBit(){let t=Math.floor(this.pos/8),e=this.bytes[t]??0,r=7-(this.pos&7),n=(e&1<<r)>>r;return this.pos++,n}readBits(t){if(t===1)return this.readBit();let e=0;for(let r=0;r<t;r++)e=2*e+this.readBit();return e}writeBits(t,e){let r=this.pos+t;for(let n=this.pos;n<r;n++){let a=Math.floor(n/8),s=this.bytes[a],o=7-(n&7),c=Math.floor(e/2**(r-n-1))&1;s&=~(1<<o),s|=c<<o,this.bytes[a]=s}this.pos=r}copyBits(t,e){let r=0;for(r;r<t-7;r+=8)this.writeBits(8,e.readBits(8));let n=t-r;n>0&&this.writeBits(n,e.readBits(n))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");let t=this.pos/8,e=this.bytes[t]??0;return this.pos+=8,e}skipBits(t){this.pos+=t}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new i(this.bytes);return t.pos=this.pos,t}};var Xe=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],dr=[-1,1,2,3,4,5,6,8],fh=[1,2,3,4,6,7,17,19,20,21,22],xt=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let t=new K(i),e=Bl(t),{frequencyIndex:r,sampleRate:n}=Ol(t),a=t.readBits(4),s=null;a>=1&&a<=7&&(s=dr[a]);let o=e,c=!1,l=n;(e===5||e===29)&&(c=e===29,l=Ol(t).sampleRate,o=Bl(t),o===22&&t.skipBits(4));let u=1024,d=null;if(fh.includes(o)&&(u=t.readBits(1)?960:1024,a===0&&(t.readBits(1)&&t.skipBits(14),t.skipBits(1),d=Jd(t),s=Wr(d))),e!==5&&e!==29)for(;t.getBitsLeft()>15;){let m=t.pos;if(t.readBits(11)!==695){t.pos=m+1;continue}Bl(t)===5&&t.readBits(1)&&(l=Ol(t).sampleRate,t.getBitsLeft()>11&&t.readBits(11)===1352&&(c=!!t.readBits(1)));break}return s!==null&&s>1&&(c=!1),{objectType:e,coreObjectType:o,frequencyIndex:r,channelConfiguration:a,coreSampleRate:n,outputSampleRate:l,outputNumberOfChannels:c&&s===1?2:s,frameLength:u,programConfigElement:d}},Bl=i=>{let t=i.readBits(5);return t===31?32+i.readBits(6):t},Ol=i=>{let t=i.readBits(4);return t===15?{frequencyIndex:t,sampleRate:i.readBits(24)}:{frequencyIndex:t,sampleRate:t<Xe.length?Xe[t]:null}},ui=i=>{let t=i.objectType===5||i.objectType===29,e=i.objectType===29,r=t?i.outputSampleRate/2:i.outputSampleRate,n=e?1:i.outputNumberOfChannels,a=i.programConfigElement?0:dr.indexOf(n);if(a===-1)throw new TypeError(`Unsupported number of channels: ${i.outputNumberOfChannels}`);let s=16;i.objectType>=32&&(s+=6),Dl(r)===15&&(s+=24),t&&(s+=9,Dl(i.outputSampleRate)===15&&(s+=24));let o=Math.ceil(s/8)+(i.programConfigElement?Yd(i.programConfigElement):0),c=new Uint8Array(o),l=new K(c);return Xd(l,i.objectType),$d(l,r),l.writeBits(4,a),t&&($d(l,i.outputSampleRate),Xd(l,2)),l.writeBits(3,0),i.programConfigElement&&Zd(l,i.programConfigElement),c.subarray(0,Math.ceil(l.pos/8))},Xd=(i,t)=>{t<32?i.writeBits(5,t):(i.writeBits(5,31),i.writeBits(6,t-32))},$d=(i,t)=>{let e=Dl(t);i.writeBits(4,e),e===15&&i.writeBits(24,t)},Dl=i=>{let t=Xe.indexOf(i);return t===-1?15:t},zs=i=>{let{coreObjectType:t,frequencyIndex:e,frameLength:r}=i,{channelConfiguration:n,programConfigElement:a}=i;if(t<1||t>4)throw new Error(`AAC object type ${t} can't be stored in ADTS.`);if(e>=Xe.length)throw new Error(`AAC sampling frequency index ${e} can't be stored in ADTS.`);if(n===11||n===12){let l={isCpe:!0,tagSelect:1};a={elementInstanceTag:0,objectType:t-1,samplingFrequencyIndex:e,frontElements:[{isCpe:!1,tagSelect:0},{isCpe:!0,tagSelect:0}],sideElements:n===12?[l]:[],backElements:n===11?[l,{isCpe:!1,tagSelect:1}]:[{isCpe:!0,tagSelect:2}],lfeElementTags:[0],assocDataElementTags:[],ccElements:[],monoMixdownElementNumber:null,stereoMixdownElementNumber:null,matrixMixdown:null,comment:new Uint8Array(0)},n=0}if(n>7)throw new Error(`AAC channel configuration ${n} can't be stored in ADTS.`);if(r!==1024)throw new Error(`AAC frame length ${r} can't be stored in ADTS.`);let s=new Uint8Array(7+(a?Yd(a):0)),o=new K(s),c=t-1;return o.writeBits(12,4095),o.writeBits(1,0),o.writeBits(2,0),o.writeBits(1,1),o.writeBits(2,c),o.writeBits(4,e),o.writeBits(1,0),o.writeBits(3,n),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(1,0),o.writeBits(1,0),o.skipBits(13),o.writeBits(11,2047),o.writeBits(2,0),a&&(o.pos=8*7,o.writeBits(3,5),Zd(o,a),s=s.subarray(0,o.pos/8)),{header:s,bitstream:o}},Yd=i=>64+i.comment.byteLength,Zd=(i,t)=>{i.writeBits(4,t.elementInstanceTag),i.writeBits(2,t.objectType),i.writeBits(4,t.samplingFrequencyIndex),i.writeBits(4,t.frontElements.length),i.writeBits(4,t.sideElements.length),i.writeBits(4,t.backElements.length),i.writeBits(2,t.lfeElementTags.length),i.writeBits(3,t.assocDataElementTags.length),i.writeBits(4,t.ccElements.length),i.writeBits(1,+(t.monoMixdownElementNumber!==null)),t.monoMixdownElementNumber!==null&&i.writeBits(4,t.monoMixdownElementNumber),i.writeBits(1,+(t.stereoMixdownElementNumber!==null)),t.stereoMixdownElementNumber!==null&&i.writeBits(4,t.stereoMixdownElementNumber),i.writeBits(1,+(t.matrixMixdown!==null)),t.matrixMixdown&&(i.writeBits(2,t.matrixMixdown.index),i.writeBits(1,+t.matrixMixdown.pseudoSurroundEnabled));for(let e of[...t.frontElements,...t.sideElements,...t.backElements])i.writeBits(1,+e.isCpe),i.writeBits(4,e.tagSelect);for(let e of[...t.lfeElementTags,...t.assocDataElementTags])i.writeBits(4,e);for(let e of t.ccElements)i.writeBits(1,+e.isIndependentlySwitched),i.writeBits(4,e.tagSelect);i.pos=8*Math.ceil(i.pos/8),i.writeBits(8,t.comment.byteLength),i.bytes.set(t.comment,i.pos/8),i.pos+=8*t.comment.byteLength},Ns=(i,t)=>{if(t>=2**13)throw new Error(`AAC frame too large for ADTS (${t} bytes, at most ${2**13-1} allowed).`);i.pos=30,i.writeBits(13,t)},mr=i=>{let t=new K(i);if(t.readBits(3)!==5)return null;let e=Jd(t),r=t.pos/8;if(r>i.byteLength)throw new Error("Invalid ADTS frame: its program config element extends past the end of the frame.");return{programConfigElement:e,size:r}},Jd=i=>{let t=i.readBits(4),e=i.readBits(2),r=i.readBits(4),n=i.readBits(4),a=i.readBits(4),s=i.readBits(4),o=i.readBits(2),c=i.readBits(3),l=i.readBits(4),u=i.readBits(1)?i.readBits(4):null,d=i.readBits(1)?i.readBits(4):null,m=i.readBits(1)?{index:i.readBits(2),pseudoSurroundEnabled:!!i.readBits(1)}:null,f=A=>Array.from({length:A},()=>({isCpe:!!i.readBits(1),tagSelect:i.readBits(4)})),p=f(n),h=f(a),y=f(s),g=Array.from({length:o},()=>i.readBits(4)),k=Array.from({length:c},()=>i.readBits(4)),T=Array.from({length:l},()=>({isIndependentlySwitched:!!i.readBits(1),tagSelect:i.readBits(4)}));i.pos=8*Math.ceil(i.pos/8);let S=i.readBits(8),w=i.bytes.slice(i.pos/8,i.pos/8+S);return i.pos+=8*S,{elementInstanceTag:t,objectType:e,samplingFrequencyIndex:r,frontElements:p,sideElements:h,backElements:y,lfeElementTags:g,assocDataElementTags:k,ccElements:T,monoMixdownElementNumber:u,stereoMixdownElementNumber:d,matrixMixdown:m,comment:w}},Wr=i=>[...i.frontElements,...i.sideElements,...i.backElements].reduce((e,r)=>e+(r.isCpe?2:1),i.lfeElementTags.length);var Vl=[44100,48e3,32e3],Ls=[-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],qr=1483304551,di=1231971951,em=1447187017,Hs=(i,t,e,r,n)=>t===0?0:t===1?Math.floor(144*e/(r<<i))+n:t===2?Math.floor(144*e/r)+n:(Math.floor(12*e/r)+n)*4,tm=(i,t,e,r)=>t===0?0:t===1?144*e/(r<<i):t===2?144*e/r:12*e/r*4,mi=(i,t)=>i===3?t===3?21:36:t===3?13:21,fr=(i,t)=>{let e=i>>>24,r=i>>>16&255,n=i>>>8&255,a=i&255;if(e!==255&&r!==255&&n!==255&&a!==255)return{header:null,bytesAdvanced:4};if(e!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let s=0,o=0;r&16?s=r&8?0:1:(s=1,o=1);let c=r>>3&3,l=r>>1&3,u=n>>4&15,d=n>>2&3;if(c===1||d===3)return{header:null,bytesAdvanced:1};let m=n>>1&1,f=a>>6&3,p=a>>4&3,h=a>>3&1,y=a>>2&1,g=a&3,k=Ls[s*16*4+l*16+u];if(k===-1)return{header:null,bytesAdvanced:1};let T=k*1e3,S=Vl[d]>>s+o,w=Hs(s,l,T,S,m);if(t!==null&&t<w)return{header:null,bytesAdvanced:1};let A;return c===3?A=l===3?384:1152:l===3?A=384:l===2?A=1152:A=576,{header:{totalSize:w,mpegVersionId:c,lowSamplingFrequency:s,layer:l,bitrate:T,frequencyIndex:d,sampleRate:S,channel:f,modeExtension:p,copyright:h,original:y,emphasis:g,audioSamplesInFrame:A},bytesAdvanced:1}},rm=i=>{let t=127,e=0,r=i;for(;(t^2147483647)!==0;)e=r&~t,e<<=1,e|=r&t,t=(t+1<<8)-1,r=e;return e},pa=i=>{let t=2130706432,e=0;for(;t!==0;)e>>=1,e|=i&t,t>>=8;return e};var fi=i=>i===3?1:2;var Ki=[48e3,44100,32e3],Ul=[24e3,22050,16e3];var ph="1.66.4",Kr=`Mediabunny v${ph}`;var pi=function*(i){let t=0,e=-1;for(;t<i.length-2;){let r=i.indexOf(0,t);if(r===-1||r>=i.length-2)break;t=r;let n=0;if(t+3<i.length&&i[t+1]===0&&i[t+2]===0&&i[t+3]===1?n=4:i[t+1]===0&&i[t+2]===1&&(n=3),n===0){t++;continue}e!==-1&&t>e&&(yield{offset:e,length:t-e}),e=t+n,t=e}e!==-1&&e<i.length&&(yield{offset:e,length:i.length-e})},qs=function*(i,t){let e=0,r=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;e+t<=i.length;){let n;t===1?n=r.getUint8(e):t===2?n=r.getUint16(e,!1):t===3?n=Ui(r,e,!1):(b(t===4),n=r.getUint32(e,!1)),e+=t,yield{offset:e,length:n},e+=n}},Nl=(i,t)=>{if(t.description){let n=(Q(t.description)[4]&3)+1;return qs(i,n)}else return pi(i)},pr=i=>i&31,Ks=i=>{let t=new Uint8Array(i.length),e=i.length,r=0;for(let n=0;n<e;n++)n+2<e&&i[n]===0&&i[n+1]===0&&i[n+2]===3?(t[r++]=0,t[r++]=0,n+=2):t[r++]=i[n];return t.subarray(0,r)},hh=i=>{let t=[],e=0;for(let r of i)e===2&&r<=3&&(t.push(3),e=0),t.push(r),e=r===0?e+1:0;return new Uint8Array(t)},zl=new Uint8Array([0,0,0,1]),ba=i=>{let t=i.reduce((n,a)=>n+zl.byteLength+a.byteLength,0),e=new Uint8Array(t),r=0;for(let n of i)e.set(zl,r),r+=zl.byteLength,e.set(n,r),r+=n.byteLength;return e},Gs=(i,t)=>{let e=i.reduce((a,s)=>a+t+s.byteLength,0),r=new Uint8Array(e),n=0;for(let a of i){let s=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:s.setUint8(n,a.byteLength);break;case 2:s.setUint16(n,a.byteLength,!1);break;case 3:zi(s,n,a.byteLength,!1);break;case 4:s.setUint32(n,a.byteLength,!1);break}n+=t,r.set(a,n),n+=a.byteLength}return r},sm=(i,t)=>{if(t.description){let n=(Q(t.description)[4]&3)+1;return Gs(i,n)}else return ba(i)},hr=i=>{try{let t=[],e=[],r=[];for(let o of pi(i)){let c=i.subarray(o.offset,o.offset+o.length),l=pr(c[0]);l===7&&t.length<31?t.push(c):l===8&&e.length<255?e.push(c):l===13&&r.length<255&&r.push(c)}if(t.length===0||e.length===0)return null;let n=t[0],a=Gt(n);if(!a)return null;let s=Ll(a.profileIdc);return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:e,chromaFormat:s?a.chromaFormatIdc:null,bitDepthLumaMinus8:s?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:s?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:s?r:null}}catch(t){return O._error("Error building AVC Decoder Configuration Record:",t),null}},In=i=>{let t=[];t.push(i.configurationVersion),t.push(i.avcProfileIndication),t.push(i.profileCompatibility),t.push(i.avcLevelIndication),t.push(252|i.lengthSizeMinusOne&3),t.push(224|i.sequenceParameterSets.length&31);for(let e of i.sequenceParameterSets){let r=e.byteLength;t.push(r>>8),t.push(r&255);for(let n=0;n<r;n++)t.push(e[n])}t.push(i.pictureParameterSets.length);for(let e of i.pictureParameterSets){let r=e.byteLength;t.push(r>>8),t.push(r&255);for(let n=0;n<r;n++)t.push(e[n])}if(Ll(i.avcProfileIndication)&&i.chromaFormat!==null){b(i.bitDepthLumaMinus8!==null),b(i.bitDepthChromaMinus8!==null),b(i.sequenceParameterSetExt!==null),t.push(252|i.chromaFormat&3),t.push(248|i.bitDepthLumaMinus8&7),t.push(248|i.bitDepthChromaMinus8&7),t.push(i.sequenceParameterSetExt.length);for(let e of i.sequenceParameterSetExt){let r=e.byteLength;t.push(r>>8),t.push(r&255);for(let n=0;n<r;n++)t.push(e[n])}}return new Uint8Array(t)},gr=i=>{try{let t=z(i),e=0,r=t.getUint8(e++),n=t.getUint8(e++),a=t.getUint8(e++),s=t.getUint8(e++),o=t.getUint8(e++)&3,c=t.getUint8(e++)&31,l=[];for(let f=0;f<c;f++){let p=t.getUint16(e,!1);e+=2,l.push(i.subarray(e,e+p)),e+=p}let u=t.getUint8(e++),d=[];for(let f=0;f<u;f++){let p=t.getUint16(e,!1);e+=2,d.push(i.subarray(e,e+p)),e+=p}let m={configurationVersion:r,avcProfileIndication:n,profileCompatibility:a,avcLevelIndication:s,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(Ll(n)&&e+4<=i.length){let f=t.getUint8(e++)&3,p=t.getUint8(e++)&7,h=t.getUint8(e++)&7,y=t.getUint8(e++);m.chromaFormat=f,m.bitDepthLumaMinus8=p,m.bitDepthChromaMinus8=h;let g=[];for(let k=0;k<y;k++){let T=t.getUint16(e,!1);e+=2,g.push(i.subarray(e,e+T)),e+=T}m.sequenceParameterSetExt=g}return m}catch(t){return O._error("Error deserializing AVC Decoder Configuration Record:",t),null}},Ll=i=>i!==66&&i!==77&&i!==88,om={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}},Gt=i=>{try{let t=Ks(i),e=new K(t);if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),a=e.readAlignedByte(),s=e.readAlignedByte();D(e);let o=1,c=0,l=0,u=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128||n===138||n===139||n===134||n===135||n===144)&&(o=D(e),o===3&&(u=e.readBits(1)),c=D(e),l=D(e),e.skipBits(1),e.readBits(1))){for(let L=0;L<(o!==3?8:12);L++)if(e.readBits(1)){let me=L<6?16:64,ye=8,ke=8;for(let Ze=0;Ze<me;Ze++){if(ke!==0){let at=cr(e);ke=(ye+at+256)%256}ye=ke===0?ye:ke}}}D(e);let d=D(e);if(d===0)D(e);else if(d===1){e.skipBits(1),cr(e),cr(e);let N=D(e);for(let L=0;L<N;L++)cr(e)}let m=D(e);e.skipBits(1);let f=D(e),p=D(e),h=e.readBits(1);h||e.skipBits(1);let y=16*(f+1),g=16*(2-h)*(p+1),k=y,T=g;if(e.skipBits(1),e.readBits(1)){let N=D(e),L=D(e),G=D(e),me=D(e),ye,ke;if((u===0?o:0)===0)ye=1,ke=2-h;else{let at=o===3?1:2,Le=o===1?2:1;ye=at,ke=Le*(2-h)}k-=ye*(N+L),T-=ke*(G+me)}if(k<=0||T<=0)return null;let w=2,A=2,C=2,E=0,I={num:1,den:1},x=null,P=null,v=null,_=null,M=e.pos;if(e.readBits(1)){if(e.readBits(1)){let at=e.readBits(8);if(at===255)I={num:e.readBits(16),den:e.readBits(16)};else{let Le=om[at];Le&&(I=Le)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),E=e.readBits(1),e.readBits(1)&&(w=e.readBits(8),A=e.readBits(8),C=e.readBits(8))),e.readBits(1)&&(D(e),D(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let ke=e.readBits(1);ke&&im(e);let Ze=e.readBits(1);Ze&&im(e),(ke||Ze)&&e.skipBits(1),e.skipBits(1),v=e.pos,_=e.readBits(1),_&&(e.skipBits(1),D(e),D(e),D(e),D(e),x=Math.min(D(e),16),P=Math.min(D(e),16))}if(x===null){b(P===null);let N=a&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&N)x=0,P=0;else{let L=f+1,G=p+1,me=(2-h)*G,ye=s===11&&N&&(n===66||n===77||n===88),ke=ga.find(at=>at.level>=(ye?10:s))??J(ga),Ze=Math.min(Math.floor(ke.maxDpbMbs/(L*me)),16);x=Ze,P=Math.min(Math.max(Ze,m),16)}}return b(P!==null),{emulationUnpreventedBytes:t,profileIdc:n,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:h,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:y,codedHeight:g,displayWidth:k,displayHeight:T,pixelAspectRatio:I,colourPrimaries:w,matrixCoefficients:C,transferCharacteristics:A,fullRangeFlag:E,numReorderFrames:x,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:M,bitstreamRestrictionFlagBitOffset:v,bitstreamRestrictionFlag:_}}catch(t){return O._error("Error parsing AVC SPS:",t),null}},im=i=>{let t=D(i);i.skipBits(4),i.skipBits(4);for(let e=0;e<=t;e++)D(i),D(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},Hl=i=>{b(i.bitstreamRestrictionFlag!==1);let t=new Uint8Array(i.emulationUnpreventedBytes.byteLength+64),e=new K(i.emulationUnpreventedBytes),r=new K(t);i.bitstreamRestrictionFlag===null?(r.copyBits(i.vuiParametersFlagBitOffset,e),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(b(i.bitstreamRestrictionFlagBitOffset!==null),r.copyBits(i.bitstreamRestrictionFlagBitOffset,e)),r.writeBits(1,1),r.writeBits(1,1),Vi(r,2),Vi(r,1),Vi(r,16),Vi(r,16),Vi(r,i.numReorderFrames),Vi(r,i.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);let n=r.pos/8;return b(Number.isInteger(n)),hh(t.subarray(0,n))},gh=(i,t)=>{if(t.description){let n=(Q(t.description)[21]&3)+1;return Gs(i,n)}else return ba(i)},ha=(i,t)=>{if(t.description){let n=(Q(t.description)[21]&3)+1;return qs(i,n)}else return pi(i)},Qt=i=>i>>1&63,Qi=i=>{try{let t=new K(Ks(i));t.skipBits(16),t.readBits(4);let e=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:a,general_profile_idc:s,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=bh(t,e);D(t);let u=D(t),d=0;u===3&&(d=t.readBits(1));let m=D(t),f=D(t),p=m,h=f;if(t.readBits(1)){let _=D(t),M=D(t),U=D(t),N=D(t),L=1,G=1,me=d===0?u:0;me===1?(L=2,G=2):me===2&&(L=2,G=1),p-=(_+M)*L,h-=(U+N)*G}if(p<=0||h<=0)return null;let y=D(t),g=D(t),k=D(t),S=t.readBits(1)?0:e,w=0;for(let _=S;_<=e;_++)D(t),w=D(t),D(t);D(t),D(t),D(t),D(t),D(t),D(t),t.readBits(1)&&t.readBits(1)&&yh(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),D(t),D(t),t.skipBits(1));let A=D(t);if(kh(t,A),t.readBits(1)){let _=D(t);for(let M=0;M<_;M++)t.skipBits(k+4),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let C=2,E=2,I=2,x=0,P=0,v={num:1,den:1};if(t.readBits(1)){let _=wh(t,e);v=_.pixelAspectRatio,C=_.colourPrimaries,E=_.transferCharacteristics,I=_.matrixCoefficients,x=_.fullRangeFlag,P=_.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:h,pixelAspectRatio:v,colourPrimaries:C,transferCharacteristics:E,matrixCoefficients:I,fullRangeFlag:x,maxDecFrameBuffering:Math.min(w+1,16),spsMaxSubLayersMinus1:e,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:s,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:y,bitDepthChromaMinus8:g,minSpatialSegmentationIdc:P}}catch(t){return O._error("Error parsing HEVC SPS:",t),null}},br=i=>{try{let t=[],e=[],r=[],n=[],a=[];for(let d of pi(i)){let m=i.subarray(d.offset,d.offset+d.length),f=Qt(m[0]);f===32&&t.length<65535?t.push(m):f===33&&e.length<65535?e.push(m):f===34&&r.length<65535?r.push(m):f===39&&n.length<65535?n.push(m):f===40&&a.length<65535&&a.push(m)}if(e.length===0||r.length===0)return null;let o=Qi(e[0]);if(!o)return null;let c=0;if(r.length>0){let d=r[0],m=new K(Ks(d));m.skipBits(16),D(m),D(m),m.skipBits(1),m.skipBits(1),m.skipBits(3),m.skipBits(1),m.skipBits(1),D(m),D(m),cr(m),m.skipBits(1),m.skipBits(1),m.readBits(1)&&D(m),cr(m),cr(m),m.skipBits(1),m.skipBits(1),m.skipBits(1),m.skipBits(1);let f=m.readBits(1),p=m.readBits(1);!f&&!p?c=0:f&&!p?c=2:!f&&p?c=3:c=0}let l=[...t.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:t}]:[],...e.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:e}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:r}]:[],...n.length?[{arrayCompleteness:0,nalUnitType:39,nalUnits:n}]:[],...a.length?[{arrayCompleteness:0,nalUnitType:40,nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:o.generalProfileSpace,generalTierFlag:o.generalTierFlag,generalProfileIdc:o.generalProfileIdc,generalProfileCompatibilityFlags:o.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:o.generalConstraintIndicatorFlags,generalLevelIdc:o.generalLevelIdc,minSpatialSegmentationIdc:o.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:o.chromaFormatIdc,bitDepthLumaMinus8:o.bitDepthLumaMinus8,bitDepthChromaMinus8:o.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:o.spsMaxSubLayersMinus1+1,temporalIdNested:o.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(t){return O._error("Error building HEVC Decoder Configuration Record:",t),null}},bh=(i,t)=>{let e=i.readBits(2),r=i.readBits(1),n=i.readBits(5),a=0;for(let u=0;u<32;u++)a=a<<1|i.readBits(1);let s=new Uint8Array(6);for(let u=0;u<6;u++)s[u]=i.readBits(8);let o=i.readBits(8),c=[],l=[];for(let u=0;u<t;u++)c.push(i.readBits(1)),l.push(i.readBits(1));if(t>0)for(let u=t;u<8;u++)i.skipBits(2);for(let u=0;u<t;u++)c[u]&&i.skipBits(88),l[u]&&i.skipBits(8);return{general_profile_space:e,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:a,general_constraint_indicator_flags:s,general_level_idc:o}},yh=i=>{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(!i.readBits(1))D(i);else{let n=Math.min(64,1<<4+(t<<1));t>1&&cr(i);for(let a=0;a<n;a++)cr(i)}},kh=(i,t)=>{let e=[];for(let r=0;r<t;r++)e[r]=Th(i,r,t,e)},Th=(i,t,e,r)=>{let n=0,a=0,s=0;if(t!==0&&(a=i.readBits(1)),a){if(t===e){let c=D(i);s=t-(c+1)}else s=t-1;i.readBits(1),D(i);let o=r[s]??0;for(let c=0;c<=o;c++)(i.readBits(1)||i.readBits(1))&&n++}else{let o=D(i),c=D(i);for(let l=0;l<o;l++)D(i),i.readBits(1);for(let l=0;l<c;l++)D(i),i.readBits(1);n=o+c}return n},wh=(i,t)=>{let e=2,r=2,n=2,a=0,s=0,o={num:1,den:1};if(i.readBits(1)){let c=i.readBits(8);if(c===255)o={num:i.readBits(16),den:i.readBits(16)};else{let l=om[c];l&&(o=l)}}return i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),a=i.readBits(1),i.readBits(1)&&(e=i.readBits(8),r=i.readBits(8),n=i.readBits(8))),i.readBits(1)&&(D(i),D(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(D(i),D(i),D(i),D(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&D(i),i.readBits(1)&&Sh(i,!0,t)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),s=D(i),D(i),D(i),D(i),D(i)),{pixelAspectRatio:o,colourPrimaries:e,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:a,minSpatialSegmentationIdc:s}},Sh=(i,t,e)=>{let r=!1,n=!1,a=!1;t&&(r=i.readBits(1)===1,n=i.readBits(1)===1,(r||n)&&(a=i.readBits(1)===1,a&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),a&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5)));for(let s=0;s<=e;s++){let o=i.readBits(1)===1,c=!0;o||(c=i.readBits(1)===1);let l=!1;c?D(i):l=i.readBits(1)===1;let u=1;l||(u=D(i)+1),r&&nm(i,u,a),n&&nm(i,u,a)}},nm=(i,t,e)=>{for(let r=0;r<t;r++)D(i),D(i),e&&(D(i),D(i)),i.readBits(1)},cm=i=>{let t=[];t.push(i.configurationVersion),t.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),t.push(i.generalProfileCompatibilityFlags>>>24&255),t.push(i.generalProfileCompatibilityFlags>>>16&255),t.push(i.generalProfileCompatibilityFlags>>>8&255),t.push(i.generalProfileCompatibilityFlags&255),t.push(...i.generalConstraintIndicatorFlags),t.push(i.generalLevelIdc&255),t.push(240|i.minSpatialSegmentationIdc>>8&15),t.push(i.minSpatialSegmentationIdc&255),t.push(252|i.parallelismType&3),t.push(252|i.chromaFormatIdc&3),t.push(248|i.bitDepthLumaMinus8&7),t.push(248|i.bitDepthChromaMinus8&7),t.push(i.avgFrameRate>>8&255),t.push(i.avgFrameRate&255),t.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),t.push(i.arrays.length&255);for(let e of i.arrays){t.push((e.arrayCompleteness&1)<<7|0|e.nalUnitType&63),t.push(e.nalUnits.length>>8&255),t.push(e.nalUnits.length&255);for(let r of e.nalUnits){t.push(r.length>>8&255),t.push(r.length&255);for(let n=0;n<r.length;n++)t.push(r[n])}}return new Uint8Array(t)},vn=i=>{try{let t=z(i),e=0,r=t.getUint8(e++),n=t.getUint8(e++),a=n>>6&3,s=n>>5&1,o=n&31,c=t.getUint32(e,!1);e+=4;let l=i.subarray(e,e+6);e+=6;let u=t.getUint8(e++),d=(t.getUint8(e++)&15)<<8|t.getUint8(e++),m=t.getUint8(e++)&3,f=t.getUint8(e++)&3,p=t.getUint8(e++)&7,h=t.getUint8(e++)&7,y=t.getUint16(e,!1);e+=2;let g=t.getUint8(e++),k=g>>6&3,T=g>>3&7,S=g>>2&1,w=g&3,A=t.getUint8(e++),C=[];for(let E=0;E<A;E++){let I=t.getUint8(e++),x=I>>7&1,P=I&63,v=t.getUint16(e,!1);e+=2;let _=[];for(let M=0;M<v;M++){let U=t.getUint16(e,!1);e+=2,_.push(i.subarray(e,e+U)),e+=U}C.push({arrayCompleteness:x,nalUnitType:P,nalUnits:_})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:m,chromaFormatIdc:f,bitDepthLumaMinus8:p,bitDepthChromaMinus8:h,avgFrameRate:y,constantFrameRate:k,numTemporalLayers:T,temporalIdNested:S,lengthSizeMinusOne:w,arrays:C}}catch(t){return O._error("Error deserializing HEVC Decoder Configuration Record:",t),null}};var lm=(i,t)=>{let e=new Set,r=0;for(let a of ha(i,t)){if(r===4){e.add(a.offset);continue}let s=Qt(i[a.offset]);if(r===3&&s!==37){e.add(a.offset);continue}let o=!1;s===35?r>0?o=!0:r=1:s<=31?r>2?o=!0:r=2:s===36?r!==2?o=!0:r=3:s===37?r<2?o=!0:r=4:s===32||s===33||s===34||s===39||s>=41&&s<=44||s>=48&&s<=55?r>1?o=!0:r=1:(s===38||s===40||s>=45&&s<=47||s>=56&&s<=63)&&r<2&&(o=!0),o&&e.add(a.offset)}if(e.size===0)return null;let n=[];for(let a of ha(i,t))e.has(a.offset)||n.push(i.subarray(a.offset,a.offset+a.length));return gh(n,t)},Ah={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},_n=i=>{let t=new K(i);if(t.readBits(2)!==2)return null;let r=t.readBits(1),a=(t.readBits(1)<<1)+r;if(a===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let l=8;a>=2&&(l=t.readBits(1)?12:10);let u=t.readBits(3),d=0,m=0;if(u!==7)if(m=t.readBits(1),a===1||a===3){let E=t.readBits(1),I=t.readBits(1);d=!E&&!I?3:E&&!I?2:1,t.skipBits(1)}else d=1;else d=3,m=1,(a===1||a===3)&&t.skipBits(1);let f=t.readBits(16),p=t.readBits(16),h=f+1,y=p+1,g=h*y,k=J(Gi).level;for(let C of Gi)if(g<=C.maxPictureSize){k=C.level;break}let T=Ah[u],S=T?.colourPrimaries??2,w=T?.transferCharacteristics??2,A=T?.matrixCoefficients??2;return{profile:a,level:k,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:S,transferCharacteristics:w,matrixCoefficients:A}},um=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,dm=function*(i){let t=new K(i),e=()=>{let r=0;for(let n=0;n<8;n++){let a=t.readAlignedByte();if(r+=(a&127)*2**(n*7),!(a&128))break;if(n===7&&a&128)return null}return r>2**32-1?null:r};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),n=t.readBits(1),a=t.readBits(1);t.skipBits(1),n&&t.skipBits(8);let s;if(a){let o=e();if(o===null)return;s=o}else s=Math.floor(t.getBitsLeft()/8);b(t.pos%8===0),yield{type:r,data:i.subarray(t.pos/8,t.pos/8+s)},t.skipBits(s*8)}},hi=i=>{for(let{type:t,data:e}of dm(i)){if(t!==1)continue;let r=new K(e),n=r.readBits(3),a=r.readBits(1),s=r.readBits(1),o=0,c=0,l=0;if(s)o=r.readBits(5);else{let x=r.readBits(1),P=0;if(x){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let U=0;for(;U<32&&!r.readBits(1);)U++;U<32&&r.skipBits(U)}P=r.readBits(1),P&&(l=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}let v=r.readBits(1),_=r.readBits(5);for(let M=0;M<=_;M++){r.skipBits(12);let U=r.readBits(5);if(M===0&&(o=U),U>7){let N=r.readBits(1);M===0&&(c=N)}if(P&&r.readBits(1)){let L=l+1;r.skipBits(L),r.skipBits(L),r.skipBits(1)}v&&r.readBits(1)&&r.skipBits(4)}}let u=r.readBits(4),d=r.readBits(4),m=u+1;r.skipBits(m);let f=d+1;r.skipBits(f);let p=0;if(s?p=0:p=r.readBits(1),p&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!s){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let x=r.readBits(1);x&&(r.skipBits(1),r.skipBits(1));let P=r.readBits(1),v=0;P?v=2:v=r.readBits(1),v>0&&(r.readBits(1)||r.skipBits(1)),x&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);let h=r.readBits(1),y=8;n===2&&h?y=r.readBits(1)?12:10:n<=2&&(y=h?10:8);let g=0;n!==1&&(g=r.readBits(1));let k=2,T=2,S=2;r.readBits(1)&&(k=r.readBits(8),T=r.readBits(8),S=r.readBits(8));let A=0,C=1,E=1,I=0;return g?A=r.readBits(1):k===1&&T===13&&S===0?(A=1,C=0,E=0):(A=r.readBits(1),n===0?(C=1,E=1):n===1?(C=0,E=0):y===12?(C=r.readBits(1),E=C?r.readBits(1):0):(C=1,E=0),C&&E&&(I=r.readBits(2))),{profile:n,level:o,tier:c,bitDepth:y,monochrome:g,chromaSubsamplingX:C,chromaSubsamplingY:E,chromaSamplePosition:I,videoFullRangeFlag:A,colourPrimaries:k,transferCharacteristics:T,matrixCoefficients:S}}return null},Qs=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,js=i=>{if(i.length<28)return null;let e=z(i);return e.getUint32(4)!==1768124518||e.getUint16(8)<20?null:{fullRange:!1,colourPrimaries:e.getUint8(22),transferCharacteristics:e.getUint8(23),matrixCoefficients:e.getUint8(24)}},yr=i=>{if(i.byteLength<19)throw new Error("Invalid Opus identification header: too short.");let t=z(i),e=t.getUint8(9),r=t.getUint16(10,!0),n=t.getUint32(12,!0),a=t.getInt16(16,!0),s=t.getUint8(18),o=null;return s&&(o=i.subarray(19)),{outputChannelCount:e,preSkip:r,inputSampleRate:n,outputGain:a,channelMappingFamily:s,channelMappingTable:o}},xh=[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],Xs=i=>{let t=i[0]>>3,e=i[0]&3,r;return e===0?r=1:e===1||e===2?r=2:r=i[1]&63,{durationInSamples:xh[t]*r}},$s=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");let e=i.length,r=new Uint8Array(e);for(let d=0;d<e;d++)r[d]=i[e-1-d];let n=new K(r),a=0;for(;n.getBitsLeft()>97;)if(n.readBits(1)===1){a=n.pos;break}if(a===0)throw new Error("Invalid Setup header: framing bit not found.");let s=0,o=!1,c=0;for(;n.getBitsLeft()>=97;){let d=n.pos,m=n.readBits(8),f=n.readBits(16),p=n.readBits(16);if(m>63||f!==0||p!==0){n.pos=d;break}if(n.skipBits(1),s++,s>64)break;n.clone().readBits(6)+1===s&&(o=!0,c=s)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);let l=c;n.pos=0,n.skipBits(a);let u=Array(l).fill(0);for(let d=l-1;d>=0;d--)n.skipBits(40),u[d]=n.readBits(1);return{modeBlockflags:u}},gi=(i,t,e)=>{switch(i){case"avc":{for(let r of Nl(e,t)){let n=e[r.offset],a=pr(n);if(a>=1&&a<=4)return"delta";if(a===5)return"key";if(a===6&&!Ni()){let s=e.subarray(r.offset,r.offset+r.length),o=Ks(s),c=1;do{let l=0;for(;;){let m=o[c++];if(m===void 0||(l+=m,m<255))break}let u=0;for(;;){let m=o[c++];if(m===void 0||(u+=m,m<255))break}if(l===6){let m=new K(o);m.pos=8*c;let f=-1;try{f=D(m)}catch{}let p=m.readBits(1);if(f===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(let r of ha(e,t)){let n=Qt(e[r.offset]);if(n<16)return"delta";if(n<=23)return"key"}return"delta"}case"vp8":return(e[0]&1)===0?"key":"delta";case"vp9":{let r=new K(e);if(r.readBits(2)!==2)return null;let n=r.readBits(1);return(r.readBits(1)<<1)+n===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(let{type:n,data:a}of dm(e))if(n===1){let s=new K(a);s.skipBits(4),r=!!s.readBits(1)}else if(n===3||n===6||n===7){if(r)return"key";let s=new K(a);if(s.readBits(1))return null;let c=s.readBits(2),l=s.readBits(1);return c===0&&l===1?"key":"delta"}return null}case"prores":return"key";default:Z(i),b(!1)}},mm=(i,t)=>{if(i==="vp8")return t[0]>>4&1;if(i==="vp9"){let e=n=>{let a=new K(n);a.skipBits(2);let s=a.readBits(1),o=a.readBits(1);return s===1&&o===1&&a.skipBits(1),a.readBits(1)===1?!0:(a.skipBits(1),a.readBits(1)===1)},r=t[t.length-1];if((r&224)===192){let n=(r&7)+1,a=(r>>3&3)+1,s=t.length-(2+n*a);if(t[s]===r){let o=0,c=0;for(let l=0;l<n;l++){let u=0;for(let d=0;d<a;d++)u+=t[s+1+l*a+d]*2**(8*d);e(t.subarray(c,c+u))&&o++,c+=u}return o}}return e(t)?1:0}return 1},Rn=(i,t)=>i==="truehd"?(t.byteLength>=8?z(t).getUint32(4):null)===4168249274?"key":"delta":"key";var ya=(i,t)=>{let e=z(i),r=0;if(i.length<4)return;let n=e.getUint32(r,!0);r+=4;let a=be.decode(i.subarray(r,r+n));if(r+=n,n>0&&(t.raw??={},t.raw.vendor??=a),r+4>i.length)return;let s=e.getUint32(r,!0);r+=4;for(let o=0;o<s&&!(r+4>i.length);o++){let c=e.getUint32(r,!0);r+=4;let l=be.decode(i.subarray(r,r+c));r+=c;let u=l.indexOf("=");if(u===-1)continue;let d=l.slice(0,u).toUpperCase(),m=l.slice(u+1);switch(t.raw??={},Array.isArray(t.raw[d])?t.raw[d].push(m):typeof t.raw[d]=="string"?t.raw[d]=[t.raw[d],m]:t.raw[d]??=m,d){case"TITLE":t.title??=m;break;case"DESCRIPTION":t.description??=m;break;case"ARTIST":t.artist??=m;break;case"ALBUM":t.album??=m;break;case"ALBUMARTIST":t.albumArtist??=m;break;case"COMMENT":t.comment??=m;break;case"LYRICS":t.lyrics??=m;break;case"TRACKNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),h=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.trackNumber??=p),h&&Number.isInteger(h)&&h>0&&(t.tracksTotal??=h)}break;case"TRACKTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.tracksTotal??=f)}break;case"DISCNUMBER":{let f=m.split("/"),p=Number.parseInt(f[0],10),h=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(t.discNumber??=p),h&&Number.isInteger(h)&&h>0&&(t.discsTotal??=h)}break;case"DISCTOTAL":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.discsTotal??=f)}break;case"DATE":{let f=Kt(m);f&&(t.date??=f)}break;case"BPM":{let f=Number.parseInt(m,10);Number.isInteger(f)&&f>0&&(t.beatsPerMinute??=f)}break;case"GENRE":t.genre??=m;break;case"METADATA_BLOCK_PICTURE":try{let f=Hi(m),p=z(f),h=p.getUint32(0,!1),y=p.getUint32(4,!1),g=be.decode(f.subarray(8,8+y)),k=p.getUint32(8+y,!1),T=be.decode(f.subarray(12+y,12+y+k)),S=p.getUint32(y+k+28),w=f.subarray(y+k+32,y+k+32+S);t.images??=[],t.images.push({data:w,mimeType:g,kind:h===3?"coverFront":h===4?"coverBack":"unknown",name:void 0,description:T||void 0})}catch{}break}}},ka=(i,t,e)=>{let r=[i],n=Y.encode(Kr),a=new Uint8Array(4+n.length),s=new DataView(a.buffer);s.setUint32(0,n.length,!0),a.set(n,4),r.push(a);let o=[],c=(f,p)=>{let h=`${f}=${p}`,y=Y.encode(h);a=new Uint8Array(4+y.length),s=new DataView(a.buffer),s.setUint32(0,y.length,!0),a.set(y,4),r.push(a),o.push(f)};for(let{key:f,value:p}of qt(t))switch(f){case"title":c("TITLE",p);break;case"description":c("DESCRIPTION",p);break;case"artist":c("ARTIST",p);break;case"album":c("ALBUM",p);break;case"albumArtist":c("ALBUMARTIST",p);break;case"genre":c("GENRE",p);break;case"date":c("DATE",p.toISOString().slice(0,10));break;case"comment":c("COMMENT",p);break;case"lyrics":c("LYRICS",p);break;case"trackNumber":c("TRACKNUMBER",p.toString());break;case"tracksTotal":c("TRACKTOTAL",p.toString());break;case"discNumber":c("DISCNUMBER",p.toString());break;case"discsTotal":c("DISCTOTAL",p.toString());break;case"beatsPerMinute":c("BPM",p.toString());break;case"images":{if(!e)break;for(let h of p){let y=h.kind==="coverFront"?3:h.kind==="coverBack"?4:0,g=new Uint8Array(h.mimeType.length);for(let A=0;A<h.mimeType.length;A++)g[A]=h.mimeType.charCodeAt(A);let k=Y.encode(h.description??""),T=new Uint8Array(8+g.length+4+k.length+16+4+h.data.length),S=z(T);S.setUint32(0,y,!1),S.setUint32(4,g.length,!1),T.set(g,8),S.setUint32(8+g.length,k.length,!1),T.set(k,12+g.length),S.setUint32(28+g.length+k.length,h.data.length,!1),T.set(h.data,32+g.length+k.length);let w=Nd(T);c("METADATA_BLOCK_PICTURE",w)}}break;case"raw":break;case"creationTime":break;default:Z(f)}if(t.raw)for(let f in t.raw){let p=t.raw[f]??t.raw[f.toLowerCase()];if(!(f==="vendor"||p==null||o.includes(f))&&!(f==="METADATA_BLOCK_PICTURE"&&!e&&(t.images?.length??0)>0)){if(typeof p=="string")c(f,p);else if(Array.isArray(p)&&p.every(y=>typeof y=="string"))for(let y of p)c(f,y)}}let l=new Uint8Array(4);z(l).setUint32(0,o.length,!0),r.splice(2,0,l);let u=r.reduce((f,p)=>f+p.length,0),d=new Uint8Array(u),m=0;for(let f of r)d.set(f,m),m+=f.length;return d},Ta=[2,1,2,3,3,4,4,5],Ys=i=>{if(i.length<7||i[0]!==11||i[1]!==119)return null;let t=new K(i);t.skipBits(16),t.skipBits(16);let e=t.readBits(2);if(e===3)return null;let r=t.readBits(6),n=t.readBits(5);if(n>8)return null;let a=t.readBits(3),s=t.readBits(3);(s&1)!==0&&s!==1&&t.skipBits(2),(s&4)!==0&&t.skipBits(2),s===2&&t.skipBits(2);let o=t.readBits(1),c=Math.floor(r/2);return{fscod:e,bsid:n,bsmod:a,acmod:s,lfeon:o,bitRateCode:c}},fm=[64*2,69*2,96*2,64*2,70*2,96*2,80*2,87*2,120*2,80*2,88*2,120*2,96*2,104*2,144*2,96*2,105*2,144*2,112*2,121*2,168*2,112*2,122*2,168*2,128*2,139*2,192*2,128*2,140*2,192*2,160*2,174*2,240*2,160*2,175*2,240*2,192*2,208*2,288*2,192*2,209*2,288*2,224*2,243*2,336*2,224*2,244*2,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],pm=1536,wa=new Uint8Array([5,4,65,67,45,51]),Sa=new Uint8Array([5,4,69,65,67,51]),Zs=[1,2,3,6],Js=i=>{if(i.length<6||i[0]!==11||i[1]!==119)return null;let t=new K(i);t.skipBits(16);let e=t.readBits(2);if(t.skipBits(3),e!==0&&e!==2)return null;let r=t.readBits(11),n=t.readBits(2),a=0,s;n===3?(a=t.readBits(2),s=3):s=t.readBits(2);let o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=Zs[s],d;n<3?d=Ki[n]/1e3:d=Ul[a]/1e3;let m=Math.round((r+1)*d/(u*16)),f=0,p=0,h=0,y=2*(r+1);for(;y+2<=i.length&&(t.seekToByte(y),!(t.readBits(16)!==2935||t.readBits(2)!==1));){t.skipBits(3);let k=t.readBits(11);t.skipBits(4);let T=t.readBits(3);if(t.skipBits(11),t.readBits(1)&&t.skipBits(8),T===0&&(t.skipBits(5),t.readBits(1)&&t.skipBits(8)),t.readBits(1)){let S=t.readBits(16);for(let w=0;w<8;w++)S&1<<10-w&&(h|=1<<w);S&2&&(h|=256)}p++,y+=2*(k+1)}return{dataRate:m,substreams:[{fscod:n,fscod2:a,bsid:l,bsmod:f,acmod:o,lfeon:c,numDepSub:p,chanLoc:h}]}},eo=i=>{let t=[],e=0;for(;e<i.length;){if(e+6>i.length||i[e]!==11||i[e+1]!==119)return null;let r=i[e+2]>>6,n=(i[e+2]&7)<<8|i[e+3],s=i[e+4]>>6===3?3:i[e+4]>>4&3,o=i[e+5]>>3,c=2*(n+1);if(o<=10||e+c>i.length)return null;if(r===1){let l=J(t);if(!l)return null;l.size+=c}else t.push({offset:e,size:c,blockCount:Zs[s]});e+=c}return t},hm=i=>{if(i.length<2)return null;let t=new K(i),e=t.readBits(13),r=t.readBits(3),n=[];for(let a=0;a<=r&&!(Math.ceil(t.pos/8)+3>i.length);a++){let s=t.readBits(2),o=t.readBits(5);t.skipBits(1),t.skipBits(1);let c=t.readBits(3),l=t.readBits(3),u=t.readBits(1);t.skipBits(3);let d=t.readBits(4),m=0;d>0?m=t.readBits(9):t.skipBits(1),n.push({fscod:s,fscod2:null,bsid:o,bsmod:c,acmod:l,lfeon:u,numDepSub:d,chanLoc:m})}return n.length===0?null:{dataRate:e,substreams:n}},to=i=>{let t=i.substreams[0];return b(t),t.fscod<3?Ki[t.fscod]:t.fscod2!==null&&t.fscod2<3?Ul[t.fscod2]:null},ro=i=>{let t=i.substreams[0];b(t);let e=Ta[t.acmod]+t.lfeon;if(t.numDepSub>0){let r=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)t.chanLoc&1<<n&&(e+=r[n])}return e};var Ch=1683496997,Aa=18,io=10,gm=4096,am=32,no=20,Ph=8,Eh=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Ih=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],vh=[16,16,20,20,0,24,24,0],Ws=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],_h=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Rh=8,Fh=44646,Mh=[32e3,44100,48e3,0],Bh=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],bm=[512,1024,2048,4096],xa=i=>{let t=Wl(i),e=z(i),r=t?Math.ceil(t.frameSize/4)*4:0,n=null;for(;r+4<=i.length&&e.getUint32(r)===Ch;){let s=Ca(i.subarray(r));if(!s)break;n??=s,r+=s.frameSize}if(t)return{frameSize:n?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:n!==null};if(!n?.asset)return null;let{asset:a}=n;return{frameSize:r,sampleRate:a.sampleRate,numberOfChannels:a.numberOfChannels,sampleCount:a.sampleCount,channelLayout:a.channelLayout,pcmResolution:a.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},ao=i=>{let t=xa(i);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Wl=i=>{if(i.length<Aa||i[0]!==127||i[1]!==254||i[2]!==128||i[3]!==1)return null;let t=new K(i);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==am-1)return null;let e=t.readBits(1),r=t.readBits(7)+1;if(r%Ph!==0)return null;let n=t.readBits(14)+1;if(n<96)return null;let a=t.readBits(6);if(a>=Ws.length)return null;let s=Eh[t.readBits(4)];if(s===0)return null;let o=Ih[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4);let c=t.readBits(3),l=t.readBits(1);t.skipBits(1);let u=t.readBits(2);if(u===3)return null;t.skipBits(1),e&&t.skipBits(16),t.skipBits(7);let d=vh[t.readBits(3)];if(d===0)return null;let m=u!==0;return{frameSize:n,sampleRate:s,numberOfChannels:Ws[a]+(m?1:0),sampleCount:r*am,channelLayout:_h[a]|(m?Rh:0),amode:a,lfePresent:m,bitRate:o,pcmResolution:d,extAudioId:l?c:null}},Ca=i=>{if(i.length<io||i[0]!==100||i[1]!==88||i[2]!==32||i[3]!==37)return null;let t=new K(i);t.skipBits(32),t.skipBits(8);let e=t.readBits(2),r=t.readBits(1),n=8+4*r,a=16+4*r;t.skipBits(n);let s=t.readBits(a)+1,o={frameSize:s,asset:null};if(!t.readBits(1))return o;let c=Mh[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let u=t.readBits(3)+1,d=t.readBits(3)+1,m=[];for(let g=0;g<u;g++)m.push(t.readBits(e+1));for(let g of m)t.skipBits(8*Bs(g));if(t.readBits(1)){t.skipBits(2);let g=t.readBits(2)+1<<2,k=t.readBits(2)+1;t.skipBits(k*g)}for(let g=0;g<d;g++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let f=t.readBits(5)+1,p=Bh[t.readBits(4)],h=t.readBits(8)+1,y=0;if(t.readBits(1)&&(h>2&&t.skipBits(1),h>6&&t.skipBits(1),t.readBits(1))){let g=t.readBits(2)+1<<2;y=t.readBits(g)}return c===0||t.getBitsLeft()<0?o:{frameSize:s,asset:{sampleRate:p,numberOfChannels:h,sampleCount:Math.round(l*p/c),channelLayout:y,pcmResolution:f}}},ym=i=>{if(i.length<no)return null;let t=z(i),e=t.getUint32(0);if(e===0)return null;let r=new K(i);r.seekToByte(13);let n=r.readBits(2);r.skipBits(5);let a=r.readBits(1),s=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);let o=r.readBits(16),c=null;return o!==0?c=Dh(o):s<Ws.length&&(c=Ws[s]+a),{sampleRate:e,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:i[12],sampleCount:bm[n],channelLayout:o,numberOfChannels:c}},Oh={0:2,2:4,6:3},km=i=>{let t=new Uint8Array(no),e=z(t);e.setUint32(0,i.sampleRate),e.setUint32(4,i.bitRate),e.setUint32(8,i.bitRate),t[12]=i.pcmResolution;let r=0;if(i.core&&!i.hasExtensions){let{extAudioId:a}=i.core;r=a===null?1:Oh[a]??0}let n=new K(t);return n.seekToByte(13),n.writeBits(2,Math.max(bm.indexOf(i.sampleCount),0)),n.writeBits(5,r),n.writeBits(1,i.core?.lfePresent?1:0),n.writeBits(6,i.core?.amode??0),n.writeBits(14,i.core?i.core.frameSize-1:0),n.writeBits(1,0),n.writeBits(3,0),n.writeBits(16,i.channelLayout),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(5,0),t},Dh=i=>Bs(i)+Bs(i&Fh);var Pa=/(?:(.+?)\n)?((?:\d{2,}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2,}:)?\d{2}:\d{2}.\d{3})/g,Vh=/^WEBVTT(.|\n)*?\n{2}/,Fn=/<(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})>/g,so=class{constructor(t){this.preambleText=null;this.preambleEmitted=!1;this.options=t}parse(t){t=t.replaceAll(`\r
|
|
9
9
|
`,`
|
|
10
10
|
`).replaceAll("\r",`
|
|
11
|
-
`),
|
|
11
|
+
`),Pa.lastIndex=0;let e;if(!this.preambleText){if(t.charCodeAt(0)===65279&&(t=t.slice(1)),!Vh.test(t))throw new Error("WebVTT preamble incorrect.");e=Pa.exec(t);let r=t.slice(0,e?.index??t.length).trimEnd();if(!r)throw new Error("No WebVTT preamble provided.");this.preambleText=r,e&&(t=t.slice(e.index),Pa.lastIndex=0)}for(;e=Pa.exec(t);){let r=t.slice(0,e.index),n=e[1],a=e.index+e[0].length,s=t.indexOf(`
|
|
12
12
|
`,a),o=s===-1?t.length:s+1,c=t.slice(a,o).trim(),l=t.indexOf(`
|
|
13
13
|
|
|
14
|
-
`,a);l===-1&&(l=t.length);let u=so(e[2]),m=so(e[3])-u,f=t.slice(o,l).trim();t=t.slice(l).trimStart(),Ca.lastIndex=0;let p={timestamp:u/1e3,duration:m/1e3,text:f,identifier:n,settings:c,notes:r},g={};this.preambleEmitted||(g.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(p,g)}}},Uh=/(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})/,so=i=>{let t=Uh.exec(i);if(!t)throw new Error("Expected match.");return 60*60*1e3*Number(t[1]||"0")+60*1e3*Number(t[2])+1e3*Number(t[3])+Number(t[4])},oo=i=>{let t=Math.round(1e3*i),e=Math.floor(t/(60*60*1e3)),r=Math.floor(t%(60*60*1e3)/(60*1e3)),n=Math.floor(t%(60*1e3)/1e3),a=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};var Tm=i=>{let r=i>>2,n=4096,a=0,s=12,o=0;for(r<0&&(r=-r,a=128),r+=33,r>8191&&(r=8191);(r&n)!==n&&s>=5;)n>>=1,s--;return o=r>>s-4&15,~(a|s-5<<4|o)&255},wm=i=>{let e=0,r=0,n=~i;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+5;let a=(1<<r|(n&15)<<r-4|1<<r-5)-33;return(e===0?a:-a)<<2},Sm=i=>{let e=2048,r=0,n=11,a=0,s=i>>3;for(s<0?s=-s-1:r=128,s>4095&&(s=4095);(s&e)!==e&&n>=5;)e>>=1,n--;return a=s>>(n===4?1:n-4)&15,(r|n-4<<4|a)^85},Am=i=>{let t=0,e=0,r=i^85;r&128&&(r&=-129,t=-1),e=((r&240)>>4)+4;let n=0;return e!==4?n=1<<e|(r&15)<<e-4|1<<e-5:n=r<<1|1,(t===0?-n:n)<<3};var co=new Map,lo=new Map,zh=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&ct(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.codedWidth!==void 0&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(t.codedHeight!==void 0&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(t.displayAspectWidth!==void 0&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(t.displayAspectHeight!==void 0&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(t.description!==void 0&&!Dr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},Nh=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&ct(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.numberOfChannels!==void 0&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(t.sampleRate!==void 0&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(t.description!==void 0&&!Dr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.")},xm=async i=>le.includes(i)?uo(i):pe.includes(i)?mo(i):!1,uo=async(i,t={})=>{if(!le.includes(i))return!1;zh(i,t);let e=t.codedWidth??1280,r=t.codedHeight??720,n={...t,codedWidth:e,codedHeight:r,codec:t.codec??fo(i,e,r,1e6,!1)};n.description??=Em(n);let a=Cm(n),s=co.get(a);if(s)return s;let o=(async()=>bi.some(l=>l.supports(i,n))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(n)).supported===!0)();return co.set(a,o),o},mo=async(i,t={})=>{if(!pe.includes(i))return!1;Nh(i,t);let e={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??po(i)};if(e.description===void 0){let s=Im(e);if(s===!1)return!1;e.description=s}let r=Cm(e),n=lo.get(r);if(n)return n;let a=(async()=>yi.some(o=>o.supports(i,e))||se.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0)();return lo.set(r,a),a},Cm=i=>JSON.stringify({...i,description:i.description&&[...G(i.description)]}),Pm=async()=>{let[i,t]=await Promise.all([Wl(),ql()]);return[...i,...t]},Wl=async(i=le,t)=>{let e=await Promise.all(i.map(r=>uo(r,t)));return i.filter((r,n)=>e[n])},ql=async(i=pe,t)=>{let e=await Promise.all(i.map(r=>mo(r,t)));return i.filter((r,n)=>e[n])};Cn();var vm=-1/0,_m=-1/0,va=null;typeof FinalizationRegistry<"u"&&(va=new FinalizationRegistry(i=>{let t=performance.now();i.type==="video"?(t-vm>=1e3&&(O._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."),vm=t),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(t-_m>=1e3&&(O._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."),_m=t),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));var jt=class{constructor(){this._referenceCount=0;this._lastAllocationBuffer=null}},_a=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Lh=new Set(_a),$e=class i{constructor(t,e){this._closed=!1;if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.format===void 0||!Lh.has(e.format))throw new TypeError("init.format must be one of: "+_a.join(", "));if(!Number.isInteger(e.codedWidth)||e.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(e.codedHeight)||e.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.layout!==void 0){if(!Array.isArray(e.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let s of e.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}let a=Ra(e.format).length;if(e.layout.length!==a)throw new TypeError(`init.layout must have ${a} entries for format ${e.format}.`)}if(e.visibleRect!==void 0&&Kl(e.visibleRect),e.displayWidth!==void 0&&(!Number.isInteger(e.displayWidth)||e.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(e.displayHeight!==void 0&&(!Number.isInteger(e.displayHeight)||e.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(e.displayWidth!==void 0!=(e.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=e.format,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0;let r=e.layout??Wh(e.format,e.codedWidth,e.codedHeight),n=e.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:e.visibleRect?.left??0,top:e.visibleRect?.top??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},e.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?e.displayWidth:e.displayHeight,this.squarePixelHeight=this.rotation%180===0?e.displayHeight:e.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=e._doNotCopy?G(t):G(t).slice(),this._layout=r,this.colorSpace=new Xi(n)}else if(typeof VideoFrame<"u"&&t instanceof VideoFrame){if(t.codedWidth===0)throw new TypeError("data must not be a closed VideoFrame.");if(e?.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e?.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(e?.timestamp!==void 0&&!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");e?.visibleRect!==void 0&&Kl(e.visibleRect),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=e?.rotation??0,this.flip=e?.flip??!1,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=e?.timestamp??t.timestamp/1e6,this.duration=e?.duration??(t.duration??0)/1e6;let{primaries:r,transfer:n,matrix:a,fullRange:s}=t.colorSpace;this.colorSpace=new Xi({primaries:r!==null&&r in _t?r:null,transfer:n!==null&&n in Rt?n:null,matrix:a!==null&&a in Ft?a:null,fullRange:s})}else if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof SVGImageElement<"u"&&t instanceof SVGImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.visibleRect!==void 0&&Kl(e.visibleRect),typeof VideoFrame<"u")return new i(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*ur),duration:Math.trunc((e.duration??0)*ur)||void 0,visibleRect:e.visibleRect&&{x:e.visibleRect.left,y:e.visibleRect.top,width:e.visibleRect.width,height:e.visibleRect.height}}),e);let r=0,n=0;if("naturalWidth"in t?(r=t.naturalWidth,n=t.naturalHeight):"videoWidth"in t?(r=t.videoWidth,n=t.videoHeight):"width"in t&&(r=Number(t.width),n=Number(t.height)),!r||!n)throw new TypeError("Could not determine dimensions.");let a=e.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(a.width,a.height),o=s.getContext("2d",{alpha:Wt(),willReadFrequently:!0});if(!o)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");o.drawImage(t,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new Xi({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(t instanceof jt){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this.format=t.getFormat(),this.format!==null&&!_a.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=t.getColorSpace(),this._data=t,t._referenceCount++}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=e?.encodeOptions??{},this.pixelAspectRatio=zr({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),va?.register(this,{type:"video",data:this._data},this)}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(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return b(this._data!==null),this._data instanceof jt?new i(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Ea(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(b(this._layout),new i(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,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new i(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(va?.unregister(this),this._data instanceof jt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ea(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(Mm(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Ea(this._data)?this._data.allocationSize(t):Bm(this,t).allocationSize}async copyTo(t,e={}){if(!Dr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Mm(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(b(this._data!==null),Ea(this._data))return this._data.copyTo(t,e);if(e.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(e.format))if(this._data instanceof jt){var l=[];try{let f=yt(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},e.colorSpace??"srgb"));if(!(f instanceof i))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(f.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${f.format}' instead.`);return await f.copyTo(t,e)}catch(u){var d=u,m=!0}finally{kt(l,d,m)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let f=this.toVideoFrame();try{return await f.copyTo(t,e)}finally{f.close()}}let r=Bm(this,e);b(this.format);let n=G(t);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);let a=Ra(this.format),s;if(this._data instanceof jt){let f=this._data.getDataPlanes();if(R(f)&&(f=await f),!Array.isArray(f)||f.some(p=>!(p.data instanceof Uint8Array)||!Number.isInteger(p.stride)||p.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=f}else if(this._data instanceof Uint8Array)b(this._layout),b(this._layout.length===a.length),s=this._layout.map((f,p)=>{let g=Math.ceil((this.visibleRect.top+this.visibleRect.height)/a[p].heightDivisor);return{data:this._data.subarray(f.offset,f.offset+f.stride*g),stride:f.stride}});else{let p=this._data.getContext("2d");b(p);let g=p.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:G(g.data),stride:4*this.codedWidth}]}let o=[],c=a.length;for(let f=0;f<c;f++){let p=r.computedLayouts[f],g=s[f].stride,h=s[f].data,y=p.sourceTop*g;y+=p.sourceLeftBytes;let k=p.destinationOffset,T=p.sourceWidthBytes,S={offset:k,stride:p.destinationStride};for(let w=0;w<p.sourceHeight;w++){if(y+T>h.byteLength)throw new Error("Source buffer OOB read.");if(k+T>n.byteLength)throw new Error("Destination buffer OOB write.");let A=h.subarray(y,y+T);n.set(A,k),y+=g,k+=p.destinationStride}o.push(S)}if(e.format!==void 0){let f=this.format.startsWith("RGB")!==e.format.startsWith("RGB"),p=this.format.includes("X")&&e.format.includes("A");if(f||p){let g=r.computedLayouts[0];for(let h=0;h<g.sourceHeight;h++){let y=g.destinationOffset+h*g.destinationStride,k=y+g.sourceWidthBytes;for(let T=y;T<k;T+=4){if(f){let S=n[T],w=n[T+2];n[T]=w,n[T+2]=S}p&&(n[T+3]=255)}}}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(b(this._data!==null),this._data instanceof jt){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let t=this._data.getDataPlanes();if(R(t))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let e=t.reduce((s,o)=>s+o.data.byteLength,0),r=new Uint8Array(e),n=0,a=[];for(let s of t)r.set(s.data,n),a.push(n),n+=s.data.byteLength;return new VideoFrame(r,{format:this.format,layout:t.map((s,o)=>({offset:a[o],stride:s.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Ea(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(b(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.visibleRect.left+this.visibleRect.width,codedHeight:this.visibleRect.top+this.visibleRect.height,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:{x:this.visibleRect.left,y:this.visibleRect.top,width:this.visibleRect.width,height:this.visibleRect.height},displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,r,n,a,s,o,c,l){let u=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,g=0,h=this.displayWidth,y=this.displayHeight;if(s!==void 0?(u=e,d=r,m=n,f=a,p=s,g=o,c!==void 0?(h=c,y=l):(h=m,y=f)):(p=e,g=r,n!==void 0&&(h=n,y=a)),!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(g))throw new TypeError("dy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:m,sHeight:f}=this._unmapSourceRegion(u,d,m,f,this.rotation,this.flip));let k=this.toCanvasImageSource();t.save();let T=p+h/2,S=g+y/2;t.translate(T,S),this.flip&&t.scale(-1,1),t.rotate(this.rotation*Math.PI/180);let w=this.rotation%180===0?1:h/y;t.scale(1/w,w),t.drawImage(k,u,d,m,f,-h/2,-y/2,h,y),t.restore()}drawWithFit(t,e){if(!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");e.crop!==void 0&&ki(e.crop,"options.");let r=t.canvas.width,n=t.canvas.height,a=e.rotation??this.rotation,s=e.flip??this.flip,[o,c]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],l=e.crop;l&&(l=Fn(l,o,c));let u,d,m,f,{sx:p,sy:g,sWidth:h,sHeight:y}=this._unmapSourceRegion(l?.left??0,l?.top??0,l?.width??o,l?.height??c,a,s);if(e.fit==="fill")u=0,d=0,m=r,f=n;else{let[S,w]=l?[l.width,l.height]:[o,c],A=e.fit==="contain"?Math.min(r/S,n/w):Math.max(r/S,n/w);m=S*A,f=w*A,u=(r-m)/2,d=(n-f)/2}let k=this.toCanvasImageSource();t.save();let T=a%180===0?1:m/f;t.translate(r/2,n/2),s&&t.scale(-1,1),t.rotate(a*Math.PI/180),t.scale(1/T,T),t.translate(-r/2,-n/2),t.drawImage(k,p,g,h,y,u,d,m,f),t.restore()}_unmapSourceRegion(t,e,r,n,a,s){return s&&(t=(a%180===0?this.squarePixelWidth:this.squarePixelHeight)-t-r),a===90?[t,e,r,n]=[e,this.squarePixelHeight-t-r,n,r]:a===180?[t,e]=[this.squarePixelWidth-t-r,this.squarePixelHeight-e-n]:a===270&&([t,e,r,n]=[this.squarePixelWidth-e-n,t,n,r]),{sx:t,sy:e,sWidth:r,sHeight:n}}_drawWithFitAndMipmapping(t,e,r){let n=t.width,a=t.height,[s,o]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=r.crop?r.crop.width:s,l=r.crop?r.crop.height:o,u=0;2*n<c&&2*a<l&&(u=Math.floor(Math.log2(Math.min(c/n,l/a))));let d=n*2**u,m=a*2**u,{canvas:f,context:p,isNew:g}=u>0?Fm(d,m):{canvas:t,context:e,isNew:r.targetIsFresh};p.imageSmoothingQuality="high",r.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,m)):g||p.clearRect(0,0,d,m),this.drawWithFit(p,{fit:r.fit,rotation:r.rotation,flip:r.flip,crop:r.crop}),p.globalCompositeOperation="copy";for(let h=u;h>1;h--){let y=n*2**h,k=a*2**h;p.drawImage(f,0,0,y,k,0,0,y/2,k/2)}p.globalCompositeOperation="source-over",u>0&&(e.imageSmoothingQuality="high",e.globalCompositeOperation="copy",e.drawImage(f,0,0,2*n,2*a,0,0,n,a),e.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(b(this._data!==null),this._data instanceof jt||this._data instanceof Uint8Array){let t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}else return this._data}async transform(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(t.crop!==void 0&&ki(t.crop,"options."),t.alpha!==void 0&&!["keep","discard"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let{rotation:e,flip:r}=vs(this.rotation,this.flip,t.rotate??0,t.flip??!1),[n,a]=e%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&(s=Fn(s,n,a));let o=s?s.width:n,c=s?s.height:a,l=o/c,u,d;t.width!==void 0&&t.height===void 0?(u=t.width,d=u/l):t.width===void 0&&t.height!==void 0?(d=t.height,u=d*l):t.width!==void 0&&t.height!==void 0?(u=t.width,d=t.height):(u=o,d=c),u=Fs(u,t.roundDimensionsTo??1),d=Fs(d,t.roundDimensionsTo??1);let m={width:u,height:d,fit:t.fit??"fill",rotation:e,flip:r,crop:s??{left:0,top:0,width:n,height:a},alpha:t.alpha??"keep"};for(let h of Gl){let y=h(this,m);if(R(y)&&(y=await y),y!==null)return y}let{canvas:f,context:p,isNew:g}=Fm(m.width,m.height);return this._drawWithFitAndMipmapping(f,p,{fit:m.fit,rotation:m.rotation,flip:m.flip,crop:m.crop,targetIsFresh:g,fillBlack:m.alpha==="discard"}),new i(f,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1,encodeOptions:this.encodeOptions})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setFlip(t){if(typeof t!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||typeof t!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},Gl=[],Om=i=>{Gl.includes(i)||Gl.push(i)},Hh=3,Pa=[],Rm=0,Fm=(i,t)=>{for(let n of Pa)if(n.canvas.width===i&&n.canvas.height===t)return n.age=Rm++,{canvas:n.canvas,context:n.context,isNew:!1};let e;if(typeof OffscreenCanvas<"u")e=new OffscreenCanvas(i,t);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");e=document.createElement("canvas"),e.width=i,e.height=t}let r=e.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Pa.length>=Hh&&Pa.splice(li(Pa,n=>n.age),1),Pa.push({canvas:e,context:r,age:Rm++}),{canvas:e,context:r,isNew:!0}},Xi=class{constructor(t){if(t!==void 0){if(!t||typeof t!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let e=Object.keys(_t);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);let r=Object.keys(Rt);if(t.transfer!=null&&!r.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);let n=Object.keys(Ft);if(t.matrix!=null&&!n.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Ea=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,Fn=(i,t,e)=>{let r=Math.min(i.left,t),n=Math.min(i.top,e),a=Math.min(i.width,t-r),s=Math.min(i.height,e-n);return b(a>=0),b(s>=0),{left:r,top:n,width:a,height:s}},ki=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},Kl=i=>{if(Wd(i,"init.visibleRect"),i.width===0||i.height===0)throw new TypeError("init.visibleRect must not be empty.")},Mm=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.colorSpace!==void 0&&!["display-p3","srgb"].includes(i.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(i.format!==void 0&&typeof i.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let t of i.layout){if(!t||typeof t!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(i.rect!==void 0){if(!i.rect||typeof i.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(i.rect.x!==void 0&&(!Number.isInteger(i.rect.x)||i.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(i.rect.y!==void 0&&(!Number.isInteger(i.rect.y)||i.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(i.rect.width!==void 0&&(!Number.isInteger(i.rect.width)||i.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(i.rect.height!==void 0&&(!Number.isInteger(i.rect.height)||i.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Wh=(i,t,e)=>{let r=Ra(i),n=[],a=0;for(let s of r){let o=Math.ceil(t/s.widthDivisor),c=Math.ceil(e/s.heightDivisor),l=o*s.sampleBytes,u=l*c;n.push({offset:a,stride:l}),a+=u}return n},Ra=i=>{let t=(e,r,n,a,s)=>{let o=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:n,heightDivisor:a},{sampleBytes:r,widthDivisor:n,heightDivisor:a}];return s&&o.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),o};switch(i){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(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:Z(i),b(!1)}},Bm=(i,t)=>{let e={x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height},r=t.rect,n=qh(e,r,i.visibleRect.left+i.visibleRect.width,i.visibleRect.top+i.visibleRect.height,i.format),a=t.layout,s;if(!t.format||t.format===i.format)s=i.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(t.format))s=t.format;else throw new Error("NotSupportedError: Invalid destination format.");return Gh(n,s,a)},qh=(i,t,e,r,n)=>{let a={...i};if(t!==void 0){if(!t.width||!t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>e)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!Kh(n,a))throw new TypeError("visibleRect alignment is invalid for the format.");return a},Kh=(i,t)=>{if(i===null)return!0;let e=Ra(i);for(let r=0;r<e.length;r++){let n=e[r],a=n.widthDivisor,s=n.heightDivisor;if((t.x||0)%a!==0||(t.y||0)%s!==0)return!1}return!0},Gh=(i,t,e)=>{let r=Ra(t),n=r.length;if(e!==void 0&&e.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let a=0,s=[],o=[];for(let c=0;c<n;c++){let l=r[c],u=l.sampleBytes,d=l.widthDivisor,m=l.heightDivisor,f={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(f.sourceTop=Math.ceil(Math.trunc(i.y||0)/m),f.sourceHeight=Math.ceil(Math.trunc(i.height||0)/m),f.sourceLeftBytes=Math.floor(Math.trunc(i.x||0)/d)*u,f.sourceWidthBytes=Math.ceil(Math.trunc(i.width||0)/d)*u,e!==void 0){let h=e[c];if(h.stride<f.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);f.destinationOffset=h.offset,f.destinationStride=h.stride}else f.destinationOffset=a,f.destinationStride=f.sourceWidthBytes;let g=f.destinationStride*f.sourceHeight+f.destinationOffset;if(g>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(g),a=Math.max(a,g);for(let h=0;h<c;h++){let y=s[h];if(!(o[c]<=y.destinationOffset||o[h]<=f.destinationOffset))throw new TypeError("Planes overlap.")}s.push(f)}return{allocationSize:a,computedLayouts:s}},ho=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Gr=class{constructor(){this._referenceCount=0}},Ce=class i{constructor(t){this._closed=!1;if(Ia(t)){if(t.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=t,this.format=t.format,this.sampleRate=t.sampleRate,this.numberOfFrames=t.numberOfFrames,this.numberOfChannels=t.numberOfChannels,this.timestamp=t.timestamp/1e6,this.duration=t.numberOfFrames/t.sampleRate}else if(t instanceof Gr){if(this.format=t.getFormat(),!ho.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=t.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=t.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=t.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=t.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate,this._data=t,t._referenceCount++}else{if(!t||typeof t!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!ho.has(t.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(t.sampleRate)||t.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp must be a number.");let e=t.data.byteLength/(Ct(t.format)*t.numberOfChannels);if(!Number.isInteger(e))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=t.format,this.sampleRate=t.sampleRate,this.numberOfFrames=e,this.numberOfChannels=t.numberOfChannels,this.timestamp=t.timestamp,this.duration=e/t.sampleRate;let r;if(t.data instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t.data instanceof SharedArrayBuffer)r=new Uint8Array(t.data);else if(ArrayBuffer.isView(t.data))r=new Uint8Array(t.data.buffer,t.data.byteOffset,t.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let n=this.numberOfFrames*this.numberOfChannels*Ct(this.format);if(r.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=t._doNotCopy?r:r.slice()}va?.register(this,{type:"audio",data:this._data},this)}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}allocationSize(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!ho.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let e=t.format??this.format,r=t.frameOffset??0;if(r>0&&r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let n=t.frameCount!==void 0?t.frameCount:this.numberOfFrames-r;if(n>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let a=Ct(e),s=ji(e);if(s&&t.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&t.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?n:n*this.numberOfChannels)*a}copyTo(t,e){if(!Dr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!ho.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{format:r,frameCount:n,frameOffset:a}=e,{planeIndex:s}=e,o=this.format,c=r??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,u=this.numberOfChannels,d=a??0;if(d>0&&d>=l)throw new RangeError("frameOffset out of range");let m=n!==void 0?n:l-d;if(m>l-d)throw new RangeError("frameCount out of range");let f=Ct(c),p=ji(c);if(p&&s>=u)throw new RangeError("planeIndex out of range");if(!p&&s!==0)throw new RangeError("planeIndex out of range");let h=(p?m:m*u)*f;if(t.byteLength<h)throw new RangeError("Destination buffer is too small");let y=N(t),k=Vm(c);if(Ia(this._data))if(et()&&u>2&&c!==o){Qh(this._data,y,o,c,u,s,d,m);return}else try{this._data.copyTo(t,{planeIndex:s,frameOffset:d,frameCount:m,format:c});return}catch(E){if(c==="f32-planar")throw E;o="f32-planar"}let T=Dm(o),S=Ct(o),w=ji(o),A;if(this._data instanceof Gr){let E=I=>{let x=this._data.getDataPlane(I);if(!(x instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let P=l*S*(w?1:u);if(x.byteLength!==P)throw new TypeError(`Data plane ${I} has invalid size. Expected exactly ${P} bytes, got ${x.byteLength} bytes.`);return x};if(w)if(p)A=E(s),s=0;else{A=new Uint8Array(l*S*u);for(let I=0;I<u;I++){let x=E(I);A.set(x,I*l*S)}}else A=E(0)}else if(this._data instanceof Uint8Array)A=this._data;else if(b(o==="f32-planar"),p)A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:s})),this._data.copyTo(A,{format:"f32-planar",planeIndex:s}),s=0;else{A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*u);for(let E=0;E<u;E++)this._data.copyTo(A.subarray(E*l*S,(E+1)*l*S),{format:"f32-planar",planeIndex:E})}let C=N(A);for(let E=0;E<m;E++)if(p){let I=E*f,x;w?x=(s*l+(E+d))*S:x=((E+d)*u+s)*S;let P=T(C,x);k(y,I,P)}else for(let I=0;I<u;I++){let P=(E*u+I)*f,v;w?v=(I*l+(E+d))*S:v=((E+d)*u+I)*S;let _=T(C,v);k(y,P,_)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Gr){let t=new i(this._data);return t.setTimestamp(this.timestamp),t}else if(Ia(this._data)){let t=new i(this._data.clone());return t.setTimestamp(this.timestamp),t}else return new i({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data,_doNotCopy:!0})}trim(t,e=this.numberOfFrames){if(!Number.isInteger(t)||t<0)throw new TypeError("startFrame must be a non-negative integer.");if(!Number.isInteger(e)||e<0)throw new TypeError("endFrame must be a non-negative integer.");if(t>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(e>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(e<t)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");let r=e-t,n=Ct(this.format),a;if(ji(this.format)){let s=r*n;if(a=new Uint8Array(s*this.numberOfChannels),r>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(a.subarray(o*s,(o+1)*s),{planeIndex:o,format:this.format,frameOffset:t,frameCount:r})}else a=new Uint8Array(r*this.numberOfChannels*n),r>0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:t,frameCount:r});return new i({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+t/this.sampleRate,_doNotCopy:!0})}close(){this._closed||(va?.unregister(this),this._data instanceof Gr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ia(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof Gr?this._createAudioDataFromData():Ia(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():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:this._data.slice()})}_createAudioDataFromData(){if(ji(this.format)){let t=this.allocationSize({planeIndex:0,format:this.format}),e=new ArrayBuffer(t*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(e,r*t,t),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}else{let t=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(t,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let t=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),e=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(e,{planeIndex:r,format:"f32-planar"}),t.copyToChannel(e,r);return t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,e){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,n=t.numberOfChannels,a=t.sampleRate,s=t.length,o=Math.floor(r/n),c=0,l=s;for(;l>0;){let u=Math.min(o,l),d=new Float32Array(n*u);for(let m=0;m<n;m++)t.copyFromChannel(d.subarray(m*u,(m+1)*u),m,c);yield new i({format:"f32-planar",sampleRate:a,numberOfFrames:u,numberOfChannels:n,timestamp:e+c/a,data:d,_doNotCopy:!0}),c+=u,l-=u}}static fromAudioBuffer(t,e){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,n=t.numberOfChannels,a=t.sampleRate,s=t.length,o=Math.floor(r/n),c=0,l=s,u=[];for(;l>0;){let d=Math.min(o,l),m=new Float32Array(n*d);for(let p=0;p<n;p++)t.copyFromChannel(m.subarray(p*d,(p+1)*d),p,c);let f=new i({format:"f32-planar",sampleRate:a,numberOfFrames:d,numberOfChannels:n,timestamp:e+c/a,data:m,_doNotCopy:!0});u.push(f),c+=d,l-=d}return u}},Ct=i=>{switch(i){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 new Error("Unknown AudioSampleFormat")}},ji=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Dm=i=>{switch(i){case"u8":case"u8-planar":return(t,e)=>(t.getUint8(e)-128)/128;case"s16":case"s16-planar":return(t,e)=>t.getInt16(e,!0)/32768;case"s32":case"s32-planar":return(t,e)=>t.getInt32(e,!0)/2147483648;case"f32":case"f32-planar":return(t,e)=>t.getFloat32(e,!0)}},Vm=i=>{switch(i){case"u8":case"u8-planar":return(t,e,r)=>t.setUint8(e,ne(Math.round(r*128)+128,0,255));case"s16":case"s16-planar":return(t,e,r)=>t.setInt16(e,ne(Math.round(r*32768),-32768,32767),!0);case"s32":case"s32-planar":return(t,e,r)=>t.setInt32(e,ne(Math.round(r*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(t,e,r)=>t.setFloat32(e,r,!0)}},Ia=i=>typeof AudioData<"u"&&i instanceof AudioData,Um=i=>{switch(i){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return i}},Qh=(i,t,e,r,n,a,s,o)=>{let c=Dm(e),l=Vm(r),u=Ct(e),d=Ct(r),m=ji(e);if(ji(r))if(m){let p=new ArrayBuffer(o*u),g=N(p);i.copyTo(p,{planeIndex:a,frameOffset:s,frameCount:o,format:e});for(let h=0;h<o;h++){let y=h*u,k=h*d,T=c(g,y);l(t,k,T)}}else{let p=new ArrayBuffer(o*n*u),g=N(p);i.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:o,format:e});for(let h=0;h<o;h++){let y=(h*n+a)*u,k=h*d,T=c(g,y);l(t,k,T)}}else if(m){let p=o*u,g=new ArrayBuffer(p),h=N(g);for(let y=0;y<n;y++){i.copyTo(g,{planeIndex:y,frameOffset:s,frameCount:o,format:e});for(let k=0;k<o;k++){let T=k*u,S=(k*n+y)*d,w=c(h,T);l(t,S,w)}}}else{let p=new ArrayBuffer(o*n*u),g=N(p);i.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:o,format:e});for(let h=0;h<o;h++)for(let y=0;y<n;y++){let k=h*n+y,T=k*u,S=k*d,w=c(g,T);l(t,S,w)}}},zm=(i,t)=>{let e=i.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(e);return i.copyTo(r,{format:t,planeIndex:0}),new Ce({data:r,format:t,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration,_doNotCopy:!0})};var go=new Map,bo=new Map,yo=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!le.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${le.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0)throw new TypeError("config.quality must be provided.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof ue))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof ue)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.width!==void 0&&(!Number.isInteger(i.transform.width)||i.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(i.transform.height!==void 0&&(!Number.isInteger(i.transform.height)||i.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(i.transform.fit!==void 0&&!["fill","contain","cover"].includes(i.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.transform.width!==void 0&&i.transform.height!==void 0&&i.transform.fit===void 0&&!["fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(i.transform.fit!==void 0&&["fill","contain","cover"].includes(i.sizeChangeBehavior)&&i.transform.fit!==i.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(i.transform.rotate!==void 0&&![0,90,180,270].includes(i.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(i.transform.flip!==void 0&&typeof i.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(i.transform.crop!==void 0&&ki(i.transform.crop,"config.transform."),i.transform.alpha!==void 0&&!["keep","discard"].includes(i.transform.alpha))throw new TypeError("config.transform.alpha, when provided, must be 'keep' or 'discard'.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(i.transform.frameRate!==void 0&&(!Number.isFinite(i.transform.frameRate)||i.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(i.transform.force!==void 0&&typeof i.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Hm(i.codec,i)},Hm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");if(t.alpha!==void 0&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.latencyMode!==void 0&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&ct(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`);if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(t.contentHint!==void 0&&typeof t.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},jl=i=>{let t=i.bitrateMode,e=i.quality._toVideoRateControl(i.codec,i.width,i.height,t),r=(a,s,o)=>({codec:i.fullCodecString??fo(i.codec,i.width,i.height,o,i.alpha==="keep"),width:i.width,height:i.height,displayWidth:i.squarePixelWidth,displayHeight:i.squarePixelHeight,bitrate:a,bitrateMode:s,alpha:i.alpha??"discard",framerate:i.framerate,latencyMode:i.latencyMode,hardwareAcceleration:i.hardwareAcceleration,scalabilityMode:i.scalabilityMode,contentHint:i.contentHint,...Jm(i.codec)}),n=[];return e.quantizer!==null&&n.push({config:r(void 0,"quantizer",e.bitrate),quantizer:e.quantizer}),e.bitrateMode!=="quantizer"&&n.push({config:r(e.bitrate,e.bitrateMode,e.bitrate),quantizer:null}),b(n.length>0),n},ko=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!pe.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${pe.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0&&!(se.includes(i.codec)||i.codec==="flac"||i.codec==="truehd"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof ue))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof ue)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.numberOfChannels!==void 0&&(!Number.isInteger(i.transform.numberOfChannels)||i.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(i.transform.sampleRate!==void 0&&(!Number.isInteger(i.transform.sampleRate)||i.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(i.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Wm(i.codec,i)},Wm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&ct(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},Xl=i=>{let t=i.bitrateMode;return{codec:i.fullCodecString??po(i.codec),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:i.quality?._toAudioBitrate(i.codec,i.numberOfChannels),bitrateMode:i.quality?._bitrateMode??t,...wo(i.codec)}},ue=class{constructor(t){if((typeof t=="number"||typeof t=="string")&&(t={quality:t}),!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.bitrateMode!==void 0&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if(typeof t.quality=="string"?!Object.prototype.hasOwnProperty.call(Nm,t.quality):typeof t.quality!="number"||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(t.preferBitrate!==void 0&&typeof t.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof t.quality=="string"?Nm[t.quality]:t.quality,this._preferBitrate=t.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(t.bitrate!==void 0&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(t.quantizer!==void 0&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(t.bitrate===void 0&&t.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=t.bitrate,this._quantizer=t.quantizer}this._bitrateMode=t.bitrateMode}_toVideoRateControl(t,e,r,n){let a=jh[t],s=null,o=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(a)if(this._quantizer<a.min||this._quantizer>a.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${t}'; must be between ${a.min} and ${a.max}.`)}else s=this._quantizer,this._bitrate===void 0&&(o="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(b(this._quality!==void 0),s=ne(Math.round(Md(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let l=this._quality;l===void 0&&(b(s!==null&&a),l=ne((s-a.worst)/(a.best-a.worst),0,1)),c=Lm(t,e,r,Ql(l))}return{quantizer:s,bitrate:c,bitrateMode:o}}_toVideoBitrate(t,e,r){return this._bitrate!==void 0?this._bitrate:(b(this._quality!==void 0),Lm(t,e,r,Ql(this._quality)))}_toAudioBitrate(t,e){if(se.includes(t)||t==="flac"||t==="truehd")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");let r=Ql(this._quality),a={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!a)throw new Error(`Unhandled codec: ${t}`);let s=a*r;return(t==="opus"||t==="vorbis")&&(s*=e/2),t==="aac"?s=[96e3,128e3,16e4,192e3].reduce((c,l)=>Math.abs(l-s)<Math.abs(c-s)?l:c):t==="opus"||t==="vorbis"?s=Math.max(6e3,s):t==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((c,l)=>Math.abs(l-s)<Math.abs(c-s)?l:c)),Math.round(s/1e3)*1e3}},Nm={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},jh={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(Dd()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},Ql=i=>.3*Math.exp(2.5538*i),Lm=(i,t,e,r)=>{let n=t*e,a=1920*1080,s=3e6,o=Math.pow(n/a,.95),c=s*o,l={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/s},d=c*l[i]*r;return Math.ceil(d/1e3)*1e3},$l=(i,t)=>{if(i==="avc")return{avc:{quantizer:t}};if(i==="hevc")return{hevc:{quantizer:t}};if(i==="vp9")return{vp9:{quantizer:t}};if(i==="av1")return{av1:{quantizer:t}};b(!1)},qm=new ue("very-low"),Km=new ue("low"),Gm=new ue("medium"),Qm=new ue("high"),jm=new ue("very-high"),Xm=i=>{if(le.includes(i))return Fa(i);if(pe.includes(i))return Ma(i);if(qe.includes(i))return Ba(i);throw new TypeError(`Unknown codec '${i}'.`)},Fa=async(i,t={})=>{let{width:e=1280,height:r=720,quality:n,bitrate:a,frameRate:s,...o}=t;if(!le.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof ue))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof ue)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(s!==void 0&&(!Number.isFinite(s)||s<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");Hm(i,o);let c=Ti(n,a)??new ue("medium"),l;try{l=jl({codec:i,width:e,height:r,quality:c,framerate:s,...o,alpha:"discard"})}catch{return!1}let u=JSON.stringify(l),d=go.get(u);if(d)return d;let m=(async()=>{for(let{config:p}of l)if(Bn.some(g=>g.supports(i,p)))return!0;if(typeof VideoEncoder>"u"||(e%2===1||r%2===1)&&(i==="avc"||i==="hevc"))return!1;for(let{config:p,quantizer:g}of l){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!Wt()||await new Promise(async y=>{let k=new VideoEncoder({output:()=>{},error:()=>y(!1)});try{k.configure(p);let T=new Uint8Array(e*r*4),S=new VideoFrame(T,{format:"RGBA",codedWidth:e,codedHeight:r,timestamp:0});k.encode(S,g!==null?$l(i,g):void 0),S.close(),await k.flush(),y(!0)}catch{y(!1)}finally{k.state!=="closed"&&k.close()}}))return!0}return!1})();return go.set(u,m),m},Ma=async(i,t={})=>{let{numberOfChannels:e=2,sampleRate:r=48e3,quality:n,bitrate:a,...s}=t;if(!pe.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof ue))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof ue)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");Wm(i,s);let o=Ti(n,a)??new ue("medium"),c=Xl({codec:i,numberOfChannels:e,sampleRate:r,quality:o,...s}),l=JSON.stringify(c),u=bo.get(l);if(u)return u;let d=(async()=>{if(On.some(m=>m.supports(i,c))||se.includes(i))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return bo.set(l,d),d},Ti=(i,t)=>{if(i!==void 0)return i;if(t!==void 0)return t instanceof ue?t:new ue({bitrate:t})},Ba=async i=>!!qe.includes(i),$m=async()=>{let[i,t,e]=await Promise.all([Yl(),Mn(),Zl()]);return[...i,...t,...e]},Yl=async(i=le,t)=>{let e=await Promise.all(i.map(r=>Fa(r,t)));return i.filter((r,n)=>e[n])},Mn=async(i=pe,t)=>{let e=await Promise.all(i.map(r=>Ma(r,t)));return i.filter((r,n)=>e[n])},Zl=async(i=qe)=>{let t=await Promise.all(i.map(Ba));return i.filter((e,r)=>t[r])},To=async(i,t)=>{for(let e of i)if(await Fa(e,t))return e;return null},Ym=async(i,t)=>{for(let e of i)if(await Ma(e,t))return e;return null},Zm=async i=>{for(let t of i)if(await Ba(t))return t;return null};var Oa=class{static supports(t,e){return!1}},Da=class{static supports(t,e){return!1}},Va=class{static supports(t,e){return!1}},Ua=class{static supports(t,e){return!1}},bi=[],yi=[],Bn=[],On=[],ef=i=>{if(i.prototype instanceof Oa){let t=i;if(bi.includes(t)){O._warn("Video decoder already registered.");return}bi.push(t),co.clear()}else if(i.prototype instanceof Da){let t=i;if(yi.includes(t)){O._warn("Audio decoder already registered.");return}yi.push(t),lo.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},tf=i=>{if(i.prototype instanceof Va){let t=i;if(Bn.includes(t)){O._warn("Video encoder already registered.");return}Bn.push(t),go.clear()}else if(i.prototype instanceof Ua){let t=i;if(On.includes(t)){O._warn("Audio encoder already registered.");return}On.push(t),bo.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var Ae=new Uint8Array(0),ee=class i{constructor(t,e,r,n,a=-1,s,o){this.data=t;this.type=e;this.timestamp=r;this.duration=n;this.sequenceNumber=a;if(t===Ae&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Ae}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,e){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let r=new Uint8Array(t.byteLength);return t.copyTo(r),new i(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,e)}clone(t){if(t!==void 0&&(typeof t!="object"||t===null))throw new TypeError("options, when provided, must be an object.");if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(t?.type!==void 0&&t.type!=="key"&&t.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw new TypeError("options.duration, when provided, must be a number.");if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(t?.sideData!==void 0&&(typeof t.sideData!="object"||t.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new i(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,t?.data?.byteLength??this.byteLength,t?.sideData??this.sideData)}};var So=class{constructor(t){this.sourceSampleRate=null;this.sourceNumberOfChannels=null;this.startTime=null;this.bufferStartFrame=0;this.maxWrittenFrame=null;this.targetSampleRate=t.targetSampleRate,this.targetNumberOfChannels=t.targetNumberOfChannels,this.onSample=t.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){b(this.sourceNumberOfChannels!==null);let t=this.sourceNumberOfChannels,e=this.targetNumberOfChannels;t===1&&e===2?this.channelMixer=(r,n)=>r[n*t]:t===1&&e===4?this.channelMixer=(r,n,a)=>r[n*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,n,a)=>r[n*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===2&&e===6?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===4&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return Math.SQRT1_2*(r[a]+r[a+1])+r[a+2]+.5*(r[a+4]+r[a+5])}:t===6&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,n,a)=>a<t?r[n*t+a]:0}ensureTempBufferSize(t){let e=this.tempSourceBuffer.length;for(;e<t;)e*=2;if(e!==this.tempSourceBuffer.length){let r=new Float32Array(e);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(t){if(this.sourceSampleRate===null){this.sourceSampleRate=t.sampleRate,this.sourceNumberOfChannels=t.numberOfChannels,this.startTime=t.timestamp;let l=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+l,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}b(this.startTime!==null);let e=t.numberOfFrames*t.numberOfChannels;this.ensureTempBufferSize(e);let r=t.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);t.copyTo(n,{planeIndex:0,format:"f32"});let a=Math.round((t.timestamp-this.startTime)*this.sourceSampleRate),s=a+t.numberOfFrames,o=Math.floor((a-1)*this.targetSampleRate/this.sourceSampleRate)+1,c=Math.ceil(s*this.targetSampleRate/this.sourceSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let u=l-this.bufferStartFrame;b(u<this.bufferCapacityInFrames);let d=l*this.sourceSampleRate/this.targetSampleRate-a,m=Math.floor(d),f=Math.ceil(d),p=d-m;for(let g=0;g<this.targetNumberOfChannels;g++){let h=0,y=0;m>=0&&m<t.numberOfFrames&&(h=this.channelMixer(n,m,g)),f>=0&&f<t.numberOfFrames&&(y=this.channelMixer(n,f,g));let k=h+p*(y-h),T=u*this.targetNumberOfChannels+g;this.outputBuffer[T]+=k}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;b(this.startTime!==null);let t=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,e=new Float32Array(t);e.set(this.outputBuffer.subarray(0,t));let r=new Ce({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:e,_doNotCopy:!0});await this.onSample(r),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}};var _e=class{constructor(t){this.input=t}dispose(){}};var Ao=2082844800,xo=i=>{let e=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e},Co=i=>{if(i.length<24)throw new Error("Invalid pssh box: too small.");let t=N(i),e=0,r=t.getUint8(e);e+=1,e+=3;let n=ci(i.subarray(e,e+16));e+=16;let a=null;if(r>0){let o=t.getUint32(e);if(e+=4,e+16*o+4>i.length)throw new Error("Invalid pssh box: key ID count exceeds box size.");if(o>0){a=[];for(let c=0;c<o;c++)a.push(ci(i.subarray(e,e+16))),e+=16}}let s=t.getUint32(e);return e+=4,{systemId:n,keyIds:a,data:i.slice(e,e+s)}},Po=(i,t)=>{if(i.systemId!==t.systemId||!Ds(i.data,t.data))return!1;let e=i.keyIds,r=t.keyIds;return!e||!r?e===r:e.length===r.length&&e.every((n,a)=>n===r[a])};var Xt=16,Qr=new Uint32Array(256),Dn=new Uint32Array(256),Vn=new Uint32Array(256),Un=new Uint32Array(256),zn=new Uint32Array(256),Ke=new Uint32Array(256),rf=new Uint32Array(10),nf=!1,Xh=()=>{let i=new Uint8Array(256),t=new Uint8Array(256),e=new Uint8Array(256);for(let a=0,s=1;a<256;a++)e[a]=s,t[s]=a,s=s^s<<1^(s&128?283:0);let r=(a,s)=>a&&s?e[(t[a]+t[s])%255]:0;i[0]=99;for(let a=1;a<256;a++){let s=e[255-t[a]],o=s^s<<1^s<<2^s<<3^s<<4;o=o>>>8^o&255^99,i[a]=o}for(let a=0;a<256;a++){let s=i[a],o=i.indexOf(a);Qr[a]=s<<24|s<<16|s<<8|s,Ke[a]=o<<24|o<<16|o<<8|o;let c=r(o,14),l=r(o,9),u=r(o,13),d=r(o,11),m=c<<24|l<<16|u<<8|d;Dn[a]=m,Vn[a]=m>>>8|m<<24,Un[a]=m>>>16|m<<16,zn[a]=m>>>24|m<<8}let n=1;for(let a=0;a<10;a++)rf[a]=n<<24,n=n<<1^(n&128?283:0);nf=!0},za=class{constructor(){this.roundkey=new Uint32Array(44);this.iv=new Uint32Array(Xt/Uint32Array.BYTES_PER_ELEMENT);this.in=new Uint8Array(Xt);this.out=new Uint8Array(Xt);this.inView=new DataView(this.in.buffer);this.outView=new DataView(this.out.buffer)}init({key:t,iv:e}){b(t.byteLength===16),b(e.byteLength===16),nf||Xh();let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=new DataView(e.buffer,e.byteOffset,e.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=n.getUint32(0,!1),this.iv[1]=n.getUint32(4,!1),this.iv[2]=n.getUint32(8,!1),this.iv[3]=n.getUint32(12,!1);for(let a=4;a<44;a+=4){let s=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^Qr[s>>>16&255]&4278190080^Qr[s>>>8&255]&16711680^Qr[s>>>0&255]&65280^Qr[s>>>24&255]&255^rf[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a<s;a+=4,s-=4)for(let o=0;o<4;o++){let c=this.roundkey[a+o];this.roundkey[a+o]=this.roundkey[s+o],this.roundkey[s+o]=c}for(let a=4;a<40;a+=4)for(let s=0;s<4;s++){let o=this.roundkey[a+s];this.roundkey[a+s]=Dn[Qr[o>>>24&255]&255]^Vn[Qr[o>>>16&255]&255]^Un[Qr[o>>>8&255]&255]^zn[Qr[o>>>0&255]&255]}}decrypt(){let t=this.inView.getUint32(0,!1)^this.roundkey[0],e=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],n=this.inView.getUint32(12,!1)^this.roundkey[3],a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1),l,u,d,m;for(let y=1;y<10;y++){let k=y*4;l=Dn[t>>>24]^Vn[n>>>16&255]^Un[r>>>8&255]^zn[e&255]^this.roundkey[k],u=Dn[e>>>24]^Vn[t>>>16&255]^Un[n>>>8&255]^zn[r&255]^this.roundkey[k+1],d=Dn[r>>>24]^Vn[e>>>16&255]^Un[t>>>8&255]^zn[n&255]^this.roundkey[k+2],m=Dn[n>>>24]^Vn[r>>>16&255]^Un[e>>>8&255]^zn[t&255]^this.roundkey[k+3],t=l,e=u,r=d,n=m}let f=Ke[t>>>24&255]&4278190080^Ke[n>>>16&255]&16711680^Ke[r>>>8&255]&65280^Ke[e>>>0&255]&255^this.roundkey[40],p=Ke[e>>>24&255]&4278190080^Ke[t>>>16&255]&16711680^Ke[n>>>8&255]&65280^Ke[r>>>0&255]&255^this.roundkey[41],g=Ke[r>>>24&255]&4278190080^Ke[e>>>16&255]&16711680^Ke[t>>>8&255]&65280^Ke[n>>>0&255]&255^this.roundkey[42],h=Ke[n>>>24&255]&4278190080^Ke[r>>>16&255]&16711680^Ke[e>>>8&255]&65280^Ke[t>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,g^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=o,this.iv[3]=c}},af=(i,t,e)=>{let r=!1,n=!1,a=0,s=2**16,o=16,c=new za,l=()=>{n||(n=!0,e())};return new ReadableStream({pull:async u=>{try{r||(c.init(await t()),r=!0);let d=s+o,m=i.requestSliceRange(a,0,d);if(R(m)&&(m=await m),!m||m.length===0)throw new Error("Invalid ciphertext.");let f=m.length;if(f%16!==0)throw new Error("Invalid ciphertext.");let p=f===d?f-o:f,g=U(m,p),h=new Uint8Array(p);for(let y=0;y<p;y+=16)c.in.set(g.subarray(y,y+16)),c.decrypt(),h.set(c.out,y);if(p<f)u.enqueue(h),a+=p;else{let y=h[p-1];if(y===0||y>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let k=h.subarray(0,p-y);u.enqueue(k),u.close(),l()}}catch(d){throw l(),d}},cancel:()=>{l()}})};var sf=[2,1,1,2,2,2,2,1,1,2,2,1,1],$h=64,vo=class i extends _e{constructor(e){super(e);this.moovSlice=null;this.currentTrack=null;this.tracks=[];this.idToTrack=new Map;this.metadataPromise=null;this.movieTimescale=-1;this.movieDurationInTimescale=-1;this.movieMatrix=si;this.isQuickTime=!1;this.metadataTags={};this.currentMetadataKeys=null;this.isFragmented=!1;this.fragmentTrackDefaults=new Map;this.psshBoxes=[];this.currentFragment=null;this.isReadingTraf=!1;this.currentFragmentTrackState=null;this.lastReadFragment=null;this.fragmentSummaries=new Map;this.decryptionKeyCache=new Map;this.boxNestingDepth=0;this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),r=await Promise.all(e.map(n=>n.getDecoderConfig().then(a=>a?.codec??null)));return xo({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(n=>n.info?.type==="video"),hasAudio:this.tracks.some(n=>n.info?.type==="audio"),codecStrings:r.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,r=!1,n=!1;for(;;){let a=this.reader.requestSliceRange(e,Ot,kr);if(R(a)&&(a=await a),!a)break;let s=e,o=jr(a);if(!o)break;if((o.name==="ftyp"||o.name==="styp")&&a.remainingLength>=4){let c=ae(a,4);this.isQuickTime=c==="qt "}else if(o.name==="moov"){let c=this.reader.requestSlice(a.filePos,o.contentSize);if(R(c)&&(c=await c),!c)break;if(this.moovSlice=c,this.readContiguousBoxes(this.moovSlice),this.movieTimescale===-1)throw new Error("Invalid moov box: missing mvhd box.");for(let l of this.tracks){let u=l.editListPreviousSegmentDurations/this.movieTimescale;l.editListOffset-=Math.round(u*l.timescale)}r=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+o.totalSize,n=!0;break}else if(o.name==="moof"){if(!this.input._initInput)throw new 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.');await this.copyMetadataFromInitInput(this.input._initInput),r=!1,n=!0;break}e=s+o.totalSize}if(!n&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),r){b(this.reader.fileSize!==null);let a=this.reader.requestSlice(this.reader.fileSize-4,4);R(a)&&(a=await a),b(a);let s=B(a),o=this.reader.fileSize-s;if(o>=0&&o<=this.reader.fileSize-kr){let c=this.reader.requestSliceRange(o,Ot,kr);if(R(c)&&(c=await c),c){let l=jr(c);if(l&&l.name==="mfra"){let u=this.reader.requestSlice(c.filePos,l.contentSize);R(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}for(let a of this.tracks){let s=a.fragmentLookupTable;s.sort((c,l)=>c.timestamp-l.timestamp);let o=0;for(let c of s)(o===0||c.timestamp!==s[o-1].timestamp)&&(s[o++]=c);s.length=o}})()}async copyMetadataFromInitInput(e){let r=await e._getDemuxer();if(r.constructor!==i)throw new Error("Init input must match the input's format.");await r.readMetadata(),this.movieTimescale=r.movieTimescale,this.movieDurationInTimescale=r.movieDurationInTimescale,this.movieMatrix=r.movieMatrix,this.metadataTags=r.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=r.fragmentTrackDefaults,this.psshBoxes=r.psshBoxes;for(let n of r.tracks){let a={id:n.id,demuxer:this,trackBacking:null,disposition:n.disposition,timescale:n.timescale,durationInMediaTimescale:n.durationInMediaTimescale,durationInMovieTimescale:n.durationInMovieTimescale,matrix:n.matrix,internalCodecId:n.internalCodecId,name:n.name,languageCode:n.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:n.editListPreviousSegmentDurations,editListOffset:n.editListOffset,encryptionInfo:n.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:n.maxBitrate,avgBitrate:n.avgBitrate,info:n.info};if(n.trackBacking){if(b(a.info),a.info.type==="video"&&a.info.width!==-1){let s=a;a.trackBacking=new Ro(s),this.tracks.push(a),this.idToTrack.set(a.id,a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let s=a;a.trackBacking=new Fo(s),this.tracks.push(a),this.idToTrack.set(a.id,a)}}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],sampleCount:0,cumulativeSampleSizes:null,keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],sortedCompositionTimeOffsets:null};if(e.sampleTable=r,e.sampleTableByteOffset===null)return r;b(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e;try{this.traverseBox(n)}catch(l){throw e.sampleTable=null,l}finally{this.currentTrack=null}let a=J(r.sampleTimingEntries),s=j(r.sampleToChunk,r.chunkOffsets.length-1,l=>l.startChunkIndex),o=r.sampleToChunk[s];if(r.sampleCount=Math.min(r.sampleCount,a?a.startIndex+a.count:0,o?o.startSampleIndex+(r.chunkOffsets.length-o.startChunkIndex)*o.samplesPerChunk:0),lf(r.sampleTimingEntries,r.sampleCount),lf(r.sampleCompositionTimeOffsets,r.sampleCount),e.info?.type==="audio"&&e.info.codec&&se.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0&&r.sampleTimingEntries.length>0){b(e.info?.type==="audio");let l=Me(e.info.codec),u=[],d=[];for(let m=0;m<r.sampleToChunk.length;m++){let f=r.sampleToChunk[m],p=r.sampleToChunk[m+1],g=Math.min(p?p.startChunkIndex:1/0,r.chunkOffsets.length)-f.startChunkIndex,h=d.length;for(let y=0;y<g;y++){let k=f.startSampleIndex+y*f.samplesPerChunk,T=k+f.samplesPerChunk,S=j(r.sampleTimingEntries,k,M=>M.startIndex),w=r.sampleTimingEntries[S],A=j(r.sampleTimingEntries,T,M=>M.startIndex),C=r.sampleTimingEntries[A],E=w.startDecodeTimestamp+(k-w.startIndex)*w.delta,x=C.startDecodeTimestamp+(T-C.startIndex)*C.delta-E,P=J(u);P&&P.delta===x?P.count++:u.push({startIndex:d.length,startDecodeTimestamp:E,count:1,delta:x});let _=Math.round(x*e.info.sampleRate/e.timescale)*l.sampleSize*e.info.numberOfChannels;d.push(_)}f.startSampleIndex=h,f.samplesPerChunk=1}r.sampleTimingEntries=u,r.sampleSizes=d,r.sampleCount=d.length}if(r.sampleCompositionTimeOffsets.length>0){let l=r.sampleCompositionTimeOffsets,u=J(l),d=u.startIndex+u.count;d<r.sampleCount&&l.push({startIndex:d,count:r.sampleCount-d,offset:0,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1});let m=l.filter(y=>y.count>0),f=r.sampleTimingEntries,p=0,g=y=>{for(;p+1<f.length&&f[p+1].startIndex<=y;)p++;let k=f[p];return k.startDecodeTimestamp+(y-k.startIndex)*k.delta};for(let y of m){let k=y.startIndex+y.count-1;y.startTimestamp=g(y.startIndex)+y.offset,y.lastTimestamp=g(k)+y.offset}m.sort((y,k)=>y.startTimestamp-k.startTimestamp||y.startIndex-k.startIndex);let h=-1/0;for(let y of m)h=Math.max(h,y.lastTimestamp),y.maxLastTimestamp=h;r.sortedCompositionTimeOffsets=m}if(r.sampleSizes.length>1){r.cumulativeSampleSizes=[0];for(let l=0;l<r.sampleSizes.length;l++)r.cumulativeSampleSizes.push(r.cumulativeSampleSizes[l]+r.sampleSizes[l])}return r}readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment.promise;let r=(async()=>{let n=this.reader.requestSliceRange(e,Ot,kr);R(n)&&(n=await n),b(n);let a=jr(n);b(a?.name==="moof");let s=this.reader.requestSlice(e,a.totalSize);if(R(s)&&(s=await s),!s)return null;this.traverseBox(s);let o=this.currentFragment;b(o&&o.moofOffset===e),this.currentFragment=null,this.fragmentSummaries.set(e,{moofSize:o.moofSize,trackIds:new Set(o.trackData.keys())});for(let[,c]of o.trackData){let l=c.track,{fragmentPositionCache:u}=l;if(!c.startTimestampIsFinal){let p=Vr(l.fragmentLookupTable,o.moofOffset,y=>y.moofOffset),g=l.fragmentLookupTable[p];if(g&&c.trunSampleCounts.length>=g.trunNumber&&c.trunSampleCounts[g.trunNumber-1]>=g.sampleNumber){let y=0;for(let S=1;S<g.trunNumber;S++)y+=c.trunSampleCounts[S-1];y+=g.sampleNumber-1;let k=c.samples[y];b(k);let T=g.timestamp-k.presentationTimestamp;Eo(c,T)}else{let y=j(u,o.moofOffset-1,k=>k.moofOffset);if(y!==-1){let k=u[y];Eo(c,k.endDecodeTimestamp)}else{let k=J(this.getSampleTableForTrack(l).sampleTimingEntries);if(k){let{startDecodeTimestamp:T,count:S,delta:w}=k;Eo(c,T+S*w)}}}c.startTimestampIsFinal=!0}let d=j(u,c.startTimestamp,p=>p.startTimestamp),m=u[d],f=u[d+1];if((!m||m.moofOffset<o.moofOffset)&&(!f||f.moofOffset>o.moofOffset)&&u.splice(d+1,0,{moofOffset:o.moofOffset,startTimestamp:c.startTimestamp,endDecodeTimestamp:c.endDecodeTimestamp,hasKeyFrame:c.firstKeyFrameTimestamp!==null}),c.encryptionAuxInfo&&l.encryptionInfo){let p=await gf(this.reader,l.encryptionInfo,c.encryptionAuxInfo);for(let g=0;g<Math.min(c.samples.length,p.length);g++){let h=p[g];c.samples[g].encryption=h}}}return o})();return this.lastReadFragment={moofOffset:e,promise:r},r.catch(()=>{this.lastReadFragment?.promise===r&&(this.lastReadFragment=null)}),r}readContiguousBoxes(e){if(this.boxNestingDepth===$h)throw new Error("Invalid file: boxes are nested too deeply.");let r=e.filePos;this.boxNestingDepth++;try{for(;e.filePos-r<=e.length-Ot&&this.traverseBox(e););}finally{this.boxNestingDepth--}}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ot;){let n=e.filePos,a=jr(e);if(!a)break;yield{boxInfo:a,slice:e},e.filePos=n+a.totalSize}}traverseBox(e){let r=e.filePos,n=jr(e);if(!n)return!1;let a=e.filePos,s=r+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mvhd":{let o=H(e);e.skip(3);let c;if(o===1?(c=Ge(e),e.skip(8),this.movieTimescale=B(e),this.movieDurationInTimescale=Ge(e)):(c=B(e),e.skip(4),this.movieTimescale=B(e),this.movieDurationInTimescale=B(e)),c!==0&&(this.metadataTags.creationTime=new Date(1e3*(c-Ao))),this.movieTimescale===0)throw new Error("Invalid mvhd box: timescale must not be 0.");e.skip(8+2*4),this.movieMatrix=of(e)}break;case"trak":{if(this.currentFragment||this.currentTrack)break;let o={id:-1,demuxer:this,trackBacking:null,disposition:{...Ve,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:si,internalCodecId:null,name:null,languageCode:ce,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};if(this.currentTrack=o,this.readContiguousBoxes(e.slice(a,n.contentSize)),o.id!==-1&&o.timescale!==-1&&o.info!==null&&o.sampleTableByteOffset!==-1){if(o.info.type==="video"&&o.info.width!==-1){let c=o;o.trackBacking=new Ro(c),this.tracks.push(o),this.idToTrack.set(o.id,o)}else if(o.info.type==="audio"&&o.info.numberOfChannels!==-1){let c=o;o.trackBacking=new Fo(c),this.tracks.push(o),this.idToTrack.set(o.id,o)}}this.currentTrack=null}break;case"tkhd":{let o=this.currentTrack;if(!o||this.currentFragment)break;let c=H(e),u=!!($t(e)&1);if(o.disposition.default=u,c===0)e.skip(8),o.id=B(e),e.skip(4),o.durationInMovieTimescale=B(e);else if(c===1)e.skip(16),o.id=B(e),e.skip(4),o.durationInMovieTimescale=Ge(e);else throw new Error(`Incorrect track header version ${c}.`);e.skip(2*4+2+2+2+2);let d=of(e);o.matrix=sr(d,this.movieMatrix)}break;case"elst":{let o=this.currentTrack;if(!o)break;let c=H(e);e.skip(3);let l=!1,u=0,d=B(e);for(let m=0;m<d;m++){let f=c===1?Ge(e):B(e),p=c===1?yf(e):Xr(e),g=wi(e);if(l){O._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(p===-1){u+=f;continue}if(g!==1){O._warn("Unsupported edit list entry: media rate must be 1.");break}o.editListPreviousSegmentDurations=u,o.editListOffset=p,l=!0}}break;case"mdhd":{let o=this.currentTrack;if(!o)break;let c=H(e);if(e.skip(3),c===0?(e.skip(8),o.timescale=B(e),o.durationInMediaTimescale=B(e)):c===1&&(e.skip(16),o.timescale=B(e),o.durationInMediaTimescale=Ge(e)),o.durationInMediaTimescale===2**(c===1?64:32)-1&&(o.durationInMediaTimescale=-1),o.timescale===0)throw new Error("Invalid mdhd box: timescale must not be 0.");let l=me(e);if(l>0){o.languageCode="";for(let u=0;u<3;u++)o.languageCode=String.fromCharCode(96+(l&31))+o.languageCode,l>>=5;Ur(o.languageCode)||(o.languageCode=ce)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let c=ae(e,4);c==="vide"?o.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Rs},avcType:null,avcCodecInfo:null,hevcType:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:c==="soun"&&(o.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let o=this.currentTrack;if(!o)break;o.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(a,n.contentSize))}break;case"stsd":{let o=this.currentTrack;if(!o||o.info===null||o.sampleTable)break;let c=H(e);e.skip(3);let l=B(e);for(let u=0;u<l;u++){let d=e.filePos,m=jr(e);if(!m)break;o.internalCodecId=m.name;let f=m.name.toLowerCase();if(o.info.type==="video"){e.skip(6*1+2+2+2+3*4),o.info.width=me(e),o.info.height=me(e),o.info.squarePixelWidth=o.info.width,o.info.squarePixelHeight=o.info.height,e.skip(50),o.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+m.totalSize-e.filePos));let p=f==="encv"?o.frmaCodecString:f;o.frmaCodecString=null,p==="avc1"||p==="avc3"?(o.info.codec="avc",o.info.avcType=p==="avc1"?1:3):p==="hvc1"||p==="hev1"?(o.info.codec="hevc",o.info.hevcType=p):p==="vp08"?o.info.codec="vp8":p==="vp09"?o.info.codec="vp9":p==="av01"?o.info.codec="av1":$r.includes(f)?(o.info.codec="prores",o.info.proresFormat=f):p===null?O._warn("Unknown encrypted video codec due to missing frma box."):O._warn(`Unsupported video codec (sample entry type '${m.name}').`)}else{e.skip(6*1+2);let p=me(e);e.skip(3*2);let g=me(e),h=me(e);e.skip(2*2);let y=B(e)/65536,k=null;c===0&&p>0&&(p===1?(e.skip(4),h=8*B(e),e.skip(2*4)):p===2&&(e.skip(4),y=Bo(e),g=B(e),e.skip(4),h=B(e),k=B(e),e.skip(2*4))),o.info.numberOfChannels=g,o.info.sampleRate=y||o.timescale,o.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+m.totalSize-e.filePos));let T=f==="enca"?o.frmaCodecString:f;if(o.frmaCodecString=null,T!=="mp4a")if(T===".mp3")o.info.codec="mp3";else if(T==="opus")o.info.codec="opus",o.info.sampleRate=tt;else if(T==="flac")o.info.codec="flac";else if(T==="ulaw")o.info.codec="ulaw";else if(T==="alaw")o.info.codec="alaw";else if(T==="ac-3")o.info.codec="ac3";else if(T==="ec-3")o.info.codec="eac3";else if(La.includes(T))o.info.codec="dts",o.info.dtsFormat=T;else if(T==="mlpa")o.info.codec="truehd";else if(T==="twos")h===8?o.info.codec="pcm-s8":h===16?o.info.codec=o.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(O._warn(`Unsupported sample size ${h} for codec 'twos'.`),o.info.codec=null);else if(T==="sowt")h===8?o.info.codec="pcm-s8":h===16?o.info.codec="pcm-s16":(O._warn(`Unsupported sample size ${h} for codec 'sowt'.`),o.info.codec=null);else if(T==="raw ")o.info.codec="pcm-u8";else if(T==="in24")o.info.codec=o.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(T==="in32")o.info.codec=o.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(T==="fl32")o.info.codec=o.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(T==="fl64")o.info.codec=o.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(T==="ipcm"){let S=o.info.pcmSampleSize;o.info.pcmLittleEndian?S===16?o.info.codec="pcm-s16":S===24?o.info.codec="pcm-s24":S===32?o.info.codec="pcm-s32":(O._warn(`Invalid ipcm sample size ${S}.`),o.info.codec=null):S===16?o.info.codec="pcm-s16be":S===24?o.info.codec="pcm-s24be":S===32?o.info.codec="pcm-s32be":(O._warn(`Invalid ipcm sample size ${S}.`),o.info.codec=null)}else if(T==="fpcm"){let S=o.info.pcmSampleSize;o.info.pcmLittleEndian?S===32?o.info.codec="pcm-f32":S===64?o.info.codec="pcm-f64":(O._warn(`Invalid fpcm sample size ${S}.`),o.info.codec=null):S===32?o.info.codec="pcm-f32be":S===64?o.info.codec="pcm-f64be":(O._warn(`Invalid fpcm sample size ${S}.`),o.info.codec=null)}else if(T==="lpcm"&&k!==null){let S=h+7>>3,w=!!(k&1),A=!!(k&2),C=k&4?-1:0;h>0&&h<=64&&(w?h===32?o.info.codec=A?"pcm-f32be":"pcm-f32":h===64&&(o.info.codec=A?"pcm-f64be":"pcm-f64"):C&1<<S-1?S===1?o.info.codec="pcm-s8":S===2?o.info.codec=A?"pcm-s16be":"pcm-s16":S===3?o.info.codec=A?"pcm-s24be":"pcm-s24":S===4&&(o.info.codec=A?"pcm-s32be":"pcm-s32"):S===1&&(o.info.codec="pcm-u8")),o.info.codec===null&&O._warn("Unsupported PCM format.")}else T===null?O._warn("Unknown encrypted audio codec due to missing frma box."):O._warn(`Unsupported audio codec (sample entry type '${m.name}').`)}e.filePos=d+m.totalSize}}break;case"frma":{let o=this.currentTrack;if(!o)break;let l=ae(e,4).toLowerCase();o.frmaCodecString=l}break;case"schm":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=ae(e,4);c==="cenc"||c==="cens"||c==="cbcs"?o.encryptionInfo={scheme:c,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:O._warn(`Unsupported encryption scheme '${c}'.`)}break;case"tenc":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=H(e);e.skip(3),e.skip(1);let l=H(e);if(c>0?(o.encryptionInfo.defaultCryptByteBlock=l>>4,o.encryptionInfo.defaultSkipByteBlock=l&15):(o.encryptionInfo.defaultCryptByteBlock=0,o.encryptionInfo.defaultSkipByteBlock=0),o.encryptionInfo.defaultIsProtected=H(e)!==0,o.encryptionInfo.defaultPerSampleIvSize=H(e),o.encryptionInfo.defaultKid=ci(U(e,16)),o.encryptionInfo.defaultPerSampleIvSize>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");if(o.encryptionInfo.defaultIsProtected&&o.encryptionInfo.defaultPerSampleIvSize===0){let u=H(e);if(u>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");let d=new Uint8Array(16);d.set(U(e,u),0),o.encryptionInfo.defaultConstantIv=d}}break;case"avcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video"||n.contentSize===0)break;o.info.codecDescription=U(e,n.contentSize);let c=gr(o.info.codecDescription)?.sequenceParameterSets[0],l=c&&Gt(c);l&&cf(o,l.pixelAspectRatio)}break;case"hvcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video"||n.contentSize===0)break;o.info.codecDescription=U(e,n.contentSize);let c=In(o.info.codecDescription)?.arrays.find(u=>u.nalUnitType===33)?.nalUnits[0],l=c&&Qi(c);l&&cf(o,l.pixelAspectRatio)}break;case"vpcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;e.skip(4);let c=H(e),l=H(e),u=H(e),d=u>>4,m=u>>1&7,f=u&1,p=H(e),g=H(e),h=H(e);o.info.vp9CodecInfo={profile:c,level:l,bitDepth:d,chromaSubsampling:m,videoFullRangeFlag:f,colourPrimaries:p,transferCharacteristics:g,matrixCoefficients:h}}break;case"av1C":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;e.skip(1);let c=H(e),l=c>>5,u=c&31,d=H(e),m=d>>7,f=d>>6&1,p=d>>5&1,g=d>>4&1,h=d>>3&1,y=d>>2&1,k=d&3,T=l===2&&f?p?12:10:f?10:8;e.skip(1);let S=U(e,n.contentSize-4),w=hi(S);o.info.av1CodecInfo={profile:l,level:u,tier:m,bitDepth:T,monochrome:g,chromaSubsamplingX:h,chromaSubsamplingY:y,chromaSamplePosition:k,videoFullRangeFlag:w?.videoFullRangeFlag??0,colourPrimaries:w?.colourPrimaries??2,transferCharacteristics:w?.transferCharacteristics??2,matrixCoefficients:w?.matrixCoefficients??2}}break;case"colr":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=ae(e,4);if(c!=="nclx"&&c!=="nclc")break;let l=me(e),u=me(e),d=me(e),m;c==="nclx"&&(m=!!(H(e)&128)),o.info.colorSpace={primaries:Tt[l],transfer:wt[u],matrix:St[d],fullRange:m}}break;case"pasp":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=B(e),l=B(e);c>0&&l>0&&(o.info.squarePixelWidth=o.info.width,o.info.squarePixelHeight=o.info.height,c>l?o.info.squarePixelWidth=Math.round(o.info.width*c/l):o.info.squarePixelHeight=Math.round(o.info.height*l/c))}break;case"btrt":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=B(e),l=B(e);o.maxBitrate=c>0?c:null,o.avgBitrate=l>0?l:null}break;case"wave":this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"esds":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4);let{objectTypeIndication:c,decoderSpecificInfo:l}=Oo(e);if(c===64||c===103?(o.info.codec="aac",o.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?o.info.codec="mp3":c===221?o.info.codec="vorbis":c===169?o.info.codec="dts":O._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),l&&(o.info.codecDescription=l,o.info.codec==="aac")){let u=xt(o.info.codecDescription);u.outputNumberOfChannels!==null&&(o.info.numberOfChannels=u.outputNumberOfChannels),u.outputSampleRate!==null&&(o.info.sampleRate=u.outputSampleRate)}}break;case"enda":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;o.info.pcmLittleEndian=!!(me(e)&255)}break;case"pcmC":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4);let c=H(e);o.info.pcmLittleEndian=!!(c&1),o.info.pcmSampleSize=H(e)}break;case"srat":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4),o.info.sampleRate=B(e)}break;case"dOps":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(1);let c=H(e),l=me(e),u=B(e),d=Na(e),m=H(e),f=m!==0?U(e,n.contentSize-11):new Uint8Array(0),p=new Uint8Array(19+f.byteLength),g=new DataView(p.buffer);g.setUint32(0,1332770163,!1),g.setUint32(4,1214603620,!1),g.setUint8(8,1),g.setUint8(9,c),g.setUint16(10,l,!0),g.setUint32(12,u,!0),g.setInt16(16,d,!0),g.setUint8(18,m),p.set(f,19),o.info.codecDescription=p,o.info.numberOfChannels=c}break;case"dfLa":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4);let c=127,l=128,u=e.filePos;for(;e.filePos<s;){let g=H(e),h=$t(e);if((g&c)===0){e.skip(10);let k=B(e),T=k>>>12,S=(k>>9&7)+1;o.info.sampleRate=T,o.info.numberOfChannels=S,e.skip(20)}else e.skip(h);if(g&l)break}let d=e.filePos;e.filePos=u;let m=U(e,d-u),f=new Uint8Array(4+m.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(m,4),o.info.codecDescription=f}break;case"dac3":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=U(e,3),l=new K(c),u=l.readBits(2);l.skipBits(8);let d=l.readBits(3),m=l.readBits(1);u<3&&(o.info.sampleRate=Ki[u]),o.info.numberOfChannels=ka[d]+m}break;case"dec3":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=U(e,n.contentSize),l=hm(c);if(!l){O._warn("Invalid dec3 box contents, ignoring.");break}let u=eo(l);u!==null&&(o.info.sampleRate=u),o.info.numberOfChannels=to(l)}break;case"ddts":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=U(e,Math.min(n.contentSize,io)),l=ym(c);if(!l){O._warn("Invalid ddts box contents, ignoring.");break}o.info.sampleRate=l.sampleRate,l.numberOfChannels!==null&&(o.info.numberOfChannels=l.numberOfChannels)}break;case"dmlp":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=B(e),l=c>>>28;if(l===15){O._warn("Invalid dmlp box contents, ignoring.");break}o.info.sampleRate=(l&8?44100:48e3)<<(l&7);let u=c>>>15&31,m=c&8191||u,f=0;for(let p=0;p<sf.length;p++)m&1<<p&&(f+=sf[p]);o.info.numberOfChannels=f}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=0,u=0;for(let d=0;d<c;d++){let m=B(e),f=B(e);o.sampleTable.sampleTimingEntries.push({startIndex:l,startDecodeTimestamp:u,count:m,delta:f}),l+=m,u+=m*f}}break;case"ctts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=0;for(let u=0;u<c;u++){let d=B(e),m=Xr(e);o.sampleTable.sampleCompositionTimeOffsets.push({startIndex:l,count:d,offset:m,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1}),l+=d}}break;case"stsz":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=B(e);if(c===0)for(let u=0;u<l;u++){let d=B(e);o.sampleTable.sampleSizes.push(d)}else o.sampleTable.sampleSizes.push(c);o.sampleTable.sampleCount=l}break;case"stz2":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),e.skip(3);let c=H(e),l=B(e);if(c!==4&&c!==8&&c!==16)throw new Error(`Invalid stz2 box: unsupported field size ${c}.`);let u=U(e,Math.ceil(l*c/8)),d=new K(u);for(let m=0;m<l;m++){let f=d.readBits(c);o.sampleTable.sampleSizes.push(f)}o.sampleTable.sampleCount=l}break;case"stss":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),o.sampleTable.keySampleIndices=[];let c=B(e);for(let l=0;l<c;l++){let u=B(e)-1;o.sampleTable.keySampleIndices.push(u)}o.sampleTable.keySampleIndices.sort((l,u)=>l-u),o.sampleTable.keySampleIndices[0]!==0&&o.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=0;for(let d=0;d<c;d++){let m=B(e)-1,f=B(e),p=B(e),g=J(o.sampleTable.sampleToChunk);if(g&&m<=g.startChunkIndex){l++;continue}o.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:m,samplesPerChunk:f,sampleDescriptionIndex:p})}l>0&&O._warn(`Skipped ${l} invalid stsc entries whose chunk indices weren't strictly increasing.`);let u=0;for(let d=0;d<o.sampleTable.sampleToChunk.length;d++)if(o.sampleTable.sampleToChunk[d].startSampleIndex=u,d<o.sampleTable.sampleToChunk.length-1){let f=o.sampleTable.sampleToChunk[d+1].startChunkIndex-o.sampleTable.sampleToChunk[d].startChunkIndex;u+=f*o.sampleTable.sampleToChunk[d].samplesPerChunk}}break;case"stco":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e);for(let l=0;l<c;l++){let u=B(e);o.sampleTable.chunkOffsets.push(u)}}break;case"co64":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e);for(let l=0;l<c;l++){let u=Ge(e);o.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mehd":{let o=H(e);e.skip(3);let c=o===1?Ge(e):B(e);this.movieDurationInTimescale=c}break;case"trex":{e.skip(4);let o=B(e),c=B(e),l=B(e),u=B(e),d=B(e);this.fragmentTrackDefaults.set(o,{trackId:o,defaultSampleDescriptionIndex:c,defaultSampleDuration:l,defaultSampleSize:u,defaultSampleFlags:d})}break;case"tfra":{let o=H(e);e.skip(3);let c=B(e),l=this.idToTrack.get(c);if(!l)break;let u=B(e),d=(u&48)>>4,m=(u&12)>>2,f=u&3,p=[H,me,$t,B],g=p[d],h=p[m],y=p[f],k=B(e);for(let T=0;T<k;T++){let S=o===1?Ge(e):B(e),w=o===1?Ge(e):B(e);g(e);let A=h(e),C=y(e);A>=1&&C>=1&&l.fragmentLookupTable.push({timestamp:S,moofOffset:w,trunNumber:A,sampleNumber:C})}}break;case"moof":{if(this.currentFragment)break;this.currentFragment={moofOffset:r,moofSize:n.totalSize,implicitBaseDataOffset:r,trackData:new Map,psshBoxes:[],sampleCount:0};try{this.readContiguousBoxes(e.slice(a,n.contentSize))}catch(o){throw this.currentFragment=null,o}finally{this.currentTrack=null,this.currentFragmentTrackState=null}}break;case"traf":{if(!this.currentFragment||this.isReadingTraf)break;this.isReadingTraf=!0;try{this.readContiguousBoxes(e.slice(a,n.contentSize))}finally{this.isReadingTraf=!1}let o=this.currentFragmentTrackState;if(this.currentFragmentTrackState=null,this.currentTrack){b(o);let c=this.currentFragment.trackData.get(this.currentTrack.id);e:if(c){if(c.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}c.presentationTimestamps=c.samples.map((d,m)=>({presentationTimestamp:d.presentationTimestamp,sampleIndex:m})).sort((d,m)=>d.presentationTimestamp-m.presentationTimestamp);for(let d=0;d<c.presentationTimestamps.length;d++){let m=c.presentationTimestamps[d],f=c.samples[m.sampleIndex];if(c.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(c.firstKeyFrameTimestamp=f.presentationTimestamp),d<c.presentationTimestamps.length-1){let g=c.presentationTimestamps[d+1].presentationTimestamp-m.presentationTimestamp;f.duration=g}}let l=c.samples[c.presentationTimestamps[0].sampleIndex],u=c.samples[J(c.presentationTimestamps).sampleIndex];c.startTimestamp=l.presentationTimestamp,c.endTimestamp=u.presentationTimestamp+u.duration,c.endDecodeTimestamp=o.currentTimestamp,o.startTimestamp!==null&&(Eo(c,o.startTimestamp),c.startTimestampIsFinal=!0),o.encryptionAuxInfo&&!c.samples[0].encryption&&(c.encryptionAuxInfo=o.encryptionAuxInfo)}this.currentTrack=null}}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let o=Co(U(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(o):this.currentTrack||this.psshBoxes.push(o)}break;case"tfhd":{if(!this.currentFragment||!this.isReadingTraf||this.currentFragmentTrackState)break;e.skip(1);let o=$t(e),c=!!(o&1),l=!!(o&2),u=!!(o&8),d=!!(o&16),m=!!(o&32),f=!!(o&65536),p=!!(o&131072),g=B(e),h=this.fragmentTrackDefaults.get(g),y={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null,currentOffset:null,currentTimestamp:0};this.currentFragmentTrackState=y,c?y.baseDataOffset=Ge(e):p&&(y.baseDataOffset=this.currentFragment.moofOffset),l&&(y.sampleDescriptionIndex=B(e)),u&&(y.defaultSampleDuration=B(e)),d&&(y.defaultSampleSize=B(e)),m&&(y.defaultSampleFlags=B(e)),f&&(y.defaultSampleDuration=0);let k=this.idToTrack.get(g);if(!k)break;if(this.currentFragment.trackData.has(g)){O._warn(`Multiple traf boxes for track ${g} in the same moof box; ignoring the samples of all but the first.`);break}this.currentTrack=k}break;case"tfdt":{if(!this.currentFragmentTrackState)break;let o=H(e);e.skip(3);let c=o===0?B(e):Ge(e);this.currentFragmentTrackState.startTimestamp=c}break;case"trun":{let o=this.currentFragmentTrackState;if(!o||!this.currentFragment)break;let c=this.currentTrack;e.skip(1);let l=$t(e),u=!!(l&1),d=!!(l&4),m=!!(l&256),f=!!(l&512),p=!!(l&1024),g=!!(l&2048),h=B(e),{defaultSampleDuration:y,defaultSampleSize:k,defaultSampleFlags:T}=o;if(h>0&&(!m&&y===null||!f&&k===null||!p&&T===null))throw new Error("Invalid trun box: sample values are missing and there are no defaults.");if(this.currentFragment.sampleCount+=h,this.currentFragment.sampleCount>2**20)throw new Error("Too many (> 2^20) samples in fragment.");let S=null;u&&(S=Xr(e));let w=null;d&&(w=B(e));let A=S!==null?o.baseDataOffset+S:o.currentOffset??o.baseDataOffset,C=null;c&&(C=this.currentFragment.trackData.get(c.id)??null,C||(C={track:c,startTimestamp:0,endTimestamp:0,endDecodeTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,trunSampleCounts:[],encryptionAuxInfo:null},this.currentFragment.trackData.set(c.id,C)),C.trunSampleCounts.push(h));for(let E=0;E<h;E++){let I;m?I=B(e):I=y;let x;f?x=B(e):x=k;let P;p?P=B(e):P=T,E===0&&w!==null&&(P=w);let v=0;g&&(v=Xr(e)),C?.samples.push({presentationTimestamp:o.currentTimestamp+v,duration:I,byteOffset:A,byteSize:x,isKeyFrame:!(P&65536),encryption:null}),A+=x,o.currentTimestamp+=I}o.currentOffset=A,this.currentFragment.implicitBaseDataOffset=A}break;case"saiz":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;if(e.skip(1),$t(e)&1){let f=ae(e,4),p=B(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let l=H(e),u=B(e),d=null;l===0&&u>0&&(d=U(e,u));let m=uf(o,this.currentFragmentTrackState);m.defaultSampleInfoSize=l,m.sampleSizes=d,m.sampleCount=u}break;case"saio":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=H(e);if($t(e)&1){let f=ae(e,4),p=B(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let u=B(e);if(u===0)break;u>1&&O._warn("Multiple saio entries are not supported; using the first offset only.");let d=c===0?B(e):Number(Ge(e));this.currentFragment&&(b(this.currentFragmentTrackState),d+=this.currentFragmentTrackState.baseDataOffset);let m=uf(o,this.currentFragmentTrackState);m.offset=d}break;case"senc":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=this.currentFragment?.trackData.get(o.id);if(!c)break;e.skip(1);let u=!!($t(e)&2),d=B(e),m=o.encryptionInfo.defaultPerSampleIvSize;if(m===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");for(let f=0;f<Math.min(d,c.samples.length);f++){let p=new Uint8Array(16);if(m>0)p.set(U(e,m),0);else if(o.encryptionInfo.defaultConstantIv)p.set(o.encryptionInfo.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let g=null;if(u){let y=me(e);g=[];for(let k=0;k<y;k++){let T=me(e),S=B(e);g.push({clearLen:T,protectedLen:S})}}let h=c.samples[f];h.encryption={iv:p,subsamples:g}}}break;case"udta":{let o=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(let{boxInfo:c,slice:l}of o){if(c.name!=="meta"&&!this.currentTrack){let u=l.filePos;this.metadataTags.raw??={},c.name[0]==="\xA9"?this.metadataTags.raw[c.name]??=Pt(l):this.metadataTags.raw[c.name]??=U(l,c.contentSize),l.filePos=u}switch(c.name){case"meta":l.skip(-c.headerSize),this.traverseBox(l);break;case"\xA9nam":this.currentTrack?this.currentTrack.name=Pt(l):this.metadataTags.title??=Pt(l);break;case"name":this.currentTrack?this.currentTrack.name=be.decode(U(l,c.contentSize)):this.metadataTags.title??=Pt(l);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Pt(l));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Pt(l));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Pt(l));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Pt(l));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Pt(l));break;case"\xA9day":if(!this.currentTrack){let u=Kt(Pt(l));u&&(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Pt(l));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Pt(l));break}}}break;case"meta":{if(this.currentTrack)break;let c=B(e)!==0;this.currentMetadataKeys=new Map,c?this.readContiguousBoxes(e.slice(a,n.contentSize)):this.readContiguousBoxes(e.slice(a+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let o=B(e);for(let c=0;c<o;c++){let l=B(e);if(l<8)throw new Error("Invalid keys box: key size must be at least 8.");e.skip(4);let u=be.decode(U(e,l-8));this.currentMetadataKeys.set(c+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let o=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(let{boxInfo:c,slice:l}of o){let u=c.name,d=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(d)&&(u=this.currentMetadataKeys.get(d));let m=kf(l);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=m,u){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof m=="string"&&(this.metadataTags.title??=m);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof m=="string"&&(this.metadataTags.description??=m);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof m=="string"&&(this.metadataTags.artist??=m);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof m=="string"&&(this.metadataTags.album??=m);break;case"aART":case"album_artist":typeof m=="string"&&(this.metadataTags.albumArtist??=m);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof m=="string"&&(this.metadataTags.comment??=m);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof m=="string"&&(this.metadataTags.genre??=m);break;case"\xA9lyr":case"lyrics":typeof m=="string"&&(this.metadataTags.lyrics??=m);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof m=="string"){let f=Kt(m);f&&(this.metadataTags.date??=f)}break;case"tmpo":if(m instanceof Uint8Array&&m.length>=2){let f=N(m).getInt16(0,!1);f>0&&(this.metadataTags.beatsPerMinute??=f)}break;case"covr":case"com.apple.quicktime.artwork":m instanceof At?(this.metadataTags.images??=[],this.metadataTags.images.push({data:m.data,kind:"coverFront",mimeType:m.mimeType})):m instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:m,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof m=="string"){let f=m.split("/"),p=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(this.metadataTags.trackNumber??=p),g&&Number.isInteger(g)&&g>0&&(this.metadataTags.tracksTotal??=g)}break;case"trkn":if(m instanceof Uint8Array&&m.length>=6){let f=N(m),p=f.getUint16(2,!1),g=f.getUint16(4,!1);p>0&&(this.metadataTags.trackNumber??=p),g>0&&(this.metadataTags.tracksTotal??=g)}break;case"disc":case"disk":if(m instanceof Uint8Array&&m.length>=6){let f=N(m),p=f.getUint16(2,!1),g=f.getUint16(4,!1);p>0&&(this.metadataTags.discNumber??=p),g>0&&(this.metadataTags.discsTotal??=g)}break}}}break}return e.filePos=s,!0}},_o=class{constructor(t){this.internalTrack=t;this.packetToSampleIndex=new WeakMap;this.packetToFragmentLocation=new WeakMap;this.nextEac3Frames=new WeakMap}getNumber(){let t=this.internalTrack.demuxer,e=this.internalTrack.trackBacking.getType(),r=0;for(let n of t.tracks)if(n.trackBacking.getType()===e&&r++,n===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let t=this.internalTrack;return t.durationInMediaTimescale<=0||t.demuxer.isFragmented&&t.demuxer.getSampleTableForTrack(t).sampleCount>0?null:(b(t.trackBacking),((await t.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+t.durationInMediaTimescale/t.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){let e=await this.fetchPacketForSampleIndex(0,t);return e||!this.internalTrack.demuxer.isFragmented?e:this.fetchFirstFragmentedPacket(!1,t)}mapTimestampIntoTimescale(t){return Fe(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,e){let r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Jl(n,r),s=await this.fetchPacketForSampleIndex(a,e,r);if(!this.internalTrack.demuxer.isFragmented)return s;let o=await this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=j(l.presentationTimestamps,r,f=>f.presentationTimestamp),d=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,m=u!==-1&&r<l.endTimestamp;return{sampleIndex:d,correctSampleFound:m}},r,r,e);return!s||!o?s??o:s.timestamp>o.timestamp?s:o}async getNextPacket(t,e){let r=this.nextEac3Frames.get(t);if(r)return r;let n=this.packetToSampleIndex.get(t);if(n!==void 0){let s=await this.fetchPacketForSampleIndex(n+1,e);return s||!this.internalTrack.demuxer.isFragmented?s:this.fetchFirstFragmentedPacket(!1,e)}let a=this.packetToFragmentLocation.get(t);if(a===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,s=>{if(s===a.fragment){let o=s.trackData.get(this.internalTrack.id);if(a.sampleIndex+1<o.samples.length)return{sampleIndex:a.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}async getKeyPacket(t,e){let r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Yh(n,r),s=await this.fetchPacketForSampleIndex(a,e,r);if(!this.internalTrack.demuxer.isFragmented)return s;let o=await this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=lr(l.presentationTimestamps,f=>l.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=r),d=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,m=u!==-1&&r<l.endTimestamp;return{sampleIndex:d,correctSampleFound:m}},r,r,e,!0);return!s||!o?s??o:s.timestamp>o.timestamp?s:o}async getNextKeyPacket(t,e){let r=this.nextEac3Frames.get(t);if(r)return r;let n=this.packetToSampleIndex.get(t);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=eg(s,n),c=await this.fetchPacketForSampleIndex(o,e);return c||!this.internalTrack.demuxer.isFragmented?c:this.fetchFirstFragmentedPacket(!0,e)}let a=this.packetToFragmentLocation.get(t);if(a===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,s=>{if(s===a.fragment){let o=s.trackData.get(this.internalTrack.id);for(let c=a.sampleIndex+1;c<o.samples.length;c++)if(o.samples[c].isKeyFrame)return{sampleIndex:c,correctSampleFound:!0}}else{let o=s.trackData.get(this.internalTrack.id);if(o&&o.firstKeyFrameTimestamp!==null){let c=o.samples.findIndex(l=>l.isKeyFrame);return b(c!==-1),{sampleIndex:c,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}fetchFirstFragmentedPacket(t,e){return this.performFragmentedLookup(null,r=>{let a=r.trackData.get(this.internalTrack.id)?.samples.findIndex(s=>!t||s.isKeyFrame)??-1;return{sampleIndex:a,correctSampleFound:a!==-1}},-1/0,1/0,e)}async fetchPacketForSampleIndex(t,e,r=-1/0){if(t===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Zh(n,t);if(!a)return null;let s;if(e.metadataOnly&&this.internalTrack.info?.codec!=="eac3")s=Ae;else{let u=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);if(R(u)&&(u=await u),!u)return null;if(s=U(u,a.sampleSize),this.internalTrack.encryptionInfo){let d=null;if(this.internalTrack.encryptionAuxInfo){let m=await gf(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);t<m.length&&(d=m[t])}d??=df(this.internalTrack.encryptionInfo),d&&(s=await mf(this.internalTrack,d,s,null))}}let o=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=a.duration/this.internalTrack.timescale,l=new ee(s,a.isKeyFrame?"key":"delta",o,c,t,a.sampleSize);return this.internalTrack.info?.codec==="eac3"?this.splitEac3Sample(l,e,r,this.packetToSampleIndex,t):(this.packetToSampleIndex.set(l,t),l)}async fetchPacketInFragment(t,e,r,n){if(e===-1)return null;let s=t.trackData.get(this.internalTrack.id).samples[e];b(s);let o;if(r.metadataOnly&&this.internalTrack.info?.codec!=="eac3")o=Ae;else{let d=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(R(d)&&(d=await d),!d)return null;if(o=U(d,s.byteSize),this.internalTrack.encryptionInfo){let m=s.encryption??df(this.internalTrack.encryptionInfo);m&&(o=await mf(this.internalTrack,m,o,t))}}let c=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=s.duration/this.internalTrack.timescale,u=new ee(o,s.isKeyFrame?"key":"delta",c,l,t.moofOffset+e,s.byteSize);return this.internalTrack.info?.codec==="eac3"?this.splitEac3Sample(u,r,n,this.packetToFragmentLocation,{fragment:t,sampleIndex:e}):(this.packetToFragmentLocation.set(u,{fragment:t,sampleIndex:e}),u)}async performFragmentedLookup(t,e,r,n,a,s=!1){let{demuxer:o,fragmentLookupTable:c,fragmentPositionCache:l}=this.internalTrack,u=null,d=-1;if(t){let{sampleIndex:g,correctSampleFound:h}=e(t);if(h)return this.fetchPacketInFragment(t,g,a,r);g!==-1&&(u=t,d=g)}let m=j(c,r,g=>g.timestamp),f=j(l,r,g=>g.startTimestamp),p=1/0;for(;;){for(;m!==-1&&c[m].moofOffset>=p;)m--;for(;f!==-1&&(l[f].moofOffset>=p||s&&!l[f].hasKeyFrame);)f--;let g=Math.max(c[m]?.moofOffset??0,l[f]?.moofOffset??0)||null,h,y=null;t?g===null||t.moofOffset>=g?(h=t.moofOffset+t.moofSize,y=t):h=g:h=g??0;let k=y?y.moofOffset:h;for(;h<p;){if(y){let C=y.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>n)break;y=null}let T=o.fragmentSummaries.get(h);if(T&&!T.trackIds.has(this.internalTrack.id)){h+=T.moofSize;continue}let S=o.reader.requestSliceRange(h,Ot,kr);if(R(S)&&(S=await S),!S)break;let w=h,A=jr(S);if(!A)break;if(A.name==="moof"){if(y=await o.readFragment(w),!y)break;let{sampleIndex:C,correctSampleFound:E}=e(y);if(E)return this.fetchPacketInFragment(y,C,a,r);C!==-1&&(u=y,d=C)}h=w+A.totalSize}if(g===null||u&&u.moofOffset>=g)break;p=k,t=null}return u?this.fetchPacketInFragment(u,d,a,r):null}splitEac3Sample(t,e,r,n,a){let s=this.internalTrack.info;b(s?.type==="audio");let o=Js(t.data)??[{offset:0,size:t.data.byteLength,blockCount:6}],c=(r-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=null,u=null,d=0;for(let m=0;m<o.length;m++){let f=o[m],p=t.timestamp+256*d/s.sampleRate,g=o.length===1?t.duration:256*f.blockCount/s.sampleRate,h=new ee(e.metadataOnly?Ae:t.data.subarray(f.offset,f.offset+f.size),"key",p,g,8*t.sequenceNumber+m,f.size);n.set(h,a),u&&this.nextEac3Frames.set(u,h),(m===0||p<=c)&&(l=h),u=h,d+=f.blockCount}return b(l),l}},Ro=class extends _o{constructor(e){super(e);this.decoderConfigPromise=null}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}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=r&&hr(r.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=r&&br(r.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!um(this.internalTrack.info.vp9CodecInfo))){let r=await this.getFirstPacket({}),n=r&&vn(r.data);n&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??n,videoFullRangeFlag:n.videoFullRangeFlag,colourPrimaries:n.colourPrimaries,transferCharacteristics:n.transferCharacteristics,matrixCoefficients:n.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!Gs(this.internalTrack.info.av1CodecInfo))){let r=await this.getFirstPacket({}),n=r&&hi(r.data);n&&(this.internalTrack.info.av1CodecInfo=n)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){let r=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=r&&Qs(r.data)}if(!wn(this.internalTrack.info.colorSpace)){let r=Do(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=r.primaries,this.internalTrack.info.colorSpace.transfer??=r.transfer,this.internalTrack.info.colorSpace.matrix??=r.matrix,this.internalTrack.info.colorSpace.fullRange??=r.fullRange}let e={codec:Si(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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},Fo=class extends _o{constructor(e){super(e);this.decoderConfigPromise=null}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&no(e.data)}return{codec:Nn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},Jl=(i,t)=>{if(i.sortedCompositionTimeOffsets)return pf(i,t,!1);{let e=j(i.sampleTimingEntries,t,n=>n.startDecodeTimestamp);if(e===-1)return-1;let r=i.sampleTimingEntries[e];return r.delta===0?r.startIndex+r.count-1:r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Yh=(i,t)=>{if(!i.keySampleIndices)return Jl(i,t);if(i.sortedCompositionTimeOffsets)return pf(i,t,!0);{let e=Jl(i,t),r=j(i.keySampleIndices,e,n=>n);return i.keySampleIndices[r]??-1}},Zh=(i,t)=>{if(t>=i.sampleCount)return null;let e=j(i.sampleTimingEntries,t,h=>h.startIndex),r=i.sampleTimingEntries[e],a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,s=j(i.sampleCompositionTimeOffsets,t,h=>h.startIndex),o=i.sampleCompositionTimeOffsets[s];o&&t-o.startIndex<o.count&&(a+=o.offset);let c=i.sampleSizes[Math.min(t,i.sampleSizes.length-1)],l=j(i.sampleToChunk,t,h=>h.startSampleIndex),u=i.sampleToChunk[l],d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),m=i.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,p=m;i.sampleSizes.length===1?p+=c*(t-f):p+=i.cumulativeSampleSizes[t]-i.cumulativeSampleSizes[f];let g=r.delta;if(i.sortedCompositionTimeOffsets){let h=Jh(i,t,a);h!==null&&(g=h-a)}return{presentationTimestamp:a,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:m,isKeyFrame:i.keySampleIndices?Vr(i.keySampleIndices,t,h=>h)!==-1:!0}},pf=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=-1,a=-1/0,s=j(r,t,o=>o.startTimestamp);for(let o=s;o>=0;o--){let c=r[o];if(c.maxLastTimestamp<a)break;let l=c.lastTimestamp<=t?c.startIndex+c.count-1:hf(i,c,(d,m)=>m>t)-1;if(e){let d=j(i.keySampleIndices,l,m=>m);l=i.keySampleIndices[d]??-1}if(l<c.startIndex)continue;let u=eu(i,l)+c.offset;(u>a||u===a&&l>n)&&(n=l,a=u)}return n},Jh=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=j(r,e,s=>s.startTimestamp),a=r[n+1]?.startTimestamp??null;for(let s=n;s>=0;s--){let o=r[s];if(o.maxLastTimestamp<e)break;let c=hf(i,o,(u,d)=>d>e||d===e&&u>t);if(c===o.startIndex+o.count)continue;let l=eu(i,c)+o.offset;(a===null||l<a)&&(a=l)}return a},hf=(i,t,e)=>{let r=t.startIndex,n=t.startIndex+t.count;for(;r<n;){let a=Math.floor((r+n)/2);e(a,eu(i,a)+t.offset)?n=a:r=a+1}return r},eu=(i,t)=>{let e=j(i.sampleTimingEntries,t,n=>n.startIndex),r=i.sampleTimingEntries[e];return r.startDecodeTimestamp+(t-r.startIndex)*r.delta},eg=(i,t)=>{if(!i.keySampleIndices)return t+1;let e=j(i.keySampleIndices,t,r=>r);return i.keySampleIndices[e+1]??-1},Eo=(i,t)=>{i.startTimestamp+=t,i.endTimestamp+=t,i.endDecodeTimestamp+=t;for(let e of i.samples)e.presentationTimestamp+=t;for(let e of i.presentationTimestamps)e.presentationTimestamp+=t},of=i=>[wi(i),wi(i),Io(i),wi(i),wi(i),Io(i),wi(i),wi(i),Io(i)],cf=(i,t)=>{let e=i.info;if(e.type!=="video")return;let{num:r,den:n}=t;!(r>0&&n>0)||r===n||(r>n?(e.squarePixelWidth=Math.round(e.width*r/n),e.squarePixelHeight=e.height):(e.squarePixelWidth=e.width,e.squarePixelHeight=Math.round(e.height*n/r)))},lf=(i,t)=>{for(;i.length>0&&J(i).startIndex>=t;)i.pop();let e=J(i);e&&(e.count=Math.min(e.count,t-e.startIndex))},uf=(i,t)=>t?t.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:i.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},gf=async(i,t,e)=>{if(e.resolved)return e.resolved;if(e.offset===null||e.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(e.defaultSampleInfoSize>0)r=e.defaultSampleInfoSize*e.sampleCount;else{b(e.sampleSizes);for(let o=0;o<e.sampleCount;o++)r+=e.sampleSizes[o]}let n=i.requestSlice(e.offset,r);if(R(n)&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");let a=t.defaultPerSampleIvSize;if(a===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");let s=[];for(let o=0;o<e.sampleCount;o++){let c=e.defaultSampleInfoSize>0?e.defaultSampleInfoSize:e.sampleSizes[o],l=new Uint8Array(16);if(a>0)l.set(U(n,a),0);else if(t.defaultConstantIv)l.set(t.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let u=null;if(c>a){let d=me(n);u=[];for(let m=0;m<d;m++){let f=me(n),p=B(n);u.push({clearLen:f,protectedLen:p})}}s.push({iv:l,subsamples:u})}return e.resolved=s,s},df=i=>i.defaultConstantIv?{iv:i.defaultConstantIv,subsamples:null}:null,mf=async(i,t,e,r)=>{b(i.encryptionInfo);let n=i.encryptionInfo;if(n.defaultKid===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");let a=n.defaultKid,s,o=i.demuxer.decryptionKeyCache.get(a);if(o)s=await o;else{if(!i.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let c=(async()=>{let l=i.demuxer.psshBoxes;if(r){l=[...l,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(a));for(let d=0;d<l.length-1;d++)for(let m=d+1;m<l.length;m++)Po(l[d],l[m])&&(l.splice(m,1),m--)}let u=await i.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:l});if(!(typeof u=="string"&&u.length===32&&Pd.test(u)||u instanceof Uint8Array&&u.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return u instanceof Uint8Array?u:Ed(u)})();i.demuxer.decryptionKeyCache.set(a,c),s=await c}return n.scheme==="cenc"||n.scheme==="cens"?tg(s,n,t,e):rg(s,n,t,e)},tg=async(i,t,e,r)=>{let n=new Uint8Array(16);n.set(e.iv,0);let a=await crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["decrypt"]),s=async p=>{let g=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},a,p);return new Uint8Array(g)};if(!e.subsamples)return s(r);b(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let o=bf(e.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock,r.length),c=0;for(let p of o)for(let g of p.perSubsample)c+=g.length;let l=new Uint8Array(c),u=0;for(let p of o)for(let g of p.perSubsample)l.set(r.subarray(g.offset,g.offset+g.length),u),u+=g.length;let d=await s(l),m=new Uint8Array(r),f=0;for(let p of o)for(let g of p.perSubsample)m.set(d.subarray(f,f+g.length),g.offset),f+=g.length;return m},rg=(i,t,e,r)=>{let n=new za;n.init({key:i,iv:e.iv});let a=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(b(a!==null&&s!==null),!e.subsamples){let u=new Uint8Array(r),d=Math.floor(r.length/16);for(let m=0;m<d;m++){let f=m*16;n.in.set(r.subarray(f,f+16)),n.decrypt(),u.set(n.out,f)}return u}if(a===0&&s===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(r),c=bf(e.subsamples,a,s,r.length),l=new DataView(e.iv.buffer,e.iv.byteOffset,16);for(let u of c){n.iv[0]=l.getUint32(0,!1),n.iv[1]=l.getUint32(4,!1),n.iv[2]=l.getUint32(8,!1),n.iv[3]=l.getUint32(12,!1);for(let d of u.perSubsample){let m=d.length/16;for(let f=0;f<m;f++){let p=d.offset+f*16;n.in.set(r.subarray(p,p+16)),n.decrypt(),o.set(n.out,p)}}}return o},bf=(i,t,e,r)=>{let n=[],a=t!==0||e!==0,s=0;for(let o of i){if(s+o.clearLen+o.protectedLen>r)throw new Error("Invalid encryption info: subsamples exceed the sample size.");s+=o.clearLen;let c=[];if(!a)o.protectedLen>0&&c.push({offset:s,length:o.protectedLen}),s+=o.protectedLen;else{let l=o.protectedLen,u=s;for(;l>0&&!(l<16*t);){let d=16*t;c.push({offset:u,length:d}),u+=d,l-=d;let m=Math.min(16*e,l);u+=m,l-=m}s+=o.protectedLen}n.push({perSubsample:c})}return n};var Tr=class{constructor(t){this.value=t}},$i=class{constructor(t){this.value=t}},Ln=class{constructor(t){this.value=t}},Dt=class{constructor(t){this.value=t}};var nu=[440786851,408125543],Hn=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],Ha=[...nu,...Hn],Vo=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,tu=i=>i<1n<<8n?1:i<1n<<16n?2:i<1n<<24n?3:i<1n<<32n?4:i<1n<<40n?5:i<1n<<48n?6:i<1n<<56n?7:8,ru=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,Ai=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)},Uo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=Vo(t)){let r=0;switch(e){case 6:this.helperView.setUint8(r++,t/2**40|0);case 5:this.helperView.setUint8(r++,t/2**32|0);case 4:this.helperView.setUint8(r++,t>>24);case 3:this.helperView.setUint8(r++,t>>16);case 2:this.helperView.setUint8(r++,t>>8);case 1:this.helperView.setUint8(r++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(t,e=tu(t)){let r=0;for(let n=e-1;n>=0;n--)this.helperView.setUint8(r++,Number(t>>BigInt(n*8)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(t,e=ru(t)){t<0&&(t+=2**(e*8)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=Ai(t)){if(t>=2**(7*e)-1)throw new Error(`EBML variable-size integer ${t} doesn't fit into ${e} bytes.`);let r=0;switch(e){case 1:this.helperView.setUint8(r++,128|t);break;case 2:this.helperView.setUint8(r++,64|t>>8),this.helperView.setUint8(r++,t);break;case 3:this.helperView.setUint8(r++,32|t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 4:this.helperView.setUint8(r++,16|t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 5:this.helperView.setUint8(r++,8|t/2**32&7),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 6:this.helperView.setUint8(r++,4|t/2**40&3),this.helperView.setUint8(r++,t/2**32|0),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(e=>e.charCodeAt(0))))}writeEBML(t){if(t!==null)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(let e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data))if(t.size===void 0)this.writeVarInt(iu(t.data)),this.dataOffsets.set(t,this.writer.getPos()),this.writeEBML(t.data);else{let e=this.writer.getPos(),r=t.size===-1?1:t.size;t.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);let n=this.writer.getPos();if(this.dataOffsets.set(t,n),this.writeEBML(t.data),t.size!==-1){let a=this.writer.getPos()-n,s=this.writer.getPos();this.writer.seek(e),this.writeVarInt(a,r),this.writer.seek(s)}}else if(typeof t.data=="number"){let e=t.size??Vo(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if(typeof t.data=="bigint"){let e=t.size??tu(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if(typeof t.data=="string")this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof Tr)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof $i)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof Ln){let e=t.size??ru(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Dt){let e=Y.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else Z(t.data)}},iu=i=>{if(i===null)return 0;if(i instanceof Uint8Array)return i.byteLength;if(Array.isArray(i))return i.reduce((r,n)=>r+iu(n),0);let t,e;return Array.isArray(i.data)?(t=iu(i.data),e=i.size===void 0?Ai(t):i.size===-1?1:i.size):typeof i.data=="number"?(t=i.size??Vo(i.data),e=Ai(t)):typeof i.data=="bigint"?(t=i.size??tu(i.data),e=Ai(t)):typeof i.data=="string"?(t=i.data.length,e=Ai(t)):i.data instanceof Uint8Array?(t=i.data.byteLength,e=i.size??Ai(t)):i.data instanceof Tr?(t=4,e=1):i.data instanceof $i?(t=8,e=1):i.data instanceof Ln?(t=i.size??ru(i.data.value),e=Ai(t)):(b(i.data instanceof Dt),t=Y.encode(i.data.value).length,e=Ai(t)),Vo(i.id)+e+t},zo=Date.UTC(2001,0,1),Tf=8,lt=2,Yt=2*Tf,au=i=>{if(i.remainingLength<1)return null;let t=H(i);if(i.skip(-1),t===0)return null;let e=1,r=128;for(;(t&r)===0;)e++,r>>=1;return i.remainingLength<e?null:e},Wn=i=>{if(i.remainingLength<1)return null;let t=H(i);if(t===0)return null;let e=1,r=128;for(;(t&r)===0;)e++,r>>=1;if(i.remainingLength<e-1)return null;let n=t&r-1;for(let a=1;a<e;a++)n*=256,n+=H(i);return n},X=(i,t)=>{if(t>8)throw new Error("Bad unsigned int size "+t);let e=0;for(let r=0;r<t;r++)e*=256,e+=H(i);return e},su=(i,t)=>{if(t>8)throw new Error("Bad unsigned int size "+t);let e=0n;for(let r=0;r<t;r++)e<<=8n,e+=BigInt(H(i));return e};var wf=(i,t)=>t===0?0n:BigInt.asIntN(8*t,su(i,t)),Sf=i=>{let t=au(i);return t===null||i.remainingLength<t?null:X(i,t)},ou=i=>{let t=i.filePos,e=Wn(i);if(e===null)return null;let r=i.filePos-t;if(e!==2**(7*r)-1)return e},Vt=i=>{b(i.remainingLength>=lt);let t=Sf(i);if(t===null)return null;let e=ou(i);return e===null?null:{id:t,size:e}},xi=(i,t)=>{let e=U(i,t),r="";for(let n=0;n<t&&e[n]!==0;n++)r+=String.fromCharCode(e[n]);return r},Yi=(i,t)=>{let e=U(i,t),r=0;for(;r<t&&e[r]!==0;)r+=1;return be.decode(e.subarray(0,r))},Zi=(i,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw new Error("Bad float size "+t);return t===4?Af(i):Bo(i)},No=async(i,t,e,r)=>{let n=new Set(e),a=t;for(;r===null||a<r;){let s=i.requestSliceRange(a,lt,Yt);if(R(s)&&(s=await s),!s)break;let o=Vt(s);if(!o)break;if(n.has(o.id))return{pos:a,found:!0};wr(o.size),a=s.filePos+o.size}return{pos:r!==null&&r>a?r:a,found:!1}},cu=async(i,t,e,r)=>{let a=new Set(e),s=t;for(;s<r;){let o=i.requestSliceRange(s,0,Math.min(65536,r-s));if(R(o)&&(o=await o),!o||o.length===0)break;let c=Math.max(o.length-Tf,1);for(let l=0;l<c;l++){o.filePos=s;let u=Sf(o);if(u!==null&&a.has(u))return s;s++}}return null},Be={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS",truehd:"A_TRUEHD","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 wr(i){if(i===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var Lo=i=>{let e=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];e+=`; codecs="${r.join(", ")}"`}return e};var lu=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],Cf=10*2**20,ig=64,Ho=class extends _e{constructor(e){super(e);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.currentProjection=null;this.currentTagTargetIsMovie=!0;this.currentSimpleTagName=null;this.currentAttachedFile=null;this.isWebM=!1;this.claimedSeekTargets=new Set;this.elementNestingDepth=0;this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),r=await Promise.all(e.map(n=>n.getDecoderConfig().then(a=>a?.codec??null)));return Lo({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsPromise||(this.reader.fileSize!==null?r.metadataTagsPromise=this.loadSegmentMetadata(r):r.metadataTagsPromise=Promise.resolve()),await r.metadataTagsPromise;let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,lt,Yt);if(R(r)&&(r=await r),!r)break;let n=Vt(r);if(!n)break;let a=n.id,s=n.size,o=r.filePos;if(a===440786851){wr(s);let c=this.reader.requestSlice(o,s);if(R(c)&&(c=await c),!c)break;this.readContiguousElements(c)}else if(a===408125543){if(await this.readSegment(o,s),s===void 0||this.reader.fileSize===null)break}else if(a===524531317){if(this.reader.fileSize===null)break;s===void 0&&(s=(await No(this.reader,o,Ha,this.reader.fileSize)).pos-o);let c=J(this.segments);c&&(c.elementEndPos=o+s)}wr(s),e=o+s}})()}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],idToTrack:new Map,cuePoints:[],dataStartPos:e,elementEndPos:r===void 0?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,clusterSummaries:new Map,metadataTags:{},metadataTagsPromise:null},this.segments.push(this.currentSegment);let n=e,a=new Set;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let c=this.reader.requestSliceRange(n,lt,Yt);if(R(c)&&(c=await c),!c)break;let l=n,u=Vt(c);if(!u||!Hn.includes(u.id)&&u.id!==236){let g=await cu(this.reader,l+1,Hn,Math.min(this.currentSegment.elementEndPos??1/0,l+Cf));if(g){n=g;continue}else break}let{id:d,size:m}=u,f=c.filePos,p=lu.findIndex(g=>g.id===d);if(p!==-1){let g=lu[p].flag;this.currentSegment[g]=!0,d===290298740&&a.add(l-e),wr(m);let h=this.reader.requestSlice(f,m);R(h)&&(h=await h),h&&this.readContiguousElements(h)}else if(d===307544935||d===423732329){d===307544935?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,wr(m);let g=this.reader.requestSlice(f,m);R(g)&&(g=await g),g&&this.readContiguousElements(g)}else if(d===524531317){this.currentSegment.clusterSeekStartPos=l;break}if(m===void 0)break;n=f+m}if(this.reader.fileSize!==null)for(let c=0;c<this.currentSegment.seekEntries.length;c++){let l=this.currentSegment.seekEntries[c];if(l.id!==290298740||a.has(l.segmentPosition)||(a.add(l.segmentPosition),!this.claimSeekTarget(e+l.segmentPosition)))continue;let u=this.reader.requestSliceRange(e+l.segmentPosition,lt,Yt);if(R(u)&&(u=await u),!u)continue;let d=Vt(u);if(!d||d.id!==290298740)continue;let{size:m}=d;wr(m);let f=this.reader.requestSlice(u.filePos,m);R(f)&&(f=await f),f&&this.readContiguousElements(f)}if(this.currentSegment.seekEntries.sort((c,l)=>c.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let l=lu.find(g=>g.id===c.id);if(!l||this.currentSegment[l.flag]||!this.claimSeekTarget(e+c.segmentPosition))continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,lt,Yt);if(R(u)&&(u=await u),!u)continue;let d=Vt(u);if(!d)continue;let{id:m,size:f}=d;if(m!==l.id)continue;wr(f),this.currentSegment[l.flag]=!0;let p=this.reader.requestSlice(u.filePos,f);R(p)&&(p=await p),p&&this.readContiguousElements(p)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let c of this.currentSegment.tracks)c.defaultDurationNs!==null&&(c.defaultDuration=this.currentSegment.timestampFactor*c.defaultDurationNs/1e9),c.codecDelay=Math.round(this.currentSegment.timestampFactor*c.codecDelayNs/1e9);for(let c of this.currentSegment.cuePoints){let l=this.currentSegment.idToTrack.get(c.trackId);l&&l.cuePoints.push(c)}for(let c of this.currentSegment.tracks){let l=c.cuePoints;l.sort((d,m)=>d.time-m.time);let u=0;for(let d of l)(u===0||d.time!==l[u-1].time)&&(l[u++]=d);l.length=u}let s=null,o=-1/0;for(let c of this.currentSegment.tracks)c.cuePoints.length>o&&(o=c.cuePoints.length,s=c);for(let c of this.currentSegment.tracks)c.cuePoints.length===0&&(c.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,lt,Yt);R(n)&&(n=await n),b(n);let a=e,s=Vt(n);b(s);let o=s.id;b(o===524531317);let c=s.size,l=n.filePos;c===void 0&&(c=(await No(this.reader,l,Ha,r.elementEndPos)).pos-l);let u=this.reader.requestSliceRange(l,0,c);R(u)&&(u=await u);let d={segment:r,elementStartPos:a,elementEndPos:l+c,dataStartPos:l,timestamp:-1,trackData:new Map};if(u){this.currentCluster=d;try{let m=this.readContiguousElements(u,Ha);d.elementEndPos=m}finally{this.currentCluster=null,this.currentBlock=null}}for(let[,m]of d.trackData){let f=m.track;b(m.blocks.length>0);let p=!1;for(let w=0;w<m.blocks.length;w++){let A=m.blocks[w];A.timestamp+=d.timestamp,p||=A.lacing!==0}m.presentationTimestamps=m.blocks.map((w,A)=>({timestamp:w.timestamp,blockIndex:A})).sort((w,A)=>w.timestamp-A.timestamp);for(let w=0;w<m.presentationTimestamps.length;w++){let A=m.presentationTimestamps[w],C=m.blocks[A.blockIndex];if(w<m.presentationTimestamps.length-1){let E=m.presentationTimestamps[w+1];C.duration=E.timestamp-C.timestamp}else C.duration===0&&f.defaultDuration!=null&&C.lacing===0&&(C.duration=Math.round(f.defaultDuration))}if(p&&(m.blocks=this.expandLacedBlocks(m.blocks,f),m.presentationTimestamps=m.blocks.map((w,A)=>({timestamp:w.timestamp,blockIndex:A})).sort((w,A)=>w.timestamp-A.timestamp)),f.info?.type==="audio"&&f.info.codec){let w=Ji.includes(f.info.codec);for(let A of m.blocks)(A.decoded||!w)&&(A.isKeyFrame=_n(f.info.codec,A.data)==="key")}let g=m.presentationTimestamps.find(w=>m.blocks[w.blockIndex].isKeyFrame);g&&(m.firstKeyFrameTimestamp=g.timestamp);let h=m.blocks[m.presentationTimestamps[0].blockIndex],y=m.blocks[J(m.presentationTimestamps).blockIndex];m.startTimestamp=h.timestamp,m.endTimestamp=y.timestamp+y.duration;let k=j(f.clusterPositionCache,m.startTimestamp,w=>w.startTimestamp),T=f.clusterPositionCache[k],S=f.clusterPositionCache[k+1];(!T||T.elementStartPos<a)&&(!S||S.elementStartPos>a)&&f.clusterPositionCache.splice(k+1,0,{elementStartPos:d.elementStartPos,startTimestamp:m.startTimestamp,hasKeyFrame:m.firstKeyFrameTimestamp!==null})}return r.lastReadCluster=d,r.clusterSummaries.set(e,{elementEndPos:d.elementEndPos,trackIds:new Set(d.trackData.keys())}),d}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){let a=e.segment.idToTrack.get(r);if(!a)return null;n={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,n)}return n}expandLacedBlocks(e,r){let n=[];for(let a of e){if(a.lacing===0){n.push(a);continue}let s=xe.tempFromBytes(a.data);if(s.length===0)throw new Error("Invalid laced block: no data.");let o=[],c=H(s)+1;switch(a.lacing){case 1:{let u=0;for(let d=0;d<c-1;d++){let m=0;for(;s.bufferPos<s.length;){let f=H(s);if(m+=f,f<255){o.push(m),u+=m;break}}}o.push(s.length-(s.bufferPos+u))}break;case 2:{let u=s.length-1,d=Math.floor(u/c);for(let m=0;m<c;m++)o.push(d)}break;case 3:{if(c===1){o.push(s.length-s.bufferPos);break}let u=Wn(s);if(u===null)throw new Error("Invalid EBML lacing: bad frame size.");let d=u;o.push(d);let m=d;for(let f=1;f<c-1;f++){let p=s.bufferPos,g=Wn(s);if(g===null)throw new Error("Invalid EBML lacing: bad frame size.");let h=g,k=(1<<(s.bufferPos-p)*7-1)-1,T=h-k;d+=T,o.push(d),m+=d}o.push(s.length-(s.bufferPos+m))}break;default:b(!1)}if(o.length!==c||o.some(u=>u<=0))throw new Error("Invalid block lacing: frame sizes don't match the block.");let l=a.duration||Math.round(c*(r.defaultDuration??0));for(let u=0;u<c;u++){let d=o[u],m=U(s,d),f=Math.floor(l*u/c),p=Math.floor(l*(u+1)/c);n.push({timestamp:a.timestamp+f,duration:p-f,isKeyFrame:a.isKeyFrame,data:m,lacing:0,decoded:a.decoded,postProcessed:!1,mainAdditional:a.mainAdditional})}}return n}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===307544935&&!e.tagsSeen)){if(!(r.id===423732329&&!e.attachmentsSeen))continue}if(!this.claimSeekTarget(e.dataStartPos+r.segmentPosition))continue;let n=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,lt,Yt);if(R(n)&&(n=await n),!n)continue;let a=Vt(n);if(!a||a.id!==r.id)continue;let{size:s}=a;wr(s);let o=this.reader.requestSlice(n.filePos,s);if(R(o)&&(o=await o),o){b(!this.currentSegment),this.currentSegment=e;try{this.readContiguousElements(o)}finally{this.currentSegment=null}}r.id===307544935?e.tagsSeen=!0:r.id===423732329&&(e.attachmentsSeen=!0)}}claimSeekTarget(e){return this.claimedSeekTargets.has(e)?!1:(this.claimedSeekTargets.add(e),!0)}readContiguousElements(e,r){if(this.elementNestingDepth===ig)throw new Error("Invalid file: elements are nested too deeply.");this.elementNestingDepth++;try{for(;e.remainingLength>=lt;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}finally{this.elementNestingDepth--}}traverseElement(e,r){let n=Vt(e);if(!n||r&&r.includes(n.id))return!1;let{id:a,size:s}=n,o=e.filePos;if(wr(s),o+s>e.end)return!1;switch(a){case 17026:this.isWebM=xi(e,s)==="webm";break;case 19899:{if(!this.currentSegment)break;let c={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(c),this.readContiguousElements(e.slice(o,s)),(c.id===-1||c.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case 21419:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.id=X(e,s)}break;case 21420:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.segmentPosition=X(e,s)}break;case 2807729:{if(!this.currentSegment)break;let c=s===0?1e6:X(e,s);if(c===0)throw new Error("Invalid TimestampScale element: must not be 0.");this.currentSegment.timestampScale=c,this.currentSegment.timestampFactor=1e9/c}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=Zi(e,s)}break;case 17505:{if(!this.currentSegment)break;let c=wf(e,s);this.currentSegment.metadataTags.creationTime=new Date(zo+Number(c/1000000n))}break;case 31657:{if(!this.currentSegment)break;this.currentSegment.metadataTags.title??=Yi(e,s)}break;case 174:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ve,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,codecDelay:0,codecDelayNs:0,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(c=>c.data?.type!=="decompress"||c.scope!==1||c.data.algorithm!==3)&&(O._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentSegment.idToTrack.has(this.currentTrack.id)&&(O._warn(`Track #${this.currentTrack.id} is defined more than once; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let c=this.currentTrack.codecId.indexOf("/"),l=c===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,c);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height;let u=this.currentTrack.info.displayWidth,d=this.currentTrack.info.displayHeight,m=this.currentTrack.info.stereoMode;if(u!==null&&[1,8,9,11].includes(m)&&(u*=2),d!==null&&[2,3,6,7].includes(m)&&(d*=2),this.currentTrack.info.displayUnit===0&&(u??=this.currentTrack.info.width,d??=this.currentTrack.info.height),this.currentTrack.info.displayUnit!==4&&u!==null&&d!==null){let p=u*this.currentTrack.info.height,g=d*this.currentTrack.info.width;p>0&&g>0&&(p>g?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*p/g):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*g/p))}if(this.currentTrack.codecId===Be.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Be.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(l===Be.vp8)this.currentTrack.info.codec="vp8";else if(l===Be.vp9)this.currentTrack.info.codec="vp9";else if(l===Be.av1)this.currentTrack.info.codec="av1";else if(l===Be.prores){let p=this.currentTrack.codecPrivate?be.decode(this.currentTrack.codecPrivate):"";$r.includes(p)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=p)}let f=this.currentTrack;this.currentTrack.trackBacking=new uu(f),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}else if(this.currentTrack.info.type==="audio"){if(this.currentTrack.info.outputSampleRate!==null&&(this.currentTrack.info.sampleRate=this.currentTrack.info.outputSampleRate),l===Be.aac){if(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,!this.currentTrack.codecPrivate&&this.currentTrack.codecId!==Be.aac){let d=this.currentTrack.codecId.split("/")[2]??"",m=["MAIN","LC","SSR","LTP"].indexOf(d)+1;if(m===0)throw new Error(`Unknown Matroska AAC codec ID '${this.currentTrack.codecId}'.`);let f=this.currentTrack.codecId.endsWith("/SBR");f&&this.currentTrack.info.outputSampleRate===null&&(this.currentTrack.info.sampleRate*=2),this.currentTrack.info.codecDescription=ui({objectType:f?5:m,outputSampleRate:this.currentTrack.info.sampleRate,outputNumberOfChannels:this.currentTrack.info.numberOfChannels,programConfigElement:null})}}else this.currentTrack.codecId===Be.mp3?this.currentTrack.info.codec="mp3":l===Be.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=tt):l===Be.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.dts?(this.currentTrack.info.codec="dts",this.currentTrack.codecId==="A_DTS/EXPRESS"?this.currentTrack.info.dtsFormat="dtse":this.currentTrack.codecId==="A_DTS/LOSSLESS"&&(this.currentTrack.info.dtsFormat="dtsl")):l===Be.truehd?this.currentTrack.info.codec="truehd":this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let u=this.currentTrack;this.currentTrack.trackBacking=new du(u),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}}this.currentTrack=null}break;case 215:{if(!this.currentTrack)break;this.currentTrack.id=X(e,s)}break;case 131:{if(!this.currentTrack)break;let c=X(e,s);c===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:0,stereoMode:0,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...Rs},alphaMode:!1,proresFormat:null}:c===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,outputSampleRate:null,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case 185:{if(!this.currentTrack)break;(s===0?1:X(e,s))||(this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.disposition.default=s===0||!!X(e,s)}break;case 21930:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!X(e,s)}break;case 21934:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!X(e,s)}break;case 21931:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!X(e,s)}break;case 21932:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!X(e,s)}break;case 21935:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!X(e,s)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=xi(e,s)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=U(e,s)}break;case 2352003:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=X(e,s)}break;case 22186:{if(!this.currentTrack)break;this.currentTrack.codecDelayNs=X(e,s)}break;case 21358:{if(!this.currentTrack)break;this.currentTrack.name=Yi(e,s)}break;case 2274716:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=s===0?"eng":xi(e,s),Ur(this.currentTrack.languageCode)||(this.currentTrack.languageCode=ce)}break;case 2274717:{if(!this.currentTrack)break;let l=xi(e,s).split("-")[0];l?this.currentTrack.languageCode=l:this.currentTrack.languageCode=ce,this.currentTrack.hasLanguageBcp47=!0}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=X(e,s)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=X(e,s)}break;case 21680:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=X(e,s)}break;case 21690:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=X(e,s)}break;case 21682:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=X(e,s)}break;case 21432:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.stereoMode=X(e,s)}break;case 21440:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=X(e,s)===1}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 21937:{if(this.currentTrack?.info?.type!=="video")break;let c=s===0?2:X(e,s),l=St[c];this.currentTrack.info.colorSpace.matrix=l}break;case 21945:{if(this.currentTrack?.info?.type!=="video")break;let c=X(e,s);this.currentTrack.info.colorSpace.fullRange=c===1||c===2?c===2:void 0}break;case 21946:{if(this.currentTrack?.info?.type!=="video")break;let c=s===0?2:X(e,s),l=wt[c];this.currentTrack.info.colorSpace.transfer=l}break;case 21947:{if(this.currentTrack?.info?.type!=="video")break;let c=s===0?2:X(e,s),l=Tt[c];this.currentTrack.info.colorSpace.primaries=l}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;let c=this.currentTrack.info,l={type:0,yaw:0,pitch:0,roll:0};if(this.currentProjection=l,this.readContiguousElements(e.slice(o,s)),this.currentProjection=null,l.type!==0)break;let u=d=>{try{return Math.round(Math.cos(ai(d)*wl))}catch{return 1}};c.horizontalScale=u(l.yaw),c.verticalScale=u(l.pitch);try{c.rotation=ai(-l.roll)}catch{}}break;case 30321:{if(!this.currentProjection)break;this.currentProjection.type=X(e,s)}break;case 30323:{if(!this.currentProjection)break;this.currentProjection.yaw=Zi(e,s)}break;case 30324:{if(!this.currentProjection)break;this.currentProjection.pitch=Zi(e,s)}break;case 30325:{if(!this.currentProjection)break;this.currentProjection.roll=Zi(e,s)}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(o,s))}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;let c=s===0?8e3:Zi(e,s);if(!(c>0)||!Number.isFinite(c))throw new Error("Invalid SamplingFrequency element: must be a positive, finite number.");this.currentTrack.info.sampleRate=c}break;case 30901:{if(this.currentTrack?.info?.type!=="audio")break;let c=Zi(e,s);if(!(c>0)||!Number.isFinite(c))throw new Error("Invalid OutputSamplingFrequency element: must be a positive, finite number.");this.currentTrack.info.outputSampleRate=c}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;let c=s===0?1:X(e,s);if(c===0)throw new Error("Invalid Channels element: must not be 0.");this.currentTrack.info.numberOfChannels=c}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=X(e,s)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,s)),this.currentCueTime=null}break;case 179:this.currentCueTime=X(e,s);break;case 183:{if(this.currentCueTime===null||!this.currentSegment)break;let c={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(c),this.readContiguousElements(e.slice(o,s)),(c.trackId===-1||c.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case 247:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;c.trackId=X(e,s)}break;case 241:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;b(this.currentSegment),c.clusterPosition=this.currentSegment.dataStartPos+X(e,s)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=X(e,s)}break;case 163:{if(!this.currentCluster)break;let c=e.slice(o,s),l=Wn(c);if(l===null||c.remainingLength<3)break;let u=this.getTrackDataInCluster(this.currentCluster,l);if(!u)break;let d=Na(c),m=H(c),f=m>>1&3,p=!!(m&128),g=U(c,c.remainingLength),h=u.track.decodingInstructions.length>0;u.blocks.push({timestamp:d,duration:0,isKeyFrame:p,data:g,lacing:f,decoded:!h,postProcessed:!1,mainAdditional:null})}break;case 160:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,s)),this.currentBlock=null}break;case 161:{if(!this.currentCluster)break;let c=e.slice(o,s),l=Wn(c);if(l===null||c.remainingLength<3)break;let u=this.getTrackDataInCluster(this.currentCluster,l);if(!u)break;let d=Na(c),f=H(c)>>1&3,p=U(c,c.remainingLength),g=u.track.decodingInstructions.length>0;this.currentBlock={timestamp:d,duration:0,isKeyFrame:!0,data:p,lacing:f,decoded:!g,postProcessed:!1,mainAdditional:null},u.blocks.push(this.currentBlock)}break;case 30113:this.readContiguousElements(e.slice(o,s));break;case 166:{let c=this.currentBlock;if(!c)break;let l={addId:1,data:null};this.currentBlockAdditional=l,this.readContiguousElements(e.slice(o,s)),l.data&&l.addId===1&&(c.mainAdditional=l.data),this.currentBlockAdditional=null}break;case 165:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=U(e,s)}break;case 238:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=s===0?1:X(e,s)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=X(e,s)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case 29555:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,s));break;case 25536:this.readContiguousElements(e.slice(o,s));break;case 26826:(s===0?50:X(e,s))!==50&&(this.currentTagTargetIsMovie=!1);break;case 25541:case 25545:case 25540:case 25542:this.currentTagTargetIsMovie=!1;break;case 26568:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,s))}break;case 17827:this.currentSimpleTagName=Yi(e,s);break;case 17543:{if(!this.currentSimpleTagName)break;let c=Yi(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case 17541:{if(!this.currentSimpleTagName)break;let c=U(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case 24999:{if(!this.currentSegment||this.currentAttachedFile)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,s));let c=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(c.raw??={},c.raw[this.currentAttachedFile.fileUid.toString()]=new Lr(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let l=this.currentAttachedFile.fileName,u="unknown";if(l){let d=l.toLowerCase();d.startsWith("cover.")?u="coverFront":d.startsWith("back.")&&(u="coverBack")}c.images??=[],c.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:u,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case 18094:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=su(e,s)}break;case 18030:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Yi(e,s)}break;case 18016:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=xi(e,s)}break;case 18012:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=U(e,s)}break;case 18046:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Yi(e,s)}break;case 28032:{let c=this.currentTrack;if(!c)break;this.readContiguousElements(e.slice(o,s)),c.decodingInstructions.sort((l,u)=>u.order-l.order)}break;case 25152:{let c=this.currentTrack;if(!c)break;let l={order:0,scope:1,data:null};this.currentDecodingInstruction=l,this.readContiguousElements(e.slice(o,s)),l.data&&c.decodingInstructions.push(l),this.currentDecodingInstruction=null}break;case 20529:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=X(e,s)}break;case 20530:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=s===0?1:X(e,s)}break;case 20532:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:0,settings:null},this.readContiguousElements(e.slice(o,s))}break;case 16980:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=X(e,s)}break;case 16981:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=U(e,s)}break;case 20533:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=o+s,!0}decodeBlockData(e,r){b(e.decodingInstructions.length>0);let n=r;for(let a of e.decodingInstructions)switch(b(a.data),a.data.type){case"decompress":switch(a.data.algorithm){case 3:if(a.data.settings&&a.data.settings.length>0){let s=a.data.settings,o=new Uint8Array(s.length+n.length);o.set(s,0),o.set(n,s.length),n=o}break;default:}break;default:}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":n.title??=r;break;case"description":n.description??=r;break;case"artist":n.artist??=r;break;case"album":n.album??=r;break;case"album_artist":n.albumArtist??=r;break;case"genre":n.genre??=r;break;case"bpm":{let a=Number.parseInt(r,10);Number.isInteger(a)&&a>0&&(n.beatsPerMinute??=a)}break;case"comment":n.comment??=r;break;case"lyrics":n.lyrics??=r;break;case"date":{let a=Kt(r);a&&(n.date??=a)}break;case"track_number":case"part_number":{let a=r.split("/"),s=Number.parseInt(a[0],10),o=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),o&&Number.isInteger(o)&&o>0&&(n.tracksTotal??=o)}break;case"disc_number":case"disc":{let a=r.split("/"),s=Number.parseInt(a[0],10),o=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),o&&Number.isInteger(o)&&o>0&&(n.discsTotal??=o)}break}}getDurationFromMetadata(e){if(e.duration<=0)return null;let r=Math.min(...e.tracks.map(n=>n.codecDelay));return(e.duration-r)/e.timestampFactor}},Wo=class{constructor(t){this.internalTrack=t;this.packetToClusterLocation=new WeakMap}getNumber(){let t=this.internalTrack.demuxer,e=this.internalTrack.trackBacking.getType(),r=0;for(let n of t.segments)for(let a of n.tracks)if(a.trackBacking.getType()===e&&r++,a===this.internalTrack)return r;b(!1)}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,t)}intoTimescale(t){return Fe(t*this.internalTrack.segment.timestampFactor)+this.internalTrack.codecDelay}async getPacket(t,e){let r=this.intoTimescale(t);return this.performClusterLookup(null,n=>{let a=n.trackData.get(this.internalTrack.id);if(!a)return{blockIndex:-1,correctBlockFound:!1};let s=j(a.presentationTimestamps,r,l=>l.timestamp),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<a.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,e)}async getNextPacket(t,e){let r=this.packetToClusterLocation.get(t);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,n=>{if(n===r.cluster){let a=n.trackData.get(this.internalTrack.id);if(r.blockIndex+1<a.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}async getKeyPacket(t,e){let r=this.intoTimescale(t);return this.performClusterLookup(null,n=>{let a=n.trackData.get(this.internalTrack.id);if(!a)return{blockIndex:-1,correctBlockFound:!1};let s=lr(a.presentationTimestamps,l=>a.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=r),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<a.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,e,!0)}async getNextKeyPacket(t,e){let r=this.packetToClusterLocation.get(t);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,n=>{if(n===r.cluster){let a=n.trackData.get(this.internalTrack.id);for(let s=r.blockIndex+1;s<a.blocks.length;s++)if(a.blocks[s].isKeyFrame)return{blockIndex:s,correctBlockFound:!0}}else{let a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let s=a.blocks.findIndex(o=>o.isKeyFrame);return b(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}async fetchPacketInCluster(t,e,r){if(e===-1)return null;let a=t.trackData.get(this.internalTrack.id).blocks[e];if(b(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0),!a.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(a.data.length>=8&&a.data[4]===105&&a.data[5]===99&&a.data[6]===112&&a.data[7]===102)){let p=new Uint8Array(a.data.length+8);N(p).setUint32(0,p.length,!1),p[4]=105,p[5]=99,p[6]=112,p[7]=102,p.set(a.data,8),a.data=p}a.postProcessed=!0}let s=r.metadataOnly?Ae:a.data,{codecDelay:o,segment:c}=this.internalTrack,l=(a.timestamp-o)/c.timestampFactor,u=a.duration/c.timestampFactor,d={};a.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(d.alpha=r.metadataOnly?Ae:a.mainAdditional,d.alphaByteLength=a.mainAdditional.byteLength);let m=new ee(s,a.isKeyFrame?"key":"delta",l,u,t.dataStartPos+e,a.data.byteLength,d);return this.packetToClusterLocation.set(m,{cluster:t,blockIndex:e}),m}async performClusterLookup(t,e,r,n,a,s=!1){let{demuxer:o,segment:c,cuePoints:l,clusterPositionCache:u}=this.internalTrack,d=null,m=-1;if(t){let{blockIndex:h,correctBlockFound:y}=e(t);if(y)return this.fetchPacketInCluster(t,h,a);h!==-1&&(d=t,m=h)}let f=j(l,r,h=>h.time),p=j(u,r,h=>h.startTimestamp),g=1/0;for(;;){for(;f!==-1&&l[f].clusterPosition>=g;)f--;for(;p!==-1&&(u[p].elementStartPos>=g||s&&!u[p].hasKeyFrame);)p--;let h=Math.max(l[f]?.clusterPosition??0,u[p]?.elementStartPos??0)||null,y,k=null;t?h===null||t.elementStartPos>=h?(y=t.elementEndPos,k=t):y=h:y=h??c.clusterSeekStartPos;let T=k?k.elementStartPos:y;for(;(c.elementEndPos===null||y<=c.elementEndPos-lt)&&y<g;){if(k){let P=k.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>n)break;k=null}let S=c.clusterSummaries.get(y);if(S&&!S.trackIds.has(this.internalTrack.id)){y=S.elementEndPos;continue}let w=o.reader.requestSliceRange(y,lt,Yt);if(R(w)&&(w=await w),!w)break;let A=y,C=Vt(w);if(c.elementEndPos===null&&C&&nu.includes(C.id)){c.elementEndPos=A;break}if(!C||!Hn.includes(C.id)&&C.id!==236){let P=await cu(o.reader,A+1,Hn,Math.min(c.elementEndPos??1/0,A+Cf));if(P){y=P;continue}else break}let E=C.id,I=C.size,x=w.filePos;if(E===524531317){k=await o.readCluster(A,c),I=k.elementEndPos-x;let{blockIndex:P,correctBlockFound:v}=e(k);if(v)return this.fetchPacketInCluster(k,P,a);P!==-1&&(d=k,m=P)}I===void 0&&(b(E!==524531317),I=(await No(o.reader,x,Ha,c.elementEndPos)).pos-x),y=x+I}if(h===null||d&&d.elementStartPos>=h)break;g=T,t=null}return d?this.fetchPacketInCluster(d,m,a):null}},uu=class extends Wo{constructor(e){super(e);this.decoderConfigPromise=null}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}getTransformationMatrix(){let e=this.internalTrack.info,r=sr(Is(e.horizontalScale,e.verticalScale),Tn(e.rotation));return Es(r,e.width,e.height)}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=this.internalTrack.codecPrivate,r=this.internalTrack.info.codec==="av1"&&e?hi(e.subarray(4)):null,n=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"&&!r||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(n=await this.getFirstPacket({})),this.internalTrack.info.codec==="av1"&&n&&(r=hi(n.data));let s={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"&&n?hr(n.data):null,hevcType:"hev1",hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&n?br(n.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&n?vn(n.data):null,av1CodecInfo:r,proresCodecInfo:this.internalTrack.info.codec==="prores"&&n?Qs(n.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!wn(this.internalTrack.info.colorSpace)){let c=Do(s);this.internalTrack.info.colorSpace.primaries??=c.primaries,this.internalTrack.info.colorSpace.transfer??=c.transfer,this.internalTrack.info.colorSpace.matrix??=c.matrix,this.internalTrack.info.colorSpace.fullRange??=c.fullRange}let o={codec:Si(s),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o})():null}},du=class extends Wo{constructor(e){super(e);this.decoderConfigPromise=null}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&no(e.data)}return{codec:Nn({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};var Sr=128,Et=10,Kn=["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"],Pf=(i,t)=>{let e=i.filePos;t.raw??={},t.raw.TAG??=U(i,Sr-3),i.filePos=e;let r=qn(i,30);r&&(t.title??=r);let n=qn(i,30);n&&(t.artist??=n);let a=qn(i,30);a&&(t.album??=a);let s=qn(i,4),o=Number.parseInt(s,10);Number.isInteger(o)&&o>0&&(t.date??=Pn(o));let c=U(i,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(t.trackNumber??=d),i.skip(-30),l=qn(i,28),i.skip(2)}else i.skip(-30),l=qn(i,30);l&&(t.comment??=l);let u=H(i);u<Kn.length&&(t.genre??=Kn[u])},qn=(i,t)=>{let e=U(i,t),r=Li(e.indexOf(0),e.length),n=e.subarray(0,r),a="";for(let s=0;s<n.length;s++)a+=String.fromCharCode(n[s]);return a.trimEnd()},Ar=async(i,t)=>{let e=t;for(;;){let r=i.requestSlice(e,Et);if(R(r)&&(r=await r),!r)return e;let n=Yr(r);if(!n)return e;e=r.filePos+n.size}},Yr=i=>{let t=i.filePos,e=ae(i,3),r=H(i),n=H(i),a=H(i),s=B(i);if(e!=="ID3"||r===255||n===255||(s&2155905152)!==0)return i.filePos=t,null;let o=fa(s);return r===4&&a&16&&(o+=Et),{majorVersion:r,revision:n,flags:a,size:o}},Pi=(i,t,e)=>{if(![2,3,4].includes(t.majorVersion)){O._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}if(t.majorVersion===2&&t.flags&64){O._warn("Skipping compressed ID3v2.2 tag");return}let r=t.majorVersion===4&&t.flags&16?t.size-Et:t.size,n=U(i,r),a=new mu(t,n);if(t.flags&128&&t.majorVersion<=3&&a.ununsynchronizeAll(),t.flags&64){if(a.bytes.length<4)return;let c=a.readU32();t.majorVersion===3?a.pos+=c:a.pos+=fa(c)-4}let s=null,o=null;for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let c=a.readId3V2Frame();if(!c)break;let l=Math.min(a.pos+c.size,a.bytes.length),u=l,d=!1,m=!1,f=!1,p=!1,g=!1;if(t.majorVersion===3?(d=!!(c.flags&64),m=!!(c.flags&128),p=!!(c.flags&32)):t.majorVersion===4&&(p=!!(c.flags&64),d=!!(c.flags&4),m=!!(c.flags&8),f=!!(c.flags&2)||!!(t.flags&128),g=!!(c.flags&1)),d){O._warn(`Skipping encrypted ID3v2 frame ${c.id}`),a.pos=l;continue}if(m){O._warn(`Skipping compressed ID3v2 frame ${c.id}`),a.pos=l;continue}p&&(a.pos+=1),g&&(a.pos+=4),f&&(u=a.ununsynchronizeRegion(a.pos,u));let h=a.pos,y=k=>{if(u-a.pos<k)throw new Error(`Invalid ID3v2 ${c.id} frame: too short.`)};if(e.raw??={},c.id==="TXXX"||c.id==="TXX"){let k=e.raw[c.id]??={};y(1);let T=a.readId3V2TextEncoding(),S=a.readId3V2Text(T,u),w=a.readId3V2Text(T,u);k[S]??=w}else if(c.id[0]==="T")e.raw[c.id]??=a.readId3V2EncodingAndText(u);else{let k=a.readBytes(u-a.pos),T=e.raw[c.id];T instanceof Uint8Array?e.raw[c.id]=[T,k]:Array.isArray(T)?T.push(k):e.raw[c.id]??=k}switch(a.pos=h,c.id){case"TIT2":case"TT2":e.title??=a.readId3V2EncodingAndText(u);break;case"TIT3":case"TT3":e.description??=a.readId3V2EncodingAndText(u);break;case"TPE1":case"TP1":e.artist??=a.readId3V2EncodingAndText(u);break;case"TALB":case"TAL":e.album??=a.readId3V2EncodingAndText(u);break;case"TPE2":case"TP2":e.albumArtist??=a.readId3V2EncodingAndText(u);break;case"TRCK":case"TRK":{let T=a.readId3V2EncodingAndText(u).split("/"),S=Number.parseInt(T[0],10),w=T[1]&&Number.parseInt(T[1],10);Number.isInteger(S)&&S>0&&(e.trackNumber??=S),w&&Number.isInteger(w)&&w>0&&(e.tracksTotal??=w)}break;case"TPOS":case"TPA":{let T=a.readId3V2EncodingAndText(u).split("/"),S=Number.parseInt(T[0],10),w=T[1]&&Number.parseInt(T[1],10);Number.isInteger(S)&&S>0&&(e.discNumber??=S),w&&Number.isInteger(w)&&w>0&&(e.discsTotal??=w)}break;case"TCON":case"TCO":{let k=a.readId3V2EncodingAndText(u),T=/^\((\d+)\)/.exec(k);if(T){let S=Number.parseInt(T[1]);if(Kn[S]!==void 0){e.genre??=Kn[S];break}}if(T=/^\d+$/.exec(k),T){let S=Number.parseInt(T[0]);if(Kn[S]!==void 0){e.genre??=Kn[S];break}}e.genre??=k}break;case"TDRC":{let k=Kt(a.readId3V2EncodingAndText(u));k&&(e.date??=k)}break;case"TYER":case"TYE":{let k=a.readId3V2EncodingAndText(u),T=Number.parseInt(k,10);Number.isInteger(T)&&(s??=T)}break;case"TDAT":case"TDA":o??=a.readId3V2EncodingAndText(u);break;case"TBPM":case"TBP":{let k=a.readId3V2EncodingAndText(u),T=Number.parseInt(k,10);Number.isInteger(T)&&T>0&&(e.beatsPerMinute??=T)}break;case"USLT":case"ULT":{y(4);let k=a.readId3V2TextEncoding();a.pos+=3,a.readId3V2Text(k,u),e.lyrics??=a.readId3V2Text(k,u)}break;case"COMM":case"COM":{y(4);let k=a.readId3V2TextEncoding();a.pos+=3,a.readId3V2Text(k,u)===""&&(e.comment??=a.readId3V2Text(k,u))}break;case"APIC":case"PIC":{y(1);let k=a.readId3V2TextEncoding(),T;if(t.majorVersion===2){y(3);let C=a.readAscii(3);T=C==="PNG"?"image/png":C==="JPG"?"image/jpeg":"image/*"}else T=a.readId3V2Text(0,u);y(1);let S=a.readU8(),w=a.readId3V2Text(k,u).trimEnd(),A=u-a.pos;if(A>=0){let C=a.readBytes(A);e.images||(e.images=[]),e.images.push({data:C,mimeType:T,kind:S===3?"coverFront":S===4?"coverBack":"unknown",description:w})}}break;default:a.pos+=c.size;break}a.pos=l}if(s!==null){let c=Pn(s),l=/^(0[1-9]|[12]\d|3[01])(0[1-9]|1[0-2])$/.exec(o??"");if(l){let u=Number(l[1]),d=Pn(s,Number(l[2])-1,u);d.getUTCDate()===u&&(c=d)}Number.isNaN(c.getTime())||(e.date??=c)}},mu=class{constructor(t,e){this.header=t;this.bytes=e;this.pos=0;this.ownsBytes=!1;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let t=new Uint8Array(this.bytes.length),e=0;for(let r=0;r<this.bytes.length;r++){let n=this.bytes[r];t[e++]=n,n===255&&r!==this.bytes.length-1&&this.bytes[r+1]===0&&r++}this.bytes=t.subarray(0,e),this.view=N(this.bytes)}ununsynchronizeRegion(t,e){this.ownsBytes||(this.bytes=this.bytes.slice(),this.view=N(this.bytes),this.ownsBytes=!0);let r=t;for(let n=t;n<e;n++){let a=this.bytes[n];this.bytes[r++]=a,a===255&&n!==e-1&&this.bytes[n+1]===0&&n++}return r}readBytes(t){let e=this.bytes.subarray(this.pos,this.pos+t);return this.pos+=t,e}readU8(){let t=this.view.getUint8(this.pos);return this.pos+=1,t}readU16(){let t=this.view.getUint16(this.pos,!1);return this.pos+=2,t}readU24(){let t=this.view.getUint16(this.pos,!1),e=this.view.getUint8(this.pos+2);return this.pos+=3,t*256+e}readU32(){let t=this.view.getUint32(this.pos,!1);return this.pos+=4,t}readAscii(t){let e="";for(let r=0;r<t;r++)e+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=t,e}readId3V2Frame(){if(this.header.majorVersion===2){let t=this.readAscii(3);if(t==="\0\0\0")return null;let e=this.readU24();return{id:t,size:e,flags:0}}else{let t=this.readAscii(4);if(t==="\0\0\0\0")return null;let e=this.readU32(),r=(e&2155905152)===0,n=this.header.majorVersion===4&&r?fa(e):e,a=this.readU16(),s=this.pos,o=c=>{let l=s+c;if(l>this.bytes.length)return!1;if(l<=this.bytes.length-this.frameHeaderSize()){this.pos=l;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(r&&!o(n)){let c=this.header.majorVersion===4?e:fa(e);o(c)&&(n=c)}return this.pos=s,{id:t,size:n,flags:a}}}readId3V2TextEncoding(){let t=this.readU8();if(t>3)throw new Error(`Unsupported text encoding: ${t}`);return t}readId3V2Text(t,e){let r=this.pos,n=this.readBytes(e-this.pos);switch(t){case 0:{let a="";for(let s=0;s<n.length;s++){let o=n[s];if(o===0){this.pos=r+s+1;break}a+=String.fromCharCode(o)}return a}case 1:if(n[0]===255&&n[1]===254){let a=new oi("utf-16le"),s=Li(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else if(n[0]===254&&n[1]===255){let a=new oi("utf-16be"),s=Li(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else{if(n[0]===0&&n[1]===0)return this.pos=r+2,"";{let a=Li(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),be.decode(n.subarray(0,a))}}case 2:{let a=new oi("utf-16be"),s=Li(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(0,s))}case 3:{let a=Li(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),be.decode(n.subarray(0,a))}}}readId3V2EncodingAndText(t){if(this.pos>=t)return"";let e=this.readId3V2TextEncoding();return this.readId3V2Text(e,t)}},Ci=class{constructor(t){this.helper=new Uint8Array(8);this.helperView=N(this.helper);this.writer=t}writeId3V2Tag(t){let e=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let r=this.writer.getPos(),n=new Set;for(let{key:o,value:c}of qt(t))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),n.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),n.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),n.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),n.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),n.add("TPE2");break;case"trackNumber":{let l=t.tracksTotal!==void 0?`${c}/${t.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",l),n.add("TRCK")}break;case"discNumber":{let l=t.discsTotal!==void 0?`${c}/${t.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",l),n.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),n.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),n.add("TDRC");break;case"beatsPerMinute":this.writeId3V2TextFrame("TBPM",`${c}`),n.add("TBPM");break;case"lyrics":this.writeId3V2LyricsFrame(c),n.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),n.add("COMM");break;case"images":{let l={coverFront:3,coverBack:4,unknown:0};for(let u of c){let d=l[u.kind]??0,m=u.description??"";this.writeId3V2ApicFrame(u.mimeType,d,m,u.data)}n.add("APIC")}break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:Z(o)}if(t.raw)for(let o in t.raw){let c=t.raw[o];if(c==null||o.length!==4||n.has(o))continue;let l;if(typeof c=="string"){let u;if(Ht(c)){u=new Uint8Array(c.length+2),u[0]=0;for(let m=0;m<c.length;m++)u[m+1]=c.charCodeAt(m)}else{let m=Y.encode(c);u=new Uint8Array(m.byteLength+2),u[0]=3,u.set(m,1)}l=[u]}else if(c instanceof Uint8Array)l=[c];else if(Array.isArray(c)&&c.every(u=>u instanceof Uint8Array))l=c;else if(o==="TXXX"&&Vs(c)){for(let u in c){let d=c[u],m=Ht(u)&&Ht(d),f=m?null:Y.encode(u),p=m?null:Y.encode(d),g=m?u.length:f.byteLength,h=m?d.length:p.byteLength,y=1+g+1+h+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(y),this.writeU16(0),this.writeU8(m?0:3),m?(this.writeIsoString(u),this.writeIsoString(d)):(this.writer.write(f),this.writeU8(0),this.writer.write(p),this.writeU8(0))}continue}else continue;for(let u of l)this.writeAscii(o),this.writeSynchsafeU32(u.byteLength),this.writeU16(0),this.writer.write(u)}let a=this.writer.getPos(),s=a-r;return this.writer.seek(e+6),this.writeSynchsafeU32(s),this.writer.seek(a),s+10}writeU8(t){this.helper[0]=t,this.writer.write(this.helper.subarray(0,1))}writeU16(t){this.helperView.setUint16(0,t,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(t){for(let e=0;e<t.length;e++)this.helper[e]=t.charCodeAt(e);this.writer.write(this.helper.subarray(0,t.length))}writeSynchsafeU32(t){this.writeU32(rm(t))}writeIsoString(t){let e=new Uint8Array(t.length+1);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);this.writer.write(e)}writeUtf8String(t){let e=Y.encode(t);this.writer.write(e),this.writeU8(0)}writeId3V2TextFrame(t,e){let r=Ht(e),a=1+(r?e.length:Y.encode(e).byteLength)+1;this.writeAscii(t),this.writeSynchsafeU32(a),this.writeU16(0),this.writeU8(r?0:3),r?this.writeIsoString(e):this.writeUtf8String(e)}writeId3V2LyricsFrame(t){let e=Ht(t),r=e?t.length:Y.encode(t).byteLength,n="",a=4+n.length+1+r+1;this.writeAscii("USLT"),this.writeSynchsafeU32(a),this.writeU16(0),this.writeU8(e?0:3),this.writeAscii("und"),e?(this.writeIsoString(n),this.writeIsoString(t)):(this.writeUtf8String(n),this.writeUtf8String(t))}writeId3V2CommentFrame(t){let e=Ht(t),r=e?t.length:Y.encode(t).byteLength,n="",a=4+n.length+1+r+1;this.writeAscii("COMM"),this.writeSynchsafeU32(a),this.writeU16(0),this.writeU8(e?0:3),this.writeU8(117),this.writeU8(110),this.writeU8(100),e?(this.writeIsoString(n),this.writeIsoString(t)):(this.writeUtf8String(n),this.writeUtf8String(t))}writeId3V2ApicFrame(t,e,r,n){let a=Ht(t)&&Ht(r),s=a?t.length:Y.encode(t).byteLength,o=a?r.length:Y.encode(r).byteLength,c=1+s+1+1+o+1+n.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(a?0:3),a?this.writeIsoString(t):this.writeUtf8String(t),this.writeU8(e),a?this.writeIsoString(r):this.writeUtf8String(r),this.writer.write(n)}};var Wa=async(i,t,e,r)=>{let n=t;for(;;){let a=await qo(i,n,t+e,r);if(!a)return null;let{header:s}=a,o=mi(s.mpegVersionId,s.channel),c=i.requestSlice(a.startPos+o,4);if(R(c)&&(c=await c),c){let d=B(c);if(d===qr||d===di)return a}let l=a.startPos+s.totalSize;if(l===i.fileSize)return a;if(l+Sr===i.fileSize){let d=i.requestSlice(l,3);if(R(d)&&(d=await d),d&&ae(d,3)==="TAG")return a}let u=await qo(i,l,l+4);if(u&&u.header.channel===s.channel&&u.header.sampleRate===s.sampleRate)return a;n=a.startPos+1}},qo=async(i,t,e,r=null)=>{let a=t;for(;e===null||a<e;){let s=e!==null?Math.min(65536,e-a):65536,o=i.requestSliceRange(a,4,s);if(R(o)&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,l=B(o),u=i.fileSize!==null?i.fileSize-a:null,d=fr(l,u);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&fi(d.header.channel)===fi(r.channel)))return{header:d.header,startPos:a};o.filePos=c+d.bytesAdvanced,a=o.filePos}}return null};var Ko=32,Go=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.firstFrameHeaderPos=null;this.xingFrameHeader=null;this.xingFrameHeaderPos=null;this.loadedSamples=[];this.metadataTags=null;this.xingData=null;this.trackBackings=[];this.readingMutex=new Ee;this.lastSampleLoaded=!1;this.lastLoadedPos=0;this.nextTimestampInSamples=0;this.primingDelay=0;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new fu(this)]})()}async advanceReader(){let e;if(this.lastLoadedPos===0){let l=await Ar(this.reader,0);e=await Wa(this.reader,l,4096,null)}else if(e=await qo(this.reader,this.lastLoadedPos,this.lastLoadedPos+2,this.firstFrameHeader),!e){if(this.firstFrameHeader){let u=this.reader.requestSlice(this.lastLoadedPos,5);if(R(u)&&(u=await u),u)for(let d=0;d<2;d++){u.filePos=this.lastLoadedPos+d;let{header:m}=fr(B(u),null);if(m&&m.sampleRate!==this.firstFrameHeader.sampleRate){O._warn(`The sample rate changes mid-stream (from ${this.firstFrameHeader.sampleRate} Hz to ${m.sampleRate} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}}}let l=await Ar(this.reader,this.lastLoadedPos+1);e=await Wa(this.reader,l,2**16,this.firstFrameHeader)}if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=mi(r.mpegVersionId,r.channel),a=this.reader.requestSlice(e.startPos+n,4);if(R(a)&&(a=await a),a){let l=B(a);if(l===qr||l===di){if(this.xingFrameHeader||(this.xingFrameHeader=r,this.xingFrameHeaderPos=e.startPos),!this.xingData){let d=this.reader.requestSlice(e.startPos+n+4,8);if(R(d)&&(d=await d),d){let m=U(d,8),f=N(m),p=f.getUint32(0,!1);this.xingData={isVbr:l===qr,frameCount:p&1?f.getUint32(4,!1):null};let g=e.startPos+n+8+(p&1?4:0)+(p&2?4:0)+(p&4?100:0)+(p&8?4:0);if(!this.firstFrameHeader&&g+24<=e.startPos+r.totalSize){let h=this.reader.requestSlice(g,24);if(R(h)&&(h=await h),h){let y=U(h,24),k=String.fromCharCode(...y.subarray(0,4));(k==="LAME"||k==="Lavf"||k==="Lavc")&&(this.primingDelay=(y[21]<<4|y[22]>>4)+529,this.nextTimestampInSamples=-this.primingDelay)}}}}return}}let s=r.layer===1?this.reader.requestSlice(e.startPos+4+32,18):null;if(R(s)&&(s=await s),s){let l=B(s),u=me(s);if(l===em&&u===1){if(this.xingFrameHeader||(this.xingFrameHeader=r,this.xingFrameHeaderPos=e.startPos),!this.xingData){s.skip(8);let d=B(s);this.xingData={isVbr:!0,frameCount:d}}return}}this.firstFrameHeader||(this.firstFrameHeader=r,this.firstFrameHeaderPos=e.startPos);let o=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,c={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:o,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(c),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,n=!1;for(;;){let a=this.reader.requestSlice(r,Et);if(R(a)&&(a=await a),!a)break;let s=Yr(a);if(!s)break;n=!0;let o=this.reader.requestSlice(a.filePos,s.size);if(R(o)&&(o=await o),!o)break;Pi(o,s,this.metadataTags),r=a.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=Sr){let a=this.reader.requestSlice(this.reader.fileSize-Sr,Sr);R(a)&&(a=await a),b(a),ae(a,3)==="TAG"&&Pf(a,this.metadataTags)}return this.metadataTags}finally{e()}}},fu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getTimeResolution(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let t=this.demuxer;if(b(t.firstFrameHeader!==null),b(t.firstFrameHeaderPos!==null),t.xingData&&t.xingData.frameCount!==null)return(t.xingData.frameCount*t.firstFrameHeader.audioSamplesInFrame-t.primingDelay)/t.firstFrameHeader.sampleRate;if(!t.xingData?.isVbr&&t.reader.fileSize!==null){let e=t.reader.fileSize;if(e-t.firstFrameHeaderPos>=Sr){let a=t.reader.requestSlice(e-Sr,3);R(a)&&(a=await a),b(a),ae(a,3)==="TAG"&&(e-=Sr)}if(e-t.firstFrameHeaderPos>=Ko){let a=t.reader.requestSlice(e-Ko,Ko);if(R(a)&&(a=await a),b(a),ae(a,8)==="APETAGEX"){a.skip(4);let s=Zt(a);a.skip(4);let c=(Zt(a)&1<<31)!==0;if(e-=s+(c?Ko:0),e<t.firstFrameHeaderPos)throw new Error("Invalid APE tag size.")}}let r=tm(t.firstFrameHeader.lowSamplingFrequency,t.firstFrameHeader.layer,t.firstFrameHeader.bitrate,t.firstFrameHeader.sampleRate),n=(e-t.firstFrameHeaderPos)/r;return(Math.round(n)*t.firstFrameHeader.audioSamplesInFrame-t.primingDelay)/t.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ce}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.firstFrameHeader),fi(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Ve}}async getDecoderConfig(){return b(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:fi(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(t,e){if(t===-1)return null;let r=this.demuxer.loadedSamples[t];if(!r)return null;let n;if(e.metadataOnly)n=Ae;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(R(a)&&(a=await a),!a)return null;n=U(a,r.dataSize)}return new ee(n,"key",r.timestamp,r.duration,t,r.dataSize)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=Vr(this.demuxer.loadedSamples,t.timestamp,s=>s.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let a=n+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,e)}finally{r()}}async getPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=this.getSampleRate(),a=Fe(t*n)/n;for(;;){let s=j(this.demuxer.loadedSamples,a,o=>o.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,e);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var qa=1399285583,ag=79764919,Ef=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^ag:t<<1;Ef[i]=t>>>0&4294967295}var If=i=>{let t=N(i),e=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n<i.length;n++){let a=i[n];r=(r<<8^Ef[r>>>24^a])>>>0}return t.setUint32(22,e,!0),r},Ka=(i,t,e)=>{let r=0,n=null;if(i.length>0)if(t.codec==="vorbis"){b(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<<Bd(a-1))-1<<1,c=(i[0]&o)>>1;if(c>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=e??t.vorbisInfo.blocksizes[0],u=t.vorbisInfo.modeBlockflags[c];if(n=t.vorbisInfo.blocksizes[u],u===1){let d=(o|1)+1,m=i[0]&d?1:0;l=t.vorbisInfo.blocksizes[m]}r=l+n>>2}else t.codec==="opus"&&(r=js(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:n}},Qo=i=>{let t="audio/ogg";if(i.codecStrings.length>0){let e=[...new Set(i.codecStrings)];t+=`; codecs="${e.join(", ")}"`}return t};var Zr=27,en=282,jo=en+255*255,Qn=i=>{let t=i.filePos;if(Zt(i)!==qa)return null;i.skip(1);let r=H(i),n=_f(i),a=Zt(i),s=Zt(i),o=Zt(i),c=H(i);if(c===0||i.remainingLength<c)return null;let l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=H(i);let u=27+c,d=l.reduce((f,p)=>f+p,0),m=u+d;return{headerStartPos:t,totalSize:m,dataStartPos:t+u,dataSize:d,headerType:r,granulePosition:n,serialNumber:a,sequenceNumber:s,checksum:o,lacingValues:l}},vf=(i,t,e)=>{for(;i.filePos<t-3;){let r=Zt(i),n=r&255,a=r>>>8&255,s=r>>>16&255,o=r>>>24&255,c=79;if(!(n!==c&&a!==c&&s!==c&&o!==c)){if(i.skip(-4),r===qa){if(e===void 0||i.filePos+18>i.end)return!0;i.skip(14);let l=Zt(i);if(i.skip(-18),l===e)return!0}i.skip(1)}}return!1};var Rf=64,sg=30,og=19,Xo=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.bitstreams=[];this.trackBackings=[];this.metadataTags={};this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Zr,en);if(R(r)&&(r=await r),!r)break;let n=Qn(r);if(!n||!!!(n.headerType&2))break;if(this.bitstreams.length===Rf)throw new Error(`Too many (> ${Rf}) logical bitstreams.`);this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let r of this.bitstreams){let n=await this.readPacket(r.bosPage,0);n&&(n.data.byteLength>=sg&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,r):n.data.byteLength>=og&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,r),r.codecInfo.codec!==null&&this.trackBackings.push(new pu(r,this)))}})()}async readVorbisMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let a=await this.readPacket(n.startPage,n.startSegmentIndex);if(!a||(n=await this.findNextPacketStart(a),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||a.data[0]!==3||s.data[0]!==5)return;let o=N(e.data),c=o.getUint8(11),l=o.getUint32(12,!0);if(c===0||l===0)throw new Error("Invalid Vorbis identification header: channel count and sample rate must not be 0.");let u=[],d=p=>{for(;u.push(Math.min(255,p)),!(p<255);)p-=255};d(e.data.length),d(a.data.length);let m=new Uint8Array(1+u.length+e.data.length+a.data.length+s.data.length);m[0]=2,m.set(u,1),m.set(e.data,1+u.length),m.set(a.data,1+u.length+e.data.length),m.set(s.data,1+u.length+e.data.length+a.data.length),r.codecInfo.codec="vorbis",r.description=m,r.lastMetadataPacket=s,r.numberOfChannels=c,r.sampleRate=l;let f=o.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Xs(s.data).modeBlockflags},ba(a.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let a=await this.readPacket(n.startPage,n.startSegmentIndex);if(!a)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=a;let s=yr(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=tt,r.codecInfo.opusInfo={preSkip:s.preSkip},ba(a.data.subarray(8),this.metadataTags)}async readPacket(e,r){b(r<e.lacingValues.length);let n=0;for(let m=0;m<r;m++)n+=e.lacingValues[m];let a=e,s=n,o=r,c=[];e:for(;;){let m=this.reader.requestSlice(a.dataStartPos,a.dataSize);if(R(m)&&(m=await m),!m)return null;let f=U(m,a.dataSize);for(;;){if(o===a.lacingValues.length){c.push(f.subarray(n,s));break}let g=a.lacingValues[o];if(s+=g,g<255){c.push(f.subarray(n,s));break e}o++}let p=a.headerStartPos+a.totalSize;for(;;){let g=this.reader.requestSliceRange(p,Zr,en);if(R(g)&&(g=await g),!g)return null;let h=Qn(g);if(!h)return null;if(a=h,a.serialNumber===e.serialNumber)break;p=a.headerStartPos+a.totalSize}n=0,s=0,o=0}let l=c.reduce((m,f)=>m+f.length,0);if(l===0)throw new Error("Invalid Ogg stream: empty packets are only allowed at the very end of a stream.");let u=new Uint8Array(l),d=0;for(let m=0;m<c.length;m++){let f=c[m];u.set(f,d),d+=f.length}return{data:u,endPage:a,endSegmentIndex:o}}async findNextPacketStart(e){let r=e.endPage,n=e.endSegmentIndex+1;if(n===r.lacingValues.length){if(!!(r.headerType&4))return null;let o=r.headerStartPos+r.totalSize;for(;;){let c=this.reader.requestSliceRange(o,Zr,en);if(R(c)&&(c=await c),!c)return null;let l=Qn(c);if(!l)return null;if(l.serialNumber===r.serialNumber){r=l,n=0;break}o=l.headerStartPos+l.totalSize}}return!!(r.headerType&4)&&n===r.lacingValues.length-1&&r.lacingValues[n]===0?null:{startPage:r,startSegmentIndex:n}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return Qo({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},pu=class{constructor(t,e){this.bitstream=t;this.demuxer=e;this.encodedPacketToMetadata=new WeakMap;this.sequentialScanCache=[];this.sequentialScanMutex=new Ee;this.firstTimestampInSamplesPromise=null;let r=t.codecInfo.codec;b(r),r==="vorbis"?this.internalSampleRate=t.sampleRate:r==="opus"?this.internalSampleRate=tt:(Z(r),b(!1))}getType(){return"audio"}getNumber(){let t=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return b(t!==-1),t+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return b(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 ce}getDisposition(){return{...Ve,primary:!1}}granulePositionToTimestampInSamples(t){let e=this.bitstream.codecInfo.codec;if(b(e),e==="vorbis")return t;if(e==="opus")return b(this.bitstream.codecInfo.opusInfo),t-this.bitstream.codecInfo.opusInfo.preSkip;Z(e),b(!1)}createEncodedPacketFromOggPacket(t,e,r){if(!t)return null;let{durationInSamples:n,vorbisBlockSize:a}=Ka(t.data,this.bitstream.codecInfo,e.vorbisLastBlocksize),s=new ee(r.metadataOnly?Ae:t.data,"key",e.timestampInSamples/this.internalSampleRate,n/this.internalSampleRate,t.endPage.headerStartPos+t.endSegmentIndex,t.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:t,timestampInSamples:e.timestampInSamples,durationInSamples:n,vorbisLastBlockSize:e.vorbisLastBlocksize,vorbisBlockSize:a}),s}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??=(async()=>{let t=this.granulePositionToTimestampInSamples(0);b(this.bitstream.lastMetadataPacket);let e=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!e)return t;let r=null,n=0,a=null,s=null;for(;e;){let u=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);if(!u||(r??=u.endPage,u.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:d,vorbisBlockSize:m}=Ka(u.data,this.bitstream.codecInfo,s);n+=d,a??=d,s=m,e=await this.demuxer.findNextPacketStart(u)}if(!r)return t;b(a!==null);let o=r.granulePosition-n;if(r.granulePosition!==-1&&!(r.headerType&4))return t+o;let c=this.bitstream.codecInfo.codec;b(c);let l;return c==="vorbis"?l=-a:c==="opus"?l=0:(Z(c),b(!1)),t+Math.max(o,l)})()}async getFirstPacket(t){b(this.bitstream.lastMetadataPacket);let e=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!e)return null;let r=await this.getFirstTimestampInSamples(),n=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:r,vorbisLastBlocksize:null},t)}async getNextPacket(t,e){let r=this.encodedPacketToMetadata.get(t);if(!r)throw new Error("Packet was not created from this track.");let n=await this.demuxer.findNextPacketStart(r.packet);if(!n)return null;let a=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},e)}async getPacket(t,e){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(t,e);let r=Fe(t*this.internalSampleRate),n=await this.getFirstTimestampInSamples();if(r===n)return this.getFirstPacket(e);if(r<n)return null;b(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,o=this.demuxer.reader.fileSize,c=[s];e:for(;s.headerStartPos+s.totalSize<o;){let T=s.headerStartPos,S=Math.floor((T+o)/2),w=S;for(;;){let A=Math.min(w+jo,o-Zr),C=this.demuxer.reader.requestSlice(w,Math.max(A-w,0));if(R(C)&&(C=await C),!C||!vf(C,A,this.bitstream.serialNumber)){if(o<=S+Zr)break e;o=S+Zr;continue e}let E=C.filePos,I=this.demuxer.reader.requestSliceRange(E,Zr,en);R(I)&&(I=await I);let x=I&&Qn(I);if(!x||x.serialNumber!==this.bitstream.serialNumber){w=E+4;continue}if(x.granulePosition===-1){w=x.headerStartPos+x.totalSize;continue}this.granulePositionToTimestampInSamples(x.granulePosition)>r||x.headerStartPos+x.totalSize>this.demuxer.reader.fileSize?o=x.headerStartPos:(s=x,c.push(x));continue e}}let l=a.startPage;for(let T of c){if(T.granulePosition===s.granulePosition)break;(!l||T.headerStartPos>l.headerStartPos)&&(l=T)}let u=l,d=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===s.granulePosition);){let T=u.headerStartPos+u.totalSize,S=this.demuxer.reader.requestSliceRange(T,Zr,en);R(S)&&(S=await S);let w=S&&Qn(S);if(!w){u=s,d.push(s);break}u=w,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}let m=null,f,p,g=u,h=0;if(u.headerStartPos===a.startPage.headerStartPos)f=n,p=!0,m=0;else{b(u.granulePosition!==-1),f=0,p=!1;for(let w=u.lacingValues.length-1;w>=0;w--)if(u.lacingValues[w]<255){m=w+1;break}if(m===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=m-1;let T={data:Ae,endPage:g,endSegmentIndex:h},S=await this.demuxer.findNextPacketStart(T);if(S){let w=Mf(d,u,m);b(w);let A=Ff(d,w.page,w.segmentIndex);A?(u=A.page,m=A.segmentIndex):(u=S.startPage,m=S.startSegmentIndex,f=this.granulePositionToTimestampInSamples(g.granulePosition),p=!0)}else for(;;){let w=Mf(d,u,m);if(!w)break;let A=Ff(d,w.page,w.segmentIndex);if(!A)break;if(u=A.page,m=A.segmentIndex,w.page.headerStartPos!==g.headerStartPos){g=w.page,h=w.segmentIndex;break}}}let y=null,k=null;for(;u!==null;){b(m!==null);let T=await this.demuxer.readPacket(u,m);if(!T)break;if(!(u.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let A=this.createEncodedPacketFromOggPacket(T,{timestampInSamples:f,vorbisLastBlocksize:k?.vorbisBlockSize??null},e);b(A);let C=this.encodedPacketToMetadata.get(A);if(b(C),!p&&T.endPage.headerStartPos===g.headerStartPos&&T.endSegmentIndex===h?(f=this.granulePositionToTimestampInSamples(g.granulePosition),p=!0,A=this.createEncodedPacketFromOggPacket(T,{timestampInSamples:f-C.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},e),b(A),C=this.encodedPacketToMetadata.get(A),b(C)):f+=C.durationInSamples,y=A,k=C,p&&(f>r||C.timestampInSamples===r))break}let w=await this.demuxer.findNextPacketStart(T);if(!w)break;u=w.startPage,m=w.startSegmentIndex}return y}async getPacketSequential(t,e){let r=await this.sequentialScanMutex.acquire();try{let n=Fe(t*this.internalSampleRate);t=n/this.internalSampleRate;let a=j(this.sequentialScanCache,n,c=>c.timestampInSamples),s;if(a!==-1){let c=this.sequentialScanCache[a];s=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},e)}else if(s=await this.getFirstPacket(e),s&&s.timestamp>t)return null;let o=0;for(;s&&s.timestamp<t;){let c=await this.getNextPacket(s,e);if(!c||c.timestamp>t)break;if(s=c,o++,o===100){o=0;let l=this.encodedPacketToMetadata.get(s);b(l),this.sequentialScanCache.length>0&&b(J(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}},Ff=(i,t,e)=>{let r=t,n=e;e:for(;;){for(n--,n;n>=0;n--)if(r.lacingValues[n]<255){n++;break e}if(b(n===-1),!(r.headerType&1)){n=0;break}let s=El(i,o=>o.headerStartPos<r.headerStartPos);if(!s)return null;r=s,n=r.lacingValues.length}if(b(n!==-1),n===r.lacingValues.length){let a=i[i.indexOf(r)+1];b(a),r=a,n=0}return{page:r,segmentIndex:n}},Mf=(i,t,e)=>{if(e>0)return{page:t,segmentIndex:e-1};let r=El(i,n=>n.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var $o=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.dataSizeCapped=!1;this.dataSizeIsPlaceholder=!1;this.audioInfo=null;this.trackBackings=[];this.metadataTags={};this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);R(e)&&(e=await e),b(e);let r=ae(e,4),n=r!=="RIFX",a=r==="RF64",s=Jr(e,n),o=!a&&s===0,c=a||o||s===4294967295?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(ae(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let u=0,d=null,m=e.filePos;for(;c===null||m<c;){let p=this.reader.requestSlice(m,8);if(R(p)&&(p=await p),!p)break;let g=ae(p,4),h=Jr(p,n),y=p.filePos;if(a&&u===0&&g!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(g==="fmt ")await this.parseFmtChunk(y,h,n);else if(g==="data"){if(d??=h,(o&&d===0||!a&&d===4294967295)&&(d=Number.MAX_SAFE_INTEGER,h=d),this.dataSizeIsPlaceholder=d===Number.MAX_SAFE_INTEGER,a&&(h=d),this.dataStart=p.filePos,this.dataSize=Math.max(Math.min(d,(c??1/0)-this.dataStart),0),this.reader.fileSize===null)break}else if(g==="ds64"){let k=this.reader.requestSlice(y,h);if(R(k)&&(k=await k),!k)break;if(h<16)throw new Error('Invalid RF64 file: "ds64" chunk is too small.');let T=Math.min(gu(k,n),Number.MAX_SAFE_INTEGER);d=Math.min(gu(k,n),Number.MAX_SAFE_INTEGER),o=T===0,c=o?this.reader.fileSize:Math.min(T+8,this.reader.fileSize??1/0)}else g==="LIST"?await this.parseListChunk(y,h,n):(g==="ID3 "||g==="id3 ")&&await this.parseId3Chunk(y,h);m=y+h+(h&1),u++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let f=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/f)*f,this.maybeCapDataSize(),this.trackBackings.push(new hu(this))})()}async parseFmtChunk(e,r,n){let a=this.reader.requestSlice(e,r);if(R(a)&&(a=await a),!a)return;if(r<14)throw new Error('Invalid WAVE file - "fmt " chunk is too small');let s=Ga(a,n),o=Ga(a,n),c=Jr(a,n);if(a.skip(6),o===0||c===0)throw new Error("Invalid WAVE file - channel count and sample rate must be positive");let l;if(r<16?l=8:l=Ga(a,n),r>=18&&s!==357){let d=Ga(a,n),m=r-18;if(Math.min(m,d)>=22&&s===65534){a.skip(6);let p=U(a,16);s=p[0]|p[1]<<8}}if((s===7||s===6)&&(l=8),s!==1&&s!==3&&s!==6&&s!==7)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and \u03BC-law are supported.`);if(s===1&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(s===3&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);let u=Math.ceil(l/8);this.audioInfo={format:s,numberOfChannels:o,sampleRate:c,sampleSizeInBytes:u,blockSizeInBytes:o*u}}async parseListChunk(e,r,n){if(r<4)return;let a=this.reader.requestSlice(e,r);if(R(a)&&(a=await a),!a)return;let s=ae(a,4);if(s!=="INFO"&&s!=="INF0")return;let o=a.filePos;for(;o<=e+r-8;){a.filePos=o;let c=ae(a,4),l=Jr(a,n);if(l>a.remainingLength)break;let u=U(a,l),d=u.indexOf(0),m=u.subarray(0,d===-1?u.length:d),f;try{f=Cd.decode(m)}catch{f="";for(let p of m)f+=String.fromCharCode(p)}switch(this.metadataTags.raw??={},this.metadataTags.raw[c]=f,c){case"INAM":case"TITL":this.metadataTags.title??=f;break;case"TIT3":this.metadataTags.description??=f;break;case"IART":this.metadataTags.artist??=f;break;case"IPRD":this.metadataTags.album??=f;break;case"IPRT":case"ITRK":case"TRCK":{let p=f.split("/"),g=Number.parseInt(p[0],10),h=p[1]&&Number.parseInt(p[1],10);Number.isInteger(g)&&g>0&&(this.metadataTags.trackNumber??=g),h&&Number.isInteger(h)&&h>0&&(this.metadataTags.tracksTotal??=h)}break;case"ICRD":{let p=Kt(f);p&&(this.metadataTags.date??=p)}break;case"YEAR":{let p=Number.parseInt(f,10),g=Pn(p);p>0&&!Number.isNaN(g.getTime())&&(this.metadataTags.date??=g)}break;case"IGNR":case"GENR":this.metadataTags.genre??=f;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=f;break}o+=8+l+(l&1)}}async parseId3Chunk(e,r){if(r<Et)return;let n=this.reader.requestSlice(e,r);if(R(n)&&(n=await n),!n)return;let a=Yr(n);if(a){let s=r-Et;if(a.size=Math.min(a.size,s),a.size>0){let o=n.slice(e+Et,a.size);Pi(o,a,this.metadataTags)}}}getCodec(){if(b(this.audioInfo),this.audioInfo.format===7)return"ulaw";if(this.audioInfo.format===6)return"alaw";if(this.audioInfo.format===1){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===3){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}b(!1)}maybeCapDataSize(){if(b(this.audioInfo),this.dataSizeCapped)return;let e=this.reader.fileSize;e!==null&&(this.dataSize=Math.min(this.dataSize,An(e-this.dataStart,this.audioInfo.blockSizeInBytes)),this.dataSizeCapped=!0)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},jn=2048,hu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let t=this.demuxer.getCodec();return t?(b(this.demuxer.audioInfo),{codec:t,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return b(this.demuxer.dataSize!==-1),this.demuxer.maybeCapDataSize(),this.demuxer.dataSizeIsPlaceholder&&!this.demuxer.dataSizeCapped?null:this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ce}getDisposition(){return{...Ve}}async getPacketAtIndex(t,e){b(t>=0),b(this.demuxer.audioInfo);let r=this.demuxer.audioInfo.blockSizeInBytes;this.demuxer.maybeCapDataSize();let n=this.demuxer.reader.fileSize,a=t*jn*r;if(a>=this.demuxer.dataSize)return null;let s=Math.min(jn*r,this.demuxer.dataSize-a);if(n===null){let u=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,s);if(R(u)&&(u=await u),!u)return b(this.demuxer.reader.fileSize!==null),this.getPacketAtIndex(t,e)}let o;if(e.metadataOnly)o=Ae;else{let u=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,s);R(u)&&(u=await u),b(u),o=U(u,s)}let c=t*jn/this.demuxer.audioInfo.sampleRate,l=s/r/this.demuxer.audioInfo.sampleRate;return new ee(o,"key",c,l,t,s)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getPacket(t,e){b(this.demuxer.audioInfo);let r=Math.floor(Math.min(Fe(t*this.demuxer.audioInfo.sampleRate)/jn,(this.demuxer.dataSize-1)/(jn*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;let n=await this.getPacketAtIndex(r,e);return n||this.getPacket(t,e)}getNextPacket(t,e){b(this.demuxer.audioInfo);let r=Math.round(t.timestamp*this.demuxer.audioInfo.sampleRate/jn);return this.getPacketAtIndex(r+1,e)}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var rt=7,Ye=9,Qa=async(i,t,e,r)=>{let n=(s,o)=>s.objectType===o.objectType&&s.samplingFrequencyIndex===o.samplingFrequencyIndex&&s.channelConfiguration===o.channelConfiguration,a=i.requestSliceRange(t,rt,e+Ye);if(R(a)&&(a=await a),!a)return null;for(let s=t;s<Math.min(t+e,a.end);s++){if(a.filePos=s,H(a)!==255)continue;a.filePos=s;let o=It(a);if(!o||r&&!n(o,r))continue;let c=s+o.frameLength;if(c===i.fileSize)return o;let l=i.requestSliceRange(c,rt,Ye);R(l)&&(l=await l);let u=l&&It(l);if(u&&n(o,u))return o}return null},It=i=>{let t=i.filePos;if(i.remainingLength<rt)return null;let e=U(i,rt),r=new K(e);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;let s=r.readBits(1),o=r.readBits(2)+1,c=r.readBits(4);if(c>=Xe.length)return null;r.skipBits(1);let l=r.readBits(3);r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let u=r.readBits(13);r.skipBits(11);let d=r.readBits(2)+1;if(d!==1)return null;let m=null;if(s===0){if(i.remainingLength<2)return null;m=me(i)}return u<i.filePos-t?null:{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:m,startPos:t}};var Yo=1024,Zo=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.numberOfChannels=null;this.loadedSamples=[];this.metadataTags=null;this.trackBackings=[];this.readingMutex=new Ee;this.lastSampleLoaded=!1;this.lastLoadedPos=0;this.nextTimestampInSamples=0;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();let e=this.firstFrameHeader;if(b(e),e.channelConfiguration===0){let r=e.crcCheck===null?rt:Ye,n=this.reader.requestSlice(e.startPos+r,e.frameLength-r);if(R(n)&&(n=await n),!n)throw new Error("Invalid ADTS file: the first frame is cut off.");let a=mr(U(n,e.frameLength-r));if(!a)throw new Error("Invalid ADTS file: frames with channel configuration 0 must begin with a program config element.");this.numberOfChannels=Wr(a.programConfigElement)}else this.numberOfChannels=dr[e.channelConfiguration];this.trackBackings=[new bu(this)]})()}async advanceReader(){let e;if(this.lastLoadedPos===0){let a=await Ar(this.reader,0);e=await Qa(this.reader,a,4096,null)}else{let a=this.reader.requestSliceRange(this.lastLoadedPos,rt,Ye);if(R(a)&&(a=await a),e=a&&It(a),!e){b(this.firstFrameHeader);let s=await Ar(this.reader,this.lastLoadedPos);e=await Qa(this.reader,s,2**16,this.firstFrameHeader)}}if(!e){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&e.startPos+e.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader??=e;let r=Xe[this.firstFrameHeader.samplingFrequencyIndex];if(b(r!==void 0),e.samplingFrequencyIndex!==this.firstFrameHeader.samplingFrequencyIndex){O._warn(`The sample rate changes mid-stream (from ${r} Hz to ${Xe[e.samplingFrequencyIndex]} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}let n={timestamp:this.nextTimestampInSamples/r,duration:Yo/r,dataStart:e.startPos,dataSize:e.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=Yo,this.lastLoadedPos=e.startPos+e.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0;for(;;){let n=this.reader.requestSlice(r,Et);if(R(n)&&(n=await n),!n)break;let a=Yr(n);if(!a)break;let s=this.reader.requestSlice(n.filePos,a.size);if(R(s)&&(s=await s),!s)break;Pi(s,a,this.metadataTags),r=n.filePos+a.size}return this.metadataTags}finally{e()}}},bu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ce}getCodec(){return"aac"}getInternalCodecId(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){return b(this.demuxer.numberOfChannels!==null),this.demuxer.numberOfChannels}getSampleRate(){b(this.demuxer.firstFrameHeader);let t=Xe[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return b(t!==void 0),t}getDisposition(){return{...Ve}}async getDecoderConfig(){return b(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(t,e){if(t===-1)return null;let r=this.demuxer.loadedSamples[t];if(!r)return null;let n;if(e.metadataOnly)n=Ae;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(R(a)&&(a=await a),!a)return null;n=U(a,r.dataSize)}return new ee(n,"key",r.timestamp,r.duration,t,r.dataSize)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=Vr(this.demuxer.loadedSamples,t.timestamp,s=>s.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let a=n+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,e)}finally{r()}}async getPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=this.getSampleRate(),a=Fe(t*n)/n;for(;;){let s=j(this.demuxer.loadedSamples,a,o=>o.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,e);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var Jo=i=>i===0?null:i===1?192:i>=2&&i<=5?144*2**i:i===6?"uncommon-u8":i===7?"uncommon-u16":i>=8&&i<=15?2**i:null,Bf=(i,t)=>{switch(i){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},ec=i=>{let t=0,e=new K(U(i,1));for(;e.readBits(1)===1;)t++;if(t===0)return e.readBits(7);let r=[],n=t-1,a=new K(U(i,n)),s=8-t-1;for(let c=0;c<s;c++)r.unshift(e.readBits(1));for(let c=0;c<n;c++)for(let l=0;l<8;l++){let u=a.readBits(1);l<2||r.unshift(u)}return r.reduce((c,l,u)=>c+l*2**u,0)},tc=(i,t)=>{if(t==="uncommon-u16")return me(i)+1;if(t==="uncommon-u8")return H(i)+1;if(typeof t=="number")return t;Z(t),b(!1)},Of=(i,t)=>t==="uncommon-u16"?me(i):t==="uncommon-u16-10"?me(i)*10:t==="uncommon-u8"?1e3*H(i):typeof t=="number"?t:null,Df=i=>{let e=0;for(let r of i){e^=r;for(let n=0;n<8;n++)(e&128)!==0?e=e<<1^7:e<<=1,e&=255}return e};var rc=class extends _e{constructor(e){super(e);this.loadedSamples=[];this.metadataPromise=null;this.trackBacking=null;this.metadataTags={};this.audioInfo=null;this.lastLoadedPos=null;this.blockingBit=null;this.readingMutex=new Ee;this.lastSampleLoaded=!1;this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),b(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSlice(e,Et);if(R(r)&&(r=await r),!r)break;let n=Yr(r);if(!n)break;let a=this.reader.requestSlice(r.filePos,n.size);R(a)&&(a=await a),b(a),Pi(a,n,this.metadataTags),e=r.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(R(r)&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);b(r);let n=H(r),a=$t(r),s=(n&128)!==0;switch(n&127){case 0:{if(a<34)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=this.reader.requestSlice(e,a);if(R(c)&&(c=await c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let l=U(c,34),u=new K(l),d=u.readBits(16),m=u.readBits(16),f=u.readBits(24),p=u.readBits(24),g=u.readBits(20);if(g===0)throw new Error("Invalid StreamInfo block: sample rate is 0. Corrupted file.");let h=u.readBits(3)+1;u.readBits(5);let y=u.readBits(36);u.skipBits(16*8);let k=new Uint8Array(42);k.set(new Uint8Array([102,76,97,67]),0),k.set(new Uint8Array([128,0,0,34]),4),k.set(l,8),this.audioInfo={numberOfChannels:h,sampleRate:g,totalSamples:y,minimumBlockSize:d,maximumBlockSize:m,minimumFrameSize:f,maximumFrameSize:p,description:k},this.trackBacking=new yu(this);break}case 4:{let c=this.reader.requestSlice(e,a);if(R(c)&&(c=await c),!c)throw new Error(`Vorbis comment block at position ${e} exceeds the file. Corrupted file.`);ba(U(c,a),this.metadataTags);break}case 6:{let c=this.reader.requestSlice(e,a);if(R(c)&&(c=await c),!c)throw new Error(`Picture block at position ${e} exceeds the file. Corrupted file.`);try{let l=B(c),u=B(c),d=be.decode(U(c,u)),m=B(c),f=be.decode(U(c,m));c.skip(16);let p=B(c),g=U(c,p);this.metadataTags.images??=[],this.metadataTags.images.push({data:g,mimeType:d,kind:l===3?"coverFront":l===4?"coverBack":"unknown",description:f})}catch{}break}default:break}if(e+=a,s)break}if(this.lastLoadedPos=e,!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame(e){b(this.audioInfo);let r=6,n=16,a=10,s=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+n+2,o=this.audioInfo.minimumFrameSize||a,l=(this.audioInfo.maximumFrameSize||s)+n,u=await this.reader.requestSliceRange(e,r,l);if(!u)return null;let d=this.readFlacFrameHeader(u);if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-r)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(H(u)===255){let f=u.filePos,p=H(u),g=this.blockingBit===1?249:248;if(p!==g){u.filePos=f;continue}u.skip(-2);let h=u.filePos-e,y=this.readFlacFrameHeader(u);if(!y){u.filePos=f;continue}if(this.blockingBit===0){if(y.num-d.num!==1){u.filePos=f;continue}}else if(y.num-d.num!==d.blockSize){u.filePos=f;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:h,isLastFrame:!1}}}}readFlacFrameHeader(e){let r=e.filePos,n=U(e,4),a=new K(n);if(a.readBits(15)!==32764)return null;let o=a.readBits(1);if(this.blockingBit!==null&&o!==this.blockingBit)return null;let c=Jo(a.readBits(4));if(!c)return null;b(this.audioInfo);let l=Bf(a.readBits(4),this.audioInfo.sampleRate);if(!l||(a.readBits(4),a.readBits(3),a.readBits(1)!==0))return null;let d=H(e);e.skip(-1);let f=4+Math.max(Math.clz32(~d<<24),1)+(c==="uncommon-u16"?2:c==="uncommon-u8"?1:0)+(l==="uncommon-u8"?1:typeof l=="number"?0:2)+1;if(r+f>e.end)return null;let p=ec(e),g=tc(e,c),h=Of(e,l);if(h===null||h!==this.audioInfo.sampleRate)return null;let y=e.filePos-r,k=H(e);e.skip(-y),e.skip(-1);let T=Df(U(e,y));return k!==T?null:(this.blockingBit=o,{num:p,blockSize:g,sampleRate:h})}async advanceReader(){await this.readMetadata(),b(this.lastLoadedPos!==null),b(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame(e);if(!r){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},yu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return ce}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Ve}}async getDecoderConfig(){return b(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(t,e){if(b(this.demuxer.audioInfo),t<0)return null;let r=await this.demuxer.readingMutex.acquire();try{let n=Fe(t*this.demuxer.audioInfo.sampleRate);for(;;){let a=j(this.demuxer.loadedSamples,n,o=>o.blockOffset);if(a===-1){if(this.demuxer.lastSampleLoaded)return null;await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[a];if(s.blockOffset+s.blockSize<=n){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,e);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(a,e)}}finally{r()}}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=t.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,e)}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}async getPacketAtIndex(t,e){let r=this.demuxer.loadedSamples[t];if(!r)return null;let n;if(e.metadataOnly)n=Ae;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(R(o)&&(o=await o),!o)return null;n=U(o,r.byteSize)}b(this.demuxer.audioInfo);let a=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.blockSize/this.demuxer.audioInfo.sampleRate;return new ee(n,"key",a,s,t,r.byteSize)}async getFirstPacket(t){let e=await this.demuxer.readingMutex.acquire();try{for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,t)}finally{e()}}};var Ue=9e4,Xn=2**33,ze=188;var ic=i=>{let t="video/MP2T",e=[...new Set(i.filter(Boolean))];return e.length>0&&(t+=`; codecs="${e.join(", ")}"`),t},ja=i=>Il(Math.round(Ue*i),Xn),nc=i=>{let t=60*Ue;return{reference:i>=Xn-t?i-t-Xn:i-t}},ac=(i,t)=>t.reference+Il(i-t.reference,Xn);var Nf="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.",Vf=5,lg=1212435798,ug=1212436562,dg=1146376960,mg=new Set([133,134,162]),Uf=new Set,sc=class i extends _e{constructor(e){super(e);this.metadataPromise=null;this.elementaryStreams=[];this.trackBackingEntries=[];this.packetOffset=0;this.packetStride=-1;this.sectionEndPositions=[];this.seekChunkSize=5*1024*1024;this.minReferencePointByteDistance=-1;this.timestampWrapInfo=null;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=ze+16+1,r=this.reader.requestSlice(0,e);R(r)&&(r=await r),b(r);let n=U(r,e);if(n[0]===71&&n[ze]===71)this.packetOffset=0,this.packetStride=ze;else if(n[0]===71&&n[ze+16]===71)this.packetOffset=0,this.packetStride=ze+16;else if(n[4]===71&&n[4+ze+4]===71)this.packetOffset=4,this.packetStride=ze+4;else throw new Error("Unreachable.");let a=256;this.minReferencePointByteDistance=a*this.packetStride;let s=this.packetOffset,o=null,c=!1,l=!1;for(;;){let u=await this.readPacketHeader(s);if(!u)break;if(u.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(l&&!this.elementaryStreams.some(h=>h.pid===u.pid&&!h.initialized)){s+=this.packetStride;continue}let d=this.elementaryStreams.some(h=>h.pid===u.pid),m=await this.readSection(s,!d,!l);if(!m)break;let f=32,p=!1;if(!l&&m.pid!==0&&(o===null||m.pid===o)&&!(m.payload[0]===0&&m.payload[1]===0&&m.payload[2]===1)){let y=new K(m.payload),k=y.readAlignedByte();y.skipBits(8*k),p=y.readBits(8)===2}if(m.pid===0&&!c){let h=new K(m.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(14);let k=h.readBits(10),T=h.pos+8*k;for(h.skipBits(40);T-h.pos>f;){let S=h.readBits(16);h.skipBits(3);let w=h.readBits(13);if(S!==0){if(o!==null)throw new Error("Only files with a single program are supported.");o=w}}if(o===null)throw new Error("Program Association Table must link to a Program Map Table.");c=!0}else if(p){let h=new K(m.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(12);let k=h.readBits(12),T=h.pos+8*k;h.skipBits(43);let S=h.readBits(13);h.skipBits(6);let w=h.readBits(10),A=h.pos+8*w,C=!1;for(;h.pos<A;){let E=h.readBits(8),I=h.readBits(8),x=h.pos+8*I;if(E===Vf&&I>=4){let P=h.readBits(32);C||=P===lg||P===ug}h.pos=x}for(h.pos=A;T-h.pos>f;){let E=h.readBits(8);h.skipBits(3);let I=h.readBits(13);h.skipBits(6);let x=h.readBits(10),P=h.pos+8*x,v=!1,_=!1,M=!1;for(;h.pos<P;){let z=h.readBits(8),$=h.readBits(8),fe=h.pos+8*$;if(z===106)v=!0;else if(z===122||z===204)_=!0;else if(z===123)M=!0;else if(z===Vf&&$>=4){let ye=h.readBits(32);M||=(ye&4294967040)===dg}h.pos=fe}let D=null,L=C&&mg.has(E)?130:E;switch(L){case 27:case 36:D={type:"video",codec:E===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:case 130:case 138:{let z;L===3||L===4?z="mp3":L===15?z="aac":L===129?z="ac3":L===135?z="eac3":z="dts",D={type:"audio",codec:z,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:_?D={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:v?D={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:M&&(D={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Uf.has(E)||(O._warn(`Note: MPEG-TS streams with stream_type 0x${E.toString(16)} are not currently supported.`),Uf.add(E))}D&&this.elementaryStreams.push({demuxer:this,pid:I,streamType:E,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:D,referencePesPackets:[]})}l=!0}else{let h=this.elementaryStreams.find(y=>y.pid===m.pid);e:if(h&&!h.initialized){if(!ei(this,m,!0))throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${h.pid}`);if(h.firstSection=m,h.canBeTrustedWithKeyPackets=m.randomAccessIndicator===1,this.input._initInput){let T=await this.input._initInput._getDemuxer();if(T.constructor!==i)throw new Error("Init input must match the input's format.");await T.readMetadata();let S=T.elementaryStreams.find(w=>w.pid===m.pid&&w.info.codec===h.info.codec&&w.initialized);if(S){h.info=S.info,h.initialized=!0;break e}}let k=new tn(h,m.startPos);if(h.info.type==="video"){for(;;){let T=k;if(T.suppliedPacket=null,await k.markNextPacket(),h.info.codec==="avc"){if(!k.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(h.info.avcCodecInfo=hr(k.suppliedPacket.data),!h.info.avcCodecInfo)continue;let S=h.info.avcCodecInfo.sequenceParameterSets[0];b(S);let w=Gt(S);h.info.width=w.displayWidth,h.info.height=w.displayHeight;let A=w.pixelAspectRatio.num,C=w.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,A>0&&C>0&&(A>C?h.info.squarePixelWidth=Math.round(h.info.width*A/C):h.info.squarePixelHeight=Math.round(h.info.height*C/A)),h.info.colorSpace={primaries:Tt[w.colourPrimaries],transfer:wt[w.transferCharacteristics],matrix:St[w.matrixCoefficients],fullRange:!!w.fullRangeFlag},h.info.reorderSize=w.maxDecFrameBuffering;break}else if(h.info.codec==="hevc"){if(!k.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(h.info.hevcCodecInfo=br(k.suppliedPacket.data),!h.info.hevcCodecInfo)continue;let w=h.info.hevcCodecInfo.arrays.find(I=>I.nalUnitType===33).nalUnits[0];b(w);let A=Qi(w);h.info.width=A.displayWidth,h.info.height=A.displayHeight;let C=A.pixelAspectRatio.num,E=A.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,C>0&&E>0&&(C>E?h.info.squarePixelWidth=Math.round(h.info.width*C/E):h.info.squarePixelHeight=Math.round(h.info.height*E/C)),h.info.colorSpace={primaries:Tt[A.colourPrimaries],transfer:wt[A.transferCharacteristics],matrix:St[A.matrixCoefficients],fullRange:!!A.fullRangeFlag},h.info.reorderSize=A.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}h.info.decoderConfig={codec:Si({width:h.info.width,height:h.info.height,codec:h.info.codec,codecDescription:null,colorSpace:h.info.colorSpace,avcType:1,avcCodecInfo:h.info.avcCodecInfo,hevcType:"hev1",hevcCodecInfo:h.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:h.info.width,codedHeight:h.info.height,colorSpace:h.info.colorSpace},(h.info.width!==h.info.squarePixelWidth||h.info.height!==h.info.squarePixelHeight)&&(h.info.decoderConfig.displayAspectWidth=h.info.squarePixelWidth,h.info.decoderConfig.displayAspectHeight=h.info.squarePixelHeight),h.initialized=!0}else{if(await k.markNextPacket(),!k.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${h.pid}`);if(h.info.codec==="aac"){let T=xe.tempFromBytes(k.suppliedPacket.data),S=It(T);if(!S)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");if(h.info.aacCodecInfo={isMpeg2:!1,objectType:S.objectType},S.channelConfiguration===0){let w=S.crcCheck===null?rt:Ye,A=mr(k.suppliedPacket.data.subarray(w,S.frameLength));if(!A)throw new Error("Invalid AAC audio stream; ADTS frames with channel configuration 0 must begin with a program config element.");h.info.numberOfChannels=Wr(A.programConfigElement)}else h.info.numberOfChannels=dr[S.channelConfiguration];h.info.sampleRate=Xe[S.samplingFrequencyIndex]}else if(h.info.codec==="mp3"){let T=B(xe.tempFromBytes(k.suppliedPacket.data)),S=fr(T,k.suppliedPacket.data.byteLength);if(!S.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");h.info.numberOfChannels=fi(S.header.channel),h.info.sampleRate=S.header.sampleRate}else if(h.info.codec==="ac3"){let T=$s(k.suppliedPacket.data);if(!T)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(T.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=ka[T.acmod]+T.lfeon,h.info.sampleRate=Ki[T.fscod]}else if(h.info.codec==="eac3"){let T=Zs(k.suppliedPacket.data);if(!T)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let S=eo(T);if(S===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=to(T),h.info.sampleRate=S}else if(h.info.codec==="dts"){let T=Aa(k.suppliedPacket.data);if(!T)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");h.info.numberOfChannels=T.numberOfChannels,h.info.sampleRate=T.sampleRate,T.core&&(h.info.dtsFormat=T.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");h.info.decoderConfig={codec:Nn({codec:h.info.codec,codecDescription:null,aacCodecInfo:h.info.aacCodecInfo,dtsFormat:h.info.dtsFormat}),numberOfChannels:h.info.numberOfChannels,sampleRate:h.info.sampleRate},h.initialized=!0}}}if(l&&this.elementaryStreams.every(h=>h.initialized))break;p?s=this.packetOffset:s+=this.packetStride}if(!l)throw c?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let u of this.elementaryStreams)u.initialized&&(u.info.type==="video"?this.trackBackingEntries.push(new ku(u)):this.trackBackingEntries.push(new Tu(u)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return ic(e)}async readSection(e,r,n=!1){let a=e,s=e,o=[],c=0,l=null,u=!0,d=0;for(;;){let f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(!l)b(f.payloadUnitStartIndicator===1),l=f;else{if(f.pid!==l.pid)if(n){u=!1;break}else continue;if(f.payloadUnitStartIndicator===1)break}let p=!!(f.adaptationFieldControl&2),g=!!(f.adaptationFieldControl&1),h=0;if(p&&(h=1+f.body[0],f===l&&h>1&&(d=f.body[1]>>6&1)),g&&(h===0?(o.push(f.body),c+=f.body.byteLength):(o.push(f.body.subarray(h)),c+=f.body.byteLength-h)),a=s,!r&&c>=64){u=!1;break}if(Vr(this.sectionEndPositions,a,k=>k)!==-1){u=!1;break}}if(u){let f=j(this.sectionEndPositions,a,p=>p);this.sectionEndPositions.splice(f+1,0,a)}if(!l)return null;let m;if(o.length===1)m=o[0];else{let f=o.reduce((g,h)=>g+h.length,0);m=new Uint8Array(f);let p=0;for(let g of o)m.set(g,p),p+=g.length}return{startPos:e,pid:l.pid,payload:m,randomAccessIndicator:d}}async readPacketHeader(e){let r=this.reader.requestSlice(e,4);if(R(r)&&(r=await r),!r)return null;if(H(r)!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");let a=me(r),s=a>>15,o=a>>14&1,c=a>>13&1,l=a&8191,u=H(r),d=u>>6,m=u>>4&3,f=u&15;return{payloadUnitStartIndicator:o,pid:l,adaptationFieldControl:m}}async readPacket(e){let r=this.reader.requestSlice(e,ze);if(R(r)&&(r=await r),!r)return null;let n=U(r,ze);if(n[0]!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");let s=(n[1]<<8)+n[2],o=s>>15,c=s>>14&1,l=s>>13&1,u=s&8191,d=n[3],m=d>>6,f=d>>4&3,p=d&15;return{payloadUnitStartIndicator:c,pid:u,adaptationFieldControl:f,body:n.subarray(4)}}normalizeTimestamp(e){return this.timestampWrapInfo??=nc(e),ac(e,this.timestampWrapInfo)}},ei=(i,t,e)=>{if(t.payload.byteLength<3)return null;let r=new K(t.payload);if(r.readBits(24)!==1)return null;let a=r.readBits(8);if(r.skipBits(16),a===188||a===190||a===191||a===240||a===241||a===255||a===242||a===248)return null;r.skipBits(8);let s=r.readBits(2);r.skipBits(14);let o=null;if(s===2||s===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=i.normalizeTimestamp(o);else if(e)throw new Error(Nf);return{sectionStartPos:t.startPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},oc=class i{constructor(t){this.elementaryStream=t;this.packetBuffers=new WeakMap;this.packetSectionStarts=new WeakMap}getNumber(){let t=this.elementaryStream.demuxer,e=this.elementaryStream.info.type,r=0;for(let n of t.trackBackingEntries)if(n.getType()===e&&r++,b(n instanceof i),n.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return ce}getDisposition(){return{...Ve,primary:!1}}getTimeResolution(){return Ue}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(t,e,r){let n;return this.allPacketsAreKeyPackets()?n="key":n=t.randomAccessIndicator===1?"key":"delta",new ee(r.metadataOnly?Ae:t.data,n,t.pts/Ue,Math.max(e/Ue,0),t.sequenceNumber,t.data.byteLength)}async getFirstPacket(t){let e=this.elementaryStream.firstSection;b(e);let r=new tn(this.elementaryStream,e.startPos),n=new Xa(this,r),a=await n.readNext();if(!a)return null;let s=this.createEncodedPacket(a.packet,a.duration,t);return this.packetBuffers.set(s,n),this.packetSectionStarts.set(s,a.packet.sectionStartPos),s}async getNextPacket(t,e){let r=this.packetBuffers.get(t);if(r){this.packetBuffers.delete(t);let d=await r.readNext();if(!d)return null;let m=this.createEncodedPacket(d.packet,d.duration,e);return this.packetBuffers.set(m,r),this.packetSectionStarts.set(m,d.packet.sectionStartPos),m}let n=this.packetSectionStarts.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");let a=this.elementaryStream.demuxer,s=n,o=this.getReorderSize(),c=n-a.packetStride;for(;o>0&&c>=a.packetOffset;){let d=await a.readPacketHeader(c);if(b(d),d.pid===this.elementaryStream.pid&&d.payloadUnitStartIndicator===1){let m=await a.readSection(c,!1);b(m);let f=ei(a,m,!1);f&&f.pts!==null&&(s=c,o--)}c-=a.packetStride}let l=new tn(this.elementaryStream,s);r=new Xa(this,l);let u=t.sequenceNumber;for(;;){let d=await r.readNext();if(!d)return null;if(d.packet.sequenceNumber>u){let m=this.createEncodedPacket(d.packet,d.duration,e);return this.packetBuffers.set(m,r),this.packetSectionStarts.set(m,d.packet.sectionStartPos),m}}}async getNextKeyPacket(t,e){let r=t;for(;;){if(r=await this.getNextPacket(r,e),!r)return null;if(r.type==="key")return r}}getPacket(t,e){return this.doPacketLookup(t,!1,e)}getKeyPacket(t,e){return this.doPacketLookup(t,!0,e)}async doPacketLookup(t,e,r){let n=Fe(t*Ue),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:o}=a,c=this.elementaryStream.pid,l=async(T,S)=>{let w=T;for(;w<S;){let A=await a.readPacketHeader(w);if(!A)return null;if(A.pid===c&&A.payloadUnitStartIndicator===1){let C=await a.readSection(w,!1);if(!C)return null;let E=ei(a,C,!1);if(E&&E.pts!==null)return E}w+=a.packetStride}return null},u=this.elementaryStream.firstSection;b(u);let d=ei(a,u,!0);b(d);let m,f=this.elementaryStream.referencePesPackets,p=j(f,n,T=>T.pts),g=p!==-1?f[p]:null;if(g&&n-g.pts<Ue/2)m=g.sectionStartPos;else{let T=0;if(s.fileSize!==null&&n>=d.pts){let S=Math.ceil(s.fileSize/o);if(S>1){let w=0,A=S-1;for(T=w;w<=A;){let C=Math.floor((w+A)/2),E=An(C*o,a.packetStride)+d.sectionStartPos,I=E+o,x=await l(E,I);if(!x){A=C-1;continue}x.pts<=n?(T=C,w=C+1):A=C-1}}}m=An(T*o,a.packetStride)+d.sectionStartPos}let h=await l(m,s.fileSize??1/0);h||(h=d);let y=this.getReorderSize(),k=async(T,S)=>{let w=new tn(this.elementaryStream,T),A=new Xa(this,w);for(;!((J(A.presentationOrderPackets)?.pts??-1/0)>=n||!await A.readNextPacket()););let C=lr(A.presentationOrderPackets,S);if(C===-1)return null;let E=A.presentationOrderPackets[C];A.decodeOrderPackets.splice(0,A.decodeOrderPackets.indexOf(E));let I=await A.readNext();b(I);let x=this.createEncodedPacket(I.packet,I.duration,r);return this.packetBuffers.set(x,A),this.packetSectionStarts.set(x,I.packet.sectionStartPos),x};if(!e||this.allPacketsAreKeyPackets()){e:for(;;){let T=h.sectionStartPos+a.packetStride;for(;;){let S=await a.readPacketHeader(T);if(!S)break e;if(S.pid===c&&S.payloadUnitStartIndicator===1){let w=await a.readSection(T,!1);if(w){let A=ei(a,w,!1);if(A&&A.pts!==null){if(A.pts>n)break e;h=A,wu(this.elementaryStream,h);break}}}T+=a.packetStride}}e:for(let T=0;T<y+1;T++){let S=h.sectionStartPos-a.packetStride;for(;S>=d.sectionStartPos;){let w=await a.readPacketHeader(S);if(!w)break e;if(w.pid===c&&w.payloadUnitStartIndicator===1){let A=await a.readSection(S,!1);if(A){let C=ei(a,A,!1);if(C&&C.pts!==null){h=C;break}}}S-=a.packetStride}if(S<d.sectionStartPos)break}return k(h.sectionStartPos,T=>T.pts<=n)}else{let T=m,S=null;for(;;){let w=null,A=T<=d.sectionStartPos,C;A?C=d:C=await l(T,S??s.fileSize??1/0);let E=!1,I=0,x=null;e:for(;C&&!(S!==null&&C.sectionStartPos>=S);){if(C.pts<=n){let v;if(this.elementaryStream.canBeTrustedWithKeyPackets)v=C.randomAccessIndicator===1;else{for(x??=new tn(this.elementaryStream,C.sectionStartPos);(!x.suppliedPacket||x.suppliedPacket.sectionStartPos<C.sectionStartPos)&&(x.suppliedPacket=null,await x.markNextPacket(),!!x.suppliedPacket););v=x.suppliedPacket?.sectionStartPos===C.sectionStartPos&&x.suppliedPacket.randomAccessIndicator===1}v&&(w=C)}if(C.pts>n&&(E=!0),E&&(I++,I>y))break;let P=C.sectionStartPos+a.packetStride;for(;;){let v=await a.readPacketHeader(P);if(!v)break e;if(v.pid===c&&v.payloadUnitStartIndicator===1){let _=await a.readSection(P,!1);if(_){let M=ei(a,_,!1);if(M&&M.pts!==null){C=M,wu(this.elementaryStream,C);break}}}P+=a.packetStride}}if(w){let P=w;if(I===0)e:for(let _=0;_<y+1;_++){let M=P.sectionStartPos-a.packetStride;for(;M>=d.sectionStartPos;){let D=await a.readPacketHeader(M);if(!D)break e;if(D.pid===c&&D.payloadUnitStartIndicator===1){let L=await a.readSection(M,!1);if(L){let z=ei(a,L,!1);if(z&&z.pts!==null){P=z;break}}}M-=a.packetStride}if(M<d.sectionStartPos)break}let v=await k(P.sectionStartPos,_=>_.pts<=n&&_.randomAccessIndicator===1);if(v)return v}if(A)return null;S=T,T=Math.max(An(T-d.sectionStartPos-o,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},ku=class extends oc{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}getTransformationMatrix(){return[...si]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return b(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Tu=class extends oc{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return b(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},wu=(i,t)=>{let e=i.referencePesPackets,r=j(e,t.sectionStartPos,a=>a.sectionStartPos),n=i.demuxer.minReferencePointByteDistance;if(r>=0){let a=e[r];if(t.pts<=a.pts||t.sectionStartPos-a.sectionStartPos<n)return!1}if(r<e.length-1){let a=e[r+1];if(a.pts<t.pts||a.sectionStartPos-t.sectionStartPos<n)return!1}return e.splice(r+1,0,{sectionStartPos:t.sectionStartPos,pts:t.pts,randomAccessIndicator:t.randomAccessIndicator}),!0},tn=class{constructor(t,e){this.reachedEnd=!1;this.isInPesPacket=!1;this.pesHeaderBytesLeft=0;this.pesDataBytesLeft=0;this.currentPos=0;this.endPos=0;this.scratch=new Uint8Array(2**16);this.scratchStartPos=0;this.pesPackets=[];this.pesPacketDataStartPositions=[];this.lastSuppliedPesPacket=null;this.nextPts=null;this.suppliedPacket=null;this.elementaryStream=t,this.pid=t.pid,this.demuxer=t.demuxer,this.nextTsPacketPos=e}ensureBuffered(t){let e=this.endPos-this.currentPos;return e>=t?t:this.bufferData(t-e).then(()=>Math.min(this.endPos-this.currentPos,t))}async bufferData(t){let e=this.endPos+t;for(;this.endPos<e&&!this.reachedEnd;){let r=this.nextTsPacketPos,n=await this.demuxer.readPacket(r);if(!n){this.reachedEnd=!0;break}if(this.nextTsPacketPos+=this.demuxer.packetStride,n.pid!==this.pid)continue;if(n.payloadUnitStartIndicator===1){this.isInPesPacket=!1;let d=await this.demuxer.readSection(r,!1);b(d);let m=ei(this.demuxer,d,!1);if(!m)continue;let f=new K(d.payload);f.skipBits(32);let p=f.readBits(16),g=6;f.skipBits(16);let h=f.readBits(8);this.pesHeaderBytesLeft=f.pos/8+h,this.pesDataBytesLeft=p>0?Math.max(g+p-this.pesHeaderBytesLeft,0):1/0,this.isInPesPacket=!0,this.pesPackets.push(m),this.pesPacketDataStartPositions.push(this.endPos)}if(!this.isInPesPacket||!(n.adaptationFieldControl&1))continue;let a=n.body,s=n.adaptationFieldControl&2?1+a[0]:0,o=Math.min(this.pesHeaderBytesLeft,Math.max(a.byteLength-s,0));this.pesHeaderBytesLeft-=o,s+=o;let c=Math.min(a.byteLength,s+this.pesDataBytesLeft);if(c<=s)continue;let l=c-s;this.pesDataBytesLeft-=l;let u=this.endPos-this.scratchStartPos;if(u+l>this.scratch.byteLength){let d=new Uint8Array(2*this.scratch.byteLength);d.set(this.scratch.subarray(0,u)),this.scratch=d}this.scratch.set(a.subarray(s,c),u),this.endPos+=l}}readBytes(t){let e=this.currentPos-this.scratchStartPos;return this.currentPos+=t,this.scratch.subarray(e,e+t)}readU8(){return this.scratch[this.currentPos++-this.scratchStartPos]}seekTo(t){b(t>=this.scratchStartPos),this.currentPos=t}skip(t){this.seekTo(this.currentPos+t)}async markNextPacket(){b(!this.suppliedPacket);let t=this.elementaryStream;if(t.info.type==="video"){let e=t.info.codec,r=1024;if(e!=="avc"&&e!=="hevc")throw new Error("Unhandled.");let n=e==="avc"?1:2,a=null,s=!1,o=0;for(;;){let c=this.ensureBuffered(r);if(R(c)&&(c=await c),c===0)break;let l=this.currentPos,u=this.readBytes(c),d=u.byteLength,m=0;for(;m<d;){let f=u.indexOf(0,m);if(f===-1||f>=d)break;m=f;let p=l+m;if(m+3>=d){this.seekTo(p);break}let g=u[m+1],h=u[m+2],y=u[m+3],k=0;if(g===0&&h===0&&y===1?k=4:g===0&&h===1&&(k=3),k===0){m++;continue}let T=p;a??=T;let S=m+k,w=S+n;if(w+1>d){this.seekTo(p);break}let A=u[S],C,E,I,x;if(e==="avc")C=pr(A),E=C===1||C===2||C===5,I=C===6||C===7||C===8||C===9,x=C===9;else{if(C=Qt(A),((A&1)<<5|u[S+1]>>3)>0){m+=k;continue}E=C<=9||C>=16&&C<=21,I=C>=32&&C<=35||C===39||C>=41&&C<=44||C>=48&&C<=55,x=C===35}let P=!1;if(E){let v;if(e==="avc"){let _=new K(u.subarray(w)),M;try{M=V(_)}catch{M=null}if(M===null||_.getBitsLeft()<0){this.seekTo(p);break}v=!s||M<=o,o=M}else v=u[w]>>7===1;v&&(s?P=!0:s=!0)}else I&&s?P=!0:x&&(a=T);if(P){let v=T-a;return this.seekTo(a),this.supplyPacket(v,0)}m+=k}if(c<r)break}if(s){b(a!==null);let c=this.endPos-a;return this.seekTo(a),this.supplyPacket(c,0)}}else{let e=t.info.codec,r=128;for(;;){let n=this.ensureBuffered(r);R(n)&&(n=await n);let a=this.currentPos;for(;this.currentPos-a<n;){let s=this.readU8();if(e==="aac"){if(s!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(Ye);if(R(c)&&(c=await c),c<Ye)return;let l=this.readBytes(Ye),u=It(xe.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return R(d)&&(d=await d),this.supplyPacket(d,Yo*Ue/t.info.sampleRate)}else this.seekTo(o+1)}else if(e==="mp3"){if(s!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(4);if(R(c)&&(c=await c),c<4)return;let l=this.readBytes(4),u=N(l).getUint32(0),d=fr(u,null);if(d.header){this.seekTo(o);let m=this.ensureBuffered(d.header.totalSize);R(m)&&(m=await m);let f=d.header.audioSamplesInFrame*Ue/t.info.sampleRate;return this.supplyPacket(m,f)}else this.seekTo(o+1)}else if(e==="ac3"){if(s!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(R(c)&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}let m=fm[3*d+u];b(m!==void 0),this.seekTo(o),c=this.ensureBuffered(m),R(c)&&(c=await c);let f=pm*Ue/t.info.sampleRate;return this.supplyPacket(c,f)}else if(e==="eac3"){if(s!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(R(c)&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let d=(((l[2]&7)<<8|l[3])+1)*2,f=l[4]>>6===3?3:l[4]>>4&3,p=Ys[f];for(;;){this.seekTo(o);let y=d+4,k=this.ensureBuffered(y);if(R(k)&&(k=await k),k<y)break;this.seekTo(o+d);let T=this.readBytes(4);if(T[0]!==11||T[1]!==119||T[2]>>6!==1)break;d+=2*(((T[2]&7)<<8|T[3])+1)}this.seekTo(o),c=this.ensureBuffered(d),R(c)&&(c=await c);let h=p*256*Ue/t.info.sampleRate;return this.supplyPacket(c,h)}else if(e==="dts"){if(s!==127&&s!==100)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(Sa);if(R(c)&&(c=await c),c<Sa)return;let l=this.readBytes(Sa),u=Hl(l),d=u?null:xa(l);if(!u&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);let g=Math.min(d.frameSize,gm),h=this.ensureBuffered(g);R(h)&&(h=await h),d=xa(this.readBytes(h))??d}let m=u?u.frameSize:d.frameSize;if(u){let g=Math.ceil(u.frameSize/4)*4;for(;;){this.seekTo(o);let h=g+ro,y=this.ensureBuffered(h);if(R(y)&&(y=await y),y<h)break;this.seekTo(o+g);let k=xa(this.readBytes(ro));if(!k)break;g+=k.frameSize,m=g}}let f=u?.sampleCount??d.asset?.sampleCount;if(f===void 0){this.seekTo(o+1);continue}this.seekTo(o),c=this.ensureBuffered(m),R(c)&&(c=await c);let p=f*Ue/t.info.sampleRate;return this.supplyPacket(c,p)}else throw new Error("Unhandled.")}if(n<r)break}}}supplyPacket(t,e){let r=lr(this.pesPacketDataStartPositions,p=>p<=this.currentPos);b(r!==-1);let n=this.pesPackets[r],a=this.pesPacketDataStartPositions[r],s;if(this.lastSuppliedPesPacket===n)b(this.nextPts!==null),s=this.nextPts;else{if(n.pts===null)throw new Error(Nf);s=n.pts,wu(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=s+e;let o=n.sectionStartPos,c=o+(this.currentPos-a),l=this.readBytes(t).slice(),u=n.randomAccessIndicator;if(u===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")u=1;else if(this.elementaryStream.info.decoderConfig){let p=gi(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,l)==="key";u=Number(p)}}let d=Math.round(s);this.suppliedPacket={pts:d,intrinsicDuration:Math.round(s+e)-d,data:l,sequenceNumber:c,sectionStartPos:o,randomAccessIndicator:u};let m=this.currentPos-this.scratchStartPos;this.scratch.copyWithin(0,m,this.endPos-this.scratchStartPos),this.scratchStartPos=this.currentPos;let f=lr(this.pesPacketDataStartPositions,p=>p<=this.currentPos);this.pesPackets.splice(0,f),this.pesPacketDataStartPositions.splice(0,f)}},Xa=class{constructor(t,e){this.decodeOrderPackets=[];this.reorderBuffer=[];this.presentationOrderPackets=[];this.reachedEnd=!1;this.lastDuration=0;this.backing=t,this.context=e,this.reorderSize=t.getReorderSize(),b(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let t=this.decodeOrderPackets[0],e=this.presentationOrderPackets.indexOf(t),r;for(e!==-1&&e<this.presentationOrderPackets.length-1?(r=this.presentationOrderPackets[e+1].pts-t.pts,this.lastDuration=r):t.intrinsicDuration>0?r=t.intrinsicDuration:e>0?r=t.pts-this.presentationOrderPackets[e-1].pts:r=this.lastDuration,this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let n=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(n))break;this.presentationOrderPackets.shift()}return{packet:t,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let t;return this.context.suppliedPacket?t=this.context.suppliedPacket:(await this.context.markNextPacket(),t=this.context.suppliedPacket),this.context.suppliedPacket=null,t?(this.decodeOrderPackets.push(t),this.processPacketThroughReorderBuffer(t),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let t=this.decodeOrderPackets[0];for(b(t);;){let e=this.presentationOrderPackets.indexOf(t);if(e!==-1&&e<=this.presentationOrderPackets.length-2||this.decodeOrderPackets.length>4*(this.reorderSize+1)||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(t){if(this.reorderBuffer.push(t),this.reorderBuffer.length>this.reorderSize){let e=0;for(let n=1;n<this.reorderBuffer.length;n++)this.reorderBuffer[n].pts<this.reorderBuffer[e].pts&&(e=n);let r=this.reorderBuffer[e];this.presentationOrderPackets.push(r),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((t,e)=>t.pts-e.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};var Cr="application/vnd.apple.mpegurl",Su="#EXT-X-STREAM-INF:",Au="#EXT-X-I-FRAME-STREAM-INF:",xu="#EXT-X-MEDIA:",Yn="#EXT-X-DEFINE:",$a="#EXTINF:",Cu="#EXT-X-MAP:",Pu="#EXT-X-KEY:",Eu="#EXT-X-MEDIA-SEQUENCE:",Iu="#EXT-X-BYTERANGE:",vu="#EXT-X-PROGRAM-DATE-TIME:",Lf="#EXT-X-DISCONTINUITY",_u="#EXT-X-DISCONTINUITY-SEQUENCE:",Ru="#EXT-X-TARGETDURATION:",Hf="#EXT-X-ENDLIST",Fu="#EXT-X-PLAYLIST-TYPE:",Wf="#EXT-X-I-FRAMES-ONLY",zt="com.apple.streaming.transportStreamTimestamp",cc=i=>i.length===0||i.startsWith("#")&&!i.startsWith("#EXT"),xr=class{constructor(t,e){this._attributes={};let r="",n="",a=!1,s=!1,o=!1,c=()=>{if(!r)return;let l=r.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,l)&&O._warn(`Duplicate AttributeName "${l}"; using last value`);let u=o||n.startsWith("0x")||n.startsWith("0X");this._attributes[l]=u&&e?e.substitute(n):n,r="",n="",a=!1,o=!1};for(let l=0;l<t.length;l++){let u=t[l];u==='"'?(a&&!s&&n.length===0&&(o=!0),s=!s):u==="="&&!a&&!s?a=!0:u===","&&!s?c():a?n+=u:r+=u}if(s)throw new Error("Invalid M3U8 file; unterminated quoted-string AttributeValue.");c()}get(t){return this._attributes[t.toLowerCase()]??null}getAsNumber(t){let e=this.get(t);if(e===null)return null;let r=Number(e);return Number.isFinite(r)?r:null}merge(t){Object.assign(this._attributes,t._attributes)}},fg=/^[A-Za-z0-9_-]+$/,pg=/\{\$([A-Za-z0-9_-]+)\}/g,hg=2**26,$n=class{constructor(t,e){this.playlistPath=t;this.importedVariables=e;this.variables=new Map;this.totalSubstitutedLength=0}define(t){let e=new xr(t,this),r=e.get("name"),n=e.get("import"),a=e.get("queryparam");if([r,n,a].filter(o=>o!==null).length!==1)throw new Error("Invalid #EXT-X-DEFINE tag; exactly one of NAME, IMPORT, or QUERYPARAM must be present.");if(r!==null){let o=e.get("value");if(o===null)throw new Error("Invalid #EXT-X-DEFINE tag; NAME requires VALUE.");this.set(r,o)}else if(n!==null){let o=this.importedVariables?.get(n);if(o===void 0)throw new Error(`Invalid #EXT-X-DEFINE tag; cannot import undefined variable "${n}".`);this.set(n,o)}else if(a!==null){let o=Ld(this.playlistPath,a);if(o===null)throw new Error(`Invalid #EXT-X-DEFINE tag; query parameter "${a}" is missing.`);this.set(a,o)}}substitute(t){return t.replaceAll(pg,(e,r)=>{let n=this.variables.get(r);if(n===void 0)throw new Error(`Invalid M3U8 file; variable "${r}" is referenced before being defined.`);if(this.totalSubstitutedLength+=n.length,this.totalSubstitutedLength>hg)throw new Error("Invalid M3U8 file; variable substitution produces an excessive amount of data.");return n})}get(t){return this.variables.get(t)}set(t,e){if(!fg.test(t))throw new Error(`Invalid #EXT-X-DEFINE tag; invalid variable name "${t}".`);if(this.variables.has(t))throw new Error(`Invalid #EXT-X-DEFINE tag; variable "${t}" is already defined.`);this.variables.set(t,e)}};var lc=class{constructor(t,e,r){this.nextInputCacheAge=0;this.inputCache=[];this.trackBackingsPromise=null;this.firstSegment=null;this.hasOnlyKeyPackets=!1;this.learnedSegmentTimestampOffset=null;this.segmentMediaOffsets=new WeakMap;this.input=t,this.path=e,this.trackDeclarations=r}async getDurationFromMetadata(t){let e=await this.getSegmentAt(1/0,{skipLiveWait:t.skipLiveWait});return e?e.timestamp+await this.getFirstSegmentTimestampOffset()+e.duration:null}async getUnixTimeForTimestamp(t){let e=await this.getSegmentAt(t,{skipLiveWait:!0});if(e??=await this.getFirstSegment({}),!e||e.unixEpochTimestamp===null)return null;let r=t-(e.timestamp+await this.getFirstSegmentTimestampOffset());return e.unixEpochTimestamp+r}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let t=[];if(this.trackDeclarations){for(let e of this.trackDeclarations)if(e.type==="video"){let r=Wi(t,n=>n.getType()==="video")+1;t.push(new dc(this,e,r))}else if(e.type==="audio"){let r=Wi(t,n=>n.getType()==="audio")+1;t.push(new mc(this,e,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let r=await this.getInputForSegment(this.firstSegment).getTracks();for(let n of r)if(n.type==="video"){let a=Wi(t,s=>s.getType()==="video")+1;t.push(new dc(this,{type:"video"},a))}else if(n.type==="audio"){let a=Wi(t,s=>s.getType()==="audio")+1;t.push(new mc(this,{type:"audio"},a))}}return t})()}getMediaOffset(t,e){let r=this.segmentMediaOffsets.get(t);return r||(r=(async()=>{let n=await this.getRawTimestampOffset(e);if(n===null)return t.timestamp;let a=n+await this.getMediaOffsetForDiscontinuity(t.discontinuityNumber),s=this.getTimestampWrapPeriod();if(s<1/0){let o=await Ya(e);if(o!==null){let c=o+a;a+=s*Math.round((t.timestamp-c)/s)}}return a})(),this.segmentMediaOffsets.set(t,r),r)}dispose(){for(let t of this.inputCache)t.input.dispose();this.inputCache.length=0}},Ya=async i=>{let t=await i.getTracks(),e=[...t.filter(r=>r.type==="video"),...t.filter(r=>r.type!=="video")];for(let r of e){let n=await r.getFirstTimestampOrNull();if(n!==null)return n}return null},uc=class{constructor(t,e,r){this.packetInfos=new WeakMap;this.hydrationPromise=null;this.firstInputTrack=null;this.firstSegment=null;this.segmentedInput=t,this.decl=e,this.number=r}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let t=this.segmentedInput.firstSegment,e=null;for(;t&&(e=(await this.segmentedInput.getInputForSegment(t).getTracks()).find(a=>a.type===this.decl.type&&a.number===this.number)??null,!e);)t=await this.segmentedInput.getNextSegment(t,{});if(!e)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=e,this.firstSegment=t})()}getType(){return this.decl.type}getNumber(){return this.number}delegate(t){return this.firstInputTrack?t():this.hydrate().then(t)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.segmentedInput.hasOnlyKeyPackets||(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(),b(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(t){return this.segmentedInput.getUnixTimeForTimestamp(t)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(t){return this.segmentedInput.getDurationFromMetadata(t)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(t,e,r){b(t.sequenceNumber>=0),b(this.segmentedInput.firstSegment);let n=await this.segmentedInput.getMediaOffset(e,r.input),a=e.timestamp-this.segmentedInput.firstSegment.timestamp,s=t.clone({timestamp:Mt(t.timestamp+n,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+t.sequenceNumber});return this.packetInfos.set(s,{segment:e,track:r,sourcePacket:t}),s}async getFirstPacket(t){await this.hydrate(),b(this.firstInputTrack),b(this.firstSegment);let e=this.firstInputTrack,r=this.firstSegment;for(;;){if(e){let s=await e._backing.getFirstPacket(t);if(s)return this.createAdjustedPacket(s,r,e)}if(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:t.skipLiveWait}),!r)break;e=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(s=>s.type===this.firstInputTrack.type&&s.number===this.firstInputTrack.number)??null}return null}getNextPacket(t,e){return this._getNextInternal(t,e,!1)}getNextKeyPacket(t,e){return this._getNextInternal(t,e,!0)}async _getNextInternal(t,e,r){let n=this.packetInfos.get(t);if(!n)throw new Error("Packet was not created from this track.");let a=r?await n.track._backing.getNextKeyPacket(n.sourcePacket,e):await n.track._backing.getNextPacket(n.sourcePacket,e);if(a)return this.createAdjustedPacket(a,n.segment,n.track);let s=n.segment;for(;;){let o=await this.segmentedInput.getNextSegment(s,{skipLiveWait:e.skipLiveWait});if(!o)return null;let u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(m=>m.type===n.track.type&&m.number===n.track.number);if(!u){s=o;continue}let d=await u._backing.getFirstPacket(e);if(d&&r&&d.type!=="key"&&(d=await u._backing.getNextKeyPacket(d,e)),!d){s=o;continue}return this.createAdjustedPacket(d,o,u)}}getPacket(t,e){return this._getPacketInternal(t,e,!1)}getKeyPacket(t,e){return this._getPacketInternal(t,e,!0)}async _getPacketInternal(t,e,r){let n=await this.segmentedInput.getSegmentAt(t,{skipLiveWait:e.skipLiveWait});if(n??=await this.segmentedInput.getFirstSegment({}),!n)return null;for(await this.hydrate();n;){let a=this.segmentedInput.getInputForSegment(n),o=(await a.getTracks()).find(f=>f.type===this.firstInputTrack.type&&f.number===this.firstInputTrack.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(n,a),l=this.segmentedInput.learnedSegmentTimestampOffset===null?await o._backing.getFirstPacket({...e,metadataOnly:!0}):null;if(l){let f=l.timestamp+c;this.segmentedInput.learnedSegmentTimestampOffset=f-n.timestamp;let p=t-f;if(p<-n.duration||p>=2*n.duration){let g=await this.segmentedInput.getSegmentAt(t,{skipLiveWait:e.skipLiveWait});if(g!==n){n=g;continue}}}let u=qf(t,c,await o.getTimeResolution()),d=r?await o._backing.getKeyPacket(u,e):await o._backing.getPacket(u,e);if(!d){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let m=r?await o._backing.getPacket(u,{...e,metadataOnly:!0}):d;if(b(m),u>=m.timestamp+m.duration){let f=await this.segmentedInput.getNextSegment(n,{skipLiveWait:e.skipLiveWait});if(f){let p=this.segmentedInput.getInputForSegment(f),h=(await p.getTracks()).find(k=>k.type===this.firstInputTrack.type&&k.number===this.firstInputTrack.number),y=h?await h._backing.getFirstPacket({...e,metadataOnly:!0}):null;if(y&&r&&y.type!=="key"&&(y=await h._backing.getNextKeyPacket(y,{...e,metadataOnly:!0})),y){let k=await this.segmentedInput.getMediaOffset(f,p),T=qf(t,k,await h.getTimeResolution());if(y.timestamp<=T){n=f;continue}}}}return this.createAdjustedPacket(d,n,o)}return null}},qf=(i,t,e)=>(Math.floor(Fe(e*i))-Math.round(e*t))/e,dc=class extends uc{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())}getTransformationMatrix(){return this.delegate(()=>this.firstInputTrack._backing.getTransformationMatrix())}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())}},mc=class extends uc{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 Kf=Sd(Mu(),1);Cn();var Gf=typeof Kf<"u"?Kf:void 0,Ou=0,Du=1/0,Qe=class extends st{constructor(){super();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(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ge;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Ou,Du),e=this._getFileSize(),b(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ge;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,r){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Ja(this,e,r)}_dispatchRead(e,r){this.onread?.(e,r),this._emit("read",{start:e,end:r})}ref(){return new Ei(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Ei=class{constructor(t){this._freed=!1;if(t._disposed)throw new Error("Cannot ref a disposed source.");t._incrementRefCount(),t._refFinalizationRegistry?.register(this,t,this),this._source=t}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");let t=this.source;b(t._refCount>0),t._decrementRefCount(),t._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},it=class extends Qe{constructor(e,r){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof r!="function")throw new TypeError("requestHandler must be a function.");super();this.rootPath=e;this.requestHandler=r}_resolveRequest(e){let r=this.requestHandler(e),n=a=>{if(!(a instanceof Qe||a instanceof Ei))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=a instanceof Qe?a.ref():a;return s.source._usedForHls||=this._usedForHls,s};return R(r)?r.then(n):n(r)}},Vu=(i,t)=>i.path===t.path,Zn=class extends it{constructor(){super(...arguments);this._root=null;this._rootRequest=null;this._removeRootReadListener=null}_read(e,r,n,a){if(!this._root){if(!this._rootRequest){let o=this._resolveRequest({path:this.rootPath,isRoot:!0}),c=l=>{let u=l instanceof Qe?l.ref():l;return this._root=u,this._rootRequest=null,this._removeRootReadListener=u.source.on("read",({start:d,end:m})=>{this._dispatchRead(d,m)}),u};R(o)?this._rootRequest=o.then(c):(c(o),b(this._root))}if(this._rootRequest)return this._rootRequest.then(()=>this._read(e,r,n,a))}let s=this._root.source;return r>(s._getFileSize()??1/0)?null:s._read(e,r,n,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?(this._removeRootReadListener(),this._root.free()):this._rootRequest&&this._rootRequest.then(e=>{this._removeRootReadListener(),e.free()}).catch(()=>{})}},fc=class extends Qe{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super();this._onreadCalled=!1;this._bytes=G(e),this._view=N(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},Qf=typeof FinalizationRegistry<"u"?new FinalizationRegistry(i=>{i.cancel().catch(()=>{})}):null,pc=class extends Qe{constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.useStreamReader!==void 0&&typeof r.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super();this._readers=new WeakMap;this._blob=e,this._options=r,this._orchestrator=new Za({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:n=>{let a=this._readers.get(n);a&&(this._readers.delete(n),Qf?.unregister(n),a.cancel().catch(()=>{}))},prefetchProfile:Uu.fileSystem,handleUnhandledError:r.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,r,n,a){return this._orchestrator.read(e,r,n,a)}async _runWorker(e){b(e.strictTarget);let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!et()&&this._options.useStreamReader!==!1?(r=this._blob.slice(e.currentPos).stream().getReader(),Qf?.register(e,r,e)):r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:n,value:a}=await r.read();if(n)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await r?.cancel().catch(()=>{})}_dispose(){this._orchestrator.dispose()}},gg=.5*2**20,bg=(i,t,e)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(e instanceof Request?e.url:e,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==window.location.origin)return O._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**(i-2),16)},jf=new Set,hc=class i extends it{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.parallelism!==void 0&&(!Number.isInteger(r.parallelism)||r.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");let n=e instanceof Request?e.url:e instanceof URL?e.href:e;super(n,o=>new i(o.path,{...this._options,requestInit:this._requestInit}));this._offset=0;this._length=null;this._fileSizeDetermined=!1;this._sequentialBacking=null;this._abortControllers=new Map;this._sequentialAbortController=null;this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??bg,this._requestInit={...r.requestInit};let a=null;if(r.requestInit?.headers){let o={...xs(r.requestInit.headers)},c=Object.keys(o).find(l=>l.toLowerCase()==="range");c!==void 0&&(a=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){let o=e,c=e.headers.get("Range");c!==null&&(a??=c,o=new Request(e),o.headers.delete("Range"),this._url=o),this._requestInit={cache:o.cache,credentials:o.credentials,integrity:o.integrity,keepalive:o.keepalive,mode:o.mode==="navigate"?void 0:o.mode,redirect:o.redirect,referrer:o.referrer,referrerPolicy:o.referrerPolicy,...this._requestInit},this._requestInit.headers=Bs({headers:o.headers},this._requestInit).headers}if(a!==null){let o=kg(a);o&&(this._offset=o.offset,this._length=o.length)}let s=2;this._orchestrator=new Za({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??s,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:o=>{this._abortControllers.get(o)?.abort(),this._abortControllers.delete(o)},prefetchProfile:Uu.network,handleUnhandledError:r.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:ne(e-this._offset,0,this._length??1/0)}_read(e,r,n,a){if(this._length!==null&&r>this._length)return null;let s=this._offset,o=this._sequentialBacking?this._sequentialBacking._read(s+e,s+r):this._orchestrator.read(s+e,s+r,Math.max(s+n,s),s+Math.min(a,this._length??1/0)),c=l=>l?(l.offset-=this._offset,l):null;return R(o)?o.then(c):c(o)}async _runWorker(e){let r=0,n=this._length!==null?this._offset+this._length-1:"";for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}let a=new AbortController;this._abortControllers.set(e,a);let s=await _l(this._options.fetchFn??fetch,this._url,Bs(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-${n}`},signal:a.signal}),this._getRetryDelay,()=>a.signal.aborted),o=s.status===416?/^bytes \*\/(\d+)$/.exec(s.headers.get("Content-Range")??""):null,c=null;if(o?c=Number(o[1]):s.status===416&&e.currentPos>e.startPos&&(c=e.currentPos),c!==null&&c<=e.currentPos){s.body?.cancel().catch(()=>{}),this._orchestrator.fileSize===null&&this._orchestrator.supplyFileSize(c),this._fileSizeDetermined=!0,this._orchestrator.onWorkerFinished(e);return}if(!s.ok)throw s.body?.cancel().catch(()=>{}),new Error(`Error fetching ${this.rootPath}: ${s.status} ${s.statusText}`);s.redirected&&(this.rootPath=s.url);e:if(this._orchestrator.fileSize===null&&!s.headers.has("Content-Encoding")&&(s.status===206||s.type==="basic")){let d=s.headers.get("Content-Range");if(d){let f=/\/(\d+)/.exec(d);if(f){this._orchestrator.supplyFileSize(Number(f[1]));break e}}let m=s.headers.get("Content-Length");if(m){let f=s.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(f+Number(m))}}if(this._fileSizeDetermined=!0,!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(s.status!==206){if(this._sequentialBacking){s.body.cancel().catch(()=>{});return}if(!this._usedForHls){let d=new URL(s.url||(this._url instanceof Request?this._url.url:this._url),typeof window<"u"?window.location.href:void 0);d.origin!=="null"&&!(d.pathname.endsWith(".m3u8")||d.pathname.endsWith(".m3u"))&&(jf.has(d.origin)||(O._warn(`HTTP server (origin ${d.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),jf.add(d.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(s.body,a);return}let l=s.body.getReader(),u=e.currentPos;for(;;){if(e.currentPos>=e.targetPos||e.aborted){a.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let d;try{d=await l.read()}catch(p){if(a.signal.aborted)throw p;let g=this._getRetryDelay(++r,p,this._url);if(g!==null){O._error("Error while reading response stream. Attempting to resume.",p),await Nr(1e3*g);break}else throw p}if(e.aborted)continue;let{done:m,value:f}=d;if(m){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(!e.strictTarget&&(e.currentPos===u||s.headers.has("Content-Encoding"))){this._orchestrator.onWorkerFinished(e);return}if(e.currentPos>u)break;r++;let p=new Error("Range response ended without delivering any data."),g=this._getRetryDelay(r,p,this._url);if(g===null)throw p;O._error("Retrying range request that ended without delivering any data."),await Nr(1e3*g);break}r=0,this._dispatchResourceRead(e.currentPos,e.currentPos+f.length),this._orchestrator.supplyWorkerData(e,f)}}}_transitionToSequentialMode(e,r){this._sequentialAbortController=r;let n=e.getReader(),a=0,s=0,o=0,c=new ReadableStream({pull:async d=>{for(;;){let m;try{m=await n.read()}catch(p){if(this._disposed)throw p;let g=this._getRetryDelay(++o,p,this._url);if(g===null)throw p;O._error("Error while reading response stream. Attempting to resume.",p),await Nr(1e3*g),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();let h=await _l(this._options.fetchFn??fetch,this._url,Bs(this._requestInit,{headers:{Range:`bytes=${a}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!h.ok)throw h.body?.cancel().catch(()=>{}),new Error(`Error fetching ${this.rootPath}: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");n=h.body.getReader(),s=h.status===206?0:a;continue}if(m.done){d.close();return}let f=m.value;if(s>0){let p=Math.min(s,f.length);if(s-=p,f=f.subarray(p),f.length===0)continue}if(o=0,f.length!==0){a+=f.length,d.enqueue(f);return}}},cancel:()=>n.cancel().catch(()=>{})}),l=new rn(c,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});l._endIndex=this._orchestrator.fileSize,l._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",l.on("read",({start:d,end:m})=>this._dispatchResourceRead(d,m)),this._sequentialBacking=l;let u=new Set;for(let d of this._orchestrator.workers){for(let m of d.pendingSlices)u.add(m);d.aborted=!0,d.pendingSlices.length=0}for(let d of this._orchestrator.queuedReads)for(let m of d.pendingSlices)u.add(m);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(let[,d]of this._abortControllers)d.abort();this._abortControllers.clear();for(let d of u){let m=l._read(d.start,d.start+d.bytes.length);R(m)?m.then(f=>{f?(b(f.offset===d.start),d.resolve(f.bytes)):d.resolve(null)},f=>d.reject(f)):(b(m===null),d.resolve(null))}}_dispatchResourceRead(e,r){let n=Math.max(e-this._offset,0),a=Math.min(r-this._offset,this._length??1/0);n<a&&this._dispatchRead(n,a)}_dispose(){this._orchestrator.dispose();for(let[,e]of this._abortControllers)e.abort();this._abortControllers.clear(),this._sequentialAbortController?.abort(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}},yg=/^bytes=(\d+)-(\d*)$/,kg=i=>{let t=yg.exec(i.trim());if(!t)return null;let e=Number(t[1]),r=t[2]===""?null:Number(t[2]);return r!==null&&r<e?null:{offset:e,length:r!==null?r-e+1:null}},Bu=null;typeof FinalizationRegistry<"u"&&(Bu=new FinalizationRegistry(i=>{i.close()}));var gc=class i extends it{constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Gf.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,n=>new i(n.path,r));this._fileHandle=null;this._customSource=new Jn({getSize:async()=>{let n=await Gf.fs.open(e,"r");if(this._disposed)throw n.close(),new ge;return this._fileHandle=n,Bu?.register(this,n,this),(await n.stat()).size},read:async(n,a)=>{b(this._fileHandle);let s=new Uint8Array(a-n),o=0;for(;o<s.length;){let c=await this._fileHandle.read(s,o,s.length-o,n+o);if(c.bytesRead===0)throw new Error(`File ended at byte ${n+o}, before byte ${a} was read; it was likely truncated while being read.`);o+=c.bytesRead}return s},maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:r.handleUnhandledError}),this._customSource.on("read",({start:n,end:a})=>this._dispatchRead(n,a))}_read(e,r,n,a){return this._customSource._read(e,r,n,a)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._disposed=!0,this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Bu?.unregister(this))}},Jn=class extends Qe{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.handleUnhandledError!==void 0&&typeof e.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!Ie(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super();this._readers=new Set;this._pendingSize=null;this._options=e,this._orchestrator=new Za({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:Uu[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,r,n,a){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,r,n,a);let s=this._pendingSize??this._options.getSize();if(R(s))return this._pendingSize=s,s.then(o=>{if(!Number.isInteger(o)||o<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");if(this._disposed)throw new ge;return this._orchestrator.fileSize=o,r>o?null:this._orchestrator.read(e,r,n,a)});if(!Number.isInteger(s)||s<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=s,r>s?null:this._orchestrator.read(e,r,n,a)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let r=e.currentPos,n=e.targetPos,a=this._options.read(e.currentPos,n);if(R(a)&&(a=await a),e.aborted){a instanceof ReadableStream&&await a.cancel().catch(()=>{});break}if(a instanceof Uint8Array){if(a=G(a),a.length!==n-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${a.length}.`);this._dispatchRead(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}else if(a instanceof ReadableStream){let s=a.getReader();this._readers.add(s);try{for(;e.currentPos<n&&!e.aborted;){let{done:o,value:c}=await s.read();if(o){if(e.currentPos<n)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-r} bytes, but got ${e.currentPos-r}`);break}if(!(c instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;let l=G(c);this._dispatchRead(e.currentPos,e.currentPos+l.length),this._orchestrator.supplyWorkerData(e,l)}}finally{this._readers.delete(s),s.cancel().catch(()=>{}),s.releaseLock()}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){this._orchestrator.dispose();for(let e of this._readers)e.cancel().catch(()=>{});this._readers.clear(),this._options.dispose?.()}},$f=Jn,rn=class extends Qe{constructor(e,r={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new 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._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.";this._stream=e,this._maxCacheSize=r.maxCacheSize??32*2**20,this._handleUnhandledError=r.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,r){if(this._endIndex!==null&&r>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,r);let n=j(this._cache,e,d=>d.start),a=n!==-1?this._cache[n]:null;if(a&&a.start<=e&&r<=a.end)return{bytes:a.bytes,view:a.view,offset:a.start};let s=e,o=[];if(n!==-1)for(let d=n;d<this._cache.length;d++){let m=this._cache[d];if(m.start>=r)break;let f=Math.max(e,m.start);f>s&&this._throwDueToCacheMiss();let p=Math.min(r,m.end);f<p&&(o.push({start:f,bytes:m.bytes.subarray(f-m.start,p-m.start)}),s=p)}if(s===r)return Xf(e,r,o);this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:c,resolve:l,reject:u}=te();return this._pendingSlices.push({start:e,end:r,parts:o,resolve:l,reject:u}),this._targetIndex=Math.max(this._targetIndex,r),this._pulling||(this._pulling=!0,this._pull().catch(d=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(m=>m.reject(d)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(d);else throw d})),c}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:r}=await this._reader.read();if(e){for(let s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,a=this._currentIndex+r.byteLength;this._dispatchRead(n,a);for(let s=0;s<this._pendingSlices.length;s++){let o=this._pendingSlices[s],c=Math.max(n,o.start),l=Math.min(a,o.end);c<l&&(o.parts.push({start:c,bytes:r.subarray(c-n,l-n)}),l===o.end&&(o.resolve(Xf(o.start,o.end,o.parts)),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:a,bytes:r,view:N(r),age:0});this._cache.length>0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=r.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new ge);this._pendingSlices.length=0,this._cache.length=0,(this._reader??this._stream).cancel().catch(()=>{})}},Xf=(i,t,e)=>{let r=new Uint8Array(t-i);for(let n of e)r.set(n.bytes,n.start-i);return{bytes:r,view:N(r),offset:i}},Uu={none:(i,t)=>({start:i,end:t}),fileSystem:(i,t)=>(i=Math.floor((i-65536)/65536)*65536,t=Math.ceil((t+65536)/65536)*65536,{start:i,end:t}),network:(i,t,e)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(let n of e){let s=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(Os(i,t,s,n.targetPos)){let o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);t=Math.max(t,n.startPos+u)}}return t=Math.max(t,i+gg),{start:i,end:t}}},Za=class{constructor(t){this.options=t;this.fileSize=null;this.nextAge=0;this.workers=[];this.cache=[];this.currentCacheSize=0;this.disposed=!1;this.queuedReads=[]}read(t,e,r,n){b(!this.disposed);let a=this.options.prefetchProfile(t,e,this.workers),s=Math.max(a.start,r),o=Math.min(a.end,this.fileSize??1/0,n);b(s<=t&&e<=o);let c=null,l=j(this.cache,t,w=>w.start),u=l!==-1?this.cache[l]:null;u&&u.start<=t&&e<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=j(this.cache,s,w=>w.start),m=c?null:new Uint8Array(e-t),f=0,p=s,g=[];if(d!==-1){for(let w=d;w<this.cache.length;w++){let A=this.cache[w];if(A.start>=o)break;if(A.end<=s)continue;let C=Math.max(s,A.start),E=Math.min(o,A.end);if(b(C<=E),p<C&&g.push({start:p,end:C}),p=E,m){let I=Math.max(t,A.start),x=Math.min(e,A.end);if(I<x){let P=I-t;m.set(A.bytes.subarray(I-A.start,x-A.start),P),P===f&&(f=x-t)}}A.age=this.nextAge++}p<o&&g.push({start:p,end:o})}else g.push({start:s,end:o});if(m&&f>=m.length&&(c={bytes:m,view:N(m),offset:t}),g.length===0)return b(c),c;let{promise:h,resolve:y,reject:k}=te(),T=[];for(let w of g){let A=Math.max(t,w.start),C=Math.min(e,w.end);A===w.start&&C===w.end?T.push(w):A<C&&T.push({start:A,end:C})}let S=m&&{start:t,bytes:m,holes:T,resolve:y,reject:k};e:for(let w of g){for(let E of this.workers)if(this.checkHoleAgainstWorker(E,w,S?[S]:[])){this.checkQueuedReadsAgainstWorker(E);continue e}let A=w.end<o||this.fileSize!==null,C=this.createWorker(w.start,w.end,A);if(C)S&&(C.pendingSlices=[S]),this.runWorker(C);else{let E=j(this.queuedReads,w.start,x=>x.hole.start),I=E!==-1?this.queuedReads[E]:null;for(I&&w.start<=I.hole.end?(I.hole.end=Math.max(I.hole.end,w.end),I.strictTarget&&=A,S&&I.pendingSlices.push(S)):(E++,I={hole:{start:w.start,end:w.end},strictTarget:A,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(E,0,I));E+1<this.queuedReads.length;){let x=this.queuedReads[E+1];if(x.hole.start>I.hole.end)break;I.hole.end=Math.max(I.hole.end,x.hole.end),I.pendingSlices.push(...x.pendingSlices),I.strictTarget&&=x.strictTarget,I.age=Math.min(I.age,x.age),this.queuedReads.splice(E+1,1)}}}return c?h.catch(w=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(w);else throw w}):(b(m),c=h.then(w=>w&&{bytes:w,view:N(w),offset:t})),c}checkHoleAgainstWorker(t,e,r){if(Os(e.start-131072,e.start,t.currentPos,t.targetPos)){t.targetPos=Math.max(t.targetPos,e.end);for(let a=0;a<r.length;a++){let s=r[a];t.pendingSlices.includes(s)||t.pendingSlices.push(s)}return t.running||this.runWorker(t),!0}return!1}checkQueuedReadsAgainstWorker(t){let e=!1;for(let r=0;r<this.queuedReads.length;r++){let n=this.queuedReads[r];if(this.checkHoleAgainstWorker(t,n.hole,n.pendingSlices))this.queuedReads.splice(r,1),r--,e=!0;else if(e)break}}createWorker(t,e,r){if(this.workers.length>=this.options.maxWorkerCount){let a=null,s=null;for(let o=0;o<this.workers.length;o++){let c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!a||c.age<a.age)&&(s=o,a=c)}if(a)b(s!==null),b(a.pendingSlices.length===0),this.workers.splice(s,1),this.options.onIdleWorkerRemoved?.(a);else return null}let n={startPos:t,currentPos:t,targetPos:e,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(n),n}runWorker(t){b(!t.running),b(t.currentPos<t.targetPos),t.running=!0,t.age=this.nextAge++,this.options.runWorker(t).catch(e=>{if(t.running=!1,t.pendingSlices.length>0)t.pendingSlices.forEach(r=>r.reject(e)),t.pendingSlices.length=0;else if(!t.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(e);else throw e}).finally(()=>{if(!t.running&&this.queuedReads.length>0){let e=0;for(let a=1;a<this.queuedReads.length;a++)this.queuedReads[a].age<this.queuedReads[e].age&&(e=a);let r=this.queuedReads[e],n=this.createWorker(r.hole.start,r.hole.end,r.strictTarget);if(!n)return;this.queuedReads.splice(e,1),n.pendingSlices=r.pendingSlices,this.runWorker(n)}})}supplyWorkerData(t,e){b(!t.aborted);let r=t.currentPos,n=r+e.length;this.insertIntoCache({start:r,end:n,bytes:e,view:N(e),age:this.nextAge++}),t.currentPos+=e.length,t.currentPos>t.targetPos&&(t.targetPos=t.currentPos,this.checkQueuedReadsAgainstWorker(t));for(let a=0;a<t.pendingSlices.length;a++){let s=t.pendingSlices[a],o=Math.max(r,s.start),c=Math.min(n,s.start+s.bytes.length);o<c&&s.bytes.set(e.subarray(o-r,c-r),o-s.start);for(let l=0;l<s.holes.length;l++){let u=s.holes[l];r<=u.start&&n>u.start&&(u.start=n),u.end<=u.start&&(s.holes.splice(l,1),l--)}s.holes.length===0&&(s.resolve(s.bytes),t.pendingSlices.splice(a,1),a--)}for(let a=0;a<this.workers.length;a++){let s=this.workers[a];t===s||s.running||Os(r,n,s.currentPos,s.targetPos)&&(this.workers.splice(a,1),this.options.onIdleWorkerRemoved?.(s),a--)}}supplyFileSize(t){b(this.fileSize===null),this.fileSize=t;for(let e of this.workers){e.targetPos=Math.min(e.targetPos,t),e.strictTarget=!0;for(let r=0;r<e.pendingSlices.length;r++){let n=e.pendingSlices[r];for(let a of n.holes)if(a.end>t){n.resolve(null),e.pendingSlices.splice(r,1),r--;break}}}for(let e=0;e<this.queuedReads.length;e++){let r=this.queuedReads[e];for(let n=0;n<r.pendingSlices.length;n++){let a=r.pendingSlices[n];a.start+a.bytes.length>t&&(a.resolve(null),r.pendingSlices.splice(n,1),n--)}r.hole.start>=t?(this.queuedReads.splice(e,1),e--):(r.hole.end=Math.min(r.hole.end,t),r.strictTarget=!0)}}signalWorkerStoppedRunning(t){t.running=!1,t.aborted||(t.pendingSlices.length=0)}onWorkerFinished(t){let e=this.workers.indexOf(t);b(e!==-1),t.running=!1,this.workers.splice(e,1),this.options.onIdleWorkerRemoved?.(t),this.fileSize===null&&this.supplyFileSize(t.currentPos);for(let r of t.pendingSlices)r.start+r.bytes.length>t.currentPos&&r.resolve(null)}insertIntoCache(t){if(this.options.maxCacheSize===0)return;let e=j(this.cache,t.start,r=>r.start)+1;if(e>0){let r=this.cache[e-1];if(r.end>=t.end)return;if(r.end>t.start){let n=new Uint8Array(t.end-r.start);n.set(r.bytes,0),n.set(t.bytes,t.start-r.start),this.currentCacheSize+=t.end-r.end,r.bytes=n,r.view=N(n),r.end=t.end,e--,t=r}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length;for(let r=e+1;r<this.cache.length;r++){let n=this.cache[r];if(t.end<=n.start)break;if(t.end>=n.end){this.cache.splice(r,1),this.currentCacheSize-=n.bytes.length,r--;continue}let a=new Uint8Array(n.end-t.start);a.set(t.bytes,0),a.set(n.bytes,n.start-t.start),this.currentCacheSize-=t.end-n.start,t.bytes=a,t.view=N(a),t.end=n.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,n=this.cache[0];for(let a=1;a<this.cache.length;a++){let s=this.cache[a];s.age<n.age&&(r=a,n=s)}if(this.currentCacheSize-n.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=n.bytes.length}}dispose(){for(let t of this.workers){for(let e of t.pendingSlices)e.reject(new ge);t.pendingSlices.length=0,t.aborted=!0,t.running||this.options.onIdleWorkerRemoved?.(t)}for(let t of this.queuedReads)for(let e of t.pendingSlices)e.reject(new ge);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}};var Ja=class extends Qe{constructor(e,r,n){super();this._ref=null;this._removeReadListener=null;if(e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=r,this._length=n??null}_getFileSize(){if(this._length!==null)return this._length;let e=this._baseSource._getFileSize();return e==null?e:Math.max(e-this._offset,0)}_read(e,r,n,a){if(this._length!==null&&r>this._length)return null;let s=this._baseSource._getFileSize(),o=typeof s=="number"&&this._offset+r>s?null:this._baseSource._read(this._offset+e,this._offset+r,this._offset+n,this._offset+Math.min(a,this._length??1/0)),c=l=>{if(!l){if(this._length!==null){let u=this._offset+this._length;throw new Error(`Underlying data too short, expected a length of at least ${u} bytes.`)}return null}return l.offset-=this._offset,l};return R(o)?o.then(c):c(o)}_dispose(){this._ref?.free(),this._removeReadListener?.()}ref(){return this._ref||(this._ref=this._baseSource.ref(),this._removeReadListener=this._baseSource.on("read",({start:e,end:r})=>{let n=Math.max(e-this._offset,0),a=Math.min(r-this._offset,this._length??1/0);n<a&&this._dispatchRead(n,a)})),super.ref()}};var Tg=/^0[xX][0-9a-fA-F]+$/,wg=/^data:.*;base64,/i,Yf=1e9,es=class extends lc{constructor(e,r,n,a){super(e.input,r,n);this.segments=[];this.nextLines=null;this.currentUpdateSegmentsPromise=null;this.streamHasEnded=!1;this.neverRemovesSegments=!1;this.lastSegmentUpdateTime=-1/0;this.refreshInterval=5;this.segmentTimestampOffsetPromise=null;this.rootPath=r,this.demuxer=e,this.nextLines=a}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await Nr(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,r=Math.max(0,1e3*this.refreshInterval-e);return r<=50?0:r}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){var S=[];try{let E=yt(S,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}));let I=new Ii(E.source);let x=I.requestSliceRange(0,0,64);R(x)&&(x=await x);if(x&&!be.decode(U(x,x.length)).trimStart().startsWith("#EXTM3U"))throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");let P=await I.requestEntireFile();b(P);e=bc(P,P.length,{ignore:cc});E.source instanceof it&&(this.rootPath=E.source.rootPath)}catch(w){var A=w,C=!0}finally{kt(S,A,C)}}let r=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1&&(this.segments.length===0||this.segments[0].unixEpochTimestamp===this.segments[0].timestamp),n=new $n(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),a=!1,s=0,o=null,c=null,l=null,u=0,d=0,m=null,f=null,p=null,g=null,h=null,y=J(this.segments)??null,k=E=>{let I=E.indexOf("@"),x=Number(I===-1?E:E.slice(0,I));if(!Number.isInteger(x)||x<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${E}'.`);let P=null;if(I!==-1&&(P=Number(E.slice(I+1)),!Number.isInteger(P)||P<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${E}'.`);return{length:x,offset:P}},T=E=>{if(u=E,y&&(b(y.sequenceNumber!==null),y.sequenceNumber<E)){let I=(E-y.sequenceNumber)*y.duration;s=y.timestamp+I,m=y.firstSegment??y,f=y.initSegment,h=y.lastProgramDateTimeSeconds,o=y.unixEpochTimestamp!==null?y.unixEpochTimestamp+I:null,y=null}};for(let E=0;E<e.length;E++){let I=e[E];if(!a){if(I!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");a=!0;continue}if(!I.startsWith("#")){if(!y){if(c===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let x=l;if(x&&x.method==="AES-128"&&!x.iv){let M=new Uint8Array(Xt),D=N(M);D.setUint32(8,Math.floor(u/2**32)),D.setUint32(12,u),x={...x,iv:M}}let v={path:ve(this.rootPath,n.substitute(I)),offset:g?.offset??0,length:g?.length??null};m&&m.discontinuityNumber!==d&&(m=null);let _={index:this.segments.length,timestamp:s,unixEpochTimestamp:o,discontinuityNumber:d,firstSegment:m,sequenceNumber:u,location:v,duration:c,encryption:x,initSegment:f,lastProgramDateTimeSeconds:h};m??=_,s+=c,o!==null&&(o+=c),this.segments.push(_)}c=null,g===null?p=null:g=null,T(u+1)}if(I.startsWith($a)){if(y)continue;let x=I.slice($a.length),P=x.indexOf(","),v=P===-1?x:x.slice(0,P),_=Number(v);if(!Number.isFinite(_)||_<0||_>Yf)throw new Error(`Invalid #EXTINF tag duration '${v}'.`);c=_}else if(I.startsWith(Yn))n.define(I.slice(Yn.length));else if(I.startsWith(Cu)){let x=new xr(I.slice(Cu.length),n),P=x.get("uri");if(!P)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let v=x.get("byterange"),_=null;if(v!==null&&(_=k(v)),_&&_.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){let D={path:ve(this.rootPath,P),offset:_?.offset??0,length:_?.length??null};if(l?.method==="AES-128"&&!l.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");f={index:-1,timestamp:s,unixEpochTimestamp:o,discontinuityNumber:d,firstSegment:null,sequenceNumber:null,location:D,duration:0,encryption:l,initSegment:null,lastProgramDateTimeSeconds:h}}}else if(I.startsWith(Pu)){let x=new xr(I.slice(Pu.length),n),P=x.get("method");if(P==="NONE")l=null;else if(P==="AES-128"){let v=x.get("uri");if(!v)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let _=null,M=x.get("iv");if(M){if(!Tg.test(M))throw new Error(`Unsupported IV format '${M}'.`);let L=M.slice(2);L=L.padStart(2*Xt,"0"),L=L.slice(-2*Xt),_=new Uint8Array(Xt);for(let z=0;z<Xt;z++){let $=2*z;_[z]=parseInt(L.slice($,$+2),16)}}let D=x.get("keyformat")??"identity";if(D!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");l={method:"AES-128",keyUri:ve(this.rootPath,v),iv:_,keyFormat:D}}else if(P==="SAMPLE-AES"||P==="SAMPLE-AES-CTR"){let v=x.get("uri");if(!v)throw new Error(`Invalid #EXT-X-KEY: ${P} requires a URI attribute.`);if((x.get("keyformat")??"identity")==="identity")throw new 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 M=null;if(wg.test(v)){let D=v.indexOf(","),L=Hi(v.slice(D+1));if(L.length>=8&&L[4]===112&&L[5]===115&&L[6]===115&&L[7]===104){let z=N(L).getUint32(0);M=Co(L.subarray(8,Math.min(z,L.length)))}}l={method:P,psshBox:M}}else throw new Error(`Unsupported encryption method '${P}'. If you think this method should be supported, please raise an issue.`)}else if(I.startsWith(Eu)){let x=I.slice(Eu.length),P=Number(x);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${x}'.`);T(P)}else if(I.startsWith(Iu)){let x=k(I.slice(Iu.length));if(x.offset===null){if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");x.offset=p}g=x,p=x.offset+x.length}else if(I.startsWith(vu)){if(y)continue;let x=I.slice(vu.length),P=Date.parse(x);if(!Number.isFinite(P))continue;let v=P/1e3;if(h===v)continue;if(h===null&&this.segments.length>0){let _=v-s;for(let M of this.segments)M.unixEpochTimestamp=M.timestamp+_,r&&(M.timestamp=M.unixEpochTimestamp)}h=v,o=v,r&&(s=v)}else if(I===Lf)m=null,d++;else if(I.startsWith(_u)){let x=I.slice(_u.length),P=Number(x);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-DISCONTINUITY-SEQUENCE value '${x}'.`);d=P}else if(I.startsWith(Ru)){let x=I.slice(Ru.length),P=Number(x);if(!Number.isFinite(P)||P<0||P>Yf)throw new Error(`Invalid EXT-X-TARGETDURATION value '${x}'.`);this.refreshInterval=ne(P,.5,3600)}else if(I===Wf)this.hasOnlyKeyPackets=!0;else if(I===Hf){this.streamHasEnded=!0;break}else if(I.startsWith(Fu)){let x=I.slice(Fu.length).toLowerCase();x==="vod"&&(this.streamHasEnded=!0),(x==="vod"||x==="event")&&(this.neverRemovesSegments=!0)}}if(!a)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&!this.streamHasEnded&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,r){this.segments.length===0&&!this.streamHasEnded&&!(r.skipLiveWait&&this.getRemainingWaitTimeMs()>0)&&await this.runUpdateSegments();let n=e-(this.learnedSegmentTimestampOffset??0),a=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let s=j(this.segments,n,c=>c.timestamp);if(s===-1)return null;if(s<this.segments.length-1||this.streamHasEnded||a)return this.segments[s];let o=this.segments[s];if(n<o.timestamp+o.duration)return o;await this.runUpdateSegments(),r.skipLiveWait&&(a=!0)}}async getNextSegment(e,r){let n=e.index;b(n!==-1);let a=n+1,s=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(a<this.segments.length)return this.segments[a];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),r.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){let r=e.index;return b(r!==-1),this.segments[r-1]??null}getInputForSegment(e){let r=e,n=this.inputCache.find(l=>l.segment===r);if(n)return n.age=this.nextInputCacheAge++,n.input;let a=null;(r.initSegment||r.firstSegment)&&(a=this.getInputForSegment(r.initSegment??r.firstSegment));let s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(l=>{if(!r.encryption||!(r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR")||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(l);let u=l.psshBoxes,{psshBox:d}=r.encryption;return(d.keyIds===null||d.keyIds.includes(l.keyId))&&!u.some(m=>Po(m,d))&&(u=[...u,d]),this.input._formatOptions.isobmff.resolveKeyId({...l,psshBoxes:u})})}},o=new vi({source:new Zn(r.location.path,async l=>{b(l.isRoot);let u={...l,isRoot:!1},d,m=r.location.offset>0||r.location.length!==null;if(!r.encryption||r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(u),m){let p=d.source.slice(r.location.offset,r.location.length??void 0).ref();d.free(),d=p}}else if(r.encryption.method==="AES-128"){let f=r.encryption;b(f.iv);let p=await this.input._getSourceCached(u);if(m){let k=p.source.slice(r.location.offset,r.location.length??void 0).ref();p.free(),p=k}let g=new Ii(p.source),h=af(g,async()=>{var w=[];try{let y=yt(w,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},Zf));let k=new Ii(y.source);let T=await k.requestSlice(0,Xt);if(!T)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");let S=U(T,Xt);return{key:S,iv:f.iv}}catch(A){var C=A,E=!0}finally{kt(w,C,E)}},()=>{p.free()});d=new rn(h).ref()}else b(!1);return d}),formats:this.input._formats.filter(l=>!(l instanceof nn)),initInput:a??void 0,formatOptions:s});if(o._onFormatDetermined=l=>{if((r.encryption?.method==="SAMPLE-AES"||r.encryption?.method==="SAMPLE-AES-CTR")&&!l._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let l=li(this.inputCache,u=>u.age);b(l!==-1),this.inputCache.splice(l,1)}return o}async getLiveRefreshInterval(){return!this.streamHasEnded&&this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}getMediaOffsetForDiscontinuity(e){return this.demuxer.getMediaOffsetForDiscontinuity(e)}getFirstSegmentTimestampOffset(){return this.segmentTimestampOffsetPromise??=(async()=>{let e=await this.getFirstSegment();b(e);let r=this.demuxer.getReferenceSegmentedInput();if(this===r)return 0;let n=await r.getFirstSegment();if(n&&(this.listsAllSegments()&&r.listsAllSegments()||e.unixEpochTimestamp===e.timestamp&&n.unixEpochTimestamp===n.timestamp))return 0;let a=this.getInputForSegment(e);if(await this.getRawTimestampOffset(a)===null)return 0;let s=await Ya(a);if(s===null)throw new Error("The playlist's first segment contains no media.");let o=await this.getMediaOffset(e,a),c=s+o-e.timestamp;return this.learnedSegmentTimestampOffset??=c,c})()}listsAllSegments(){return this.segments[0].sequenceNumber===0||this.neverRemovesSegments}async getRawTimestampOffset(e){if((await e.getFormat()).supportsTimestampedMediaData)return 0;let a=(await e.getMetadataTags()).raw?.PRIV;for(let s of Bt(a)){if(!(s instanceof Uint8Array)||s.length!==zt.length+1+8||be.decode(s.subarray(0,zt.length))!==zt||s[zt.length]!==0)continue;let o=N(s),c=o.getUint32(zt.length+1),l=o.getUint32(zt.length+5);if(c>1)continue;let u=2**32*c+l;return ac(u,nc(u))/Ue-await e.getFirstTimestamp()}return null}getTimestampWrapPeriod(){return Xn/Ue}};var Sg=256,Ag=256,kc=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.trackBackings=null;this.internalTracks=null;this.segmentedInputs=[];this.hasMasterPlaylist=!0;this.masterPlaylistVariables=null;this.mediaOffsets=new Map}readMetadata(){return this.metadataPromise??=(async()=>{b(this.input._rootSource instanceof it);let e=await this.input._reader.requestEntireFile();b(e);let r=bc(e,e.length,{ignore:cc}),{rootPath:n}=this.input._rootSource,a=new $n(n,null),s=[],o=[];for(let d=1;d<r.length;d++){let m=r[d];if(m.startsWith(Yn))a.define(m.slice(Yn.length));else if(m.startsWith(Su)){let f=d,p=r[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");p=a.substitute(p);let g=ve(n,p),h=new xr(m.slice(Su.length),a);if(h.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");s.push({fullPath:g,attributes:h,lineNumber:f,hasOnlyKeyPackets:!1})}else if(m.startsWith(Au)){let f=new xr(m.slice(Au.length),a),p=f.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(f.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let h=ve(n,p);s.push({fullPath:h,attributes:f,lineNumber:d,hasOnlyKeyPackets:!0})}else if(m.startsWith(xu)){let f=new xr(m.slice(xu.length),a);if(f.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(f.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let h=null,y=f.get("uri");y!==null&&(h=ve(n,y)),o.push({fullPath:h,attributes:f,lineNumber:d})}else if(m.startsWith($a)){let f=new es(this,n,null,r);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}if(s.length>Sg||o.length>Ag)throw new Error("Unsupported M3U8 file; too many variant streams or media tags.");this.masterPlaylistVariables=a;let c=await Promise.all(s.map(async(d,m)=>{let f=[],p=d.attributes.get("codecs"),g;if(p)g=p.split(",").map(x=>x.trim());else{let P=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),v=await Promise.all(P.map(async _=>({track:_,codec:await _.getCodec()})));g=await Promise.all(v.filter(_=>_.codec!==null).map(_=>_.track.getDecoderConfig().then(M=>M.codec)))}let h=d.attributes.get("video"),y=d.attributes.get("audio"),k=g.some(x=>le.includes(ct(x))),T=g.some(x=>pe.includes(ct(x)));if(h!==null&&!k){let x=o.find(P=>{let v=P.attributes.get("group-id"),_=P.attributes.get("type");return v===h&&_.toLowerCase()==="video"});e:if(x){let P=x.attributes.get("uri");if(P===null)break e;let v=ve(n,P),D=(await this.getSegmentedInputForPath(v).getTrackBackings()).find(z=>z.getType()==="video");if(!D||await D.getCodec()===null)break e;let L=await D.getDecoderConfig().then(z=>z?.codec??null);b(L!==null),g.push(L)}}if(y!==null&&!T){let x=o.find(P=>{let v=P.attributes.get("group-id"),_=P.attributes.get("type");return v===y&&_.toLowerCase()==="audio"});e:if(x){let P=x.attributes.get("uri");if(P===null)break e;let v=ve(n,P),D=(await this.getSegmentedInputForPath(v).getTrackBackings()).find(z=>z.getType()==="audio");if(!D||await D.getCodec()===null)break e;let L=await D.getDecoderConfig().then(z=>z?.codec??null);b(L!==null),g.push(L)}}g=[...new Set(g)];let S=d.attributes.getAsNumber("bandwidth");b(S!==null);let w=d.attributes.getAsNumber("average-bandwidth"),A=d.attributes.get("name"),C=async(x,P,v)=>{let _=new Set(x.map($=>ct($)));if(_.size===1){let[$]=_;return b($),{codec:$,fullCodecString:x.length===1?x[0]:null}}let D=(await this.getSegmentedInputForPath(P).getTrackBackings()).filter($=>$.getType()===v);if(D.length!==1)throw new Error(`Unsupported M3U8 file; a variant stream lists several ${v} codecs, but its media doesn't contain exactly one ${v} track.`);let L=await D[0].getCodec();if(L===null)return null;let z=await D[0].getDecoderConfig();return b(z),{codec:L,fullCodecString:z.codec}},E=g.filter(x=>le.includes(ct(x))),I=g.filter(x=>pe.includes(ct(x)));for(let x of g)if(x===E[0]){let P=o.filter(v=>v.attributes.get("group-id")===h&&v.attributes.get("type").toLowerCase()==="video");if(P.length===0){let v=d.attributes.get("resolution"),_=null,M=null;if(v){let L=v.match(/^(\d+)x(\d+)$/);L&&(_=Number(L[1]),M=Number(L[2]))}let D=await C(E,d.fullPath,"video");D&&f.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ce,lineNumber:d.lineNumber,fullPath:d.fullPath,codec:D.codec,fullCodecString:D.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:S,averageBitrate:w,name:A,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:_,height:M}})}else{let v=await Promise.all(P.map(_=>C(E,_.fullPath??d.fullPath,"video")));for(let _=0;_<P.length;_++){let M=P[_],D=v[_];if(!D)continue;let L=M.attributes.get("resolution")??d.attributes.get("resolution"),z=null,$=null;if(L){let fe=L.match(/^(\d+)x(\d+)$/);fe&&(z=Number(fe[1]),$=Number(fe[2]))}f.push({demuxer:this,backingTrack:null,default:yc(M.attributes),autoselect:yc(M.attributes)||Jf(M.attributes),languageCode:ep(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,codec:D.codec,fullCodecString:D.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:M.fullPath===null?S:null,averageBitrate:M.fullPath===null?w:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:z,height:$}})}}}else if(x===I[0]){let P=o.filter(v=>v.attributes.get("group-id")===y&&v.attributes.get("type").toLowerCase()==="audio");if(P.length===0){let v=await C(I,d.fullPath,"audio");if(v){let _=d.attributes.get("channels");f.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ce,lineNumber:d.lineNumber,fullPath:d.fullPath,codec:v.codec,fullCodecString:v.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:S,averageBitrate:w,name:A,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:tp(_)}})}}else{let v=await Promise.all(P.map(_=>C(I,_.fullPath??d.fullPath,"audio")));for(let _=0;_<P.length;_++){let M=P[_],D=v[_];if(!D)continue;let L=M.attributes.get("channels")??d.attributes.get("channels");f.push({demuxer:this,backingTrack:null,default:yc(M.attributes),autoselect:yc(M.attributes)||Jf(M.attributes),languageCode:ep(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,codec:D.codec,fullCodecString:D.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:M.fullPath===null?S:null,averageBitrate:M.fullPath===null?w:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:tp(L)}})}}}return f})),l=[],u=d=>{let m=l.find(f=>f.fullPath===d.fullPath&&f.info.type===d.info.type);m?(m.pairingMask|=d.pairingMask,m.default||=d.default,m.autoselect||=d.autoselect,m.lineNumber=Math.min(m.lineNumber,d.lineNumber),d.peakBitrate!==null&&(m.peakBitrate=Math.max(m.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(m.averageBitrate=Math.max(m.averageBitrate??-1/0,d.averageBitrate)),m.languageCode===ce&&(m.languageCode=d.languageCode)):l.push(d)};for(let d of c)for(let m of d)u(m);l.sort((d,m)=>d.lineNumber-m.lineNumber),this.trackBackings=[];for(let d of l)d.info.type==="video"?this.trackBackings.push(new wc(d)):this.trackBackings.push(new Sc(d));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),b(this.trackBackings),this.trackBackings}getMediaOffsetForDiscontinuity(e){let r=this.mediaOffsets.get(e);return r||(r=(async()=>{let n=this.getReferenceSegmentedInput(),a=await n.getFirstSegment();for(;a&&a.discontinuityNumber<e;)a=await n.getNextSegment(a,{});if(!a||a.discontinuityNumber!==e)throw new Error(`The reference playlist contains no segment in discontinuity ${e}, so the discontinuity can't be synchronized across tracks. If you think this is a bug, please raise an issue and include the playlist.`);let s=n.getInputForSegment(a),o=await n.getRawTimestampOffset(s)??0,c=await Ya(s);if(c===null)throw new Error("The reference playlist's segment contains no media.");return a.timestamp-(o+c)})(),this.mediaOffsets.set(e,r),r)}getReferenceSegmentedInput(){if(!this.hasMasterPlaylist)return this.segmentedInputs[0];b(this.internalTracks);let e=this.internalTracks.filter(o=>!o.hasOnlyKeyPackets),r=e.length>0?e:this.internalTracks,n=r.filter(o=>o.info.type==="video"),a=n.length>0?n:r,s=li(a,o=>o.peakBitrate??1/0);return b(s!==-1),this.getSegmentedInputForPath(a[s].fullPath)}getSegmentedInputForPath(e){let r=this.segmentedInputs.find(a=>a.path===e);if(r)return r;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({type:s.info.type}))),r=new es(this,e,n,null),this.segmentedInputs.push(r),r}async getMetadataTags(){return{}}async getMimeType(){return Cr}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Tc=class{constructor(t){this.internalTrack=t;this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let t=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),e=null,n=(await t.getTrackBackings()).filter(a=>a.getType()===this.getType());if(n.length===1)e=n[0];else if(this instanceof wc){for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}else{b(this instanceof Sc);for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}if(!e)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=e})()}delegate(t){return this.internalTrack.backingTrack?t():this.hydrate().then(t)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...Ve,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){b(this.internalTrack.demuxer.internalTracks);let t=this.internalTrack.info.type,e=0;for(let r of this.internalTrack.demuxer.internalTracks)if(r.info.type===t&&e++,r===this.internalTrack)break;return e}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(t){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(t))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(t){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(t)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(t){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(t)}async getPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(t,e)}async getKeyPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(t,e)}async getNextPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(t,e)}async getNextKeyPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(t,e)}},wc=class extends Tc{constructor(t){super(t)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return this.internalTrack.codec}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(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){if(await this.hydrate(),await this.backingVideoTrack.getCodec()!==this.getCodec())throw new Error("The codec in the playlist doesn't match the codec of the media data.");return this.backingVideoTrack.getDecoderConfig()}},Sc=class extends Tc{constructor(t){super(t)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return this.internalTrack.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){if(await this.hydrate(),await this.backingAudioTrack.getCodec()!==this.getCodec())throw new Error("The codec in the playlist doesn't match the codec of the media data.");return this.backingAudioTrack.getDecoderConfig()}},yc=i=>{let t=i.get("default");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},Jf=i=>{let t=i.get("autoselect");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},ep=i=>{if(i===null)return ce;let t=i.split("-")[0];return t||ce},tp=i=>{if(i===null)return null;let[t,e]=i.split("/");if(e!==void 0&&e!=="-")return null;let r=Number(t);return Number.isInteger(r)&&r>0?r:null};var nt=class{constructor(){this._isIsobmff=!1}},ea=class extends nt{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);if(R(r)&&(r=await r),!r)return null;let n=B(r),a=ae(r,4);if(a!=="ftyp"&&a!=="styp")return null;if(n===1){let s=e._reader.requestSlice(16,4);return R(s)&&(s=await s),s?ae(s,4):null}return ae(r,4)}_createDemuxer(e){return new vo(e)}get supportsTimestampedMediaData(){return!0}},ts=class extends ea{async _getMatchPosition(t){let e=await this._getMajorBrand(t);if(e!==null)return e!=="qt "?0:null;let r=0;for(let n=0;n<10;n++){let a=t._reader.requestSlice(r,8);if(R(a)&&(a=await a),!a)return null;let s=B(a),o=8;if(s===1){let l=t._reader.requestSlice(r+8,8);if(R(l)&&(l=await l),!l)return null;s=Ge(l),o=16}if(s<o)return null;let c=ae(a,4);if(c==="moof"||c==="sidx"||c==="moov"||c==="mdat")return 0;if(c==="emsg"||c==="prft"||c==="free"||c==="skip"||c==="wide")r+=s;else return null}return null}get name(){return"MP4"}get mimeType(){return"video/mp4"}},rs=class extends ea{async _getMatchPosition(t){return await this._getMajorBrand(t)==="qt "?0:null}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},ta=class extends nt{async isSupportedEBMLOfDocType(t,e){let r=t._reader.requestSlice(0,Yt);if(R(r)&&(r=await r),!r)return!1;let n=au(r);if(n===null||n<1||n>8||X(r,n)!==440786851)return!1;let s=ou(r);if(typeof s!="number")return!1;let o=t._reader.requestSlice(r.filePos,s);if(R(o)&&(o=await o),!o)return!1;let c=r.filePos;for(;o.filePos<=c+s-lt;){let l=Vt(o);if(!l)break;let{id:u,size:d}=l,m=o.filePos;if(d===void 0||m+d>c+s||d>8&&u!==17026)return!1;switch(u){case 17143:if(X(o,d)!==1)return!1;break;case 17026:if(xi(o,d)!==e)return!1;break;case 17029:if(X(o,d)>4)return!1;break}o.filePos=m+d}return!0}async _getMatchPosition(t){return await this.isSupportedEBMLOfDocType(t,"matroska")?0:null}_createDemuxer(t){return new Ho(t)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}get supportsTimestampedMediaData(){return!0}},is=class extends ta{async _getMatchPosition(t){return await this.isSupportedEBMLOfDocType(t,"webm")?0:null}get name(){return"WebM"}get mimeType(){return"video/webm"}},ns=class extends nt{async _getMatchPosition(t){let e=await Ar(t._reader,0),r=await Wa(t._reader,e,4096,null);return r?r.startPos===e?0:r.startPos:null}_createDemuxer(t){return new Go(t)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}get supportsTimestampedMediaData(){return!1}},as=class extends nt{async _getMatchPosition(t){let e=t._reader.requestSlice(0,12);if(R(e)&&(e=await e),!e)return null;let r=ae(e,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?null:(e.skip(4),ae(e,4)==="WAVE"?0:null)}_createDemuxer(t){return new $o(t)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}get supportsTimestampedMediaData(){return!1}},ss=class extends nt{async _getMatchPosition(t){let e=t._reader.requestSlice(0,4);return R(e)&&(e=await e),e&&ae(e,4)==="OggS"?0:null}_createDemuxer(t){return new Xo(t)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}get supportsTimestampedMediaData(){return!0}},os=class extends nt{async _getMatchPosition(t){let e=await Ar(t._reader,0),r=t._reader.requestSlice(e,4);return R(r)&&(r=await r),r&&ae(r,4)==="fLaC"?0:null}get name(){return"FLAC"}get mimeType(){return"audio/flac"}get supportsTimestampedMediaData(){return!1}_createDemuxer(t){return new rc(t)}},cs=class extends nt{async _getMatchPosition(t){let e=await Ar(t._reader,0),r=await Qa(t._reader,e,4096,null);return r?r.startPos===e?0:r.startPos:null}_createDemuxer(t){return new Zo(t)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}get supportsTimestampedMediaData(){return!1}},ls=class extends nt{async _getMatchPosition(t){let e=ze+16+1,r=t._reader.requestSlice(0,e);if(R(r)&&(r=await r),!r)return null;let n=U(r,e);return n[0]===71&&n[ze]===71||n[0]===71&&n[ze+16]===71||n[4]===71&&n[4+ze+4]===71?0:null}_createDemuxer(t){return new sc(t)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}get supportsTimestampedMediaData(){return!0}},nn=class extends nt{async _getMatchPosition(t){let e=t._reader.requestSlice(0,7);if(R(e)&&(e=await e),!e||!(ae(e,7)==="#EXTM3U"))return null;if(!(t._rootSource instanceof it))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return t._rootSource._usedForHls=!0,0}_createDemuxer(t){return new kc(t)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Cr}get supportsTimestampedMediaData(){return!0}},Ac=new ts,xc=new rs,zu=new ta,Nu=new is,Cc=new ns,Lu=new as,Hu=new ss,Pc=new cs,Wu=new os,Ec=new ls,Ic=new nn,rp=[Ic,Ac,xc,zu,Nu,Lu,Hu,Wu,Cc,Pc,Ec],ip=[Ic,Ac,xc,Cc,Pc,Ec],np=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(`${t}, when provided, must be an object.`);if(i.isobmff!==void 0){if(!i.isobmff||typeof i.isobmff!="object")throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(i.isobmff.resolveKeyId!==void 0&&typeof i.isobmff.resolveKeyId!="function")throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(i.hls!==void 0){if(!i.hls||typeof i.hls!="object")throw new TypeError(`${t}.hls, when provided, must be an object.`);if(i.hls.offsetTimestampsByDateTime!==void 0&&typeof i.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var an=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(i.skipLiveWait!==void 0&&typeof i.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},ti=i=>{if(!Ie(i))throw new TypeError("timestamp must be a number.")},qu=(i,t,e)=>e.verifyKeyPackets?t.then(async r=>{if(!r||r.type==="delta")return r;let n=await i.determinePacketType(r);return n&&(r.type=n),r}):t,ut=class{constructor(t){if(!(t instanceof Ri))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(an(t),this._track.input._disposed)throw new ge;return qu(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){an(t);let e=await this.getFirstPacket(t);return e?e.type==="key"?e:this.getNextKeyPacket(e,t):null}async getPacket(t,e={}){if(ti(t),an(e),this._track.input._disposed)throw new ge;return qu(this._track,this._track._backing.getPacket(t,e),e)}async getNextPacket(t,e={}){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(an(e),this._track.input._disposed)throw new ge;return qu(this._track,this._track._backing.getNextPacket(t,e),e)}async getKeyPacket(t,e={}){if(ti(t),an(e),this._track.input._disposed)throw new ge;if(!e.verifyKeyPackets)return this._track._backing.getKeyPacket(t,e);let r=await this._track._backing.getKeyPacket(t,e);for(;r;){if(b(r.type==="key"),await this._track.determinePacketType(r)!=="delta")return r;let a=1/await this._track.getTimeResolution(),s;for(;s=await this._track._backing.getKeyPacket(r.timestamp-a,e),!(!s||s.timestamp<r.timestamp);)a*=2;r=s}return null}async getNextKeyPacket(t,e={}){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(an(e),this._track.input._disposed)throw new ge;if(!e.verifyKeyPackets)return this._track._backing.getNextKeyPacket(t,e);let r=await this._track._backing.getNextKeyPacket(t,e);for(;r;){if(b(r.type==="key"),await this._track.determinePacketType(r)!=="delta")return r;r=await this._track._backing.getNextKeyPacket(r,e)}return null}packets(t,e,r={}){if(t!==void 0&&!(t instanceof ee))throw new TypeError("startPacket must be an EncodedPacket.");if(t!==void 0&&t.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(e!==void 0&&!(e instanceof ee))throw new TypeError("endPacket must be an EncodedPacket.");if(an(r),this._track.input._disposed)throw new ge;let n=[],{promise:a,resolve:s}=te(),{promise:o,resolve:c}=te(),l=!1,u=!1,d=null,m=!1,f=()=>{if(n.length>=128)return!0;if(n.length<8)return!1;let g=1/0,h=-1/0;for(let y of n)g=Math.min(g,y.timestamp),h=Math.max(h,y.timestamp);return h-g>=1};(async()=>{let g=t??await this.getFirstPacket(r);for(;g&&!u&&!this._track.input._disposed&&!(e&&g.sequenceNumber>=e?.sequenceNumber);){if(f()){({promise:o,resolve:c}=te()),await o;continue}n.push(g),s(),{promise:a,resolve:s}=te(),g=await this.getNextPacket(g,r)}l=!0,s()})().catch(g=>{m||(d=g,m=!0,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new ge;if(u)return{value:void 0,done:!0};if(m)throw d;if(n.length>0){let g=n.shift();return c(),{value:g,done:!1}}else{if(l)return{value:void 0,done:!0};await a}}},async return(){return u=!0,c(),s(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}},ap=4,us=class{constructor(t,e){this.onSample=t;this.onError=e;this.onDequeue=null}},ra=class{mediaSamplesInRange(t=-1/0,e=1/0,r){ti(t),ti(e);let n=[],a=!1,s=null,{promise:o,resolve:c}=te(),{promise:l,resolve:u}=te(),d=!1,m=!1,f=!1,p=null,g=null,h=!1,y={...r,verifyKeyPackets:!0,metadataOnly:!1},k=this._track,T=()=>{s?.close(),s=null;for(let w of n)w.close();n.length=0},S=()=>{f=!0,m=!0,u(),c()};return k.input._disposed||k.input._disposeCallbacks.add(S),(async()=>{p=await this._createDecoder(v=>{if(u(),v.timestamp>=e&&(m=!0),m){v.close();return}s&&(v.timestamp>t?(n.push(s),a=!0):s.close()),v.timestamp>=t&&(n.push(v),a=!0),s=a?null:v,n.length>0&&(c(),{promise:o,resolve:c}=te())},v=>{h||(g=v,h=!0,c())}),p.onDequeue=()=>u();let w=this._createPacketSink(),A=await this._getPreRollDuration(),C=await w.getPacket(t,y),E=await w.getKeyPacket((C?.timestamp??t)-A,y)??await w.getFirstKeyPacket(y),I=E,P=w.packets(E??void 0,void 0,y);for(await P.next();I&&!m&&!this._track.input._disposed;){if(n.length+p.getDecodeQueueSize()>=ap){({promise:l,resolve:u}=te()),await l;continue}p.decode(I);let v=await P.next();if(v.done)break;I=v.value}await P.return(),!f&&!this._track.input._disposed&&await p.flush(),!a&&s&&(n.push(s),s=null),d=!0,c()})().catch(w=>{h||(g=w,h=!0,c())}).finally(()=>{k.input._disposeCallbacks.delete(S),p?.close(),k.input._disposed&&T()}),{async next(){for(;;){if(k.input._disposed)throw S(),T(),new ge;if(f)return{value:void 0,done:!0};if(h)throw S(),T(),g;if(n.length>0){let w=n.shift();return u(),{value:w,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return S(),T(),{value:void 0,done:!0}},async throw(w){throw await this.return(),w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,e){vd(t);let r=Id(t),n=[],a=[],{promise:s,resolve:o}=te(),{promise:c,resolve:l}=te(),u=!1,d=!1,{promise:m,resolve:f}=te(),p=null,g=null,h=!1,y=E=>{a.push(E),o(),{promise:s,resolve:o}=te()},k=null,T=E=>{for(let I=0;I<E;I++)y(k&&(I<E-1?k.clone():k));E===0&&k?.close(),k=null},S={...e,verifyKeyPackets:!0,metadataOnly:!1},w=this._track,A=()=>{k?.close(),k=null;for(let E of a)E?.close();a.length=0},C=()=>{d=!0,f(),l(),o()};return w.input._disposed||w.input._disposeCallbacks.add(C),(async()=>{p=await this._createDecoder(z=>{if(l(),d){z.close();return}let $=0;for(;n.length>0&&z.timestamp-n[0]>1e-10;)$++,n.shift();T($),k=z},z=>{h||(g=z,h=!0,o())}),p.onDequeue=()=>l();let E=this._createPacketSink(),I=await this._getPreRollDuration(),x=null,P=-1/0,v=null,_=null,M=-1,D=async()=>{b(v),b(p);let z=_;for(z||(z=v,p.decode(z));z.sequenceNumber<M;){for(;a.length+p.getDecodeQueueSize()>=ap&&!d;)({promise:c,resolve:l}=te()),await c;if(d)break;let $=await E.getNextPacket(z,S);if(!$)throw new Error("Internal error: couldn't get next packet when one was expected.");p.decode($),z=$}_=z},L=async()=>{b(p),await p.flush(),T(n.length),n.length=0};try{for(;;){let z=r.next();z.catch(()=>{});let $=await Promise.race([z,m]);if(!$||$.done)break;let fe=$.value;if(ti(fe),d||this._track.input._disposed)break;let ye=await E.getPacket(fe,S),we=ye&&await E.getKeyPacket(ye.timestamp-I,S);if(ye&&!we){let Ze=await E.getFirstKeyPacket(S);Ze&&Ze.timestamp<=ye.timestamp&&(we=Ze)}if(!ye||!we){x&&await L(),y(null),x=null;continue}(!x||we.sequenceNumber>M+1||fe<P)&&(x&&await L(),v=we,_=null,M=-1),n.push(fe),M=Math.max(ye.sequenceNumber,M),x=ye,P=fe,await D()}}finally{r.return().catch(()=>{})}!d&&!this._track.input._disposed&&await L(),u=!0,o()})().catch(E=>{h||(g=E,h=!0,o())}).finally(()=>{w.input._disposeCallbacks.delete(C),p?.close(),w.input._disposed&&A()}),{async next(){for(;;){if(w.input._disposed)throw C(),A(),new ge;if(d)return{value:void 0,done:!0};if(h)throw C(),A(),g;if(a.length>0){let E=a.shift();return b(E!==void 0),l(),{value:E,done:!1}}else if(!u)await s;else return{value:void 0,done:!0}}},async return(){return C(),A(),{value:void 0,done:!0}},async throw(E){throw await this.return(),E},[Symbol.asyncIterator](){return this}}}},Gu=class extends us{constructor(e,r,n,a,s,o,c){super(e,r);this.codec=n;this.decoderConfig=a;this.rotation=s;this.flip=o;this.timeResolution=c;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new ni;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];this.currentPacketIndex=0;this.raslSkipped=!1;this.alphaDecoder=null;this.alphaHadKeyframe=!1;this.colorQueue=[];this.alphaQueue=[];this.merger=null;this.decodedAlphaChunkCount=0;this.alphaDecoderQueueSize=0;this.nullAlphaFrameQueue=[];this.currentAlphaPacketIndex=0;this.alphaRaslSkipped=!1;this.finalSamples=[];this.mergeAlphaPromises=[];this.flushing=!1;this.frameCopyContext=null;let l=bi.find(u=>u.supports(n,a));if(l)this.customDecoder=new l,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=u=>{if(!(u instanceof $e))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(u)},this.customDecoder.onError=u=>{r(u)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(u=>r(u));else{let u=m=>{if(this.alphaQueue.length>0){let f=this.alphaQueue.shift();b(f!==void 0),this.mergeAlpha(m,f)}else this.colorQueue.push(m)};if(Ni()){if(n==="avc"&&this.decoderConfig.description){let m=gr(G(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){let f=Gt(m.sequenceParameterSets[0]);f&&f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"});let p=!1;for(let g=0;g<m.sequenceParameterSets.length;g++){let h=Gt(m.sequenceParameterSets[g]);h&&h.maxDecFrameBuffering!==0&&h.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[g]=Ll(h),p=!0)}p&&(this.decoderConfig={...this.decoderConfig,description:En(m)})}}wn(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}let d=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:m=>{try{u(this.copyFrameIfNeeded(m))}catch(f){this.onError(f)}},error:m=>{m.stack=d,this.onError(m)}}),this.decoder.addEventListener("dequeue",()=>{this.onDequeue?.()}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0)+this.finalSamples.length)}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()});else{if(b(this.decoder),!et()){let r=mm(this.codec,e.data);for(let n=0;n<r;n++)Pl(this.inputTimestamps,e.timestamp,a=>a)}if(Ni()&&this.currentPacketIndex===0){let r=this.fixFirstPacketDataForChromium(e.data);r&&(e=e.clone({data:r}))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new Qu),!this.alphaDecoder){let n=s=>{if(this.colorQueue.length>0){let o=this.colorQueue.shift();b(o!==void 0),this.mergeAlpha(o,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let o=this.colorQueue.shift();b(o!==void 0),this.mergeAlpha(o,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},a=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(this.copyFrameIfNeeded(s))}catch(o){this.onError(o)}},error:s=>{s.stack=a,this.onError(s)}}),this.alphaDecoder.addEventListener("dequeue",()=>{this.onDequeue?.()}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"}})}let r=gi(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}if(Ni()&&this.currentAlphaPacketIndex===0){let n=this.fixFirstPacketDataForChromium(e.sideData.alpha);n&&(e=e.clone({sideData:{...e.sideData,alpha:n}}))}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}fixFirstPacketDataForChromium(e){if(this.codec==="avc"){let r=[],n=!1;for(let a of zl(e,this.decoderConfig)){let s=pr(e[a.offset]);if(n||=s>=1&&s<=5,s===9){if(n)break;r.length=0}s>=20&&s<=31||r.push(e.subarray(a.offset,a.offset+a.length))}if(!this.decoderConfig.description)for(let a=0;a<r.length;a++){let s=r[a];if(pr(s[0])!==7)continue;let o=Gt(s);o&&o.maxDecFrameBuffering!==0&&o.bitstreamRestrictionFlag!==1&&(r[a]=Ll(o))}return sm(r,this.decoderConfig)}else return this.codec==="hevc"?lm(e,this.decoderConfig):null}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of pa(e,this.decoderConfig)){let n=Qt(e[r.offset]);if(n===8||n===9)return!0}return!1}sampleHandler(e){if(et()){if(this.sampleQueue.length>0&&e.timestamp>=J(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}Pl(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();b(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,r){let n=te();this.mergeAlphaPromises.push(n.promise);let a={sample:null};this.finalSamples.push(a);try{if(!r)a.sample=new $e(e);else{b(this.merger);let s=await this.merger.merge(e,r);a.sample=new $e(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){for(Sn(this.finalSamples,a);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;)this.finalSamples.shift().sample.close();this.onError(s)}finally{Sn(this.mergeAlphaPromises,n.promise),n.resolve()}}copyFrameIfNeeded(e){if(!Ni()||!Vd())return e;let r=e.visibleRect,n=r.width,a=r.height;if(!this.frameCopyContext){let c;if(typeof OffscreenCanvas<"u"?c=new OffscreenCanvas(n,a).getContext("2d",{alpha:!1}):c=document.createElement("canvas").getContext("2d",{alpha:!1}),!c)throw new Error("The '2d' canvas context is required to decode video on Chromium for Android.");this.frameCopyContext=c}let s=this.frameCopyContext.canvas;(s.width!==n||s.height!==a)&&(s.width=n,s.height=a),this.frameCopyContext.drawImage(e,0,0,n,a),this.flushing&&this.frameCopyContext.getImageData(0,0,1,1);let o=new VideoFrame(s,{timestamp:e.timestamp,duration:e.duration??void 0,displayWidth:e.displayWidth,displayHeight:e.displayHeight});return e.close(),o}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),this.flushing=!0,await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.flushing=!1,await Promise.all(this.mergeAlphaPromises),this.inputTimestamps.length=0,this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),et()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()).catch(e=>this.onError(e)):(b(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Ku=null,Qu=class{constructor(){this.workers=[];this.nextWorkerIndex=0;this.pendingRequests=new Map;this.nextRequestId=0}merge(t,e){if(this.workers.length===0){if(!Ku){let o=new Blob([`(${xg.toString()})()`],{type:"application/javascript"});Ku=URL.createObjectURL(o)}let s=ne(navigator.hardwareConcurrency,1,4);for(let o=0;o<s;o++){let c=new Worker(Ku);c.addEventListener("message",l=>{let u=l.data,d=this.pendingRequests.get(u.id);if(!d){"frame"in u&&u.frame.close();return}this.pendingRequests.delete(u.id),"error"in u?d.reject(new Error(u.error)):d.resolve(u.frame)}),c.addEventListener("error",l=>{let u=new Error(l.message||"Color/alpha merge worker error.");for(let d of this.pendingRequests.values())d.reject(u);this.pendingRequests.clear()}),this.workers.push(c)}}let r=this.nextRequestId++,n=te();this.pendingRequests.set(r,n);let a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:r,color:t,alpha:e},{transfer:[t,e]}),n.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let t=new Error("Color/alpha merger closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},xg=()=>{let i=null,t=null,e=Promise.resolve();self.addEventListener("message",c=>{let{id:l,color:u,alpha:d}=c.data;e=e.then(async()=>{try{let m=await r(u,d);self.postMessage({id:l,frame:m},{transfer:[m]})}catch(m){self.postMessage({id:l,error:m.message})}finally{u.close(),d.close()}})});let r=async(c,l)=>{let u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let m=u.includes("P10"),f=u.includes("P12"),p=d.includes("P10"),g=d.includes("P12");if(p!==m||g!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await n(c,l,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await a(c,l,u);if(u==="NV12")return await s(c,l);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},n=async(c,l,u)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=d*m,p=new Uint8Array(f*4);await c.copyTo(p);let g=await o(l,d,m,1);for(let k=0,T=3;k<f;k++,T+=4)p[T]=g[k];let y={format:u==="RGBX"||u==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:m,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},a=async(c,l,u)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=u.includes("P10"),p=u.includes("P12"),g=f||p?2:1,h,y;u.startsWith("I420")?(h=Math.ceil(d/2),y=Math.ceil(m/2)):u.startsWith("I422")?(h=Math.ceil(d/2),y=m):(h=d,y=m);let k=d*m,T=h*y,S=k*g,w=T*g,A=k*g,C=S+2*w+A,E=new Uint8Array(C);await c.copyTo(E);let I=await o(l,d,m,g),x=S+2*w;E.set(I,x);let v={format:u.slice(0,4)+"A"+u.slice(4),codedWidth:d,codedHeight:m,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[E.buffer]};return new VideoFrame(E,v)},s=async(c,l)=>{let u=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,m=u*d,f=Math.ceil(u/2),p=Math.ceil(d/2),g=f*p,h=c.allocationSize();(!t||t.byteLength!==h)&&(t=new Uint8Array(h)),await c.copyTo(t);let y=new Uint8Array(m+2*g+m);y.set(t.subarray(0,m),0);let k=m,T=m+g,S=m;for(let C=0;C<g;C++)y[k+C]=t[S+C*2],y[T+C]=t[S+C*2+1];let w=await o(l,u,d,1);y.set(w,m+2*g);let A={format:"I420A",codedWidth:u,codedHeight:d,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,A)},o=async(c,l,u,d)=>{let m=c.allocationSize();(!i||i.byteLength!==m)&&(i=new Uint8Array(m)),await c.copyTo(i);let f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){let p=f==="RGBA"||f==="RGBX"?0:2,g=l*u;for(let h=0;h<g;h++)i[h]=i[h*4+p];return i.subarray(0,g)}else{let p=i.subarray(0,l*u*d);if(c.colorSpace.fullRange===!1){let g=f.includes("P12")?12:f.includes("P10")?10:8,h=16<<g-8,y=235<<g-8,k=(1<<g)-1,T=d===2?new Uint16Array(p.buffer,0,l*u):p;for(let S=0;S<T.length;S++){let w=Math.round((T[S]-h)*k/(y-h));T[S]=Math.min(Math.max(w,0),k)}}return p}}},sp=i=>{if(!i||typeof i!="object")throw new TypeError("decoderOptions must be an object.");if(i.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i.optimizeForLatency!==void 0&&typeof i.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},_i=class extends ra{constructor(t,e={}){if(!(t instanceof Pr))throw new TypeError("videoTrack must be an InputVideoTrack.");sp(e),super(),this._track=t,this._decoderOptions=e}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(xn("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getRotation(),a=await this._track.getFlip(),s=await this._track.getDecoderConfig(),o=await this._track.getTimeResolution();return b(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Gu(t,e,r,s,n,a,o)}_createPacketSink(){return new ut(this._track)}async _getPreRollDuration(){return 0}async getSample(t,e={}){ti(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},vc=class{constructor(t,e={}){this._rotation=0;this._flip=!1;this._initPromise=null;this._nextCanvasIndex=0;if(!(t instanceof Pr))throw new TypeError("videoTrack must be an InputVideoTrack.");if(e&&typeof e!="object")throw new TypeError("options must be an object.");if(e.alpha!==void 0&&typeof e.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&ki(e.crop,"options."),e.poolSize!==void 0&&(typeof e.poolSize!="number"||!Number.isInteger(e.poolSize)||e.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");e.decoderOptions!==void 0&&sp(e.decoderOptions),this._videoTrack=t,this._alpha=e.alpha??!1,this._options=e,this._fit=e.fit??"fill",this._videoSampleSink=new _i(t,e.decoderOptions),this._canvasPool=Array.from({length:e.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let t=this._options,e=this._videoTrack,r=t.rotation??await e.getRotation(),n=t.flip??await e.getFlip(),a=await e.getSquarePixelWidth(),s=await e.getSquarePixelHeight(),[o,c]=r%180===0?[a,s]:[s,a],l=t.crop;l&&(l=Fn(l,o,c));let[u,d]=l?[l.width,l.height]:[o,c],m=u/d;t.width!==void 0&&t.height===void 0?(u=t.width,d=Math.round(u/m)):t.width===void 0&&t.height!==void 0?(d=t.height,u=Math.round(d*m)):t.width!==void 0&&t.height!==void 0&&(u=t.width,d=t.height),this._width=u,this._height=d,this._rotation=r,this._flip=n,this._crop=l})()}_videoSampleToWrappedCanvas(t){let e=this._width,r=this._height,n=this._canvasPool[this._nextCanvasIndex],a=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=e,n.height=r):n=new OffscreenCanvas(e,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let s=n.getContext("2d",{alpha:this._alpha||Wt()});b(s);try{return t._drawWithFitAndMipmapping(n,s,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&Wt()}),{canvas:n,timestamp:t.timestamp,duration:t.duration}}finally{t.close()}}async getCanvas(t,e){ti(t),await this._ensureInit();let r=await this._videoSampleSink.getSample(t,e);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(t,e,r){await this._ensureInit(),yield*da(this._videoSampleSink.samples(t,e,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,e){await this._ensureInit(),yield*da(this._videoSampleSink.samplesAtTimestamps(t,e),r=>r&&this._videoSampleToWrappedCanvas(r))}},ju=class extends us{constructor(e,r,n,a){super(e,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new ni;this.customDecoderQueueSize=0;this.currentTimestamp=null;this.expectedFirstTimestamp=null;this.timestampOffset=0;this.packetsSinceFlush=0;this.inputTimestampShift=0;this.referencePacketIndex=n==="vorbis"?1:0;let s=n==="opus"&&a.description?yr(G(a.description)).preSkip/tt:0,o=l=>{if(l.numberOfFrames===0){l.close();return}let u=l.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp+s-u),u+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(u-this.currentTimestamp)>=l.duration)&&(this.currentTimestamp=u);let d=this.currentTimestamp;this.currentTimestamp+=l.duration;let m=a.sampleRate;l.setTimestamp(Math.round(d*m)/m),e(l)},c=yi.find(l=>l.supports(n,a));if(c)this.customDecoder=new c,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=l=>{if(!(l instanceof Ce))throw new TypeError("The argument passed to onSample must be an AudioSample.");o(l)},this.customDecoder.onError=l=>{r(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>r(l));else{let l=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:u=>{try{o(new Ce(u))}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.addEventListener("dequeue",()=>{this.onDequeue?.()}),this.decoder.configure(a)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(this.decoder),this.decoder.decodeQueueSize)}decode(e){if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()});else{b(this.decoder),this.packetsSinceFlush===0&&(this.inputTimestampShift=-e.timestamp),this.packetsSinceFlush===this.referencePacketIndex&&(this.expectedFirstTimestamp=e.timestamp),this.packetsSinceFlush++;let r=e.clone({timestamp:e.timestamp+this.inputTimestampShift});this.decoder.decode(r.toEncodedAudioChunk())}}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.packetsSinceFlush=0,this.inputTimestampShift=0,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()).catch(e=>this.onError(e)):(b(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}},Xu=class extends us{constructor(e,r,n){super(e,r);this.decoderConfig=n;this.currentTimestamp=null;b(se.includes(n.codec)),this.codec=n.codec;let{dataType:a,sampleSize:s,littleEndian:o}=Me(this.codec);switch(this.inputSampleSize=s,s){case 1:a==="unsigned"?this.readInputValue=(c,l)=>c.getUint8(l)-2**7:a==="signed"?this.readInputValue=(c,l)=>c.getInt8(l):a==="ulaw"?this.readInputValue=(c,l)=>wm(c.getUint8(l)):a==="alaw"?this.readInputValue=(c,l)=>Am(c.getUint8(l)):b(!1);break;case 2:a==="unsigned"?this.readInputValue=(c,l)=>c.getUint16(l,o)-2**15:a==="signed"?this.readInputValue=(c,l)=>c.getInt16(l,o):b(!1);break;case 3:a==="unsigned"?this.readInputValue=(c,l)=>Ui(c,l,o)-2**23:a==="signed"?this.readInputValue=(c,l)=>_d(c,l,o):b(!1);break;case 4:a==="unsigned"?this.readInputValue=(c,l)=>c.getUint32(l,o)-2**31:a==="signed"?this.readInputValue=(c,l)=>c.getInt32(l,o):a==="float"?this.readInputValue=(c,l)=>c.getFloat32(l,o):b(!1);break;case 8:a==="float"?this.readInputValue=(c,l)=>c.getFloat64(l,o):b(!1);break;default:Z(s),b(!1)}switch(s){case 1:a==="ulaw"||a==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,l,u)=>c.setUint8(l,u+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u<<8,!0);break;case 4:this.outputSampleSize=4,a==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0);break;default:Z(s),b(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=N(e.data),n=Math.floor(e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize);if(n===0)return;let a=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(a),o=new DataView(s);for(let m=0;m<n*this.decoderConfig.numberOfChannels;m++){let f=m*this.inputSampleSize,p=m*this.outputSampleSize,g=this.readInputValue(r,f);this.writeOutputValue(o,p,g)}let c=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=e.timestamp);let l=this.currentTimestamp;this.currentTimestamp+=c;let u=this.decoderConfig.sampleRate,d=new Ce({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:u,numberOfFrames:n,timestamp:Mt(l,u),_doNotCopy:!0});this.onSample(d)}async flush(){this.currentTimestamp=null}close(){}},sn=class extends ra{constructor(t){if(!(t instanceof Er))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=t}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof AudioDecoder>"u"?new Error(xn("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getDecoderConfig();return b(r&&n),se.includes(n.codec)?new Xu(t,e,n):new ju(t,e,r,n)}_createPacketSink(){return new ut(this._track)}async _getPreRollDuration(){let t=await this._track.getPreRollDuration();return b(t!==null),t}async getSample(t,e={}){ti(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},_c=class{constructor(t){if(!(t instanceof Er))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new sn(t)}_audioSampleToWrappedArrayBuffer(t){try{return{buffer:t.toAudioBuffer(),timestamp:t.timestamp,duration:t.duration}}finally{t.close()}}async getBuffer(t,e){ti(t);let r=await this._audioSampleSink.getSample(t,e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(t,e,r){return da(this._audioSampleSink.samples(t,e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(t,e){return da(this._audioSampleSink.samplesAtTimestamps(t,e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}};var Ri=class i{constructor(t,e){this.input=t,this._backing=e}isVideoTrack(){return this instanceof Pr}isAudioTrack(){return this instanceof Er}get id(){let t=this.input._trackBackingsCache;b(t);let e=t.indexOf(this._backing);return b(e!==-1),e+1}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ke(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ke(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ke(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ke(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(t){return this._backing.getUnixTimeForTimestamp(t)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return ke(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return await this.getFirstTimestampOrNull()??0}async getFirstTimestampOrNull(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??null}async computeDuration(t){return await this.computeDurationOrNull(t)??0}async computeDurationOrNull(t){let e=await this._backing.getPacket(1/0,{metadataOnly:!0,...t});return e?Mt(e.timestamp+e.duration,await this.getTimeResolution()):null}async getDurationFromMetadata(t={}){return this._backing.getDurationFromMetadata(t)}async computePacketStats(t=1/0,e){let r=new ut(this),n=1/0,a=-1/0,s=0,o=0;for await(let l of r.packets(void 0,void 0,{metadataOnly:!0,...e})){if(s>=t&&l.timestamp>=a&&a>n)break;n=Math.min(n,l.timestamp),a=Math.max(a,l.timestamp+l.duration),s++,o+=l.byteLength}let c=a-n;return{packetCount:s,averagePacketRate:s>0?Number((s/c).toPrecision(16)):0,averageBitrate:o>0?Number((8*o/c).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an InputTrack.");return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(t){return this.input.getTracks(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPairableVideoTracks(t){return this.input.getVideoTracks(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPairableAudioTracks(t){return this.input.getAudioTracks(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableVideoTrack(t){return this.input.getPrimaryVideoTrack(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableAudioTrack(t){return this.input.getPrimaryAudioTrack(Fi({filter:e=>e.canBePairedWith(this)},t))}async hasPairableTrack(t){t&&=$u(t);let e=await this.input.getTracks();for(let r of e)if(this.canBePairedWith(r)&&(!t||await t(r)))return!0;return!1}hasPairableVideoTrack(t){return t&&=$u(t),this.hasPairableTrack(async e=>e.isVideoTrack()&&(!t||await t(e)))}hasPairableAudioTrack(t){return t&&=$u(t),this.hasPairableTrack(async e=>e.isAudioTrack()&&(!t||await t(e)))}},ke=(i,t,e)=>{if(R(i))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${e}()' instead.`);return i},$u=i=>{if(i!==void 0&&typeof i!="function")throw new TypeError("predicate, when provided, must be a function.");return i?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return n},r=i(t);return R(r)?r.then(e):e(r)}:void 0},Pr=class extends Ri{constructor(e,r){super(e,r);this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ke(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return ke(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ke(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Di(await this._backing.getTransformationMatrix())}get rotation(){return Di(ke(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return Sl(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ke(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ke(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=op(await this.getSquarePixelWidth()*await this.getCodedHeight(),await this.getSquarePixelHeight()*await this.getCodedWidth())}get pixelAspectRatio(){return this._pixelAspectRatioCache??=op(ke(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ke(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),ke(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ke(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio"))}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let a=ke(e,"displayWidth","getDisplayWidth");if(a!==null)return a}let n=Di(ke(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ke(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let a=ke(e,"displayHeight","getDisplayHeight");if(a!==null)return a}let n=Di(ke(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ke(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.transfer==="pq"||e.transfer==="hlg"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=await this._backing.getCodec();return b(r!==null),bi.some(a=>a.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return O._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let r=await this.getCodec();if(r===null)return null;let n=await this.getDecoderConfig();return b(n),gi(r,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!Ie(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");let r=await this.getTimeResolution(),n=e.targetPacketCount??256,a=new ut(this),s=[],o=-1/0,c=0;for await(let P of a.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=n&&P.timestamp>=o)break;s.push(P.timestamp),o=Math.max(o,P.timestamp),c++}let l=new Float64Array(s.length);for(let P=0;P<s.length;P++)l[P]=Math.round(s[P]*r);l.sort();let u=1;for(let P=1;P<l.length;P++)l[P]!==l[u-1]&&(l[u++]=l[P]);if(u<2)return{underlyingFrameRate:null,bestGuessFrameRate:r,minFrameRate:r,maxFrameRate:r,averageFrameRate:r,medianFrameRate:r,frameRateIsConstant:!0,probedPacketCount:c};let d=l.subarray(0,u),m=Cg(d,r),f=m??r,p=m!==null?r/m:null,g=new Map,h=1/0,y=-1/0,k=0;for(let P=1;P<u;P++){let v=d[P]-d[P-1],_=p!==null?Math.max(1,Math.round(v/p)):v;g.set(_,(g.get(_)??0)+1),h=Math.min(h,_),y=Math.max(y,_),k+=_}let T=u-1,S=[...g.keys()].sort((P,v)=>P-v),w=T-1>>1,A=T>>1,C=0,E=0,I=0;for(let P of S)if(I+=g.get(P),C===0&&I>w&&(C=P),I>A){E=P;break}let x=(f/C+f/E)/2;return{underlyingFrameRate:m,bestGuessFrameRate:m!==null?m:Pg(x),minFrameRate:f/y,maxFrameRate:f/h,averageFrameRate:f*T/k,medianFrameRate:x,frameRateIsConstant:m!==null&&h===1&&y===1,probedPacketCount:c}}},op=(i,t)=>i===0||t===0?{num:1,den:1}:zr({num:i,den:t}),Er=class extends Ri{constructor(t,e){super(t,e)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ke(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){let t=await this._backing.getCodec();return await this._backing.getHasOnlyKeyPackets?.()??(t===null||!Ji.includes(t))}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ke(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ke(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let t=await this._backing.getMetadataCodecParameterString?.();return t??(await this._backing.getDecoderConfig())?.codec??null}async getPreRollDuration(){let t=await this._backing.getCodec();if(t===null)return null;let e=await this._backing.getDecoderConfig();return b(e),Fc(t,e)}async canDecode(){try{let t=await this._backing.getDecoderConfig();if(!t)return!1;let e=await this._backing.getCodec();return b(e!==null),yi.some(r=>r.supports(e,t))||se.includes(t.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0}catch(t){return O._error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let e=await this.getCodec();return e===null?null:_n(e,t.data)}},lp=i=>i??1/0,ds=i=>-(i??-1/0),Mi=i=>-i,ia=i=>{if(typeof i!="object"||!i)throw new TypeError("query must be an object.");if(i.filter!==void 0&&typeof i.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(i.sortBy!==void 0&&typeof i.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:i.filter?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return n},r=i.filter(t);return R(r)?r.then(e):e(r)}:void 0,sortBy:i.sortBy?t=>{let e=n=>{if(typeof n!="number"&&(!Array.isArray(n)||!n.every(a=>typeof a=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return n},r=i.sortBy(t);return R(r)?r.then(e):e(r)}:void 0}},Fi=(i,t)=>({filter:i?.filter||t?.filter?e=>{let r=i?.filter?.(e)??!0,n=a=>a===!1?!1:t?.filter?.(e)??!0;return R(r)?r.then(n):n(r)}:void 0,sortBy:i?.sortBy||t?.sortBy?e=>{let r=i?.sortBy?.(e)??[],n=t?.sortBy?.(e)??[],a=(s,o)=>[...Array.isArray(s)?s:[s],...Array.isArray(o)?o:[o]];return R(r)||R(n)?Promise.all([r,n]).then(([s,o])=>a(s,o)):a(r,n)}:void 0}),Rc=async(i,t)=>{let e=i;if(t?.filter){let s=i.map(c=>t.filter(c));if(s.some(c=>R(c))){let c=await Promise.all(s);e=i.filter((l,u)=>c[u])}else e=i.filter((c,l)=>s[l])}if(!t?.sortBy)return e;let r=e.map(s=>t.sortBy(s)),a=r.some(s=>R(s))?await Promise.all(r):r;return e.map((s,o)=>({track:s,sortValue:a[o]})).sort((s,o)=>{let c=Array.isArray(s.sortValue)?s.sortValue:[s.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){let m=c[d]??0,f=l[d]??0;if(m!==f)return m-f}return 0}).map(s=>s.track)},Cg=(i,t)=>{let n=1.000000001,a=1e3,s=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(i.length<2)return null;let o=new Float64Array(i.length-1);for(let E=1;E<i.length;E++){let I=i[E]-i[E-1];if(!(I>0))return null;o[E-1]=I}let c=o.slice();c.sort();let l=c[Math.floor(c.length*.05)],u=1;for(let E=0;E<6;E++){let I=0,x=0;for(let v of o){let _=Math.max(1,Math.round(v/l));Math.abs(v-_*l)>=n+_*u||(I+=v,x+=_)}if(x===0)return null;let P=I/x;if(u=1/Math.min(x,a),Math.abs(P-l)<=1e-12*Math.max(1,l)){l=P;break}l=P}let d=0,m=0,f=0;for(let E of o){let I=Math.max(1,Math.round(E/l));Math.abs(E-I*l)>=n+I*u||(d++,m+=E,f+=I)}if(d/o.length<.98)return null;l=m/f;let p=1/Math.min(f,a),g=Math.max(Number.EPSILON,l-p),h=l+p,y=t/h,k=t/g,T=t/l,S=null,w=1/0;for(let E of s){if(E<y||E>k)continue;let I=Math.abs(E/T-1);I<w&&(S=E,w=I)}if(S===null){let E=cp(g,h,1e6),I=cp(y,k,1e6);if(I&&(!E||I.den<E.den||I.den===E.den&&I.num<=E.num))S=I.num/I.den;else if(E)S=t*E.den/E.num;else return null}let A=t/S,C=0;for(let E of o){let I=Math.max(1,Math.round(E/A));Math.abs(E-I*A)<n&&C++}return C/o.length<.98?null:S},cp=(i,t,e)=>{for(let r=1;r<=e;r++){let n=Math.floor(i*r)+1;if(n/r<t)return zr({num:n,den:r})}return null},Pg=i=>{let t=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],e=[12,15,20,24,25,30,48,50,60,100,120,144,240],r=5e-4,n=.025;for(let o of t)if(Math.abs(o/i-1)<=r)return o;let a=i,s=1/0;for(let o of e){let c=Math.abs(o/i-1);c<=n&&c<s&&(a=o,s=c)}return a};Cn();var Eg=1,Zf=2,vi=class i extends st{constructor(e){super();this._demuxerPromise=null;this._format=null;this._trackBackingsCache=null;this._backingToTrack=new Map;this._disposed=!1;this._disposeCallbacks=new Set;this._nextSourceCacheAge=0;this._sourceRefs=[];this._sourceCache=[];this._sourceCachePromises=[];this._onFormatDetermined=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof nt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Qe||e.source instanceof Ei))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Qe&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof i))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&np(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Qe?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get disposed(){return this._disposed}get _rootSource(){if(this._disposed)throw new ge;return this._rootRef.source}async _getSourceUncached(e){b(this._rootSource instanceof it);let r=await this._rootSource._resolveRequest(e);return this._emit("source",{source:r.source,request:e,isRoot:e.isRoot}),r}_getSourceCached(e,r=Eg){let n=this._sourceCache.find(o=>o.cacheGroup===r&&Vu(o.request,e));if(n)return n.age=this._nextSourceCacheAge++,Promise.resolve(n.sourceRef.source.ref());let a=this._sourceCachePromises.find(o=>o.cacheGroup===r&&Vu(o.request,e));if(a)return a.promise.then(o=>o.sourceRef.source.ref());let s=(async()=>{let o;try{o=await this._getSourceUncached(e)}finally{let d=this._sourceCachePromises.findIndex(m=>m.request===e);b(d!==-1),this._sourceCachePromises.splice(d,1)}if(this._disposed)throw o.free(),new ge;if(Wi(this._sourceCache,d=>d.cacheGroup===r&&d.sourceRef.source._refCount===1)>=4){let d=li(this._sourceCache,f=>f.cacheGroup===r&&f.sourceRef.source._refCount===1?f.age:1/0);b(d!==-1);let m=this._sourceCache[d];this._sourceCache.splice(d,1),m.sourceRef.free(),Sn(this._sourceRefs,m.sourceRef)}return this._sourceRefs.push(o),{request:e,sourceRef:o,age:this._nextSourceCacheAge++,cacheGroup:r}})();return this._sourceCachePromises.push({request:e,cacheGroup:r,promise:s}),s.then(o=>{let c=o.sourceRef.source.ref();return this._sourceCache.push(o),c})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new Ii(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});let e=null,r=1/0;for(let n of this._formats){let a=await n._getMatchPosition(this);if(a!==null&&a<r&&(e=n,r=a,a===0))break}if(!e)throw new na;return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),b(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof na)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let r=e.filter(s=>s!==null);if(r.length===0)return 0;let n=await Promise.all(r.map(s=>s.getFirstTimestampOrNull())),a=Math.min(...n.map(s=>s??1/0));return a===1/0?0:a}async computeDuration(e,r){e??=await this.getTracks();let n=e.filter(o=>o!==null);if(n.length===0)return 0;let a=await Promise.all(n.map(o=>o.computeDurationOrNull(r))),s=Math.max(...a.map(o=>o??-1/0));return s===-1/0?0:s}async getDurationFromMetadata(e,r){e??=await this.getTracks();let n=e.filter(o=>o!==null),s=(await Promise.all(n.map(o=>o.getDurationFromMetadata(r)))).filter(o=>o!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=ia(e);let n=(await this._getTrackBackings()).map(a=>this._wrapBackingAsTrack(a));return Rc(n,e)}async getVideoTracks(e){e&&=ia(e);let n=(await this.getTracks()).filter(a=>a.isVideoTrack());return Rc(n,e)}async getAudioTracks(e){e&&=ia(e);let n=(await this.getTracks()).filter(a=>a.isAudioTrack());return Rc(n,e)}async getPrimaryVideoTrack(e){e&&=ia(e);let r=Fi(e,{sortBy:async a=>[Mi((await a.getDisposition()).default),Mi(await a.hasPairableAudioTrack()),Mi(!await a.hasOnlyKeyPackets()),ds(await a.getBitrate())]});return(await this.getVideoTracks(r))[0]??null}async getPrimaryAudioTrack(e){e&&=ia(e);let r=await this.getPrimaryVideoTrack(),n=Fi(e,{sortBy:async s=>[Mi(!r||s.canBePairedWith(r)),Mi((await s.getDisposition()).default),ds(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let r=this._backingToTrack.get(e);if(r)return r;let a=e.getType()==="video"?new Pr(this,e):new Er(this,e);return this._backingToTrack.set(e,a),a}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._disposeCallbacks)e();this._disposeCallbacks.clear();for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._sourceCache.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},na=class extends Error{constructor(t="Input has an unsupported or unrecognizable format."){super(t),this.name="UnsupportedInputFormatError"}},ge=class extends Error{constructor(t="Input has been disposed."){super(t),this.name="InputDisposedError"}};var Ii=class{constructor(t){this.source=t}get fileSize(){let t=this.source._getFileSize();if(t===void 0)throw new Error("Reading file size too early; read required first.");return t}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(t,e){if(this.source._disposed)throw new ge;if(t<0||this.fileSizeNonStrict!==null&&t+e>this.fileSizeNonStrict)return null;if(e===0){let a=new Uint8Array(0);return new xe(a,N(a),0,t,t)}let r=t+e,n=this.source._read(t,r,Ou,Du);return R(n)?n.then(a=>a?new xe(a.bytes,a.view,a.offset,t,r):null):n?new xe(n.bytes,n.view,n.offset,t,r):null}requestSliceRange(t,e,r){if(this.source._disposed)throw new ge;if(t<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(t,ne(this.fileSizeNonStrict-t,e,r));{let n=this.requestSlice(t,r),a=s=>s||(b(this.fileSizeNonStrict!==null),this.requestSlice(t,ne(this.fileSizeNonStrict-t,e,r)));return R(n)?n.then(a):a(n)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let t=1024;return(async()=>{let e=[],r=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let s=this.requestSliceRange(r,0,t);if(R(s)&&(s=await s),!s||s.length===0)break;let o=U(s,s.length);e.push(o),r+=s.length}let n=new Uint8Array(r),a=0;for(let s of e)n.set(s,a),a+=s.length;return new xe(n,N(n),0,0,r)})()}},xe=class i{constructor(t,e,r,n,a){this.bytes=t;this.view=e;this.offset=r;this.start=n;this.end=a;this.bufferPos=n-r}static tempFromBytes(t){return new i(t,N(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(t,e=this.end-t){if(t<this.start||t+e>this.end)throw new RangeError("Slicing outside of original slice.");return new i(this.bytes,this.view,this.offset,t,t+e)}},dt=(i,t)=>{if(t<0||i.filePos<i.start||i.filePos+t>i.end)throw new RangeError(`Tried reading [${i.filePos}, ${i.filePos+t}), but slice is [${i.start}, ${i.end}). This is likely an internal error, please report it alongside the file that caused it.`)},U=(i,t)=>{dt(i,t);let e=i.bytes.subarray(i.bufferPos,i.bufferPos+t);return i.bufferPos+=t,e},H=i=>(dt(i,1),i.view.getUint8(i.bufferPos++)),Ga=(i,t)=>{dt(i,2);let e=i.view.getUint16(i.bufferPos,t);return i.bufferPos+=2,e},me=i=>{dt(i,2);let t=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,t},$t=i=>{dt(i,3);let t=Ui(i.view,i.bufferPos,!1);return i.bufferPos+=3,t},Na=i=>{dt(i,2);let t=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,t},Jr=(i,t)=>{dt(i,4);let e=i.view.getUint32(i.bufferPos,t);return i.bufferPos+=4,e},B=i=>{dt(i,4);let t=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,t},Zt=i=>{dt(i,4);let t=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,t},Xr=i=>{dt(i,4);let t=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,t},Ig=i=>{dt(i,4);let t=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,t},gu=(i,t)=>{let e,r;return t?(e=Jr(i,!0),r=Jr(i,!0)):(r=Jr(i,!1),e=Jr(i,!1)),r*4294967296+e},Ge=i=>{let t=B(i),e=B(i);return t*4294967296+e},yf=i=>{let t=Xr(i),e=B(i);return t*4294967296+e},_f=i=>{let t=Zt(i);return Ig(i)*4294967296+t},Af=i=>{dt(i,4);let t=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,t},Bo=i=>{dt(i,8);let t=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,t},ae=(i,t)=>{dt(i,t);let e="";for(let r=0;r<t;r++)e+=String.fromCharCode(i.bytes[i.bufferPos++]);return e},bc=(i,t,e)=>be.decode(U(i,t)).split(`
|
|
15
|
-
`).map(a=>a.trim()).filter(a=>a.length>0&&!e?.ignore?.(a));var Ot=8,kr=16,jr=i=>{let t=B(i),e=ae(i,4),r=8;t===1&&(t=Ge(i),r=16);let a=t-r;return a<0?null:{name:e,totalSize:t,headerSize:r,contentSize:a}},wi=i=>Xr(i)/65536,Io=i=>Xr(i)/1073741824,Yu=i=>{let t=0;for(let e=0;e<4;e++){t<<=7;let r=H(i);if(t|=r&127,(r&128)===0)break}return t},Oo=i=>{if(H(i)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");Yu(i),i.skip(2);let e=H(i),r=(e&128)!==0,n=(e&64)!==0,a=(e&32)!==0;if(r&&i.skip(2),n){let d=H(i);i.skip(d)}if(a&&i.skip(2),H(i)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");let o=Yu(i),c=i.filePos,l=H(i);i.skip(12);let u=null;if(o>i.filePos-c){if(H(i)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");let m=Yu(i);u=U(i,m)}return{objectTypeIndication:l,decoderSpecificInfo:u}},Pt=i=>{let t=me(i);return i.skip(2),t=Math.min(t,i.remainingLength),be.decode(U(i,t))},kf=i=>{let t=jr(i);if(!t||t.name!=="data"||t.contentSize<8||i.remainingLength<8)return null;let e=B(i);i.skip(4);let r=U(i,t.contentSize-8);switch(e){case 1:return be.decode(r);case 2:return new oi("utf-16be").decode(r);case 13:return new At(r,"image/jpeg");case 14:return new At(r,"image/png");case 27:return new At(r,"image/bmp");default:return r}};var on=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closingPromise)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;let t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),!(t.output.state==="finalizing"||t.output.state==="finalized")&&await t.output._muxer.onTrackClose(t)})(),this._closingPromise.catch(()=>{})}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=this._flushAndClose(t)}},Ir=class extends on{constructor(t){if(super(),!le.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${le.join(", ")}.`);this._codec=t}},rd=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},ri=class extends Ir{constructor(t){super(t)}add(t,e){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),rd(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},fs=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.encoderConfig=null;this.encodersReclaimed=!1;this.muxer=null;this.lastMultipleOfKeyFrameInterval=null;this.emittedEncoderPackets=0;this.chunkTimestampsAreShiftedByDuration=!1;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.addMutex=new Ee;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new ni;this.customEncoderQueueSize=0;this.defaultEncodeOptions={};this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e,r){let n=t,a=null;try{if(this.checkForEncoderError(),a=await this.addMutex.acquire(),this.closed)return;let s=this.encodingConfig,o=s.sizeChangeBehavior??"deny",c=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(c=!0,o==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.flip!==void 0||s.transform?.crop!==void 0||s.transform?.alpha==="discard"||s.transform?.force===!0||c&&o!=="passThrough"){let m=s.transform?.width,f=s.transform?.height,p=s.transform?.fit??"fill";o!=="deny"&&o!=="passThrough"&&(p=o),c&&o!=="passThrough"&&(b(this.outputWidth),b(this.outputHeight),m=this.outputWidth,f=this.outputHeight);let g=await t.transform({width:m,height:f,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,flip:s.transform?.flip,fit:p,alpha:s.transform?.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=g.displayWidth,this.outputHeight=g.displayHeight),e&&t.close(),t=g,e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let d=s.transform?.frameRate;if(d!==void 0){let m=t.timestamp+t.duration,f=vl(t.timestamp,d);if(this.frameRateLastSample!==null)if(f<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=m;return}else await this.padFrameRate(f,r);if(t===n){let p=t.clone();e&&t.close(),t=p,e=!0}t.setTimestamp(f),t.setDuration(1/d),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=f,this.frameRateLastEndTimestamp=m}await this.processAndEncode(t,r)}finally{a?.(),e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,n;if(r.transform?.process){let a=r.transform.process(t);if(R(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);let s=[];try{for(let o of a)o instanceof $e?s.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?s.push(new $e(o)):s.push(new $e(o,{timestamp:t.timestamp,duration:t.duration}))}catch(o){for(let c of s)c!==t&&c.close();for(let c of a)(c instanceof $e&&c!==t||typeof VideoFrame<"u"&&c instanceof VideoFrame)&&c.close();throw o}n=s}else n=[t];try{for(let a of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),b(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...this.defaultEncodeOptions,...a.encodeOptions,...e},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(a),this.customEncoder){this.customEncoderQueueSize++;let u=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).catch(m=>this.setError(m)).finally(()=>{this.customEncoderQueueSize--,u.close()});this.customEncoderQueueSize>=4&&await d}else{b(this.encoder);let u=a.toVideoFrame(),d=j(this.preciseTimings,u.timestamp,f=>f.microsecondTimestamp),m=d!==-1?this.preciseTimings[d]:null;if(m&&m.microsecondTimestamp===u.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(u,l)}finally{u.close()}}else{this.splitter||(this.splitter=new id);let{colorFrame:p,alphaFrame:g}=await this.splitter.split(u);this.alphaFrameQueue.push(g);try{this.encoder.encode(p,l)}finally{p.close()}}else try{this.encoder.encode(u,l)}finally{u.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of n)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;b(this.frameRateLastSample);let n=Math.round((t-this.frameRateLastTimestamp)*r);for(let l=1;l<n;l++){var a=[];try{let u=yt(a,this.frameRateLastSample.clone());u.setTimestamp(this.frameRateLastTimestamp+l/r);u.setDuration(1/r);await this.processAndEncode(u,e)}catch(s){var o=s,c=!0}finally{kt(a,o,c)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let e=Ti(this.encodingConfig.quality,this.encodingConfig.bitrate);b(e!==void 0);let r=jl({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),n=null,a;for(let o of r){let c=o.config;if(this.encodingConfig.onEncoderConfig?.(c),a=Bn.find(u=>u.supports(this.encodingConfig.codec,c)),a){n=o;break}if(typeof VideoEncoder>"u")continue;if(c.alpha="discard",this.encodingConfig.alpha==="keep"&&(c.latencyMode="quality"),(c.width%2===1||c.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${c.width}x${c.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(c)).supported){n=o;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(xn("VideoEncoder"));let o=r[0].config,c=r.map(({config:l,quantizer:u})=>u!==null?`quantizer ${u}`:`${l.bitrate} bps`);throw new Error(`This specific encoder configuration (${o.codec}, ${c.join(" / ")}, ${o.width}x${o.height}, hardware acceleration: ${o.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let s=n.config;n.quantizer!==null?this.defaultEncodeOptions=$l(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=s.bitrate??null,a?(this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof ee))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");rd(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(l=>{this.setError(l)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init()):(this.encoderConfig=s,this.encodingConfig.codec==="avc"&&Wt()&&(this.chunkTimestampsAreShiftedByDuration=await vg()),this.createWebCodecsEncoders()),b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(e=>this.setError(e))}createWebCodecsEncoders(){let t=this.encoderConfig;b(t);let e=[],r=[],n=0,a=0,s=(c,l)=>{if(Ud(c)){this.encodersReclaimed=!0;return}c.stack=l,this.setError(c)},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(c,l)=>{try{if(!this.alphaEncoder){this.addPacket(c,null,l);return}let u=this.alphaFrameQueue.shift();b(u!==void 0),u?(this.alphaEncoder.encode(u,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),a++,u.close(),e.push({chunk:c,meta:l})):a===0?this.addPacket(c,null,l):(r.push(n+a),e.push({chunk:c,meta:l}))}catch(u){this.setError(u)}},error:c=>s(c,o)}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let c=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(l,u)=>{try{a--;let d=e.shift();for(b(d!==void 0),this.addPacket(d.chunk,l,d.meta),n++;r.length>0&&r[0]===n;){r.shift();let m=e.shift();b(m!==void 0),this.addPacket(m.chunk,null,m.meta)}}catch(d){this.setError(d)}},error:l=>s(l,c)}),this.alphaEncoder.configure(t)}}addPacket(t,e,r){let n={};if(e){let d=new Uint8Array(e.byteLength);e.copyTo(d),n.alpha=d}let a=ee.fromEncodedChunk(t,n),s=this.encoderConfig;if(b(s),r?.decoderConfig&&(r.decoderConfig.codec=Si({width:s.width,height:s.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?G(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:s.codec.includes("avc1.")?1:s.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!r.decoderConfig.description?hr(a.data):null,hevcType:s.codec.includes("hev1.")?"hev1":s.codec.includes("hvc1.")?"hvc1":null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?br(a.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?vn(a.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?hi(a.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&r.decoderConfig.description&&Wt())){let d=gr(G(r.decoderConfig.description)),m=d?.sequenceParameterSets[0];if(m&&m[0]===m[1]){b(d),m=m.subarray(1);let f=d.pictureParameterSets[0];f&&(f=f.subarray(1));let p=En({...d,sequenceParameterSets:[m],pictureParameterSets:f?[f]:[]});r.decoderConfig.description=p}}let o=t.timestamp;this.chunkTimestampsAreShiftedByDuration&&(o-=t.duration??0,a=a.clone({timestamp:o/1e6}));let c=j(this.preciseTimings,o,d=>d.microsecondTimestamp),l=c!==-1?this.preciseTimings[c]:null,u=null;this.emittedEncoderPackets===0&&a.type==="delta"&&r?.decoderConfig&&(u=gi(this.encodingConfig.codec,r.decoderConfig,a.data)),(l&&l.microsecondTimestamp===o||u!==null)&&(a=a.clone({timestamp:l?.timestampIsValid?l.timestamp:void 0,duration:l?.durationIsValid?l.duration:void 0,type:u??void 0})),rd(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(d=>{this.setError(d)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){b(this.encoder),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=null,this.createWebCodecsEncoders()}async flushAndClose(t){await this.ensureEncoderPromise?.catch(()=>{});try{if(!t){this.checkForEncoderError();let e=await this.addMutex.acquire();try{if(this.frameRateLastSample){let r=this.encodingConfig.transform.frameRate,n=vl(this.frameRateLastEndTimestamp,r);await this.padFrameRate(n)}}finally{e()}}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(e=>this.setError(e)):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await Nr(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.addMutex.pending+(this.encoder?.encodeQueueSize??0)}checkForEncoderError(){if(this.errorSet)throw this.error}},up=null,vg=()=>up??=(async()=>{let i=null,t=new VideoEncoder({output:e=>{i??=e.timestamp},error:()=>{}});try{t.configure({codec:"avc1.64001f",width:1280,height:720});let e=new VideoFrame(new Uint8Array(1280*720*1.5),{format:"I420",codedWidth:1280,codedHeight:720,timestamp:0,duration:500});t.encode(e,{keyFrame:!0}),e.close(),await t.flush()}catch{return up=null,!1}finally{t.state!=="closed"&&t.close()}return i===500})(),Zu=null,id=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){if(!this.worker){if(!Zu){let n=new Blob([`(${_g.toString()})()`],{type:"application/javascript"});Zu=URL.createObjectURL(n)}this.worker=new Worker(Zu),this.worker.addEventListener("message",n=>{let a=n.data,s=this.pendingRequests.get(a.id);s&&(this.pendingRequests.delete(a.id),"error"in a?s.reject(new Error(a.error)):s.resolve({colorFrame:a.colorFrame,alphaFrame:a.alphaFrame}))}),this.worker.addEventListener("error",n=>{let a=new Error(n.message||"Color/alpha splitter worker error.");for(let s of this.pendingRequests.values())s.reject(a);this.pendingRequests.clear()})}let e=this.nextRequestId++,r=te();return this.pendingRequests.set(e,r),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),r.promise}close(){this.worker?.terminate(),this.worker=null;let t=new Error("Color/alpha splitter closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},_g=()=>{let i=null,t=Promise.resolve();self.addEventListener("message",a=>{let{id:s,sourceFrame:o}=a.data;t=t.then(async()=>{try{let{colorFrame:c,alphaFrame:l}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:s,error:c.message})}finally{o.close()}})});let e=async a=>{let s=a.format;if(!s)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=a.allocationSize();if((!i||i.byteLength!==o)&&(i=new Uint8Array(o)),await a.copyTo(i),s==="RGBA"||s==="BGRA")return r(i,s,a);if(s==="I420A"||s==="I420AP10"||s==="I420AP12"||s==="I422A"||s==="I422AP10"||s==="I422AP12"||s==="I444A"||s==="I444AP10"||s==="I444AP12")return n(i,s,a);throw new Error(`CPU color/alpha splitting does not support format '${s}'.`)},r=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=c*l,d=Math.ceil(c/2),m=Math.ceil(l/2),f=u+d*m*2,p=new Uint8Array(f);for(let k=0,T=3;k<u;k++,T+=4)p[k]=a[T];p.fill(128,u);let g=new VideoFrame(a,{format:s==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),h={format:"I420",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[p.buffer]},y=new VideoFrame(p,h);return{colorFrame:g,alphaFrame:y}},n=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=s.includes("P10"),d=s.includes("P12"),m=u||d?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(l/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=l):(f=c,p=l);let g=c*l,h=f*p,y=g*m,k=h*m,T=g*m,S=y+k*2,w=s.replace("A",""),A=Math.ceil(c/2),C=Math.ceil(l/2),E=A*C,I=E*m,x=T+2*I,P=new Uint8Array(x),v=S;P.set(a.subarray(v,v+T),0);let _=T,M=u?512:d?2048:128;m===1?P.fill(M,_):new Uint16Array(P.buffer,_,2*E).fill(M);let D=u?"I420P10":d?"I420P12":"I420",L=new VideoFrame(a.subarray(0,S),{format:w,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:o.colorSpace}),z={format:D,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[P.buffer]},$=new VideoFrame(P,z);return{colorFrame:L,alphaFrame:$}}},cn=class extends Ir{constructor(t){yo(t),super(t.codec),this._encoder=new fs(this,t)}add(t,e){if(!(t instanceof $e))throw new TypeError("videoSample must be a VideoSample.");return this._ensureValidAdd(),this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Mc=class extends Ir{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");yo(e),super(e.codec),this._encoder=new fs(this,e),this._canvas=t}add(t,e=0,r){if(!Number.isFinite(t))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");this._ensureValidAdd();let n=new $e(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Bc=class extends Ir{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(yo(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(!Number.isFinite(n.frameRate)||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a finite positive number or null.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._workerTrackId=null;this._workerListener=null;this._promiseWithResolvers=te();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new fs(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||O._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let r=null,n=null,a=null,s=0,o=!1,c=null,l=0,u=()=>{if(b(e!==null),!this._lastVideoFrame)return;b(a!==null),b(n!==null);let f=performance.now();for(;f-a>1e3/e;){a+=1e3/e;let p=n+s/e,g=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*p,duration:1e6/e});m(g,f)}};e!==null&&(this._timerHandle=Gd(u,4));let d=f=>{if(this._closingPromise){f.close();return}if(e===null)m(f);else{let p=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=f):(n=f.timestamp/1e6,m(f.clone(),p),a=p,this._lastVideoFrame=f)}},m=(f,p=performance.now())=>{if(o||this._closingPromise||this._connectedTrack.output.state!=="started"){f.close();return}s++;let g=f.timestamp/1e6;if(this._paused){if(r!==null){if(c!==null&&this._options.timestampBase!=="unix"){let k=g-c;l-=k}c=g}f.close();return}if(r===null){r=g;let y,k=this._options.timestampBase??"synced-zero";if(k==="unix")y=Date.now()/1e3;else if(k==="zero")y=0;else{let T=this._connectedTrack.output;T._firstMediaStreamTimestamp===null?(T._firstMediaStreamTimestamp=p/1e3,y=0):y=p/1e3-T._firstMediaStreamTimestamp}l=y-r}if(c=g,this._encoder.getQueueSize()>=8){f.close();return}let h=new $e(f,{timestamp:g+l});this._encoder.add(h,!0).catch(y=>{o=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(y),this._workerTrackId!==null&&td({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let f=new MediaStreamTrackProcessor({track:this._track}),p=new WritableStream({write:d});f.readable.pipeTo(p,{signal:this._abortController.signal}).catch(g=>{g instanceof DOMException&&g.name==="AbortError"||this._promiseWithResolvers.reject(g)})}else if(await Og()){this._workerTrackId=Mg++;let p=this._track.clone();td({type:"videoTrack",trackId:this._workerTrackId,track:p},[p]),this._workerListener=g=>{let h=g.data;h.type==="videoFrame"&&h.trackId===this._workerTrackId?d(h.videoFrame):h.type==="error"&&h.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(h.error)},Nt.addEventListener("message",this._workerListener)}else if(e!==null){let p=document.createElement("video");p.style.position="fixed",p.style.left="-10000px",p.style.top="-10000px",p.style.width="1px",p.style.height="1px",p.style.opacity="0",p.style.pointerEvents="none",p.muted=!0,p.srcObject=new MediaStream([this._track]),document.body.appendChild(p),this._videoElement=p,p.addEventListener("loadeddata",()=>{if(o||!this._videoElement)return;let g=new VideoFrame(p,{timestamp:1e3*performance.now()});d(g),g.close()},{once:!0}),p.play().catch(g=>{o=!0,this._promiseWithResolvers.reject(g)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&Qd(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(b(this._workerListener),td({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let n=a=>{let s=a.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(b(this._workerListener),Nt.removeEventListener("message",this._workerListener),Nt.removeEventListener("message",n),r())};Nt.addEventListener("message",n)}))}finally{await this._encoder.flushAndClose(e)}}},vr=class extends on{constructor(t){if(super(),!pe.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${pe.join(", ")}.`);this._codec=t}},ii=class extends vr{constructor(t){super(t)}add(t,e){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,t,e)}},ms=2048,ps=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;this.addMutex=new Ee;this.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.pcmMeta=null;this.pcmStartTimestamp=0;this.pcmEmittedFrames=0;this.pcmReadBuffer=new ArrayBuffer(0);this.pcmScratchView=null;this.pcmScratchFrames=0;this.customEncoder=null;this.customEncoderCallSerializer=new ni;this.customEncoderQueueSize=0;this.lastEndSampleIndex=null;this.resampler=null;this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e){let r=null;try{if(this.checkForEncoderError(),r=await this.addMutex.acquire(),this.closed)return;if(this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(t.numberOfChannels!==this.lastNumberOfChannels||t.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${t.numberOfChannels} channels at ${t.sampleRate} Hz.`)}else this.lastNumberOfChannels=t.numberOfChannels,this.lastSampleRate=t.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new So({targetNumberOfChannels:n.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:n.transform.sampleRate??t.sampleRate,onSample:async s=>{await this.processAndEncode(s,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{r?.(),e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&Um(t.format)!==r.transform.sampleFormat){let n=zm(t,r.transform.sampleFormat);e&&t.close(),t=n,e=!0}if(r.transform?.process)try{let n=r.transform.process(t);if(R(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(let a of n)if(!(a instanceof Ce))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(let a of n)await this.encodeSample(a,a!==t)}finally{for(let a of n)a instanceof Ce&&a!==t&&a.close()}}finally{e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(t.numberOfFrames===0||(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),b(this.encoderInitialized),this.closed))return;{let r=Math.round(t.timestamp*t.sampleRate),n=Math.round((t.timestamp+t.duration)*t.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let a=r-this.lastEndSampleIndex;if(a>=64){let s=Ct(t.format)*t.numberOfChannels,o=new Uint8Array(s*Math.min(a,t.sampleRate));(t.format==="u8"||t.format==="u8-planar")&&o.fill(2**7);let c=a;for(;c>0;){let l=Math.min(c,t.sampleRate),u=new Ce({data:o.subarray(0,s*l),_doNotCopy:!0,format:t.format,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:l,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(u,!0),c-=l}}this.lastEndSampleIndex+=t.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;let r=t.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).catch(a=>this.setError(a)).finally(()=>{this.customEncoderQueueSize--,r.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(t,e);else{b(this.encoder),this.checkForEncoderError();let r=t.toAudioData();try{this.encoder.encode(r)}finally{r.close()}e&&t.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{e&&t.close()}}async doPcmEncoding(t,e){b(this.outputSampleSize),b(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:n,sampleRate:a,timestamp:s}=t;this.pcmMeta||(this.pcmMeta={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}},this.pcmStartTimestamp=s);let o=t.format==="s32"||t.format==="s32-planar",c=o?"s32":"f32",l=o?1/2147483648:1,u=t.allocationSize({planeIndex:0,format:c});this.pcmReadBuffer.byteLength<u&&(this.pcmReadBuffer=new ArrayBuffer(u));let d=o?new Int32Array(this.pcmReadBuffer,0,u/4):new Float32Array(this.pcmReadBuffer,0,u/4);t.copyTo(d,{planeIndex:0,format:c}),e&&t.close();let m=0;for(;m<n;){this.pcmScratchView??=new DataView(new ArrayBuffer(ms*r*this.outputSampleSize));let f=Math.min(ms-this.pcmScratchFrames,n-m),p=this.pcmScratchFrames*r,g=m*r;for(let h=0;h<f*r;h++)this.writeOutputValue(this.pcmScratchView,(p+h)*this.outputSampleSize,d[g+h]*l);this.pcmScratchFrames+=f,m+=f,this.pcmScratchFrames===ms&&await this.emitPcmScratchPacket()}}async emitPcmScratchPacket(){b(this.outputSampleSize),b(this.pcmScratchView),b(this.pcmMeta?.decoderConfig);let{numberOfChannels:t,sampleRate:e}=this.pcmMeta.decoderConfig,r=this.pcmScratchFrames*t*this.outputSampleSize,n=new ee(new Uint8Array(this.pcmScratchView.buffer,0,r),"key",this.pcmStartTimestamp+this.pcmEmittedFrames/e,this.pcmScratchFrames/e);this.pcmEmittedFrames+=this.pcmScratchFrames,this.pcmScratchView=null,this.pcmScratchFrames=0,this.encodingConfig.onEncodedPacket?.(n,this.pcmMeta),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,this.pcmMeta)}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let{format:e,numberOfChannels:r,sampleRate:n,timestamp:a}=t,s=Ti(this.encodingConfig.quality,this.encodingConfig.bitrate),o=Xl({numberOfChannels:r,sampleRate:n,...this.encodingConfig,quality:s});this.encodingConfig.onEncoderConfig?.(o),this.source._nominalBitrate=o.bitrate??null;let c=On.find(l=>l.supports(this.encodingConfig.codec,o));if(c)this.customEncoder=new c,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(l,u)=>{if(!(l instanceof ee))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(u!==void 0&&(!u||typeof u!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(l,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u).catch(d=>{this.setError(d)})},this.customEncoder.onError=l=>{this.setError(l)},await this.customEncoder.init();else if(se.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(xn("AudioEncoder"));let l;try{l=(await AudioEncoder.isConfigSupported(o)).supported??!1}catch{l=!1}if(!l)throw new Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let d=await Rg(this.encodingConfig.codec,o.codec)/o.sampleRate,m=0,f=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(p,g)=>{try{if(g?.decoderConfig&&(mp(this.encodingConfig.codec,o,g.decoderConfig),this.encodingConfig.codec==="opus"&&g.decoderConfig.description)){let y=G(g.decoderConfig.description);m=yr(y).preSkip/tt}let h=ee.fromEncodedChunk(p);h=h.clone({timestamp:Mt(h.timestamp-d-m,o.sampleRate),duration:p.duration!=null?Mt(h.duration,o.sampleRate):void 0}),Wt()&&(m=0),this.encodingConfig.onEncodedPacket?.(h,g),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,h,g).catch(y=>{this.setError(y)})}catch(h){this.setError(h)}},error:p=>{p.stack=f,this.setError(p)}}),this.encoder.configure(o),this.encodingConfig.codec==="aac"&&et()&&dp(this.encoder,e,r,n,a)}b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(e=>this.setError(e))}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Me(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,ne(Math.round(o*128)+128,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,ne(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=ne(Math.round(o*32768),-32768,32767);a.setUint8(s,Tm(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=ne(Math.round(o*32768),-32768,32767);a.setUint8(s,Sm(c))}:b(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,ne(Math.round(o*32768)+32768,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,ne(Math.round(o*32768),-32768,32767),n):b(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>zi(a,s,ne(Math.round(o*8388608)+8388608,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Rd(a,s,ne(Math.round(o*8388608),-8388608,8388607),n):b(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,ne(Math.round(o*2147483648)+2147483648,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,ne(Math.round(o*2147483648),-2147483648,2147483647),n):e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat32(s,o,n):b(!1);break;case 8:e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat64(s,o,n):b(!1);break;default:Z(r),b(!1)}}async flushAndClose(t){await this.ensureEncoderPromise?.catch(()=>{});try{if(!t){this.checkForEncoderError();let e=await this.addMutex.acquire();try{this.resampler&&await this.resampler.finalize(),this.pcmScratchFrames>0&&await this.emitPcmScratchPacket()}finally{e()}}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(e=>this.setError(e)):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}t||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.isPcmEncoder?this.addMutex.pending:this.addMutex.pending+(this.encoder?.encodeQueueSize??0)}checkForEncoderError(){if(this.errorSet)throw this.error}},Ju=new Map,Rg=(i,t)=>{let e=Ju.get(t);return e||(e=(async()=>{let a={codec:t,numberOfChannels:1,sampleRate:48e3,...wo(i)},s=4096,o=2*s,c="f32-planar",l=[],u=null,d=null,m=-1/0,f=0,p=null,g=new AudioEncoder({output:(k,T)=>{T?.decoderConfig&&(u??=T.decoderConfig),l.push(k)},error:k=>{p??=k}}),h=new AudioDecoder({output:k=>{let T=new Float32Array(k.numberOfFrames);k.copyTo(T,{planeIndex:0,format:c}),k.close();for(let S=0;S<T.length;S++)T[S]>m&&(m=T[S],d=f+S);f+=T.length},error:k=>{p??=k}});try{g.configure(a),i==="aac"&&et()&&dp(g,c,1,48e3,0);let k=new Float32Array(1*o);k[s]=1;let T=new AudioData({data:k,format:c,numberOfChannels:1,numberOfFrames:o,sampleRate:48e3,timestamp:0});g.encode(T),T.close(),await g.flush(),b(u),mp(i,a,u),h.configure(u);for(let S of l)h.decode(S);await h.flush()}catch(k){throw p??k}finally{g.state!=="closed"&&g.close(),h.state!=="closed"&&h.close()}b(d!==null);let y=Math.round(l[0].timestamp/1e6*48e3);return d-s+y})(),Ju.set(t,e),e.catch(()=>Ju.delete(t)),e)},dp=(i,t,e,r,n)=>{let s=Ct(t),o=new Uint8Array(s*1024*e);(t==="u8"||t==="u8-planar")&&o.fill(2**7);let c=new AudioData({data:o,format:t,numberOfChannels:e,numberOfFrames:1024,sampleRate:r,timestamp:Math.round(1e6*(n-1024/r))});i.encode(c),c.close()},mp=(i,t,e)=>{if(i==="aac"){if(e.description&&e.description.byteLength>0&&G(e.description)[0]===3){let{decoderSpecificInfo:n}=Oo(xe.tempFromBytes(G(e.description)));e.description=n??void 0}let r=!1;if(!e.description||e.description.byteLength<2?r=!0:r=xt(G(e.description)).objectType===0,r){let n=Number(J(t.codec.split(".")));e.description=ui({objectType:n,outputNumberOfChannels:e.numberOfChannels,outputSampleRate:e.sampleRate,programConfigElement:null})}}},aa=class extends vr{constructor(t){ko(t),super(t.codec),this._encoder=new ps(this,t)}add(t){if(!(t instanceof Ce))throw new TypeError("audioSample must be an AudioSample.");return this._ensureValidAdd(),this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Oc=class extends vr{constructor(e,r={}){if(ko(e),typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.startTimestamp!==void 0&&!Number.isFinite(r.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(e.codec);this._addMutex=new Ee;this._encoder=new ps(this,e),this._accumulatedTime=r.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");this._ensureValidAdd();let r=Ce._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;let n=await this._addMutex.acquire();try{for(let a of r)await this._encoder.add(a,!0)}finally{n()}}async _flushAndClose(e){return e||(await this._addMutex.acquire())(),this._encoder.flushAndClose(e)}},Dc=class extends vr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(ko(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=te();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new ps(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||O._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,r=!1,n=null,a=0,s=o=>{if(r||this._closingPromise||this._connectedTrack.output.state!=="started"){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let u=c-n;a-=u}n=c}o.close();return}if(e===null){e=o.timestamp;let l,u=this._options.timestampBase??"synced-zero";if(u==="unix")l=Date.now()/1e3;else if(u==="zero")l=0;else{let d=this._connectedTrack.output;d._firstMediaStreamTimestamp===null?(d._firstMediaStreamTimestamp=performance.now()/1e3,l=0):l=performance.now()/1e3-d._firstMediaStreamTimestamp}a=l-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(l=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(l),this._audioContext&&this._audioContext.state!=="closed"&&this._audioContext.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:l=>s(new Ce(l))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(l=>{l instanceof DOMException&&l.name==="AbortError"||this._promiseWithResolvers.reject(l)})}else{let o=window.AudioContext||window.webkitAudioContext;this._audioContext=new o({sampleRate:this._track.getSettings().sampleRate});let c=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),c.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let l=0;this._scriptProcessorNode.onaudioprocess=u=>{let d=Ce._fromAudioBuffer(u.inputBuffer,l);l+=u.inputBuffer.duration;for(let m of d)s(m)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(b(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.close())}finally{await this._encoder.flushAndClose(e)}}},Fg=()=>{let i=(r,n)=>{n?self.postMessage(r,{transfer:n}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let t=new Map,e=new Map;self.addEventListener("message",r=>{let n=r.data;switch(n.type){case"videoTrack":{e.set(n.trackId,n.track);let a=new MediaStreamTrackProcessor({track:n.track}),s=new WritableStream({write:c=>{if(!e.has(n.trackId)){c.close();return}i({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;t.set(n.trackId,o),a.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{let a=t.get(n.trackId);a&&(a.abort(),t.delete(n.trackId)),e.get(n.trackId)?.stop(),e.delete(n.trackId),i({type:"trackStopped",trackId:n.trackId})}break;default:Z(n)}})},Mg=0,Nt=null,Bg=()=>{let i=new Blob([`(${Fg.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(i);Nt=new Worker(t)},ed=null,Og=async()=>ed!==null?ed:(Nt||Bg(),new Promise(i=>{b(Nt);let t=e=>{let r=e.data;r.type==="support"&&(ed=r.supported,Nt.removeEventListener("message",t),i(r.supported))};Nt.addEventListener("message",t)})),td=(i,t)=>{b(Nt),t?Nt.postMessage(i,t):Nt.postMessage(i)},ln=class extends on{constructor(t){if(super(),!qe.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${qe.join(", ")}.`);this._codec=t}},Vc=class extends ln{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new ao({codec:e,output:(r,n)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,r,n).catch(a=>{this._setError(a)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};var le=["avc","hevc","vp9","av1","vp8","prores"],se=["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"],Jt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts","truehd"],pe=[...Jt,...se],qe=["webvtt"],Ji=["truehd"],ha=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],fp=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Gi=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],Uc=[{maxPictureSize:147456,maxHSize:2048,maxVSize:1152,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxHSize:2816,maxVSize:1584,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxHSize:4352,maxVSize:2448,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxHSize:5504,maxVSize:3096,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:"H",level:19}],pp=".01.01.01.01.00",hp=".0.110.01.01.01.0",$r=["ap4x","ap4h","apch","apcn","apcs","apco"],La=["dtsc","dtsh","dtsl","dtse"],Dg=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],fo=(i,t,e,r,n)=>{if(i==="avc"){let a=et(),s=a?66:100,o=Math.ceil(t/16)*Math.ceil(e/16),c=ha.find(f=>o<=f.maxMacroblocks&&r<=f.maxBitrate)??J(ha),l=c?c.level:0,u=s.toString(16).padStart(2,"0"),d=a?"40":"00",m=l.toString(16).padStart(2,"0");return`avc1.${u}${d}${m}`}else if(i==="hevc"){let a="",o="6",c=t*e,l=fp.find(d=>c<=d.maxPictureSize&&r<=d.maxBitrate)??J(fp);return`hvc1.${a}1.${o}.${l.tier}${l.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",s=t*e,o=Gi.find(l=>s<=l.maxPictureSize&&r<=l.maxBitrate)??J(Gi);return`vp09.${a}.${o.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let s=t*e,o=Uc.find(u=>s<=u.maxPictureSize&&t<=u.maxHSize&&e<=u.maxVSize&&r<=u.maxBitrate)??J(Uc);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(i==="prores"){let s=Math.pow(t*e/2073600,.95),o=Dg.filter(u=>u.alpha===n),c=o[0].fourCc,l=1/0;for(let{fourCc:u,bitrate:d}of o){let m=Math.abs(d*s-r);m<l&&(l=m,c=u)}return c}else Z(i)}throw new TypeError(`Unhandled codec '${String(i)}'.`)},gp=i=>{let t=i.split("."),e=Number(t[1]),r=Number(t[2]),n=Number(t[3]),a=t[4]?Number(t[4]):1;return[1,1,e,2,1,r,3,1,n,4,1,a]},zc=i=>{let t=i.split("."),n=(1<<7)+1,a=Number(t[1]),s=t[2],o=Number(s.slice(0,-1)),c=(a<<5)+o,l=s.slice(-1)==="H"?1:0,u=Number(t[3]),d=u===8?0:1,m=u===12?1:0,f=t[4]?Number(t[4]):0,p=t[5]?Number(t[5][0]):1,g=t[5]?Number(t[5][1]):1,h=t[5]?Number(t[5][2]):0,y=(l<<7)+(d<<6)+(m<<5)+(f<<4)+(p<<3)+(g<<2)+h;return[n,c,y,0]},Si=i=>{let{codec:t,codecDescription:e,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:a,vp9CodecInfo:s,av1CodecInfo:o,proresFormat:c}=i;if(t==="avc"){if(b(i.avcType!==null),n){let l=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${i.avcType}.${ci(l)}`}if(!e||e.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${i.avcType}.${ci(e.subarray(1,4))}`}else if(t==="hevc"){b(i.hevcType!==null);let l,u,d,m,f,p;if(a)l=a.generalProfileSpace,u=a.generalProfileIdc,d=Cl(a.generalProfileCompatibilityFlags),m=a.generalTierFlag,f=a.generalLevelIdc,p=[...a.generalConstraintIndicatorFlags];else{if(!e||e.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let h=N(e),y=h.getUint8(1);l=y>>6&3,u=y&31,d=Cl(h.getUint32(2)),m=y>>5&1,f=h.getUint8(12),p=[];for(let k=0;k<6;k++)p.push(h.getUint8(6+k))}let g=`${i.hevcType}.`;for(g+=["","A","B","C"][l]+u,g+=".",g+=d.toString(16).toUpperCase(),g+=".",g+=m===0?"L":"H",g+=f;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(g+=".",g+=p.map(h=>h.toString(16).toUpperCase()).join(".")),g}else{if(t==="vp8")return"vp8";if(t==="vp9"){let l=i.width*i.height,u=J(Gi).level;for(let S of Gi)if(l<=S.maxPictureSize){u=S.level;break}if(!s)return`vp09.00.${u.toString().padStart(2,"0")}.08`;let d=s.profile.toString().padStart(2,"0"),m=(s.level===0?u:s.level).toString().padStart(2,"0"),f=s.bitDepth.toString().padStart(2,"0"),p=s.chromaSubsampling.toString().padStart(2,"0"),g=s.colourPrimaries.toString().padStart(2,"0"),h=s.transferCharacteristics.toString().padStart(2,"0"),y=s.matrixCoefficients.toString().padStart(2,"0"),k=s.videoFullRangeFlag.toString().padStart(2,"0"),T=`vp09.${d}.${m}.${f}.${p}`;return T+=`.${g}.${h}.${y}.${k}`,T.endsWith(pp)&&(T=T.slice(0,-pp.length)),T}else if(t==="av1"){if(!o){let S=i.width*i.height,w=J(Uc).level;for(let A of Uc)if(S<=A.maxPictureSize&&i.width<=A.maxHSize&&i.height<=A.maxVSize){w=A.level;break}return`av01.0.${w.toString().padStart(2,"0")}M.08`}let l=o.profile,u=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",m=o.bitDepth.toString().padStart(2,"0"),f=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),g,h,y,k;Gs(o)?(g=o.colourPrimaries,h=o.transferCharacteristics,y=o.matrixCoefficients,k=o.videoFullRangeFlag):(g=r?.primaries?_t[r.primaries]:1,h=r?.transfer?Rt[r.transfer]:1,y=r?.matrix?Ft[r.matrix]:1,k=r?.fullRange?1:0);let T=`av01.${l}.${u}${d}.${m}`;return T+=`.${f}.${p.toString().padStart(3,"0")}`,T+=`.${g.toString().padStart(2,"0")}`,T+=`.${h.toString().padStart(2,"0")}`,T+=`.${y.toString().padStart(2,"0")}`,T+=`.${k}`,T.endsWith(hp)&&(T=T.slice(0,-hp.length)),T}else{if(t==="prores")return c??"apch";t!==null&&Z(t)}}throw new TypeError(`Unhandled codec '${t}'.`)},Do=i=>{switch(i.codec){case"avc":{let t=i.avcCodecInfo?.sequenceParameterSets[0];if(!t&&i.codecDescription&&(t=gr(i.codecDescription)?.sequenceParameterSets[0]),t){let e=Gt(t);if(e)return{primaries:Tt[e.colourPrimaries],transfer:wt[e.transferCharacteristics],matrix:St[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=i.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0];if(!t&&i.codecDescription&&(t=In(i.codecDescription)?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0]),t){let e=Qi(t);if(e)return{primaries:Tt[e.colourPrimaries],transfer:wt[e.transferCharacteristics],matrix:St[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(i.vp9CodecInfo)return{primaries:Tt[i.vp9CodecInfo.colourPrimaries],transfer:wt[i.vp9CodecInfo.transferCharacteristics],matrix:St[i.vp9CodecInfo.matrixCoefficients],fullRange:!!i.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(i.av1CodecInfo)return{primaries:Tt[i.av1CodecInfo.colourPrimaries],transfer:wt[i.av1CodecInfo.transferCharacteristics],matrix:St[i.av1CodecInfo.matrixCoefficients],fullRange:!!i.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(i.proresCodecInfo)return{primaries:Tt[i.proresCodecInfo.colourPrimaries],transfer:wt[i.proresCodecInfo.transferCharacteristics],matrix:i.proresCodecInfo.matrixCoefficients===0?void 0:St[i.proresCodecInfo.matrixCoefficients],fullRange:i.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},po=i=>{if(i==="aac")return"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(i==="ac3")return"ac-3";if(i==="eac3")return"ec-3";if(i==="dts")return"dtsc";if(i==="truehd")return"mlpa";if(se.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},Nn=i=>{let{codec:t,codecDescription:e,aacCodecInfo:r,dtsFormat:n}=i;if(t==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let a;return r.objectType!==null?a=r.objectType:a=xt(e).objectType,`mp4a.40.${a}`}}else{if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(t==="ac3")return"ac-3";if(t==="eac3")return"ec-3";if(t==="dts")return n??"dtsc";if(t==="truehd")return"mlpa";if(t&&se.includes(t))return t}throw new TypeError(`Unhandled codec '${t}'.`)},Em=i=>{},Im=i=>{switch(i.codec){case"flac":{let t=Hi("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");return i.sampleRate>=1<<20||i.numberOfChannels>8?!1:(t[18]=i.sampleRate>>>12,t[19]=i.sampleRate>>>4,t[20]=(i.sampleRate&15)<<4|i.numberOfChannels-1<<1,t)}case"vorbis":{let t=Hi("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),e=N(t);return e.setUint8(15,i.numberOfChannels),e.setUint32(16,i.sampleRate,!0),t}default:return}},Fc=(i,t)=>{switch(i){case"aac":{if(!t.description)return 1024/t.sampleRate;let e=xt(G(t.description));if(e.coreSampleRate===null)throw new Error("Invalid AAC sampling frequency index.");return e.frameLength/e.coreSampleRate}case"opus":return nd;case"mp3":{let{sampleRate:e,numberOfChannels:r}=t,n=e>=32e3,a=n?1152:576,s=n?32e3:8e3,o=n?511:255,c=n?r===1?17:32:r===1?9:17,u=Math.floor(a/8*s/e)-4-c;return(1+Math.ceil(o/u))*a/e}case"vorbis":{b(t.description);let e=G(t.description),r=1,n=2;for(;n>0;)e[r++]<255&&n--;return(1<<(e[r+28]>>4))/2/t.sampleRate}case"ac3":case"eac3":return 256/t.sampleRate;case"dts":return 512/t.sampleRate;case"flac":case"truehd":case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":case"pcm-u8":case"pcm-s8":case"ulaw":case"alaw":return 0;default:Z(i),b(!1)}},bp=(i,t)=>{switch(i){case"aac":return 1024;case"opus":return .02*t;case"mp3":return 576;case"vorbis":return 256;case"flac":return 1152;case"ac3":return 1536;case"eac3":return 256;case"dts":return 512;case"truehd":return 40;case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":case"pcm-u8":case"pcm-s8":case"ulaw":case"alaw":return ms;default:Z(i),b(!1)}},tt=48e3,nd=.4,yp=/^pcm-([usf])(\d+)(be)?$/,Me=i=>{if(b(se.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let t=yp.exec(i);b(t);let e;t[1]==="u"?e="unsigned":t[1]==="s"?e="signed":e="float";let r=Number(t[2])/8,n=t[3]!=="be",a=i==="pcm-u8"?2**7:0;return{dataType:e,sampleSize:r,littleEndian:n,silentValue:a}},ct=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":$r.includes(i)?"prores":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"||i==="mp4a.40.34"?"mp3":i.startsWith("mp4a.40.")||i==="mp4a.67"?"aac":i==="opus"||i==="Opus"?"opus":i==="vorbis"?"vorbis":i==="flac"||i==="fLaC"?"flac":i==="ac-3"||i==="ac3"?"ac3":i==="ec-3"||i==="eac3"?"eac3":La.includes(i)?"dts":i==="mlpa"?"truehd":i==="ulaw"?"ulaw":i==="alaw"?"alaw":yp.test(i)?i:i==="webvtt"?"webvtt":null,Jm=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},wo=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},Vg=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...$r],Ug=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,zg=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ng=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Lg=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,_r=(i,t)=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Vg.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectWidth)||i.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectHeight)||i.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectWidth!==void 0!=(i.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(i.decoderConfig.description!==void 0&&!Dr(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=i.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(_t);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let n=Object.keys(Rt);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let a=Object.keys(Ft);if(e.matrix!=null&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!Ug.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!zg.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!Ng.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(i.decoderConfig.codec.startsWith("av01")){if(!Lg.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if($r.some(e=>i.decoderConfig.codec.startsWith(e))&&!$r.some(e=>i.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${$r.join(", ")}.`);if(t!==null&&ct(i.decoderConfig.codec)!==t)throw new TypeError(`Video chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Hg=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts","mlpa"],Re=(i,t)=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Hg.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!Dr(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.40.42","mp4a.67"].includes(i.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("ac-3")||i.decoderConfig.codec.startsWith("ac3")){if(i.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(i.decoderConfig.codec.startsWith("ec-3")||i.decoderConfig.codec.startsWith("eac3")){if(i.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(i.decoderConfig.codec.startsWith("dts")){if(!La.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${La.join(", ")}.`)}else if(i.decoderConfig.codec.startsWith("mlpa")){if(i.decoderConfig.codec!=="mlpa")throw new TypeError('Audio chunk metadata decoder configuration codec string for TrueHD must be "mlpa".')}else if((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!se.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${se.join(", ")}).`);if(t!==null&&ct(i.decoderConfig.codec)!==t)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Nc=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var Pe=class{constructor(t){this.mutex=new Ee;this.trackPacketOrderValidators=new WeakMap;this.output=t}async onTrackClose(t){}validateTimestamp(t,e,r){let n=this.trackPacketOrderValidators.get(t);n||(n=new sa,this.trackPacketOrderValidators.set(t,n));let a=r?"key":"delta";if(n.digest(e,a))return;if(n.maxTimestamp===null)throw new Error("First packet must be a key packet.");let s=a==="key"?n.maxTimestamp:n.maxTimestampBeforeLastKeyPacket;throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${s}s.`)}},sa=class{constructor(){this.maxTimestamp=null;this.maxTimestampBeforeLastKeyPacket=null}check(t,e){if(this.maxTimestamp===null)return e==="key";let r=e==="key"?this.maxTimestamp:this.maxTimestampBeforeLastKeyPacket;return r===null||t>=r}digest(t,e){return this.check(t,e)?(e==="key"&&(this.maxTimestampBeforeLastKeyPacket=this.maxTimestamp),this.maxTimestamp=Math.max(this.maxTimestamp??-1/0,t),!0):!1}},Lc=class extends Pe{async start(){}async getMimeType(){return"application/x-black-hole"}async addEncodedVideoPacket(){}async addEncodedAudioPacket(){}async addSubtitleCue(){}async finalize(){}};var Hc=class extends Pe{constructor(e,r){super(e);this.header=null;this.headerBitstream=null;this.inputIsAdts=null;this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0),Hr(this.output._metadataTags)||new Ci(this.writer).writeId3V2Tag(this.output._metadataTags)}finally{e()}}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.validateTimestamp(e,r.timestamp,r.type==="key"),this.inputIsAdts===null){Re(n,e.source._codec);let s=n?.decoderConfig?.description;if(s){let o=xt(G(s)),c=Us(o);this.header=c.header,this.headerBitstream=c.bitstream}this.inputIsAdts=!s}if(this.inputIsAdts){let s=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,s)}else{b(this.header);let s=r.data.byteLength+this.header.byteLength;zs(this.headerBitstream,s);let o=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(r.data),this.format._options.onFrame){let c=new Uint8Array(s);c.set(this.header,0),c.set(r.data,this.header.byteLength),this.format._options.onFrame(c,o)}}await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.inputIsAdts===null)throw new Error("Cannot finalize an empty ADTS file: not a single packet was added.");e()}};var kp=new Uint8Array([102,76,97,67]),Wg=38,qg=34,Wc=2**24-1,qc=class extends Pe{constructor(e,r){super(e);this.metadataWritten=!1;this.frameCount=0;this.minimumBlockSize=1/0;this.maximumBlockSize=0;this.lastBlockSize=null;this.minimumFrameSize=1/0;this.maximumFrameSize=0;this.totalSamples=0;this.sampleRate=null;this.channels=null;this.bitsPerSample=null;this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(kp);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Re({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.applyDecoderConfig(r.metadata.decoderConfig))}finally{e()}}applyDecoderConfig(e){b(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;let r=new K(G(e.description));r.skipBits(167),this.bitsPerSample=r.readBits(5)+1,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}writeHeader({bitsPerSample:e,minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:a,maximumFrameSize:s,sampleRate:o,channels:c,totalSamples:l}){b(this.writer.getPos()===4);let u=!Hr(this.output._metadataTags),d=new K(new Uint8Array(4));d.writeBits(1,+!u),d.writeBits(7,0),d.writeBits(24,qg),this.writer.write(d.bytes);let m=new K(new Uint8Array(18));m.writeBits(16,r),m.writeBits(16,n),m.writeBits(24,a),m.writeBits(24,s),m.writeBits(20,o),m.writeBits(3,c-1),m.writeBits(5,e-1),m.writeBits(36,l<2**36?l:0),this.writer.write(m.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=Y.encode(e.mimeType),n=Y.encode(e.description??""),a=32+r.length+n.length+e.data.length;if(a>Wc)throw new Error(`Picture is too big for FLAC: its metadata block would take ${a} bytes, but FLAC metadata blocks can take at most ${Wc} bytes.`);let s=new Uint8Array(a),o=0,c=N(s);c.setUint32(o,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),o+=4,c.setUint32(o,r.length),o+=4,s.set(r,o),o+=r.length,c.setUint32(o,n.length),o+=4,s.set(n,o),o+=n.length,o+=16,c.setUint32(o,e.data.length),o+=4,s.set(e.data,o),o+=e.data.length,b(o===a);let l=new K(new Uint8Array(4));l.writeBits(1,0),l.writeBits(7,6),l.writeBits(24,a),this.writer.write(l.bytes),this.writer.write(s)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(Wg+kp.byteLength),Hr(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let a of e)this.writePictureBlock(a);let r=ya(new Uint8Array(0),this.output._metadataTags,!1);if(r.length>Wc)throw new Error(`Metadata tags are too big for FLAC: their Vorbis comment block would take ${r.length} bytes, but FLAC metadata blocks can take at most ${Wc} bytes.`);let n=new K(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,4),n.writeBits(24,r.length),this.writer.write(n.bytes),this.writer.write(r),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),this.sampleRate===null&&(Re(n,e.source._codec),b(n),b(n.decoderConfig),this.applyDecoderConfig(n.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=xe.tempFromBytes(r.data);s.skip(2);let o=U(s,2),c=new K(o),l=Jo(c.readBits(4));if(l===null)throw new Error("Invalid FLAC frame: Invalid block size.");ec(s);let u=tc(s,l);this.format._options.appendOnly||(this.lastBlockSize!==null&&(this.minimumBlockSize=Math.min(this.minimumBlockSize,this.lastBlockSize)),this.frameCount++,this.maximumBlockSize=Math.max(this.maximumBlockSize,u),this.lastBlockSize=u,this.minimumFrameSize=Math.min(this.minimumFrameSize,r.data.length),this.maximumFrameSize=Math.max(this.maximumFrameSize,r.data.length),this.totalSamples+=u);let d=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,d),await this.writer.flush()}finally{a()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.sampleRate===null)throw new Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let r=this.minimumBlockSize,n=this.maximumBlockSize,a=this.minimumFrameSize,s=this.maximumFrameSize;this.frameCount===0?(r=16,n=65535,a=0,s=0):this.frameCount===1&&(n=Math.max(n,16),r=n),b(this.channels!==null),b(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:a,maximumFrameSize:s,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:this.totalSamples})}e()}};var un=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8===7&&this.writer.write(this.helper);t.length%8!==0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{let e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(let a of t.children)a&&this.writeBox(a);let r=this.writer.getPos(),n=t.size??r-e;this.writer.seek(e),this.writeBoxHeader(t,n),this.writer.seek(r)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){let e=this.offsets.get(t);b(e!==void 0);let r=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(r)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(let r of t.children)r&&(e+=this.measureBox(r));return e}}},Q=new Uint8Array(8),vt=new DataView(Q.buffer),Te=i=>[(i%256+256)%256],W=i=>(vt.setUint16(0,i,!1),[Q[0],Q[1]]),hs=i=>(vt.setInt16(0,i,!1),[Q[0],Q[1]]),Ap=i=>(vt.setUint32(0,i,!1),[Q[1],Q[2],Q[3]]),F=i=>(vt.setUint32(0,i,!1),[Q[0],Q[1],Q[2],Q[3]]),tr=i=>(vt.setInt32(0,i,!1),[Q[0],Q[1],Q[2],Q[3]]),rr=i=>(vt.setUint32(0,Math.floor(i/2**32),!1),vt.setUint32(4,i,!1),[Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7]]),Tp=i=>(vt.setInt32(0,Math.floor(i/2**32),!1),vt.setUint32(4,i,!1),[Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7]]),Kg=i=>(vt.setFloat64(0,i,!1),[Q[0],Q[1],Q[2],Q[3],Q[4],Q[5],Q[6],Q[7]]),xp=i=>(vt.setInt16(0,2**8*i,!1),[Q[0],Q[1]]),Lt=i=>(vt.setInt32(0,2**16*i,!1),[Q[0],Q[1],Q[2],Q[3]]),ad=i=>(vt.setInt32(0,2**30*i,!1),[Q[0],Q[1],Q[2],Q[3]]),sd=(i,t)=>{let e=[],r=i;do{let n=r&127;r>>=7,e.length>0&&(n|=128),e.push(n),t!==void 0&&t--}while(r>0||t);return e.reverse()},oe=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,n)=>i.charCodeAt(n));return t&&e.push(0),e},Cp=i=>[Lt(i[0]),Lt(i[1]),ad(i[2]),Lt(i[3]),Lt(i[4]),ad(i[5]),Lt(i[6]),Lt(i[7]),ad(i[8])],q=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),re=(i,t,e,r,n)=>q(i,[Te(t),Ap(e),r??[]],n),Pp=i=>i.isQuickTime?q("ftyp",[oe("qt "),F(512),oe("qt ")]):i.fragmented?i.cmaf?q("ftyp",[oe("iso5"),F(512),oe("iso5"),oe("iso6"),oe("mp41"),oe("cmfc"),oe("dash")]):q("ftyp",[oe("iso5"),F(512),oe("iso5"),oe("iso6"),oe("mp41")]):q("ftyp",[oe("isom"),F(512),oe("isom"),i.holdsAvc?oe("avc1"):[],oe("mp41")]),cd=()=>q("styp",[oe("iso5"),F(0),oe("iso5"),oe("iso6"),oe("mp41"),oe("cmfc"),oe("dash")]),ld=(i,t)=>{b(t<2**31);let e=Math.max(0,i.minWrittenTimestamp),r=Math.max(0,i.maxWrittenEndTimestamp-e);Number.isFinite(r)||(r=0);let n=de(r,mt);if(n>=2**32)throw new Error("CMAF segments must be shorter than 20.712612 hours.");return re("sidx",1,0,[F(1),F(mt),rr(de(e,mt)),rr(0),W(0),W(1),F(t),F(n),F(0)])},gs=i=>({type:"mdat",largeSize:i}),Ep=i=>({type:"free",size:i}),oa=i=>q("moov",void 0,[Gg(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>Qg(t,i.creationTime)),i.isFragmented?Mb(i.trackDatas):null,Hb(i)]),Gg=(i,t)=>{let e=Math.max(0,...t.map(s=>Math.max(0,de(dn(s),mt)+de(s.startTimestampOffset??0,mt)))),r=Math.max(0,...t.map(s=>s.track.id))+1,n=!or(i)||!or(e),a=n?rr:F;return re("mvhd",+n,0,[a(i),a(i),F(mt),a(e),Lt(1),xp(1),Array(10).fill(0),Cp(si),Array(24).fill(0),F(r)])},Qg=(i,t)=>{let e=zp(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset!==0;return q("trak",void 0,[jg(i,t),r?Xg(i):null,$g(i,t),e.name!==void 0?q("udta",void 0,[q("name",[...Y.encode(e.name)])]):null])},jg=(i,t)=>{let e=Math.max(0,de(dn(i),mt)+de(i.startTimestampOffset??0,mt)),r=!or(t)||!or(e),n=r?rr:F,a;if(i.type==="video"&&i.track.metadata.transformationMatrix)a=i.track.metadata.transformationMatrix;else if(i.type==="video"){let{rotation:c,flip:l}=i.track.metadata,u=sr(Tn(c??0),Is(l?-1:1,1));a=Es(u,i.info.width,i.info.height)}else a=si;let s=2;i.track.metadata.disposition?.default!==!1&&(s|=1);let o=i.type==="video"?0:i.type==="audio"?1:i.type==="subtitle"?2:Z(i);return re("tkhd",+r,s,[n(t),n(t),F(i.track.id),F(0),n(e),Array(8).fill(0),W(0),W(o),xp(i.type==="audio"?1:0),W(0),Cp(a),Lt(i.type==="video"?i.info.width:0),Lt(i.type==="video"?i.info.height:0)])},Xg=i=>{let t=i.startTimestampOffset;if(b(t!==null),t>0){let e=de(t,mt),r=de(dn(i),mt),n=!or(e)||!or(r),a=n?rr:F,s=n?Tp:tr;return q("edts",void 0,[re("elst",n?1:0,0,[F(2),a(e),s(-1),Lt(1),a(r),s(0),Lt(1)])])}else{let e=de(-t,i.timescale),r=Math.max(0,de(dn(i),mt)+de(t,mt)),n=!Al(e)||!or(r),a=n?rr:F,s=n?Tp:tr;return q("edts",void 0,[re("elst",n?1:0,0,[F(1),a(r),s(e),Lt(1)])])}},$g=(i,t)=>q("mdia",void 0,[Yg(i,t),ud(!0,Zg[i.type],Jg[i.type],void 0,i.muxer.isQuickTime),eb(i)]),Yg=(i,t)=>{let e=de(dn(i),i.timescale),r=!or(t)||!or(e),n=r?rr:F;return re("mdhd",+r,0,[n(t),n(t),F(i.timescale),n(e),W(Up(i.track.metadata.languageCode??ce)),W(0)])},Zg={video:"vide",audio:"soun",subtitle:"text"},Jg={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ud=(i,t,e,r="\0\0\0\0",n=!1)=>re("hdlr",0,0,[i?oe("mhlr"):F(0),oe(t),oe(r),F(0),F(0),n?[Te(e.length),oe(e)]:oe(e,!0)]),eb=i=>q("minf",void 0,[nb[i.type](),ab(),cb(i)]),tb=()=>re("vmhd",0,1,[W(0),W(0),W(0),W(0)]),rb=()=>re("smhd",0,0,[W(0),W(0)]),ib=()=>re("nmhd",0,0),nb={video:tb,audio:rb,subtitle:ib},ab=()=>q("dinf",void 0,[sb()]),sb=()=>re("dref",0,0,[F(1)],[ob()]),ob=()=>re("url ",0,1),cb=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return q("stbl",void 0,[lb(i),Pb(i),t?Rb(i):null,t?Fb(i):null,Ib(i),vb(i),_b(i),Eb(i),..._p(i.samples,!1)])},lb=i=>{let t;if(i.type==="video")t=ub(Qb(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){let e=Vp(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime);b(e),t=gb(e,i)}else i.type==="subtitle"&&(t=xb($b[i.track.source._codec],i));return b(t),re("stsd",0,0,[F(1)],[t])},ub=(i,t)=>q(i,[Array(6).fill(0),W(1),W(0),W(0),Array(12).fill(0),W(t.info.width),W(t.info.height),F(4718592),F(4718592),F(0),W(1),Te(Kr.length),oe(Kr),Array(31-Kr.length).fill(0),W(t.info.hasAlphaChannel?32:24),hs(65535)],[jb[t.track.source._codec]?.(t)??null,db(t),_s(t.info.decoderConfig.colorSpace)?null:mb(t),dd(t)]),dd=i=>i.avgBitrate===0&&i.maxBitrate===0?null:q("btrt",[F(0),F(i.maxBitrate),F(i.avgBitrate)]),db=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:q("pasp",[F(i.info.pixelAspectRatio.num),F(i.info.pixelAspectRatio.den)]),mb=i=>{let t=i.info.decoderConfig.colorSpace;return q("colr",[oe(i.muxer.isQuickTime?"nclc":"nclx"),W(t?.primaries!=null?_t[t.primaries]:2),W(t?.transfer!=null?Rt[t.transfer]:2),W(t?.matrix!=null?Ft[t.matrix]:2),i.muxer.isQuickTime?[]:Te((t?.fullRange?1:0)<<7)])},fb=i=>i.info.decoderConfig&&q("avcC",[...G(i.info.decoderConfig.description)]),pb=i=>i.info.decoderConfig&&q("hvcC",[...G(i.info.decoderConfig.description)]),wp=i=>{if(!i.info.decoderConfig)return null;let t=i.info.decoderConfig,e=t.codec.split("."),r=Number(e[1]),n=Number(e[2]),a=e[3]?Number(e[3]):8,s=e[4]?Number(e[4]):1,o=e[8]?Number(e[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(s<<1)+o,l=e[5]?Number(e[5]):t.colorSpace?.primaries?_t[t.colorSpace.primaries]:1,u=e[6]?Number(e[6]):t.colorSpace?.transfer?Rt[t.colorSpace.transfer]:1,d=e[7]?Number(e[7]):t.colorSpace?.matrix?Ft[t.colorSpace.matrix]:1;return re("vpcC",1,0,[Te(r),Te(n),Te(c),Te(l),Te(u),Te(d),W(0)])},hb=i=>q("av1C",zc(i.info.decoderConfig.codec)),gb=(i,t)=>{let e=0,r,n=16,a=t.info.sampleRate,s=Xb(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,o=se.includes(t.track.source._codec);if(o){let c=t.track.source._codec,{sampleSize:l}=Me(c);n=8*l}else if(t.track.source._codec==="flac"){let c=t.info.decoderConfig?.description;b(c);let l=new K(G(c));for(l.skipBits(167),n=l.readBits(5)+1;a>=2**16;)a=Math.floor(a/2)}if(t.muxer.isQuickTime&&t.track.source._codec!=="truehd"&&(e=t.info.sampleRate<2**16&&t.info.numberOfChannels<=2?1:2),e===0)r=[Array(6).fill(0),W(1),W(e),W(0),F(0),W(t.info.numberOfChannels),W(n),W(0),W(0),t.track.source._codec==="truehd"?F(t.info.sampleRate):[W(a<2**16?a:0),W(0)]];else if(e===1){let c=o?0:-2;r=[Array(6).fill(0),W(1),W(e),W(0),F(0),W(t.info.numberOfChannels),W(Math.min(n,16)),hs(c),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0),o?[F(1),F(n/8),F(t.info.numberOfChannels*n/8)]:[F(0),F(0),F(0)],F(2)]}else if(e===2){let c=0;if(o){let{dataType:l,littleEndian:u}=Me(t.track.source._codec);l!=="ulaw"&&l!=="alaw"&&(i="lpcm",s=null,c=(l==="float"?1:0)|(u?0:2)|(l==="signed"?4:0)|8)}r=[Array(6).fill(0),W(1),W(e),W(0),F(0),W(3),W(16),hs(-2),W(0),F(65536),F(72),Kg(t.info.sampleRate),F(t.info.numberOfChannels),F(2130706432),o?[F(n),F(c),F(t.info.numberOfChannels*n/8),F(1)]:[F(0),F(0),F(0),F(0)]]}else Z(e),b(!1);return q(i,r,[(i==="ipcm"||i==="fpcm")&&t.info.sampleRate>=2**16?bb(t):null,s,dd(t)])},bb=i=>re("srat",0,0,[F(i.info.sampleRate)]),od=i=>{let t;switch(i.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let e=[...Te(t),...Te(21),...Ap(0),...F(i.maxBitrate),...F(i.avgBitrate)];if(i.info.decoderConfig.description){let r=G(i.info.decoderConfig.description);e=[...e,...Te(5),...sd(r.byteLength),...r]}return e=[...W(1),...Te(0),...Te(4),...sd(e.length),...e,...Te(6),...Te(1),...Te(2)],e=[...Te(3),...sd(e.length),...e],re("esds",0,0,e)},Rr=i=>q("wave",void 0,[yb(i),i.track.source._codec==="ac3"?Ip(i):i.track.source._codec==="eac3"?vp(i):kb(i),q("\0\0\0\0")]),yb=i=>q("frma",[oe(Vp(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime))]),kb=i=>{let{littleEndian:t}=Me(i.track.source._codec);return q("enda",[W(+t)])},Tb=i=>{let t=i.info.numberOfChannels,e=312,r=i.info.sampleRate,n=0,a=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){b(o.byteLength>=18);let c=G(o),l=yr(c);t=l.outputChannelCount,e=l.preSkip,r=l.inputSampleRate,n=l.outputGain,a=l.channelMappingFamily,l.channelMappingTable&&(s=l.channelMappingTable)}return q("dOps",[Te(0),Te(t),W(e),F(r),hs(n),Te(a),...s])},wb=i=>{let t=i.info.decoderConfig?.description;b(t);let e=G(t);return re("dfLa",0,0,[...e.subarray(4)])},Fr=i=>{let{littleEndian:t,sampleSize:e}=Me(i.track.source._codec),r=+t;return re("pcmC",0,0,[Te(r),Te(8*e)])},Ip=i=>{b(i.info.primingPacket);let t=$s(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let e=new Uint8Array(3),r=new K(e);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),q("dac3",[...e])},vp=i=>{b(i.info.primingPacket);let t=Zs(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let e=16;for(let s of t.substreams)e+=23,s.numDepSub>0?e+=9:e+=1;let r=Math.ceil(e/8),n=new Uint8Array(r),a=new K(n);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let s of t.substreams)a.writeBits(2,s.fscod),a.writeBits(5,s.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,s.bsmod),a.writeBits(3,s.acmod),a.writeBits(1,s.lfeon),a.writeBits(3,0),a.writeBits(4,s.numDepSub),s.numDepSub>0?a.writeBits(9,s.chanLoc):a.writeBits(1,0);return q("dec3",[...n])},Sb=i=>{b(i.info.primingPacket);let t=Aa(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return q("ddts",[...km(t)])},Ab=i=>{b(i.info.primingPacket);let t=i.info.primingPacket.data;if(_n("truehd",t)!=="key")throw new Error("Couldn't extract TrueHD stream info from the audio packet. Ensure the first packet is an access unit carrying a major sync.");let e=N(t),r=e.getUint32(8),n=e.getUint16(18)&32767;return q("dmlp",[F(r),W(n<<1),F(0)])},xb=(i,t)=>q(i,[Array(6).fill(0),W(1)],[Yb[t.track.source._codec](t),dd(t)]),Cb=i=>q("vttC",[...Y.encode(i.info.config.description)]);var Pb=i=>re("stts",0,0,[F(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[F(t.sampleCount),F(t.sampleDelta)])]),Eb=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return re("stss",0,0,[F(t.length),t.map(([e])=>F(e+1))])},Ib=i=>re("stsc",0,0,[F(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[F(t.firstChunk),F(t.samplesPerChunk),F(1)])]),vb=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:t}=Me(i.track.source._codec);return re("stsz",0,0,[F(t*i.info.numberOfChannels),F(i.samples.reduce((e,r)=>e+de(r.duration,i.timescale),0))])}return re("stsz",0,0,[F(0),F(i.samples.length),i.samples.map(t=>F(t.size))])},_b=i=>i.finalizedChunks.length>0&&J(i.finalizedChunks).offset>=2**32?re("co64",0,0,[F(i.finalizedChunks.length),i.finalizedChunks.map(t=>rr(t.offset))]):re("stco",0,0,[F(i.finalizedChunks.length),i.finalizedChunks.map(t=>F(t.offset))]),Rb=i=>re("ctts",1,0,[F(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[F(t.sampleCount),tr(t.sampleCompositionTimeOffset)])]),Fb=i=>{if(b(i.compositionTimeOffsetTable.length>0),i.samples.length===0)return null;let t=1/0,e=-1/0,r=1/0,n=-1/0;for(let s=0;s<i.compositionTimeOffsetTable.length;s++){let o=i.compositionTimeOffsetTable[s];t=Math.min(t,o.sampleCompositionTimeOffset),e=Math.max(e,o.sampleCompositionTimeOffset)}for(let s=0;s<i.samples.length;s++){let o=i.samples[s];r=Math.min(r,de(o.timestamp,i.timescale)),n=Math.max(n,de(o.timestamp+o.duration,i.timescale))}let a=Math.max(-t,0);return n>=2**31?null:re("cslg",0,0,[tr(a),tr(t),tr(e),tr(r),tr(n)])},_p=(i,t)=>{let e=[];for(let a of i)if(e.length===0)e.push({sampleCount:1,prerollSamples:a.prerollSamples});else{let s=e[e.length-1];s.prerollSamples===a.prerollSamples?s.sampleCount++:e.push({sampleCount:1,prerollSamples:a.prerollSamples})}let r=e.filter(a=>a.prerollSamples!==0);if(r.length===0)return[];let n=t?65537:1;return[re("sgpd",1,0,[oe("roll"),F(2),F(r.length),...r.map(a=>hs(a.prerollSamples))]),re("sbgp",0,0,[oe("roll"),F(e.length),...e.map(a=>[F(a.sampleCount),F(a.prerollSamples!==0?n++:0)])])]},Mb=i=>q("mvex",void 0,i.map(Bb)),Bb=i=>re("trex",0,0,[F(i.track.id),F(1),F(0),F(0),F(0)]),md=(i,t)=>q("moof",void 0,[Ob(i),...t.map(Db)]),Ob=i=>re("mfhd",0,0,[F(i)]),Rp=i=>{let t=0,e=0,r=0,n=0,a=i.type==="delta";return e|=+a,a?t|=1:t|=2,t<<24|e<<16|r<<8|n},Db=i=>q("traf",void 0,[Vb(i),Ub(i),zb(i),..._p(i.currentChunk.samples,!0)]),Vb=i=>{b(i.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let e=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:Rp(e)};return re("tfhd",0,t,[F(i.track.id),F(r.duration),F(r.size),F(r.flags)])},Ub=i=>(b(i.currentChunk),re("tfdt",1,0,[rr(de(i.currentChunk.startTimestamp,i.timescale))])),zb=i=>{b(i.currentChunk);let t=i.currentChunk.offset-i.currentChunk.moofOffset||0;b(Al(t));let e=i.currentChunk.samples.map(h=>h.timescaleUnitsToNextSample),r=i.currentChunk.samples.map(h=>h.size),n=i.currentChunk.samples.map(Rp),a=i.currentChunk.samples.map(h=>de(h.timestamp-h.decodeTimestamp,i.timescale)),s=new Set(e),o=new Set(r),c=new Set(n),l=new Set(a),u=c.size===2&&n.lastIndexOf(n[0])===0,d=s.size>1,m=o.size>1,f=!u&&c.size>1,p=l.size>1||[...l].some(h=>h!==0),g=0;return g|=1,g|=4*+u,g|=256*+d,g|=512*+m,g|=1024*+f,g|=2048*+p,re("trun",1,g,[F(i.currentChunk.samples.length),tr(t),u?F(n[0]):[],i.currentChunk.samples.map((h,y)=>[d?F(e[y]):[],m?F(r[y]):[],f?F(n[y]):[],p?tr(a[y]):[]])])},Fp=i=>q("mfra",void 0,[...i.map(Nb),Lb()]),Nb=i=>re("tfra",1,0,[F(i.track.id),F(63),F(i.tfraEntries.length),i.tfraEntries.map(e=>[rr(de(e.timestamp,i.timescale)),rr(e.moofOffset),F(e.trafIndex+1),F(1),F(e.sampleIndex+1)])]),Lb=()=>re("mfro",0,0,[F(0)]),Mp=()=>q("vtte"),Bp=(i,t,e,r,n)=>q("vttc",void 0,[n!==null?q("vsid",[tr(n)]):null,e!==null?q("iden",[...Y.encode(e)]):null,t!==null?q("ctim",[...Y.encode(oo(t))]):null,r!==null?q("sttg",[...Y.encode(r)]):null,q("payl",[...Y.encode(i)])]),Op=i=>q("vtta",[...Y.encode(i)]),Hb=i=>{let t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){let n=Kb(r);n&&t.push(n)}else if(e==="mdta"){let n=Gb(r);n&&t.push(n)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&Wb(t,i.output._metadataTags);return t.length===0?null:q("udta",void 0,t)},Wb=(i,t)=>{for(let{key:e,value:r}of qt(t))switch(e){case"title":i.push(Mr("\xA9nam",r));break;case"description":i.push(Mr("\xA9des",r));break;case"artist":i.push(Mr("\xA9ART",r));break;case"album":i.push(Mr("\xA9alb",r));break;case"albumArtist":i.push(Mr("albr",r));break;case"genre":i.push(Mr("\xA9gen",r));break;case"date":i.push(Mr("\xA9day",r.toISOString().slice(0,10)));break;case"comment":i.push(Mr("\xA9cmt",r));break;case"lyrics":i.push(Mr("\xA9lyr",r));break;case"raw":break;case"creationTime":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:Z(e)}if(t.raw)for(let e in t.raw){let r=t.raw[e];r==null||e.length!==4||i.some(n=>n.type===e)||(typeof r=="string"?i.push(Mr(e,r)):r instanceof Uint8Array&&i.push(q(e,Array.from(r))))}},Mr=(i,t)=>{let e=Y.encode(t);return q(i,[W(e.length),W(Up("und")),Array.from(e)])},Sp={"image/jpeg":13,"image/png":14,"image/bmp":27},qb=new Set(["HMMT","loci","chpl"]),Dp=(i,t)=>{let e=[];for(let{key:r,value:n}of qt(i))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:er(n)});break;case"description":e.push({key:t?"description":"\xA9des",value:er(n)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:er(n)});break;case"album":e.push({key:t?"album":"\xA9alb",value:er(n)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:er(n)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:er(n)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:er(n)});break;case"beatsPerMinute":t||e.push({key:"tmpo",value:q("data",[F(21),F(0),W(n)])});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:er(n)});break;case"date":e.push({key:t?"date":"\xA9day",value:er(n.toISOString().slice(0,10))});break;case"images":for(let a of n)a.kind==="coverFront"&&e.push({key:"covr",value:q("data",[F(Sp[a.mimeType]??0),F(0),Array.from(a.data)])});break;case"trackNumber":if(t){let a=i.tracksTotal!==void 0?`${n}/${i.tracksTotal}`:n.toString();e.push({key:"track",value:er(a)})}else e.push({key:"trkn",value:q("data",[F(0),F(0),W(0),W(n),W(i.tracksTotal??0),W(0)])});break;case"discNumber":t||e.push({key:"disk",value:q("data",[F(0),F(0),W(0),W(n),W(i.discsTotal??0),W(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:Z(r)}if(i.raw)for(let r in i.raw){let n=i.raw[r];n==null||!t&&(r.length!==4||qb.has(r))||e.some(a=>a.key===r)||(typeof n=="string"?e.push({key:r,value:er(n)}):n instanceof Uint8Array?e.push({key:r,value:q("data",[F(0),F(0),Array.from(n)])}):n instanceof At&&e.push({key:r,value:q("data",[F(Sp[n.mimeType]??0),F(0),Array.from(n.data)])}))}return e},Kb=i=>{let t=Dp(i,!1);return t.length===0?null:re("meta",0,0,void 0,[ud(!1,"mdir","","appl"),q("ilst",void 0,t.map(e=>q(e.key,void 0,[e.value])))])},Gb=i=>{let t=Dp(i,!0);return t.length===0?null:q("meta",void 0,[ud(!1,"mdta",""),re("keys",0,0,[F(t.length)],t.map(e=>q("mdta",[...Y.encode(e.key)]))),q("ilst",void 0,t.map((e,r)=>{let n=String.fromCharCode(...F(r+1));return q(n,void 0,[e.value])}))])},er=i=>q("data",[F(1),F(0),...Y.encode(i)]),Qb=(i,t)=>{switch(i){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return t}},jb={avc:fb,hevc:pb,vp8:wp,vp9:wp,av1:hb,prores:null},Vp=(i,t,e)=>{switch(i){case"aac":return"mp4a";case"mp3":return e?".mp3":"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return t;case"truehd":return"mlpa"}if(e)switch(i){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(i){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Xb=(i,t)=>{switch(i){case"aac":return od;case"mp3":return t?null:od;case"opus":return Tb;case"vorbis":return od;case"flac":return wb;case"ac3":return t?Rr:Ip;case"eac3":return t?Rr:vp;case"dts":return Sb;case"truehd":return Ab}if(t)switch(i){case"pcm-s24":return Rr;case"pcm-s24be":return Rr;case"pcm-s32":return Rr;case"pcm-s32be":return Rr;case"pcm-f32":return Rr;case"pcm-f32be":return Rr;case"pcm-f64":return Rr;case"pcm-f64be":return Rr}else switch(i){case"pcm-s16":return Fr;case"pcm-s16be":return Fr;case"pcm-s24":return Fr;case"pcm-s24be":return Fr;case"pcm-s32":return Fr;case"pcm-s32be":return Fr;case"pcm-f32":return Fr;case"pcm-f32be":return Fr;case"pcm-f64":return Fr;case"pcm-f64be":return Fr}return null},$b={webvtt:"wvtt"},Yb={webvtt:Cb},Up=i=>{b(i.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=i.charCodeAt(e)-96;return t};var Br=class{constructor(t,e){this.finalized=!1;this.started=!1;this.pos=0;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1;if(t._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");if(t._closed)throw new Error("Can't create a Writer for a Target that has already been closed.");this.target=t,t._setMonotonicity(e),t._writerAcquired=!0}start(){b(!this.started),this.target._start(),this.started=!0}write(t){b(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target._write(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return b(this.started&&!this.finalized),this.target._flush()}async finalize(){b(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=this.trackedStart}let r=e+t.byteLength-this.trackedStart,n=this.trackedWrites.byteLength;for(;n<r;)n*=2;if(n!==this.trackedWrites.byteLength){let a=new Uint8Array(n);a.set(this.trackedWrites,0),this.trackedWrites=a}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};var Np=Sd(Mu(),1);var Lp=typeof Np<"u"?Np:void 0,Oe=class extends st{constructor(){super(...arguments);this._writerAcquired=!1;this._closed=!1;this._monotonicity=null;this.onwrite=null}_close(){return this._closed=!0,this._release()}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,r){this.onwrite?.(e,r),this._emit("write",{start:e,end:r})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new bs(this,e)}},fd=2**16,pd=2**32,Bi=class extends Oe{constructor(e={}){super();this.buffer=null;this._maxPos=0;if(!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(fd,{maxByteLength:pd})}catch{this._buffer=new ArrayBuffer(fd),this._supportsResize=!1}else this._buffer=new ArrayBuffer(fd);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){b(this._buffer),b(this._bytes);let r=this._buffer.byteLength;for(;r<e;)r*=2;if(r!==this._buffer.byteLength){if(r>pd)throw new Error(`ArrayBuffer exceeded maximum size of ${pd} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{let n=new ArrayBuffer(r),a=new Uint8Array(n);a.set(this._bytes,0),this._buffer=n,this._bytes=a}}}_start(){}_write(e,r){b(this._bytes),this._ensureSize(r+e.byteLength),this._bytes.set(e,r),this._maxPos=Math.max(this._maxPos,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){}async _finalize(){b(this._buffer),"transferToFixedLength"in this._buffer?this.buffer=this._buffer.transferToFixedLength(this._maxPos):this.buffer=this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _release(){}_getSlice(e,r){return b(this._bytes),this._bytes.slice(e,r)}},Zb=2**24,Jb=2,ca=class extends Oe{constructor(e,r={}){super();this._sections=[];this._lastWriteEnd=0;this._lastFlushEnd=0;this._streamWriter=null;this._writeError=null;this._chunks=[];if(!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r,this._chunked=r.chunked??!1,this._chunkSize=r.chunkSize??Zb}_start(){this._streamWriter=this._writable.getWriter()}_write(e,r){if(r>this._lastWriteEnd){let n=r-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:r}),this._lastWriteEnd=Math.max(this._lastWriteEnd,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(b(this._streamWriter),this._sections.length===0)return;let e=[],r=[...this._sections].sort((n,a)=>n.start-a.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let n=1;n<r.length;n++){let a=e[e.length-1],s=r[n];s.start<=a.start+a.size?a.size=Math.max(a.size,s.start+s.data.byteLength-a.start):e.push({start:s.start,size:s.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let a of this._sections)n.start<=a.start&&a.start<n.start+n.size&&n.data.set(a.data,a.start-n.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(n.data,n.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&n.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data,position:n.start}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,r){for(;;){let n=this._chunks.findIndex(l=>l.start<=r&&r<l.start+this._chunkSize);n===-1&&(n=this._createChunk(r));let a=this._chunks[n],s=r-a.start,o=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));a.data.set(o,s);let c={start:s,end:s+o.byteLength};if(this._insertSectionIntoChunk(a,c),a.written[0].start===0&&a.written[0].end===this._chunkSize&&(a.shouldFlush=!0),this._chunks.length>Jb){for(let l=0;l<this._chunks.length-1;l++)this._chunks[l].shouldFlush=!0;this._tryToFlushChunks()}if(o.byteLength===e.byteLength)break;e=e.subarray(o.byteLength),r+=o.byteLength}}_insertSectionIntoChunk(e,r){let n=0,a=e.written.length-1,s=-1;for(;n<=a;){let o=Math.floor(n+(a-n+1)/2);e.written[o].start<=r.start?(n=o+1,s=o):a=o-1}for(e.written.splice(s+1,0,r),(s===-1||e.written[s].end<r.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((a,s)=>a.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){b(this._streamWriter);for(let r=0;r<this._chunks.length;r++){let n=this._chunks[r];if(!(!n.shouldFlush&&!e)){for(let a of n.written){let s=n.start+a.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");let o=a.start!==0||a.end!==n.data.byteLength,c;o&&et()?c=n.data.slice(a.start,a.end):c=n.data.subarray(a.start,a.end),this._streamWriter.write({type:"write",data:c,position:s}).catch(l=>{this._writeError??=l}),this._lastFlushEnd=n.start+a.end}this._chunks.splice(r--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;b(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _release(){let e=this._streamWriter??this._writable.getWriter();e.desiredSize!==null&&await e.close()}},Kc=class extends Oe{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new ca(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:r=>{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return b(r.position===this._nextWritePos),this._nextWritePos+=r.data.byteLength,b(this._writer),this._writer.write(r.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}_flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}_release(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Gc=class extends Oe{constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Lp.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super();this._fileHandle=null;let n=new WritableStream({start:async()=>{this._fileHandle=await Lp.fs.open(e,"w")},write:async a=>{b(this._fileHandle),await this._fileHandle.write(a.data,0,a.data.byteLength,a.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new ca(n,{chunked:!0,...r})}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _release(){try{await this._streamTarget._close()}finally{await this._fileHandle?.close(),this._fileHandle=null}}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Oi=class extends Oe{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _release(){}},bs=class extends Oe{constructor(t,e){super(),this._baseTarget=t,this._offset=e}_start(){}_write(t,e){this._baseTarget._write(t,this._offset+e),this._dispatchWrite(e,e+t.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _release(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}},ft=class{constructor(t,e){this.rootPath=t;this.getTarget=e;if(typeof t!="string")throw new TypeError("rootPath must be a string.");if(typeof e!="function")throw new TypeError("getTarget must be a function.")}};var mt=57600,Hp=.5,zp=i=>{let t={},e=i.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},de=(i,t,e=!0)=>{let r=i*t;return e?Math.round(r):r},dn=i=>{if(i.samples.length===0)return 0;let t=1/0,e=-1/0;for(let r=0;r<i.samples.length;r++){let n=i.samples[r];n.timestamp<t&&(t=n.timestamp),n.timestamp+n.duration>e&&(e=n.timestamp+n.duration)}return t===1/0?0:e-t},Qc=class extends Pe{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new Bi;this.auxWriter=new Br(this.auxTarget,!1);this.auxBoxWriter=new un(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.closedTracks=new Set;this.allTracksKnown=te();this.finalizedChunks=[];this.wroteFragmentedHeader=!1;this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.minWrittenTimestamp=1/0;this.maxWrittenEndTimestamp=-1/0;this.segmentHeaderSize=null;this.format=r,this.formatOptions={...r._options},this.isQuickTime=r instanceof fn,this.isCmaf=r instanceof mn,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof mn?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();try{let r=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;if(this.creationTime=r?Math.floor(r.getTime()/1e3)+Ao:0,r&&this.creationTime<=0)throw new Error("creationTime must be after 1904-01-01T00:00:00Z for MP4/QuickTime files.");if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(a=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="in-memory"||this.formatOptions.fastStart==="fragmented":a instanceof Bi),this.boxWriter=new un(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Bi?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let a=await this.output._getInitTarget(),s=new Br(a,!0);s.start(),this.initWriter=s,this.initBoxWriter=new un(s)}let n=this.output.tracks.some(a=>a.isVideoTrack()&&a.source._codec==="avc");{let a=this.initBoxWriter??this.boxWriter;if(b(a),this.formatOptions.onFtyp&&a.writer.startTrackingWrites(),a.writeBox(Pp({isQuickTime:this.isQuickTime,holdsAvc:n,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:s,start:o}=a.writer.stopTrackingWrites();this.formatOptions.onFtyp(s,o)}this.ftypSize=a.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve")for(let a of this.output.tracks){if(a.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.");if(a.metadata.maximumPacketCount>2**32-1)throw new Error(`Track #${a.id} has a maximumPacketCount of ${a.metadata.maximumPacketCount}, which exceeds the maximum of ${2**32-1} packets per track that a non-fragmented file can hold.`)}else this.isFragmented||(b(this.writer),b(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=gs(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let a of this.output.tracks)a.isVideoTrack()&&a.metadata.decoderConfig?this.getVideoTrackData(a,a.metadata.primingPacket??null,{decoderConfig:a.metadata.decoderConfig}):a.isAudioTrack()&&a.metadata.decoderConfig&&this.getAudioTrackData(a,a.metadata.primingPacket??null,{decoderConfig:a.metadata.decoderConfig})}finally{e()}}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return xo({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(p=>p.track===e);if(a)return a;_r(n,e.source._codec),b(n),b(n.decoderConfig);let s={...n.decoderConfig};b(s.codedWidth!==void 0),b(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){if(!r)throw new Error("No AVC description provided; you must therefore provide a priming packet.");let p=hr(r.data);if(!p)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=En(p),o=!0}else if(e.source._codec==="hevc"&&!s.description){if(!r)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");let p=br(r.data);if(!p)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=cm(p),o=!0}let c=Od(1/(e.metadata.frameRate??mt),1e6).den,l=s.displayAspectWidth,u=s.displayAspectHeight,d=l===void 0||u===void 0?{num:1,den:1}:zr({num:l*s.codedHeight,den:u*s.codedWidth}),m=s.codec==="ap4h"||s.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o,hasAlphaChannel:m},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,tfraEntries:[],compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((p,g)=>p.track.id-g.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,r,n){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;Re(n,e.source._codec),b(n),b(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let l=It(xe.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u,d=null;if(l.channelConfiguration===0){let m=l.crcCheck===null?rt:Ye,f=mr(r.data.subarray(m));if(!f)throw new Error("ADTS frames with channel configuration 0 must begin with a program config element.");d=f.programConfigElement,u=Wr(d)}else u=dr[l.channelConfiguration];s.description=ui({objectType:l.objectType,outputSampleRate:Xe[l.samplingFrequencyIndex],outputNumberOfChannels:u,programConfigElement:d}),o=!0}if(!r){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.");if(e.source._codec==="truehd")throw new Error("TrueHD requires a priming packet.")}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&se.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r,pendingEac3Packets:[],preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,tfraEntries:[],compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Nc(r),b(r),b(r.config);let a={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,tfraEntries:[],compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),o=r.data;if(s.info.requiresAnnexBTransformation){let l=[...pi(o)].map(u=>o.subarray(u.offset,u.offset+u.length));if(l.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=Ks(l,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type,0);await this.registerSample(s,c)}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let f=It(xe.tempFromBytes(o));if(!f)throw new Error("Expected ADTS frame, didn't get one.");let p=f.crcCheck===null?rt:Ye;if(o=o.subarray(p),f.channelConfiguration===0){let g=mr(o);g&&(o=o.subarray(g.size))}}if(this.validateTimestamp(s.track,r.timestamp,r.type==="key"),e.source._codec==="eac3"){let f=Js(o),p=f?f.reduce((y,k)=>y+k.blockCount,0):6,g=s.info.pendingEac3Packets,h=g.reduce((y,k)=>y+k.blockCount,0)+p;if(h>6)throw new Error("E-AC-3 frames must add up to exactly six blocks to be muxed into MP4 samples.");g.push({packet:r,blockCount:p}),h===6&&await this.writePendingEac3Packets(s);return}let c=r.timestamp,l=r.duration;if(s.info.requiresPcmTransformation){let p=Me(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(l=o.byteLength/p/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let g=c-s.info.expectedNextPcmPacketTimestamp;if(g<.01)c=s.info.expectedNextPcmPacketTimestamp;else{let h=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,g);c=s.info.expectedNextPcmPacketTimestamp+h}}s.info.expectedNextPcmPacketTimestamp=c+l}let{preroll:u}=s.info,d=0;if(e.source._codec==="aac"||e.source._codec==="vorbis")d=-Math.min(1,u.packetCount);else if(e.source._codec==="mp3")d=-Math.min(2,u.packetCount);else if(e.source._codec==="opus"){let f=Math.round(nd*tt);d=-u.audioSampleDurationHistory.length;let p=js(o);for(u.accumulatedAudioSamples+=p.durationInSamples,u.audioSampleDurationHistory.push(p.durationInSamples);u.accumulatedAudioSamples-u.audioSampleDurationHistory[0]>=f;)u.accumulatedAudioSamples-=u.audioSampleDurationHistory.shift(),b(u.audioSampleDurationHistory.length>0)}u.packetCount++;let m=this.createSampleForTrack(s,o,c,l,r.type,d);await this.registerSample(s,m)}finally{a()}}async padWithSilence(e,r,n){let a=de(n,e.timescale),{sampleSize:s,silentValue:o}=Me(e.info.decoderConfig.codec),c=s*e.info.numberOfChannels,l=new Uint8Array(c*Math.min(a,e.timescale)).fill(o);for(let u=0;u<a;u+=e.timescale){let d=Math.min(a-u,e.timescale),m=this.createSampleForTrack(e,l.subarray(0,c*d),r+u/e.timescale,d/e.timescale,"key",0);await this.registerSample(e,m)}return a/e.timescale}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);if(this.validateTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"){let o=de(r.timestamp,s.timescale)/s.timescale,c=de(r.timestamp+r.duration,s.timescale)/s.timescale;c>o&&s.cueQueue.push({cue:r,start:o,end:c}),await this.processWebVTTCues(s,o)}}finally{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].start);let n=new Set([]);for(let{start:u,end:d}of e.cueQueue)b(u<=r),b(e.lastCueEndTimestamp<=d),n.add(Math.max(u,e.lastCueEndTimestamp)),n.add(d);let a=[...n].sort((u,d)=>u-d),s=a[0],o=a[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let u=Mp();this.auxBoxWriter.writeBox(u);let d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),m=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key",0);await this.registerSample(e,m),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let u=0;u<e.cueQueue.length;u++){let{cue:d,start:m,end:f}=e.cueQueue[u];if(m>=o)break;Rn.lastIndex=0;let p=Rn.test(d.text),g=e.cueToSourceId.get(d);if(g===void 0&&o<f&&(g=e.nextSourceId++,e.cueToSourceId.set(d,g)),d.notes){let y=Op(d.notes);this.auxBoxWriter.writeBox(y)}let h=Bp(d.text,p?s:null,d.identifier??null,d.settings??null,g??null);this.auxBoxWriter.writeBox(h),f===o&&e.cueQueue.splice(u--,1)}let c=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,c,s,o-s,"key",0);await this.registerSample(e,l),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,n,a,s,o){return{timestamp:n,decodeTimestamp:n,duration:a,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:de(a,e.timescale),prerollSamples:o}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){b(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let a=0;for(let s=0;s<e.timestampProcessingQueue.length;s++){let o=e.timestampProcessingQueue[s],c=de(o.duration,e.timescale);a+=c}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:a,sampleDelta:1});else{let s=J(e.timeToSampleTable);s.sampleCount+=a}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(a=>a.timestamp).sort((a,s)=>a-s);this.isFragmented?e.startTimestampOffset??=Math.min(n[0],0):e.startTimestampOffset??=n[0];for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a];s.decodeTimestamp=n[a];let o=de(s.timestamp-s.decodeTimestamp,e.timescale),c=de(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){b(e.lastSample);let l=de(s.decodeTimestamp,e.timescale,!1),u=Math.round(l-e.lastTimescaleUnits);if(b(u>=0),e.lastTimescaleUnits+=u,e.lastSample.timescaleUnitsToNextSample=u,!this.isFragmented){let d=J(e.timeToSampleTable);if(b(d),d.sampleCount===1){d.sampleDelta=u;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===u&&(f.sampleCount++,e.timeToSampleTable.pop(),d=f)}else d.sampleDelta!==u&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:u}));d.sampleDelta===c?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let m=J(e.compositionTimeOffsetTable);b(m),m.sampleCompositionTimeOffset===o?m.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=de(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:c}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,b(e.lastSample),b(e.lastTimescaleUnits!==null),r!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){b(r.type==="key");let a=de(r.timestamp,e.timescale,!1),s=Math.round(a-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=s}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),e.sampleQueue.push(r),await this.interleaveSamples()}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let a=e.track.metadata.maximumPacketCount;if(b(a!==void 0),e.samples.length>a)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${a}). Either add fewer packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let a=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(c=>{if(e===c)return r.type==="key";let l=c.sampleQueue[0];return l?l.type==="key":this.closedTracks.has(c.track)}),o=this.wroteFragmentedHeader||this.trackDatas.every(c=>c.startTimestampOffset!==null||this.closedTracks.has(c.track));a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&o&&(n=!0,await this.finalizeFragment())}else n=a>=Hp}if(n){if(!this.isFragmented){let a=this.trackDatas.filter(s=>s.currentChunk&&r.timestamp-s.currentChunk.startTimestamp>=Hp).sort((s,o)=>s.currentChunk.startTimestamp-o.currentChunk.startTimestamp);for(let s of a)await this.finalizeCurrentChunk(s)}e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}}b(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,r.timestamp+r.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){b(!this.isFragmented),b(this.writer);let r=e.currentChunk;b(r),e.currentChunk=null,e.finalizedChunks.push(r);let n=r.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(n=r.samples.reduce((a,s)=>a+de(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||J(e.compactlyCodedChunkTable).samplesPerChunk!==n)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:n}),this.fastStart==="in-memory"){r.offset=0,this.finalizedChunks.push(r);return}r.offset=this.writer.getPos();for(let a of r.samples)b(a.data),this.writer.write(a.data),a.data=null;r.samples.length=0,await this.writer.flush()}async interleaveSamples(e=!1){if(!(!e&&!this.allTracksAreKnown())){this.fastStart==="reserve"&&!this.mdat&&await this.createFastStartReserveMdat();e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!this.closedTracks.has(s.track))break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(r=s,n=s.sampleQueue[0].timestamp)}if(!r)break;let a=r.sampleQueue.shift();await this.addSampleToTrack(r,a)}}}async finalizeFragment(e=!this.isCmaf){if(b(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let p=this.initBoxWriter??this.boxWriter;b(p),this.formatOptions.onMoov&&p.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let g=oa(this);if(p.writeBox(g),this.formatOptions.onMoov){let{data:h,start:y}=p.writer.stopTrackingWrites();this.formatOptions.onMoov(h,y)}if(this.isCmaf){b(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new un(this.writer);let h=this.boxWriter.measureBox(cd()),y=this.boxWriter.measureBox(ld(this,0));this.segmentHeaderSize=h+y,this.writer.seek(this.segmentHeaderSize)}}b(this.writer),b(this.boxWriter);let r=this.trackDatas.filter(p=>p.currentChunk);if(r.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,a=md(n,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+Ot,l=1/0;for(let p=0;p<r.length;p++){let g=r[p];b(g.currentChunk),b(g.startTimestampOffset!==null),l=Math.min(l,g.currentChunk.startTimestamp),g.currentChunk.offset=c,g.currentChunk.moofOffset=s,g.currentChunk.startTimestamp-=g.startTimestampOffset;for(let h of g.currentChunk.samples)c+=h.size,h.timestamp-=g.startTimestampOffset,h.decodeTimestamp-=g.startTimestampOffset}let u=c-o,d=u>=2**32;if(d){for(let p of r)p.currentChunk.offset+=kr-Ot;u+=kr-Ot}if(J(r).currentChunk.offset-s>=2**31)throw new Error("The data of a fragment's track must start less than 2 GiB after its moof box; use shorter fragments.");this.formatOptions.onMoof&&this.writer.startTrackingWrites();let m=md(n,r);if(this.boxWriter.writeBox(m),this.formatOptions.onMoof){let{data:p,start:g}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(p,g,l)}b(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=gs(d);f.size=u,this.boxWriter.writeBox(f),this.writer.seek(o+(d?kr:Ot));for(let p of r)for(let g of p.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.formatOptions.onMdat){let{data:p,start:g}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(p,g)}for(let p=0;p<r.length;p++){let g=r[p];if(b(g.currentChunk),!this.isCmaf){let h=g.currentChunk.samples.findIndex(y=>y.type==="key");h!==-1&&g.tfraEntries.push({timestamp:g.currentChunk.samples[h].timestamp,moofOffset:s,trafIndex:p,sampleIndex:h})}g.currentChunk=null}e&&await this.writer.flush()}async createFastStartReserveMdat(){b(this.writer),b(this.boxWriter),this.ensureOneEnabledTrack();let e=oa(this),n=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;b(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=gs(!0),this.boxWriter.writeBox(this.mdat)}computeSampleTableSizeUpperBound(){b(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let n=r.track.metadata.maximumPacketCount;b(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n,r.type==="audio"&&(e+=2*n,e+=8*n)}return e}async onTrackClose(e){let r=await this.mutex.acquire();try{let n=this.trackDatas.find(a=>a.track===e);n?.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),n?.type==="audio"&&n.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(n),this.closedTracks.add(e),n&&this.processTimestamps(n),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveSamples()}finally{r()}}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let r=this.trackDatas.filter(a=>a.type===e);if(r.length===0)continue;if(!r.some(a=>a.track.metadata.disposition?.default!==!1)){let a=r[0];a.track.metadata.disposition={...a.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){b(this.isFragmented);let e=await this.mutex.acquire();try{for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async writePendingEac3Packets(e){let r=e.info.pendingEac3Packets.map(o=>o.packet);e.info.pendingEac3Packets.length=0;let n=r[0].data;if(r.length>1){n=new Uint8Array(r.reduce((c,l)=>c+l.data.byteLength,0));let o=0;for(let c of r)n.set(c.data,o),o+=c.data.byteLength}let a=r.reduce((o,c)=>o+c.duration,0),s=this.createSampleForTrack(e,n,r[0].timestamp,a,"key",0);await this.registerSample(e,s)}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),r.type==="audio"&&r.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(r),this.closedTracks.add(r.track),this.processTimestamps(r);if(await this.interleaveSamples(!0),this.isFragmented)await this.finalizeFragment(!1);else{let r=this.trackDatas.filter(n=>n.currentChunk).sort((n,a)=>n.currentChunk.startTimestamp-a.currentChunk.startTimestamp);for(let n of r)await this.finalizeCurrentChunk(n);for(let n of this.trackDatas){let a=dn(n);if(a>0){let l=0;for(let u of n.samples)l+=u.size;n.avgBitrate=Math.round(8*l/a)}else n.avgBitrate=0;let s=0,o=0,c=0;for(let l=0;l<n.samples.length;l++){let u=n.samples[l];for(o+=u.size;u.decodeTimestamp-n.samples[s].decodeTimestamp>=1;)o-=n.samples[s].size,s++;c=Math.max(c,o)}if(n.maxBitrate=8*c,n.startTimestampOffset!==null)for(let l=0;l<n.samples.length;l++){let u=n.samples[l];u.timestamp-=n.startTimestampOffset,u.decodeTimestamp-=n.startTimestampOffset}}}if(b(this.writer),b(this.boxWriter),this.fastStart==="in-memory"){this.mdat=gs(!1);let r,n=null;for(;;){let s=this.boxWriter.measureBox(oa(this)),o=this.boxWriter.measureBox(this.mdat),c=s+o;if(c===n)break;n=c,r=o;let l=this.writer.getPos()+c;for(let u of this.finalizedChunks){u.offset=l;for(let{data:d}of u.samples)b(d),l+=d.byteLength,r+=d.byteLength}r>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let a=oa(this);if(this.boxWriter.writeBox(a),this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let s of this.finalizedChunks){for(let o of s.samples)b(o.data),this.writer.write(o.data),o.data=null;await this.writer.flush()}if(this.formatOptions.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;if(r>=2**31)throw new Error("CMAF segments must be smaller than 2 GiB, as their sidx box can't index anything larger.");this.writer.seek(0),this.boxWriter.writeBox(cd()),this.boxWriter.writeBox(ld(this,r))}else{let r=this.writer.getPos(),n=Fp(this.trackDatas);this.boxWriter.writeBox(n);let a=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{b(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);b(r!==void 0);let n=this.writer.getPos()-r;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}let a=oa(this);if(this.fastStart==="reserve"){b(this.ftypSize!==null);let s=this.boxWriter.offsets.get(this.mdat)-this.ftypSize,o=this.boxWriter.measureBox(a);if(o+8>s)throw new Error(`The moov box (${o} bytes) plus a free box (8 bytes) exceed the space reserved for them (${s} bytes) with fastStart: 'reserve'. This is a bug; please report it.`);this.writer.seek(this.ftypSize+o),this.boxWriter.writeBox(Ep(s-o)),this.writer.seek(this.ftypSize)}if(this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a),this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}};var ey=-(2**15),ty=2**15-1,Wp=6,ry=6,iy={video:1,audio:2,subtitle:17},jc=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.closedTracks=new Set;this.allTracksKnown=te();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.tagsElement=null;this.attachmentsElement=null;this.segmentDuration=null;this.cues=null;this.currentClusterBlocks=[];this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.endTimestamp=-1/0;this.warnedAboutTooNegativeTimestamp=!1;this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new Uo(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(let r of this.output.tracks)r.isVideoTrack()&&r.metadata.decoderConfig?this.getVideoTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig}):r.isAudioTrack()&&r.metadata.decoderConfig&&this.getAudioTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig})}finally{e()}}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof ir?"webm":"matroska"},{id:17031,data:4},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),c={id:290298740,data:[{id:19899,data:[{id:21419,data:n},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:s},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:o},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=c}createSegmentInfo(){let e={id:17545,data:new $i(0)};this.segmentDuration=e;let r=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime,n=null;if(r){let s=1000000n*BigInt(r.getTime()-zo);if(BigInt.asIntN(64,s)!==s)throw new Error("creationTime is out of the range representable by Matroska files.");n={id:17505,size:8,data:BigInt.asUintN(64,s)}}let a={id:357149030,data:[{id:2807729,data:1e6},this.format._options.appendOnly?null:e,n,{id:19840,data:Kr},{id:22337,data:Kr}]};this.segmentInfo=a}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=Be[r.track.source._codec];b(n),r.type==="audio"&&r.track.source._codec==="dts"?r.info.decoderConfig.codec==="dtse"?n="A_DTS/EXPRESS":r.info.decoderConfig.codec==="dtsl"&&(n="A_DTS/LOSSLESS"):r.type==="subtitle"&&this.format instanceof ir&&(n="D_WEBVTT/SUBTITLES");let a=0;if(r.type==="audio"){let s=Fc(r.track.source._codec,r.info.decoderConfig);a=Math.round(1e9*s)}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:iy[r.type]},r.track.metadata.disposition?.default===!1?{id:136,data:0}:null,r.track.metadata.disposition?.forced?{id:21930,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,r.track.metadata.disposition?.original?{id:21934,data:1}:null,r.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},r.type==="video"&&r.info.alphaMode||r.type==="subtitle"&&!(this.format instanceof ir)?{id:21998,data:1}:null,{id:2274716,data:r.track.metadata.languageCode??ce},{id:134,data:n},r.codecPrivate?{id:25506,data:G(r.codecPrivate)}:null,r.type==="audio"&&r.info.codecDelay?{id:22186,data:Math.round(1e9*r.info.codecDelay)}:null,a>0?{id:22203,data:a}:null,r.track.metadata.name!==void 0?{id:21358,data:new Dt(r.track.metadata.name)}:null,r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){let{frameRate:r,transformationMatrix:n}=e.track.metadata,a=[r?{id:2352003,data:Math.round(1e9/r)}:null],s,o,c;if(n){s=Di(n);let g=sr(Tn(-s),n);o=Math.sign(g[0]),c=Math.sign(g[4]),c===-1&&(c=1,o=-o,s=ai(s+180))}else s=e.track.metadata.rotation??0,o=e.track.metadata.flip?-1:1,c=1;let l=s?ai(o===-1?s:-s):0,u=Math.round(Math.acos(o)*Ps),d=Math.round(Math.acos(c)*Ps),m=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,f=e.info.decoderConfig.colorSpace,p={id:224,data:[{id:176,data:e.info.width},{id:186,data:e.info.height},m?{id:21680,data:e.info.aspectRatio.num}:null,m?{id:21690,data:e.info.aspectRatio.den}:null,m?{id:21682,data:3}:null,e.info.alphaMode?{id:21440,data:1}:null,_s(f)?null:{id:21936,data:[{id:21937,data:f?.matrix!=null?Ft[f.matrix]:2},{id:21946,data:f?.transfer!=null?Rt[f.transfer]:2},{id:21947,data:f?.primaries!=null?_t[f.primaries]:2},{id:21945,data:f?.fullRange!=null?f.fullRange?2:1:0}]},l||u||d?{id:30320,data:[{id:30321,data:0},u?{id:30323,data:new Tr(u)}:null,d?{id:30324,data:new Tr(d)}:null,l?{id:30325,data:new Tr((l+180)%360-180)}:null]}:null]};return a.push(p),a}audioSpecificTrackInfo(e){let r=se.includes(e.track.source._codec)?Me(e.track.source._codec):null,n=e.info.sampleRate;return e.track.source._codec==="aac"&&(b(e.codecPrivate),n=xt(G(e.codecPrivate)).coreSampleRate??n),[{id:225,data:[{id:181,data:new Tr(n)},n!==e.info.sampleRate?{id:30901,data:new Tr(e.info.sampleRate)}:null,{id:159,data:e.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],r=(s,o)=>{e.push({id:26568,data:[{id:17827,data:new Dt(s)},typeof o=="string"?{id:17543,data:new Dt(o)}:{id:17541,data:o}]})},n=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of qt(n))switch(s){case"title":r("TITLE",o),a.add("TITLE");break;case"description":r("DESCRIPTION",o),a.add("DESCRIPTION");break;case"artist":r("ARTIST",o),a.add("ARTIST");break;case"album":r("ALBUM",o),a.add("ALBUM");break;case"albumArtist":r("ALBUM_ARTIST",o),a.add("ALBUM_ARTIST");break;case"genre":r("GENRE",o),a.add("GENRE");break;case"beatsPerMinute":r("BPM",o.toString()),a.add("BPM");break;case"comment":r("COMMENT",o),a.add("COMMENT");break;case"lyrics":r("LYRICS",o),a.add("LYRICS");break;case"date":r("DATE",o.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":{let c=n.tracksTotal!==void 0?`${o}/${n.tracksTotal}`:o.toString();r("PART_NUMBER",c),a.add("PART_NUMBER")}break;case"discNumber":{let c=n.discsTotal!==void 0?`${o}/${n.discsTotal}`:o.toString();r("DISC",c),a.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":case"creationTime":break;default:Z(s)}if(n.raw)for(let s in n.raw){let o=n.raw[s];o==null||a.has(s)||(typeof o=="string"||o instanceof Uint8Array)&&r(s,o)}e.length!==0&&(this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,r=[],n=new Set,a=e.images??[];for(let s of a){let o=s.name;o===void 0&&(o=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(zd(s.mimeType)??""));let c;for(;;){c=0n;for(let l=0;l<8;l++)c<<=8n,c|=BigInt(Math.floor(Math.random()*256));if(c!==0n&&!n.has(c))break}n.add(c),r.push({id:24999,data:[s.description!==void 0?{id:18046,data:new Dt(s.description)}:null,{id:18030,data:new Dt(o)},{id:18016,data:s.mimeType},{id:18012,data:s.data},{id:18094,data:c}]})}for(let[s,o]of Object.entries(e.raw??{}))!(o instanceof Lr)||!/^\d+$/.test(s)||a.find(l=>l.mimeType===o.mimeType&&Ds(l.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new Dt(o.description)}:null,{id:18030,data:new Dt(o.name??"")},{id:18016,data:o.mimeType??""},{id:18012,data:o.data},{id:18094,data:BigInt(s)}]});r.length!==0&&(this.attachmentsElement={id:423732329,data:r})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:408125543,size:this.format._options.appendOnly?-1:Wp,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,n)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return b(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Lo({isWebM:this.format instanceof ir,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;_r(n,e.source._codec),b(n),b(n.decoderConfig),b(n.decoderConfig.codedWidth!==void 0),b(n.decoderConfig.codedHeight!==void 0);let s=n.decoderConfig.displayAspectWidth,o=n.decoderConfig.displayAspectHeight,c=s===void 0||o===void 0?null:zr({num:s,den:o}),l={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:n.decoderConfig,alphaMode:e.metadata.canBeTransparent||(r?!!r.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.decoderConfig.description??null};return e.source._codec==="vp9"?l.codecPrivate=new Uint8Array(gp(l.info.decoderConfig.codec)):e.source._codec==="av1"?l.codecPrivate=new Uint8Array(zc(l.info.decoderConfig.codec)):e.source._codec==="prores"&&(l.codecPrivate=Y.encode(n.decoderConfig.codec)),this.trackDatas.push(l),this.trackDatas.sort((u,d)=>u.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,r,n){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;Re(n,e.source._codec),b(n),b(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let l=It(xe.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u,d=null;if(l.channelConfiguration===0){let m=l.crcCheck===null?rt:Ye,f=mr(r.data.subarray(m));if(!f)throw new Error("ADTS frames with channel configuration 0 must begin with a program config element.");d=f.programConfigElement,u=Wr(d)}else u=dr[l.channelConfiguration];s.description=ui({objectType:l.objectType,outputSampleRate:Xe[l.samplingFrequencyIndex],outputNumberOfChannels:u,programConfigElement:d}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o,codecDelay:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Nc(r),b(r),b(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Y.encode(r.config.description)};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n);s.info.alphaMode??=!!r.sideData.alpha;let o=r.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let l=r.timestamp,u=r.duration;e.metadata.frameRate!==void 0&&(l=Mt(l,e.metadata.frameRate),u=Mt(u,e.metadata.frameRate));let d=s.info.alphaMode?r.sideData.alpha??null:null,m=this.createInternalChunk(o,l,u,r.type,d);s.chunkQueue.push(m),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let u=It(xe.tempFromBytes(o));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let d=u.crcCheck===null?rt:Ye;if(o=o.subarray(d),u.channelConfiguration===0){let m=mr(o);m&&(o=o.subarray(m.size))}}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c),s.info.codecDelay??=Math.max(-r.timestamp,0);let l=this.createInternalChunk(o,r.timestamp+s.info.codecDelay,r.duration,r.type);s.chunkQueue.push(l),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,!0);let o=r.text,c=Math.round(r.timestamp*1e3);Rn.lastIndex=0,o=o.replace(Rn,u=>{let m=so(u.slice(1,-1))-c;return`<${oo(m/1e3)}>`});let l;if(this.format instanceof ir){let u=Y.encode(`${r.identifier??""}
|
|
14
|
+
`,a);l===-1&&(l=t.length);let u=oo(e[2]),m=oo(e[3])-u,f=t.slice(o,l).trim();t=t.slice(l).trimStart(),Pa.lastIndex=0;let p={timestamp:u/1e3,duration:m/1e3,text:f,identifier:n,settings:c,notes:r},h={};this.preambleEmitted||(h.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(p,h)}}},Uh=/(?:(\d{2,}):)?(\d{2}):(\d{2}).(\d{3})/,oo=i=>{let t=Uh.exec(i);if(!t)throw new Error("Expected match.");return 60*60*1e3*Number(t[1]||"0")+60*1e3*Number(t[2])+1e3*Number(t[3])+Number(t[4])},co=i=>{let t=Math.round(1e3*i),e=Math.floor(t/(60*60*1e3)),r=Math.floor(t%(60*60*1e3)/(60*1e3)),n=Math.floor(t%(60*1e3)/1e3),a=t%1e3;return e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+n.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};var Tm=i=>{let r=i>>2,n=4096,a=0,s=12,o=0;for(r<0&&(r=-r,a=128),r+=33,r>8191&&(r=8191);(r&n)!==n&&s>=5;)n>>=1,s--;return o=r>>s-4&15,~(a|s-5<<4|o)&255},wm=i=>{let e=0,r=0,n=~i;n&128&&(n&=-129,e=-1),r=((n&240)>>4)+5;let a=(1<<r|(n&15)<<r-4|1<<r-5)-33;return(e===0?a:-a)<<2},Sm=i=>{let e=2048,r=0,n=11,a=0,s=i>>3;for(s<0?s=-s-1:r=128,s>4095&&(s=4095);(s&e)!==e&&n>=5;)e>>=1,n--;return a=s>>(n===4?1:n-4)&15,(r|n-4<<4|a)^85},Am=i=>{let t=0,e=0,r=i^85;r&128&&(r&=-129,t=-1),e=((r&240)>>4)+4;let n=0;return e!==4?n=1<<e|(r&15)<<e-4|1<<e-5:n=r<<1|1,(t===0?-n:n)<<3};var lo=new Map,uo=new Map,zh=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&ct(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.codedWidth!==void 0&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(t.codedHeight!==void 0&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(t.displayAspectWidth!==void 0&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(t.displayAspectHeight!==void 0&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(t.description!==void 0&&!Dr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},Nh=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.codec!==void 0&&typeof t.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(t.codec!==void 0&&ct(t.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(t.numberOfChannels!==void 0&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(t.sampleRate!==void 0&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(t.description!==void 0&&!Dr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.")},xm=async i=>ue.includes(i)?mo(i):pe.includes(i)?fo(i):!1,mo=async(i,t={})=>{if(!ue.includes(i))return!1;zh(i,t);let e=t.codedWidth??1280,r=t.codedHeight??720,n={...t,codedWidth:e,codedHeight:r,codec:t.codec??po(i,e,r,1e6,!1)};n.description??=Em(n);let a=Cm(n),s=lo.get(a);if(s)return s;let o=(async()=>bi.some(l=>l.supports(i,n))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(n)).supported===!0)();return lo.set(a,o),o},fo=async(i,t={})=>{if(!pe.includes(i))return!1;Nh(i,t);let e={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??ho(i)};if(e.description===void 0){let s=Im(e);if(s===!1)return!1;e.description=s}let r=Cm(e),n=uo.get(r);if(n)return n;let a=(async()=>yi.some(o=>o.supports(i,e))||se.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0)();return uo.set(r,a),a},Cm=i=>JSON.stringify({...i,description:i.description&&[...Q(i.description)]}),Pm=async()=>{let[i,t]=await Promise.all([ql(),Kl()]);return[...i,...t]},ql=async(i=ue,t)=>{let e=await Promise.all(i.map(r=>mo(r,t)));return i.filter((r,n)=>e[n])},Kl=async(i=pe,t)=>{let e=await Promise.all(i.map(r=>fo(r,t)));return i.filter((r,n)=>e[n])};Cn();var vm=-1/0,_m=-1/0,_a=null;typeof FinalizationRegistry<"u"&&(_a=new FinalizationRegistry(i=>{let t=performance.now();i.type==="video"?(t-vm>=1e3&&(O._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."),vm=t),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(t-_m>=1e3&&(O._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."),_m=t),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));var jt=class{constructor(){this._referenceCount=0;this._lastAllocationBuffer=null}},Ra=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Lh=new Set(Ra),$e=class i{constructor(t,e){this._closed=!1;if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.format===void 0||!Lh.has(e.format))throw new TypeError("init.format must be one of: "+Ra.join(", "));if(!Number.isInteger(e.codedWidth)||e.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(e.codedHeight)||e.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.layout!==void 0){if(!Array.isArray(e.layout))throw new TypeError("init.layout, when provided, must be an array.");for(let s of e.layout){if(!s||typeof s!="object"||Array.isArray(s))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(s.offset)||s.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(s.stride)||s.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}let a=Fa(e.format).length;if(e.layout.length!==a)throw new TypeError(`init.layout must have ${a} entries for format ${e.format}.`)}if(e.visibleRect!==void 0&&Gl(e.visibleRect),e.displayWidth!==void 0&&(!Number.isInteger(e.displayWidth)||e.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(e.displayHeight!==void 0&&(!Number.isInteger(e.displayHeight)||e.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(e.displayWidth!==void 0!=(e.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=e.format,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0;let r=e.layout??Wh(e.format,e.codedWidth,e.codedHeight),n=e.colorSpace??null;n===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?n={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:n={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:e.visibleRect?.left??0,top:e.visibleRect?.top??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},e.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?e.displayWidth:e.displayHeight,this.squarePixelHeight=this.rotation%180===0?e.displayHeight:e.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=e._doNotCopy?Q(t):Q(t).slice(),this._layout=r,this.colorSpace=new Xi(n)}else if(typeof VideoFrame<"u"&&t instanceof VideoFrame){if(t.codedWidth===0)throw new TypeError("data must not be a closed VideoFrame.");if(e?.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e?.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(e?.timestamp!==void 0&&!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");e?.visibleRect!==void 0&&Gl(e.visibleRect),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=e?.rotation??0,this.flip=e?.flip??!1,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=e?.timestamp??t.timestamp/1e6,this.duration=e?.duration??(t.duration??0)/1e6;let{primaries:r,transfer:n,matrix:a,fullRange:s}=t.colorSpace;this.colorSpace=new Xi({primaries:r!==null&&r in _t?r:null,transfer:n!==null&&n in Rt?n:null,matrix:a!==null&&a in Ft?a:null,fullRange:s})}else if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof SVGImageElement<"u"&&t instanceof SVGImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(e.visibleRect!==void 0&&Gl(e.visibleRect),typeof VideoFrame<"u")return new i(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*ur),duration:Math.trunc((e.duration??0)*ur)||void 0,visibleRect:e.visibleRect&&{x:e.visibleRect.left,y:e.visibleRect.top,width:e.visibleRect.width,height:e.visibleRect.height}}),e);let r=0,n=0;if("naturalWidth"in t?(r=t.naturalWidth,n=t.naturalHeight):"videoWidth"in t?(r=t.videoWidth,n=t.videoHeight):"width"in t&&(r=Number(t.width),n=Number(t.height)),!r||!n)throw new TypeError("Could not determine dimensions.");let a=e.visibleRect??{left:0,top:0,width:r,height:n},s=new OffscreenCanvas(a.width,a.height),o=s.getContext("2d",{alpha:Wt(),willReadFrequently:!0});if(!o)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");o.drawImage(t,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=new Xi({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(t instanceof jt){if(!e||typeof e!="object")throw new TypeError("init must be an object.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");if(!Number.isFinite(e.timestamp))throw new TypeError("init.timestamp must be a number.");if(e.duration!==void 0&&(!Number.isFinite(e.duration)||e.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this.format=t.getFormat(),this.format!==null&&!Ra.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=e.rotation??0,this.flip=e.flip??!1,this.timestamp=e.timestamp,this.duration=e.duration??0,this.colorSpace=t.getColorSpace(),this._data=t,t._referenceCount++}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=e?.encodeOptions??{},this.pixelAspectRatio=zr({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),_a?.register(this,{type:"video",data:this._data},this)}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(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return b(this._data!==null),this._data instanceof jt?new i(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Ia(this._data)?new i(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(b(this._layout),new i(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,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new i(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(_a?.unregister(this),this._data instanceof jt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ia(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(Mm(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Ia(this._data)?this._data.allocationSize(t):Bm(this,t).allocationSize}async copyTo(t,e={}){if(!Dr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Mm(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(b(this._data!==null),Ia(this._data))return this._data.copyTo(t,e);if(e.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(e.format))if(this._data instanceof jt){var l=[];try{let f=yt(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},e.colorSpace??"srgb"));if(!(f instanceof i))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(f.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${f.format}' instead.`);return await f.copyTo(t,e)}catch(u){var d=u,m=!0}finally{kt(l,d,m)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let f=this.toVideoFrame();try{return await f.copyTo(t,e)}finally{f.close()}}let r=Bm(this,e);b(this.format);let n=Q(t);if(n.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${n.byteLength}`);let a=Fa(this.format),s;if(this._data instanceof jt){let f=this._data.getDataPlanes();if(R(f)&&(f=await f),!Array.isArray(f)||f.some(p=>!(p.data instanceof Uint8Array)||!Number.isInteger(p.stride)||p.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=f}else if(this._data instanceof Uint8Array)b(this._layout),b(this._layout.length===a.length),s=this._layout.map((f,p)=>{let h=Math.ceil((this.visibleRect.top+this.visibleRect.height)/a[p].heightDivisor);return{data:this._data.subarray(f.offset,f.offset+f.stride*h),stride:f.stride}});else{let p=this._data.getContext("2d");b(p);let h=p.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:Q(h.data),stride:4*this.codedWidth}]}let o=[],c=a.length;for(let f=0;f<c;f++){let p=r.computedLayouts[f],h=s[f].stride,y=s[f].data,g=p.sourceTop*h;g+=p.sourceLeftBytes;let k=p.destinationOffset,T=p.sourceWidthBytes,S={offset:k,stride:p.destinationStride};for(let w=0;w<p.sourceHeight;w++){if(g+T>y.byteLength)throw new Error("Source buffer OOB read.");if(k+T>n.byteLength)throw new Error("Destination buffer OOB write.");let A=y.subarray(g,g+T);n.set(A,k),g+=h,k+=p.destinationStride}o.push(S)}if(e.format!==void 0){let f=this.format.startsWith("RGB")!==e.format.startsWith("RGB"),p=this.format.includes("X")&&e.format.includes("A");if(f||p){let h=r.computedLayouts[0];for(let y=0;y<h.sourceHeight;y++){let g=h.destinationOffset+y*h.destinationStride,k=g+h.sourceWidthBytes;for(let T=g;T<k;T+=4){if(f){let S=n[T],w=n[T+2];n[T]=w,n[T+2]=S}p&&(n[T+3]=255)}}}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(b(this._data!==null),this._data instanceof jt){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let t=this._data.getDataPlanes();if(R(t))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let e=t.reduce((s,o)=>s+o.data.byteLength,0),r=new Uint8Array(e),n=0,a=[];for(let s of t)r.set(s.data,n),a.push(n),n+=s.data.byteLength;return new VideoFrame(r,{format:this.format,layout:t.map((s,o)=>({offset:a[o],stride:s.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Ia(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(b(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.visibleRect.left+this.visibleRect.width,codedHeight:this.visibleRect.top+this.visibleRect.height,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:{x:this.visibleRect.left,y:this.visibleRect.top,width:this.visibleRect.width,height:this.visibleRect.height},displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,r,n,a,s,o,c,l){let u=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,h=0,y=this.displayWidth,g=this.displayHeight;if(s!==void 0?(u=e,d=r,m=n,f=a,p=s,h=o,c!==void 0?(y=c,g=l):(y=m,g=f)):(p=e,h=r,n!==void 0&&(y=n,g=a)),!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(m)||m<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(f)||f<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(p))throw new TypeError("dx must be a number.");if(!Number.isFinite(h))throw new TypeError("dy must be a number.");if(!Number.isFinite(y)||y<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:m,sHeight:f}=this._unmapSourceRegion(u,d,m,f,this.rotation,this.flip));let k=this.toCanvasImageSource();t.save();let T=p+y/2,S=h+g/2;t.translate(T,S),this.flip&&t.scale(-1,1),t.rotate(this.rotation*Math.PI/180);let w=this.rotation%180===0?1:y/g;t.scale(1/w,w),t.drawImage(k,u,d,m,f,-y/2,-g/2,y,g),t.restore()}drawWithFit(t,e){if(!(typeof CanvasRenderingContext2D<"u"&&t instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&t instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");e.crop!==void 0&&ki(e.crop,"options.");let r=t.canvas.width,n=t.canvas.height,a=e.rotation??this.rotation,s=e.flip??this.flip,[o,c]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],l=e.crop;l&&(l=Mn(l,o,c));let u,d,m,f,{sx:p,sy:h,sWidth:y,sHeight:g}=this._unmapSourceRegion(l?.left??0,l?.top??0,l?.width??o,l?.height??c,a,s);if(e.fit==="fill")u=0,d=0,m=r,f=n;else{let[S,w]=l?[l.width,l.height]:[o,c],A=e.fit==="contain"?Math.min(r/S,n/w):Math.max(r/S,n/w);m=S*A,f=w*A,u=(r-m)/2,d=(n-f)/2}let k=this.toCanvasImageSource();t.save();let T=a%180===0?1:m/f;t.translate(r/2,n/2),s&&t.scale(-1,1),t.rotate(a*Math.PI/180),t.scale(1/T,T),t.translate(-r/2,-n/2),t.drawImage(k,p,h,y,g,u,d,m,f),t.restore()}_unmapSourceRegion(t,e,r,n,a,s){return s&&(t=(a%180===0?this.squarePixelWidth:this.squarePixelHeight)-t-r),a===90?[t,e,r,n]=[e,this.squarePixelHeight-t-r,n,r]:a===180?[t,e]=[this.squarePixelWidth-t-r,this.squarePixelHeight-e-n]:a===270&&([t,e,r,n]=[this.squarePixelWidth-e-n,t,n,r]),{sx:t,sy:e,sWidth:r,sHeight:n}}_drawWithFitAndMipmapping(t,e,r){let n=t.width,a=t.height,[s,o]=r.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=r.crop?r.crop.width:s,l=r.crop?r.crop.height:o,u=0;2*n<c&&2*a<l&&(u=Math.floor(Math.log2(Math.min(c/n,l/a))));let d=n*2**u,m=a*2**u,{canvas:f,context:p,isNew:h}=u>0?Fm(d,m):{canvas:t,context:e,isNew:r.targetIsFresh};p.imageSmoothingQuality="high",r.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,m)):h||p.clearRect(0,0,d,m),this.drawWithFit(p,{fit:r.fit,rotation:r.rotation,flip:r.flip,crop:r.crop}),p.globalCompositeOperation="copy";for(let y=u;y>1;y--){let g=n*2**y,k=a*2**y;p.drawImage(f,0,0,g,k,0,0,g/2,k/2)}p.globalCompositeOperation="source-over",u>0&&(e.imageSmoothingQuality="high",e.globalCompositeOperation="copy",e.drawImage(f,0,0,2*n,2*a,0,0,n,a),e.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(b(this._data!==null),this._data instanceof jt||this._data instanceof Uint8Array){let t=this.toVideoFrame();return queueMicrotask(()=>t.close()),t}else return this._data}async transform(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(t.crop!==void 0&&ki(t.crop,"options."),t.alpha!==void 0&&!["keep","discard"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let{rotation:e,flip:r}=_s(this.rotation,this.flip,t.rotate??0,t.flip??!1),[n,a]=e%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&(s=Mn(s,n,a));let o=s?s.width:n,c=s?s.height:a,l=o/c,u,d;t.width!==void 0&&t.height===void 0?(u=t.width,d=u/l):t.width===void 0&&t.height!==void 0?(d=t.height,u=d*l):t.width!==void 0&&t.height!==void 0?(u=t.width,d=t.height):(u=o,d=c),u=Ms(u,t.roundDimensionsTo??1),d=Ms(d,t.roundDimensionsTo??1);let m={width:u,height:d,fit:t.fit??"fill",rotation:e,flip:r,crop:s??{left:0,top:0,width:n,height:a},alpha:t.alpha??"keep"};for(let y of Ql){let g=y(this,m);if(R(g)&&(g=await g),g!==null)return g}let{canvas:f,context:p,isNew:h}=Fm(m.width,m.height);return this._drawWithFitAndMipmapping(f,p,{fit:m.fit,rotation:m.rotation,flip:m.flip,crop:m.crop,targetIsFresh:h,fillBlack:m.alpha==="discard"}),new i(f,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1,encodeOptions:this.encodeOptions})}setRotation(t){if(![0,90,180,270].includes(t))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=t}setFlip(t){if(typeof t!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}setDuration(t){if(!Number.isFinite(t)||t<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=t}setEncodeOptions(t){if(!t||typeof t!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=t}[Symbol.dispose](){this.close()}},Ql=[],Om=i=>{Ql.includes(i)||Ql.push(i)},Hh=3,Ea=[],Rm=0,Fm=(i,t)=>{for(let n of Ea)if(n.canvas.width===i&&n.canvas.height===t)return n.age=Rm++,{canvas:n.canvas,context:n.context,isNew:!1};let e;if(typeof OffscreenCanvas<"u")e=new OffscreenCanvas(i,t);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");e=document.createElement("canvas"),e.width=i,e.height=t}let r=e.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Ea.length>=Hh&&Ea.splice(li(Ea,n=>n.age),1),Ea.push({canvas:e,context:r,age:Rm++}),{canvas:e,context:r,isNew:!0}},Xi=class{constructor(t){if(t!==void 0){if(!t||typeof t!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");let e=Object.keys(_t);if(t.primaries!=null&&!e.includes(t.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${e.join(", ")}.`);let r=Object.keys(Rt);if(t.transfer!=null&&!r.includes(t.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);let n=Object.keys(Ft);if(t.matrix!=null&&!n.includes(t.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=t?.primaries??null,this.transfer=t?.transfer??null,this.matrix=t?.matrix??null,this.fullRange=t?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},Ia=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,Mn=(i,t,e)=>{let r=Math.min(i.left,t),n=Math.min(i.top,e),a=Math.min(i.width,t-r),s=Math.min(i.height,e-n);return b(a>=0),b(s>=0),{left:r,top:n,width:a,height:s}},ki=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},Gl=i=>{if(Wd(i,"init.visibleRect"),i.width===0||i.height===0)throw new TypeError("init.visibleRect must not be empty.")},Mm=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.colorSpace!==void 0&&!["display-p3","srgb"].includes(i.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(i.format!==void 0&&typeof i.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("options.layout, when provided, must be an array.");for(let t of i.layout){if(!t||typeof t!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(i.rect!==void 0){if(!i.rect||typeof i.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(i.rect.x!==void 0&&(!Number.isInteger(i.rect.x)||i.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(i.rect.y!==void 0&&(!Number.isInteger(i.rect.y)||i.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(i.rect.width!==void 0&&(!Number.isInteger(i.rect.width)||i.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(i.rect.height!==void 0&&(!Number.isInteger(i.rect.height)||i.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Wh=(i,t,e)=>{let r=Fa(i),n=[],a=0;for(let s of r){let o=Math.ceil(t/s.widthDivisor),c=Math.ceil(e/s.heightDivisor),l=o*s.sampleBytes,u=l*c;n.push({offset:a,stride:l}),a+=u}return n},Fa=i=>{let t=(e,r,n,a,s)=>{let o=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:n,heightDivisor:a},{sampleBytes:r,widthDivisor:n,heightDivisor:a}];return s&&o.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),o};switch(i){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(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:Z(i),b(!1)}},Bm=(i,t)=>{let e={x:i.visibleRect.left,y:i.visibleRect.top,width:i.visibleRect.width,height:i.visibleRect.height},r=t.rect,n=qh(e,r,i.visibleRect.left+i.visibleRect.width,i.visibleRect.top+i.visibleRect.height,i.format),a=t.layout,s;if(!t.format||t.format===i.format)s=i.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(t.format))s=t.format;else throw new Error("NotSupportedError: Invalid destination format.");return Gh(n,s,a)},qh=(i,t,e,r,n)=>{let a={...i};if(t!==void 0){if(!t.width||!t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>e)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!Kh(n,a))throw new TypeError("visibleRect alignment is invalid for the format.");return a},Kh=(i,t)=>{if(i===null)return!0;let e=Fa(i);for(let r=0;r<e.length;r++){let n=e[r],a=n.widthDivisor,s=n.heightDivisor;if((t.x||0)%a!==0||(t.y||0)%s!==0)return!1}return!0},Gh=(i,t,e)=>{let r=Fa(t),n=r.length;if(e!==void 0&&e.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let a=0,s=[],o=[];for(let c=0;c<n;c++){let l=r[c],u=l.sampleBytes,d=l.widthDivisor,m=l.heightDivisor,f={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(f.sourceTop=Math.ceil(Math.trunc(i.y||0)/m),f.sourceHeight=Math.ceil(Math.trunc(i.height||0)/m),f.sourceLeftBytes=Math.floor(Math.trunc(i.x||0)/d)*u,f.sourceWidthBytes=Math.ceil(Math.trunc(i.width||0)/d)*u,e!==void 0){let y=e[c];if(y.stride<f.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);f.destinationOffset=y.offset,f.destinationStride=y.stride}else f.destinationOffset=a,f.destinationStride=f.sourceWidthBytes;let h=f.destinationStride*f.sourceHeight+f.destinationOffset;if(h>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),a=Math.max(a,h);for(let y=0;y<c;y++){let g=s[y];if(!(o[c]<=g.destinationOffset||o[y]<=f.destinationOffset))throw new TypeError("Planes overlap.")}s.push(f)}return{allocationSize:a,computedLayouts:s}},go=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Gr=class{constructor(){this._referenceCount=0}},Ce=class i{constructor(t){this._closed=!1;if(va(t)){if(t.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=t,this.format=t.format,this.sampleRate=t.sampleRate,this.numberOfFrames=t.numberOfFrames,this.numberOfChannels=t.numberOfChannels,this.timestamp=t.timestamp/1e6,this.duration=t.numberOfFrames/t.sampleRate}else if(t instanceof Gr){if(this.format=t.getFormat(),!go.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=t.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=t.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=t.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=t.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate,this._data=t,t._referenceCount++}else{if(!t||typeof t!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!go.has(t.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(t.sampleRate)||t.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp must be a number.");let e=t.data.byteLength/(Ct(t.format)*t.numberOfChannels);if(!Number.isInteger(e))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=t.format,this.sampleRate=t.sampleRate,this.numberOfFrames=e,this.numberOfChannels=t.numberOfChannels,this.timestamp=t.timestamp,this.duration=e/t.sampleRate;let r;if(t.data instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t.data instanceof SharedArrayBuffer)r=new Uint8Array(t.data);else if(ArrayBuffer.isView(t.data))r=new Uint8Array(t.data.buffer,t.data.byteOffset,t.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");let n=this.numberOfFrames*this.numberOfChannels*Ct(this.format);if(r.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=t._doNotCopy?r:r.slice()}_a?.register(this,{type:"audio",data:this._data},this)}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}allocationSize(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!go.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let e=t.format??this.format,r=t.frameOffset??0;if(r>0&&r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");let n=t.frameCount!==void 0?t.frameCount:this.numberOfFrames-r;if(n>this.numberOfFrames-r)throw new RangeError("frameCount out of range");let a=Ct(e),s=ji(e);if(s&&t.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&t.planeIndex!==0)throw new RangeError("planeIndex out of range");return(s?n:n*this.numberOfChannels)*a}copyTo(t,e){if(!Dr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!go.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");let{format:r,frameCount:n,frameOffset:a}=e,{planeIndex:s}=e,o=this.format,c=r??this.format;if(!c)throw new Error("Destination format not determined");let l=this.numberOfFrames,u=this.numberOfChannels,d=a??0;if(d>0&&d>=l)throw new RangeError("frameOffset out of range");let m=n!==void 0?n:l-d;if(m>l-d)throw new RangeError("frameCount out of range");let f=Ct(c),p=ji(c);if(p&&s>=u)throw new RangeError("planeIndex out of range");if(!p&&s!==0)throw new RangeError("planeIndex out of range");let y=(p?m:m*u)*f;if(t.byteLength<y)throw new RangeError("Destination buffer is too small");let g=z(t),k=Vm(c);if(va(this._data))if(et()&&u>2&&c!==o){Qh(this._data,g,o,c,u,s,d,m);return}else try{this._data.copyTo(t,{planeIndex:s,frameOffset:d,frameCount:m,format:c});return}catch(E){if(c==="f32-planar")throw E;o="f32-planar"}let T=Dm(o),S=Ct(o),w=ji(o),A;if(this._data instanceof Gr){let E=I=>{let x=this._data.getDataPlane(I);if(!(x instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let P=l*S*(w?1:u);if(x.byteLength!==P)throw new TypeError(`Data plane ${I} has invalid size. Expected exactly ${P} bytes, got ${x.byteLength} bytes.`);return x};if(w)if(p)A=E(s),s=0;else{A=new Uint8Array(l*S*u);for(let I=0;I<u;I++){let x=E(I);A.set(x,I*l*S)}}else A=E(0)}else if(this._data instanceof Uint8Array)A=this._data;else if(b(o==="f32-planar"),p)A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:s})),this._data.copyTo(A,{format:"f32-planar",planeIndex:s}),s=0;else{A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*u);for(let E=0;E<u;E++)this._data.copyTo(A.subarray(E*l*S,(E+1)*l*S),{format:"f32-planar",planeIndex:E})}let C=z(A);for(let E=0;E<m;E++)if(p){let I=E*f,x;w?x=(s*l+(E+d))*S:x=((E+d)*u+s)*S;let P=T(C,x);k(g,I,P)}else for(let I=0;I<u;I++){let P=(E*u+I)*f,v;w?v=(I*l+(E+d))*S:v=((E+d)*u+I)*S;let _=T(C,v);k(g,P,_)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Gr){let t=new i(this._data);return t.setTimestamp(this.timestamp),t}else if(va(this._data)){let t=new i(this._data.clone());return t.setTimestamp(this.timestamp),t}else return new i({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data,_doNotCopy:!0})}trim(t,e=this.numberOfFrames){if(!Number.isInteger(t)||t<0)throw new TypeError("startFrame must be a non-negative integer.");if(!Number.isInteger(e)||e<0)throw new TypeError("endFrame must be a non-negative integer.");if(t>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(e>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(e<t)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");let r=e-t,n=Ct(this.format),a;if(ji(this.format)){let s=r*n;if(a=new Uint8Array(s*this.numberOfChannels),r>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(a.subarray(o*s,(o+1)*s),{planeIndex:o,format:this.format,frameOffset:t,frameCount:r})}else a=new Uint8Array(r*this.numberOfChannels*n),r>0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:t,frameCount:r});return new i({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+t/this.sampleRate,_doNotCopy:!0})}close(){this._closed||(_a?.unregister(this),this._data instanceof Gr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):va(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof Gr?this._createAudioDataFromData():va(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():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:this._data.slice()})}_createAudioDataFromData(){if(ji(this.format)){let t=this.allocationSize({planeIndex:0,format:this.format}),e=new ArrayBuffer(t*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(e,r*t,t),{planeIndex:r,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}else{let t=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(t,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");let t=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),e=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(e,{planeIndex:r,format:"f32-planar"}),t.copyToChannel(e,r);return t}setTimestamp(t){if(!Number.isFinite(t))throw new TypeError("newTimestamp must be a number.");this.timestamp=t}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,e){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,n=t.numberOfChannels,a=t.sampleRate,s=t.length,o=Math.floor(r/n),c=0,l=s;for(;l>0;){let u=Math.min(o,l),d=new Float32Array(n*u);for(let m=0;m<n;m++)t.copyFromChannel(d.subarray(m*u,(m+1)*u),m,c);yield new i({format:"f32-planar",sampleRate:a,numberOfFrames:u,numberOfChannels:n,timestamp:e+c/a,data:d,_doNotCopy:!0}),c+=u,l-=u}}static fromAudioBuffer(t,e){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let r=48e3*5,n=t.numberOfChannels,a=t.sampleRate,s=t.length,o=Math.floor(r/n),c=0,l=s,u=[];for(;l>0;){let d=Math.min(o,l),m=new Float32Array(n*d);for(let p=0;p<n;p++)t.copyFromChannel(m.subarray(p*d,(p+1)*d),p,c);let f=new i({format:"f32-planar",sampleRate:a,numberOfFrames:d,numberOfChannels:n,timestamp:e+c/a,data:m,_doNotCopy:!0});u.push(f),c+=d,l-=d}return u}},Ct=i=>{switch(i){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 new Error("Unknown AudioSampleFormat")}},ji=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Dm=i=>{switch(i){case"u8":case"u8-planar":return(t,e)=>(t.getUint8(e)-128)/128;case"s16":case"s16-planar":return(t,e)=>t.getInt16(e,!0)/32768;case"s32":case"s32-planar":return(t,e)=>t.getInt32(e,!0)/2147483648;case"f32":case"f32-planar":return(t,e)=>t.getFloat32(e,!0)}},Vm=i=>{switch(i){case"u8":case"u8-planar":return(t,e,r)=>t.setUint8(e,ne(Math.round(r*128)+128,0,255));case"s16":case"s16-planar":return(t,e,r)=>t.setInt16(e,ne(Math.round(r*32768),-32768,32767),!0);case"s32":case"s32-planar":return(t,e,r)=>t.setInt32(e,ne(Math.round(r*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(t,e,r)=>t.setFloat32(e,r,!0)}},va=i=>typeof AudioData<"u"&&i instanceof AudioData,Um=i=>{switch(i){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return i}},Qh=(i,t,e,r,n,a,s,o)=>{let c=Dm(e),l=Vm(r),u=Ct(e),d=Ct(r),m=ji(e);if(ji(r))if(m){let p=new ArrayBuffer(o*u),h=z(p);i.copyTo(p,{planeIndex:a,frameOffset:s,frameCount:o,format:e});for(let y=0;y<o;y++){let g=y*u,k=y*d,T=c(h,g);l(t,k,T)}}else{let p=new ArrayBuffer(o*n*u),h=z(p);i.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:o,format:e});for(let y=0;y<o;y++){let g=(y*n+a)*u,k=y*d,T=c(h,g);l(t,k,T)}}else if(m){let p=o*u,h=new ArrayBuffer(p),y=z(h);for(let g=0;g<n;g++){i.copyTo(h,{planeIndex:g,frameOffset:s,frameCount:o,format:e});for(let k=0;k<o;k++){let T=k*u,S=(k*n+g)*d,w=c(y,T);l(t,S,w)}}}else{let p=new ArrayBuffer(o*n*u),h=z(p);i.copyTo(p,{planeIndex:0,frameOffset:s,frameCount:o,format:e});for(let y=0;y<o;y++)for(let g=0;g<n;g++){let k=y*n+g,T=k*u,S=k*d,w=c(h,T);l(t,S,w)}}},zm=(i,t)=>{let e=i.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(e);return i.copyTo(r,{format:t,planeIndex:0}),new Ce({data:r,format:t,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration,_doNotCopy:!0})};var bo=new Map,yo=new Map,ko=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!ue.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${ue.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0)throw new TypeError("config.quality must be provided.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof de))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof de)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.width!==void 0&&(!Number.isInteger(i.transform.width)||i.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(i.transform.height!==void 0&&(!Number.isInteger(i.transform.height)||i.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(i.transform.fit!==void 0&&!["fill","contain","cover"].includes(i.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.transform.width!==void 0&&i.transform.height!==void 0&&i.transform.fit===void 0&&!["fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(i.transform.fit!==void 0&&["fill","contain","cover"].includes(i.sizeChangeBehavior)&&i.transform.fit!==i.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(i.transform.rotate!==void 0&&![0,90,180,270].includes(i.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(i.transform.flip!==void 0&&typeof i.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(i.transform.crop!==void 0&&ki(i.transform.crop,"config.transform."),i.transform.alpha!==void 0&&!["keep","discard"].includes(i.transform.alpha))throw new TypeError("config.transform.alpha, when provided, must be 'keep' or 'discard'.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(i.transform.frameRate!==void 0&&(!Number.isFinite(i.transform.frameRate)||i.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(i.transform.force!==void 0&&typeof i.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Hm(i.codec,i)},Hm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");if(t.alpha!==void 0&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.latencyMode!==void 0&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&ct(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`);if(t.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(t.contentHint!==void 0&&typeof t.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},Xl=i=>{let t=i.bitrateMode,e=i.quality._toVideoRateControl(i.codec,i.width,i.height,t),r=(a,s,o)=>({codec:i.fullCodecString??po(i.codec,i.width,i.height,o,i.alpha==="keep"),width:i.width,height:i.height,displayWidth:i.squarePixelWidth,displayHeight:i.squarePixelHeight,bitrate:a,bitrateMode:s,alpha:i.alpha??"discard",framerate:i.framerate,latencyMode:i.latencyMode,hardwareAcceleration:i.hardwareAcceleration,scalabilityMode:i.scalabilityMode,contentHint:i.contentHint,...Jm(i.codec)}),n=[];return e.quantizer!==null&&n.push({config:r(void 0,"quantizer",e.bitrate),quantizer:e.quantizer}),e.bitrateMode!=="quantizer"&&n.push({config:r(e.bitrate,e.bitrateMode,e.bitrate),quantizer:null}),b(n.length>0),n},To=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!pe.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${pe.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0&&!(se.includes(i.codec)||i.codec==="flac"||i.codec==="truehd"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(i.quality!==void 0&&t!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(i.quality!==void 0&&!(i.quality instanceof de))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof de)&&(!Number.isInteger(t)||t<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.numberOfChannels!==void 0&&(!Number.isInteger(i.transform.numberOfChannels)||i.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(i.transform.sampleRate!==void 0&&(!Number.isInteger(i.transform.sampleRate)||i.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(i.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(i.onEncodedSample!==void 0&&typeof i.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Wm(i.codec,i)},Wm=(i,t)=>{if(!t||typeof t!="object")throw new TypeError("Encoding options must be an object.");let e=t.bitrateMode;if(e!==void 0&&!["constant","variable"].includes(e))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(t.fullCodecString!==void 0&&typeof t.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(t.fullCodecString!==void 0&&ct(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},$l=i=>{let t=i.bitrateMode;return{codec:i.fullCodecString??ho(i.codec),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:i.quality?._toAudioBitrate(i.codec,i.numberOfChannels),bitrateMode:i.quality?._bitrateMode??t,...So(i.codec)}},de=class{constructor(t){if((typeof t=="number"||typeof t=="string")&&(t={quality:t}),!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.bitrateMode!==void 0&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in t){if(typeof t.quality=="string"?!Object.prototype.hasOwnProperty.call(Nm,t.quality):typeof t.quality!="number"||Number.isNaN(t.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(t.preferBitrate!==void 0&&typeof t.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in t||"quantizer"in t)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof t.quality=="string"?Nm[t.quality]:t.quality,this._preferBitrate=t.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(t.bitrate!==void 0&&(!Number.isInteger(t.bitrate)||t.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(t.quantizer!==void 0&&(!Number.isInteger(t.quantizer)||t.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(t.bitrate===void 0&&t.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in t)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=t.bitrate,this._quantizer=t.quantizer}this._bitrateMode=t.bitrateMode}_toVideoRateControl(t,e,r,n){let a=jh[t],s=null,o=this._bitrateMode??n??"variable";if(this._quantizer!==void 0){if(a)if(this._quantizer<a.min||this._quantizer>a.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${t}'; must be between ${a.min} and ${a.max}.`)}else s=this._quantizer,this._bitrate===void 0&&(o="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${t}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&a&&!this._preferBitrate&&(b(this._quality!==void 0),s=ne(Math.round(Md(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let l=this._quality;l===void 0&&(b(s!==null&&a),l=ne((s-a.worst)/(a.best-a.worst),0,1)),c=Lm(t,e,r,jl(l))}return{quantizer:s,bitrate:c,bitrateMode:o}}_toVideoBitrate(t,e,r){return this._bitrate!==void 0?this._bitrate:(b(this._quality!==void 0),Lm(t,e,r,jl(this._quality)))}_toAudioBitrate(t,e){if(se.includes(t)||t==="flac"||t==="truehd")return;if(this._bitrate!==void 0)return this._bitrate;if(this._quality===void 0)throw new Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");let r=jl(this._quality),a={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!a)throw new Error(`Unhandled codec: ${t}`);let s=a*r;return(t==="opus"||t==="vorbis")&&(s*=e/2),t==="aac"?s=[96e3,128e3,16e4,192e3].reduce((c,l)=>Math.abs(l-s)<Math.abs(c-s)?l:c):t==="opus"||t==="vorbis"?s=Math.max(6e3,s):t==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((c,l)=>Math.abs(l-s)<Math.abs(c-s)?l:c)),Math.round(s/1e3)*1e3}},Nm={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},jh={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:(Dd()??1/0)<145?{min:0,max:63,worst:52,best:20}:{min:0,max:255,worst:208,best:80},av1:{min:0,max:255,worst:208,best:80}},jl=i=>.3*Math.exp(2.5538*i),Lm=(i,t,e,r)=>{let n=t*e,a=1920*1080,s=3e6,o=Math.pow(n/a,.95),c=s*o,l={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/s},d=c*l[i]*r;return Math.ceil(d/1e3)*1e3},Yl=(i,t)=>{if(i==="avc")return{avc:{quantizer:t}};if(i==="hevc")return{hevc:{quantizer:t}};if(i==="vp9")return{vp9:{quantizer:t}};if(i==="av1")return{av1:{quantizer:t}};b(!1)},qm=new de("very-low"),Km=new de("low"),Gm=new de("medium"),Qm=new de("high"),jm=new de("very-high"),Xm=i=>{if(ue.includes(i))return Ma(i);if(pe.includes(i))return Ba(i);if(qe.includes(i))return Oa(i);throw new TypeError(`Unknown codec '${i}'.`)},Ma=async(i,t={})=>{let{width:e=1280,height:r=720,quality:n,bitrate:a,frameRate:s,...o}=t;if(!ue.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(n!==void 0&&!(n instanceof de))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof de)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(s!==void 0&&(!Number.isFinite(s)||s<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");Hm(i,o);let c=Ti(n,a)??new de("medium"),l;try{l=Xl({codec:i,width:e,height:r,quality:c,framerate:s,...o,alpha:"discard"})}catch{return!1}let u=JSON.stringify(l),d=bo.get(u);if(d)return d;let m=(async()=>{for(let{config:p}of l)if(On.some(h=>h.supports(i,p)))return!0;if(typeof VideoEncoder>"u"||(e%2===1||r%2===1)&&(i==="avc"||i==="hevc"))return!1;for(let{config:p,quantizer:h}of l){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!Wt()||await new Promise(async g=>{let k=new VideoEncoder({output:()=>{},error:()=>g(!1)});try{k.configure(p);let T=new Uint8Array(e*r*4),S=new VideoFrame(T,{format:"RGBA",codedWidth:e,codedHeight:r,timestamp:0});k.encode(S,h!==null?Yl(i,h):void 0),S.close(),await k.flush(),g(!0)}catch{g(!1)}finally{k.state!=="closed"&&k.close()}}))return!0}return!1})();return bo.set(u,m),m},Ba=async(i,t={})=>{let{numberOfChannels:e=2,sampleRate:r=48e3,quality:n,bitrate:a,...s}=t;if(!pe.includes(i))return!1;if(!Number.isInteger(e)||e<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("sampleRate must be a positive integer.");if(n!==void 0&&!(n instanceof de))throw new TypeError("quality, when provided, must be a Quality.");if(n!==void 0&&a!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(a!==void 0&&!(a instanceof de)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");Wm(i,s);let o=Ti(n,a)??new de("medium"),c=$l({codec:i,numberOfChannels:e,sampleRate:r,quality:o,...s}),l=JSON.stringify(c),u=yo.get(l);if(u)return u;let d=(async()=>{if(Dn.some(m=>m.supports(i,c))||se.includes(i))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return yo.set(l,d),d},Ti=(i,t)=>{if(i!==void 0)return i;if(t!==void 0)return t instanceof de?t:new de({bitrate:t})},Oa=async i=>!!qe.includes(i),$m=async()=>{let[i,t,e]=await Promise.all([Zl(),Bn(),Jl()]);return[...i,...t,...e]},Zl=async(i=ue,t)=>{let e=await Promise.all(i.map(r=>Ma(r,t)));return i.filter((r,n)=>e[n])},Bn=async(i=pe,t)=>{let e=await Promise.all(i.map(r=>Ba(r,t)));return i.filter((r,n)=>e[n])},Jl=async(i=qe)=>{let t=await Promise.all(i.map(Oa));return i.filter((e,r)=>t[r])},wo=async(i,t)=>{for(let e of i)if(await Ma(e,t))return e;return null},Ym=async(i,t)=>{for(let e of i)if(await Ba(e,t))return e;return null},Zm=async i=>{for(let t of i)if(await Oa(t))return t;return null};var Da=class{static supports(t,e){return!1}},Va=class{static supports(t,e){return!1}},Ua=class{static supports(t,e){return!1}},za=class{static supports(t,e){return!1}},bi=[],yi=[],On=[],Dn=[],ef=i=>{if(i.prototype instanceof Da){let t=i;if(bi.includes(t)){O._warn("Video decoder already registered.");return}bi.push(t),lo.clear()}else if(i.prototype instanceof Va){let t=i;if(yi.includes(t)){O._warn("Audio decoder already registered.");return}yi.push(t),uo.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},tf=i=>{if(i.prototype instanceof Ua){let t=i;if(On.includes(t)){O._warn("Video encoder already registered.");return}On.push(t),bo.clear()}else if(i.prototype instanceof za){let t=i;if(Dn.includes(t)){O._warn("Audio encoder already registered.");return}Dn.push(t),yo.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var Ae=new Uint8Array(0),ee=class i{constructor(t,e,r,n,a=-1,s,o){this.data=t;this.type=e;this.timestamp=r;this.duration=n;this.sequenceNumber=a;if(t===Ae&&s===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(s===void 0&&(s=t.byteLength),!(t instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(e!=="key"&&e!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Ae}get microsecondTimestamp(){return Math.trunc(ur*this.timestamp)}get microsecondDuration(){return Math.trunc(ur*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(t=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:t,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,e){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let r=new Uint8Array(t.byteLength);return t.copyTo(r),new i(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,e)}clone(t){if(t!==void 0&&(typeof t!="object"||t===null))throw new TypeError("options, when provided, must be an object.");if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(t?.type!==void 0&&t.type!=="key"&&t.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw new TypeError("options.duration, when provided, must be a number.");if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(t?.sideData!==void 0&&(typeof t.sideData!="object"||t.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new i(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,t?.data?.byteLength??this.byteLength,t?.sideData??this.sideData)}};var Ao=class{constructor(t){this.sourceSampleRate=null;this.sourceNumberOfChannels=null;this.startTime=null;this.bufferStartFrame=0;this.maxWrittenFrame=null;this.targetSampleRate=t.targetSampleRate,this.targetNumberOfChannels=t.targetNumberOfChannels,this.onSample=t.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels}doChannelMixerSetup(){b(this.sourceNumberOfChannels!==null);let t=this.sourceNumberOfChannels,e=this.targetNumberOfChannels;t===1&&e===2?this.channelMixer=(r,n)=>r[n*t]:t===1&&e===4?this.channelMixer=(r,n,a)=>r[n*t]*+(a<2):t===1&&e===6?this.channelMixer=(r,n,a)=>r[n*t]*+(a===2):t===2&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .5*(r[a]+r[a+1])}:t===2&&e===4?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===2&&e===6?this.channelMixer=(r,n,a)=>a<2?r[n*t+a]:0:t===4&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return .25*(r[a]+r[a+1]+r[a+2]+r[a+3])}:t===4&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return .5*(r[s+a]+r[s+a+2])}:t===4&&e===6?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]:a===2||a===3?0:r[s+a-2]}:t===6&&e===1?this.channelMixer=(r,n)=>{let a=n*t;return Math.SQRT1_2*(r[a]+r[a+1])+r[a+2]+.5*(r[a+4]+r[a+5])}:t===6&&e===2?this.channelMixer=(r,n,a)=>{let s=n*t;return r[s+a]+Math.SQRT1_2*(r[s+2]+r[s+a+4])}:t===6&&e===4?this.channelMixer=(r,n,a)=>{let s=n*t;return a<2?r[s+a]+Math.SQRT1_2*r[s+2]:r[s+a+2]}:this.channelMixer=(r,n,a)=>a<t?r[n*t+a]:0}ensureTempBufferSize(t){let e=this.tempSourceBuffer.length;for(;e<t;)e*=2;if(e!==this.tempSourceBuffer.length){let r=new Float32Array(e);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(t){if(this.sourceSampleRate===null){this.sourceSampleRate=t.sampleRate,this.sourceNumberOfChannels=t.numberOfChannels,this.startTime=t.timestamp;let l=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+l,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}b(this.startTime!==null);let e=t.numberOfFrames*t.numberOfChannels;this.ensureTempBufferSize(e);let r=t.allocationSize({planeIndex:0,format:"f32"}),n=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);t.copyTo(n,{planeIndex:0,format:"f32"});let a=Math.round((t.timestamp-this.startTime)*this.sourceSampleRate),s=a+t.numberOfFrames,o=Math.floor((a-1)*this.targetSampleRate/this.sourceSampleRate)+1,c=Math.ceil(s*this.targetSampleRate/this.sourceSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let u=l-this.bufferStartFrame;b(u<this.bufferCapacityInFrames);let d=l*this.sourceSampleRate/this.targetSampleRate-a,m=Math.floor(d),f=Math.ceil(d),p=d-m;for(let h=0;h<this.targetNumberOfChannels;h++){let y=0,g=0;m>=0&&m<t.numberOfFrames&&(y=this.channelMixer(n,m,h)),f>=0&&f<t.numberOfFrames&&(g=this.channelMixer(n,f,h));let k=y+p*(g-y),T=u*this.targetNumberOfChannels+h;this.outputBuffer[T]+=k}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;b(this.startTime!==null);let t=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,e=new Float32Array(t);e.set(this.outputBuffer.subarray(0,t));let r=new Ce({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:e,_doNotCopy:!0});await this.onSample(r),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}};var _e=class{constructor(t){this.input=t}dispose(){}};var xo=2082844800,Co=i=>{let e=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings)];e+=`; codecs="${r.join(", ")}"`}return e},Po=i=>{if(i.length<24)throw new Error("Invalid pssh box: too small.");let t=z(i),e=0,r=t.getUint8(e);e+=1,e+=3;let n=ci(i.subarray(e,e+16));e+=16;let a=null;if(r>0){let o=t.getUint32(e);if(e+=4,e+16*o+4>i.length)throw new Error("Invalid pssh box: key ID count exceeds box size.");if(o>0){a=[];for(let c=0;c<o;c++)a.push(ci(i.subarray(e,e+16))),e+=16}}let s=t.getUint32(e);return e+=4,{systemId:n,keyIds:a,data:i.slice(e,e+s)}},Eo=(i,t)=>{if(i.systemId!==t.systemId||!Vs(i.data,t.data))return!1;let e=i.keyIds,r=t.keyIds;return!e||!r?e===r:e.length===r.length&&e.every((n,a)=>n===r[a])};var Xt=16,Qr=new Uint32Array(256),Vn=new Uint32Array(256),Un=new Uint32Array(256),zn=new Uint32Array(256),Nn=new Uint32Array(256),Ke=new Uint32Array(256),rf=new Uint32Array(10),nf=!1,Xh=()=>{let i=new Uint8Array(256),t=new Uint8Array(256),e=new Uint8Array(256);for(let a=0,s=1;a<256;a++)e[a]=s,t[s]=a,s=s^s<<1^(s&128?283:0);let r=(a,s)=>a&&s?e[(t[a]+t[s])%255]:0;i[0]=99;for(let a=1;a<256;a++){let s=e[255-t[a]],o=s^s<<1^s<<2^s<<3^s<<4;o=o>>>8^o&255^99,i[a]=o}for(let a=0;a<256;a++){let s=i[a],o=i.indexOf(a);Qr[a]=s<<24|s<<16|s<<8|s,Ke[a]=o<<24|o<<16|o<<8|o;let c=r(o,14),l=r(o,9),u=r(o,13),d=r(o,11),m=c<<24|l<<16|u<<8|d;Vn[a]=m,Un[a]=m>>>8|m<<24,zn[a]=m>>>16|m<<16,Nn[a]=m>>>24|m<<8}let n=1;for(let a=0;a<10;a++)rf[a]=n<<24,n=n<<1^(n&128?283:0);nf=!0},Na=class{constructor(){this.roundkey=new Uint32Array(44);this.iv=new Uint32Array(Xt/Uint32Array.BYTES_PER_ELEMENT);this.in=new Uint8Array(Xt);this.out=new Uint8Array(Xt);this.inView=new DataView(this.in.buffer);this.outView=new DataView(this.out.buffer)}init({key:t,iv:e}){b(t.byteLength===16),b(e.byteLength===16),nf||Xh();let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=new DataView(e.buffer,e.byteOffset,e.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=n.getUint32(0,!1),this.iv[1]=n.getUint32(4,!1),this.iv[2]=n.getUint32(8,!1),this.iv[3]=n.getUint32(12,!1);for(let a=4;a<44;a+=4){let s=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^Qr[s>>>16&255]&4278190080^Qr[s>>>8&255]&16711680^Qr[s>>>0&255]&65280^Qr[s>>>24&255]&255^rf[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a<s;a+=4,s-=4)for(let o=0;o<4;o++){let c=this.roundkey[a+o];this.roundkey[a+o]=this.roundkey[s+o],this.roundkey[s+o]=c}for(let a=4;a<40;a+=4)for(let s=0;s<4;s++){let o=this.roundkey[a+s];this.roundkey[a+s]=Vn[Qr[o>>>24&255]&255]^Un[Qr[o>>>16&255]&255]^zn[Qr[o>>>8&255]&255]^Nn[Qr[o>>>0&255]&255]}}decrypt(){let t=this.inView.getUint32(0,!1)^this.roundkey[0],e=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],n=this.inView.getUint32(12,!1)^this.roundkey[3],a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1),l,u,d,m;for(let g=1;g<10;g++){let k=g*4;l=Vn[t>>>24]^Un[n>>>16&255]^zn[r>>>8&255]^Nn[e&255]^this.roundkey[k],u=Vn[e>>>24]^Un[t>>>16&255]^zn[n>>>8&255]^Nn[r&255]^this.roundkey[k+1],d=Vn[r>>>24]^Un[e>>>16&255]^zn[t>>>8&255]^Nn[n&255]^this.roundkey[k+2],m=Vn[n>>>24]^Un[r>>>16&255]^zn[e>>>8&255]^Nn[t&255]^this.roundkey[k+3],t=l,e=u,r=d,n=m}let f=Ke[t>>>24&255]&4278190080^Ke[n>>>16&255]&16711680^Ke[r>>>8&255]&65280^Ke[e>>>0&255]&255^this.roundkey[40],p=Ke[e>>>24&255]&4278190080^Ke[t>>>16&255]&16711680^Ke[n>>>8&255]&65280^Ke[r>>>0&255]&255^this.roundkey[41],h=Ke[r>>>24&255]&4278190080^Ke[e>>>16&255]&16711680^Ke[t>>>8&255]&65280^Ke[n>>>0&255]&255^this.roundkey[42],y=Ke[n>>>24&255]&4278190080^Ke[r>>>16&255]&16711680^Ke[e>>>8&255]&65280^Ke[t>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,h^this.iv[2],!1),this.outView.setUint32(12,y^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=o,this.iv[3]=c}},af=(i,t,e)=>{let r=!1,n=!1,a=0,s=2**16,o=16,c=new Na,l=()=>{n||(n=!0,e())};return new ReadableStream({pull:async u=>{try{let d=r?null:Promise.resolve(t());d?.catch(()=>{});let m=s+o,f=i.requestSliceRange(a,0,m);if(R(f)&&(f=await f),!f||f.length===0)throw new Error("Invalid ciphertext.");let p=f.length;if(p%16!==0)throw new Error("Invalid ciphertext.");let h=p===m?p-o:p,y=V(f,h),g=new Uint8Array(h);d&&(c.init(await d),r=!0);for(let k=0;k<h;k+=16)c.in.set(y.subarray(k,k+16)),c.decrypt(),g.set(c.out,k);if(h<p)u.enqueue(g),a+=h;else{let k=g[h-1];if(k===0||k>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let T=g.subarray(0,h-k);u.enqueue(T),u.close(),l()}}catch(d){throw l(),d}},cancel:()=>{l()}})};var sf=[2,1,1,2,2,2,2,1,1,2,2,1,1],$h=64,_o=class i extends _e{constructor(e){super(e);this.moovSlice=null;this.currentTrack=null;this.tracks=[];this.idToTrack=new Map;this.metadataPromise=null;this.movieTimescale=-1;this.movieDurationInTimescale=-1;this.movieMatrix=si;this.isQuickTime=!1;this.metadataTags={};this.currentMetadataKeys=null;this.isFragmented=!1;this.fragmentTrackDefaults=new Map;this.psshBoxes=[];this.currentFragment=null;this.isReadingTraf=!1;this.currentFragmentTrackState=null;this.lastReadFragment=null;this.fragmentSummaries=new Map;this.decryptionKeyCache=new Map;this.boxNestingDepth=0;this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),r=await Promise.all(e.map(n=>n.getDecoderConfig().then(a=>a?.codec??null)));return Co({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(n=>n.info?.type==="video"),hasAudio:this.tracks.some(n=>n.info?.type==="audio"),codecStrings:r.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,r=!1,n=!1;for(;;){let a=this.reader.requestSliceRange(e,Ot,kr);if(R(a)&&(a=await a),!a)break;let s=e,o=jr(a);if(!o)break;if((o.name==="ftyp"||o.name==="styp")&&a.remainingLength>=4){let c=ae(a,4);this.isQuickTime=c==="qt "}else if(o.name==="moov"){let c=this.reader.requestSlice(a.filePos,o.contentSize);if(R(c)&&(c=await c),!c)break;if(this.moovSlice=c,this.readContiguousBoxes(this.moovSlice),this.movieTimescale===-1)throw new Error("Invalid moov box: missing mvhd box.");for(let l of this.tracks){let u=l.editListPreviousSegmentDurations/this.movieTimescale;l.editListOffset-=Math.round(u*l.timescale)}r=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+o.totalSize,n=!0;break}else if(o.name==="moof"){if(!this.input._initInput)throw new 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.');await this.copyMetadataFromInitInput(this.input._initInput),r=!1,n=!0;break}e=s+o.totalSize}if(!n){if(!this.input._initInput)throw new Error('No "moov" box found; the file is invalid or incomplete.');await this.copyMetadataFromInitInput(this.input._initInput)}if(r){b(this.reader.fileSize!==null);let a=this.reader.requestSlice(this.reader.fileSize-4,4);R(a)&&(a=await a),b(a);let s=B(a),o=this.reader.fileSize-s;if(o>=0&&o<=this.reader.fileSize-kr){let c=this.reader.requestSliceRange(o,Ot,kr);if(R(c)&&(c=await c),c){let l=jr(c);if(l&&l.name==="mfra"){let u=this.reader.requestSlice(c.filePos,l.contentSize);R(u)&&(u=await u),u&&this.readContiguousBoxes(u)}}}}for(let a of this.tracks){let s=a.fragmentLookupTable;s.sort((c,l)=>c.timestamp-l.timestamp);let o=0;for(let c of s)(o===0||c.timestamp!==s[o-1].timestamp)&&(s[o++]=c);s.length=o}})()}async copyMetadataFromInitInput(e){let r=await e._getDemuxer();if(r.constructor!==i)throw new Error("Init input must match the input's format.");await r.readMetadata(),this.movieTimescale=r.movieTimescale,this.movieDurationInTimescale=r.movieDurationInTimescale,this.movieMatrix=r.movieMatrix,this.metadataTags=r.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=r.fragmentTrackDefaults,this.psshBoxes=r.psshBoxes;for(let n of r.tracks){let a={id:n.id,demuxer:this,trackBacking:null,disposition:n.disposition,timescale:n.timescale,durationInMediaTimescale:n.durationInMediaTimescale,durationInMovieTimescale:n.durationInMovieTimescale,matrix:n.matrix,internalCodecId:n.internalCodecId,name:n.name,languageCode:n.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:n.editListPreviousSegmentDurations,editListOffset:n.editListOffset,encryptionInfo:n.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:n.maxBitrate,avgBitrate:n.avgBitrate,info:n.info};if(n.trackBacking){if(b(a.info),a.info.type==="video"&&a.info.width!==-1){let s=a;a.trackBacking=new Fo(s),this.tracks.push(a),this.idToTrack.set(a.id,a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){let s=a;a.trackBacking=new Mo(s),this.tracks.push(a),this.idToTrack.set(a.id,a)}}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],sampleCount:0,cumulativeSampleSizes:null,keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],sortedCompositionTimeOffsets:null};if(e.sampleTable=r,e.sampleTableByteOffset===null)return r;b(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e;try{this.traverseBox(n)}catch(l){throw e.sampleTable=null,l}finally{this.currentTrack=null}let a=J(r.sampleTimingEntries),s=X(r.sampleToChunk,r.chunkOffsets.length-1,l=>l.startChunkIndex),o=r.sampleToChunk[s];if(r.sampleCount=Math.min(r.sampleCount,a?a.startIndex+a.count:0,o?o.startSampleIndex+(r.chunkOffsets.length-o.startChunkIndex)*o.samplesPerChunk:0),lf(r.sampleTimingEntries,r.sampleCount),lf(r.sampleCompositionTimeOffsets,r.sampleCount),e.info?.type==="audio"&&e.info.codec&&se.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0&&r.sampleTimingEntries.length>0){b(e.info?.type==="audio");let l=Me(e.info.codec),u=[],d=[];for(let m=0;m<r.sampleToChunk.length;m++){let f=r.sampleToChunk[m],p=r.sampleToChunk[m+1],h=Math.min(p?p.startChunkIndex:1/0,r.chunkOffsets.length)-f.startChunkIndex,y=d.length;for(let g=0;g<h;g++){let k=f.startSampleIndex+g*f.samplesPerChunk,T=k+f.samplesPerChunk,S=X(r.sampleTimingEntries,k,M=>M.startIndex),w=r.sampleTimingEntries[S],A=X(r.sampleTimingEntries,T,M=>M.startIndex),C=r.sampleTimingEntries[A],E=w.startDecodeTimestamp+(k-w.startIndex)*w.delta,x=C.startDecodeTimestamp+(T-C.startIndex)*C.delta-E,P=J(u);P&&P.delta===x?P.count++:u.push({startIndex:d.length,startDecodeTimestamp:E,count:1,delta:x});let _=Math.round(x*e.info.sampleRate/e.timescale)*l.sampleSize*e.info.numberOfChannels;d.push(_)}f.startSampleIndex=y,f.samplesPerChunk=1}r.sampleTimingEntries=u,r.sampleSizes=d,r.sampleCount=d.length}if(r.sampleCompositionTimeOffsets.length>0){let l=r.sampleCompositionTimeOffsets,u=J(l),d=u.startIndex+u.count;d<r.sampleCount&&l.push({startIndex:d,count:r.sampleCount-d,offset:0,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1});let m=l.filter(g=>g.count>0),f=r.sampleTimingEntries,p=0,h=g=>{for(;p+1<f.length&&f[p+1].startIndex<=g;)p++;let k=f[p];return k.startDecodeTimestamp+(g-k.startIndex)*k.delta};for(let g of m){let k=g.startIndex+g.count-1;g.startTimestamp=h(g.startIndex)+g.offset,g.lastTimestamp=h(k)+g.offset}m.sort((g,k)=>g.startTimestamp-k.startTimestamp||g.startIndex-k.startIndex);let y=-1/0;for(let g of m)y=Math.max(y,g.lastTimestamp),g.maxLastTimestamp=y;r.sortedCompositionTimeOffsets=m}if(r.sampleSizes.length>1){r.cumulativeSampleSizes=[0];for(let l=0;l<r.sampleSizes.length;l++)r.cumulativeSampleSizes.push(r.cumulativeSampleSizes[l]+r.sampleSizes[l])}return r}readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment.promise;let r=(async()=>{let n=this.reader.requestSliceRange(e,Ot,kr);R(n)&&(n=await n),b(n);let a=jr(n);b(a?.name==="moof");let s=this.reader.requestSlice(e,a.totalSize);if(R(s)&&(s=await s),!s)return null;this.traverseBox(s);let o=this.currentFragment;b(o&&o.moofOffset===e),this.currentFragment=null,this.fragmentSummaries.set(e,{moofSize:o.moofSize,trackIds:new Set(o.trackData.keys())});for(let[,c]of o.trackData){let l=c.track,{fragmentPositionCache:u}=l;if(!c.startTimestampIsFinal){let p=Vr(l.fragmentLookupTable,o.moofOffset,g=>g.moofOffset),h=l.fragmentLookupTable[p];if(h&&c.trunSampleCounts.length>=h.trunNumber&&c.trunSampleCounts[h.trunNumber-1]>=h.sampleNumber){let g=0;for(let S=1;S<h.trunNumber;S++)g+=c.trunSampleCounts[S-1];g+=h.sampleNumber-1;let k=c.samples[g];b(k);let T=h.timestamp-k.presentationTimestamp;Io(c,T)}else{let g=X(u,o.moofOffset-1,k=>k.moofOffset);if(g!==-1){let k=u[g];Io(c,k.endDecodeTimestamp)}else{let k=J(this.getSampleTableForTrack(l).sampleTimingEntries);if(k){let{startDecodeTimestamp:T,count:S,delta:w}=k;Io(c,T+S*w)}}}c.startTimestampIsFinal=!0}let d=X(u,c.startTimestamp,p=>p.startTimestamp),m=u[d],f=u[d+1];if((!m||m.moofOffset<o.moofOffset)&&(!f||f.moofOffset>o.moofOffset)&&u.splice(d+1,0,{moofOffset:o.moofOffset,startTimestamp:c.startTimestamp,endDecodeTimestamp:c.endDecodeTimestamp,hasKeyFrame:c.firstKeyFrameTimestamp!==null}),c.encryptionAuxInfo&&l.encryptionInfo){let p=await gf(this.reader,l.encryptionInfo,c.encryptionAuxInfo);for(let h=0;h<Math.min(c.samples.length,p.length);h++){let y=p[h];c.samples[h].encryption=y}}}return o})();return this.lastReadFragment={moofOffset:e,promise:r},r.catch(()=>{this.lastReadFragment?.promise===r&&(this.lastReadFragment=null)}),r}readContiguousBoxes(e){if(this.boxNestingDepth===$h)throw new Error("Invalid file: boxes are nested too deeply.");let r=e.filePos;this.boxNestingDepth++;try{for(;e.filePos-r<=e.length-Ot&&this.traverseBox(e););}finally{this.boxNestingDepth--}}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Ot;){let n=e.filePos,a=jr(e);if(!a)break;yield{boxInfo:a,slice:e},e.filePos=n+a.totalSize}}traverseBox(e){let r=e.filePos,n=jr(e);if(!n)return!1;let a=e.filePos,s=r+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mvhd":{let o=H(e);e.skip(3);let c;if(o===1?(c=Ge(e),e.skip(8),this.movieTimescale=B(e),this.movieDurationInTimescale=Ge(e)):(c=B(e),e.skip(4),this.movieTimescale=B(e),this.movieDurationInTimescale=B(e)),c!==0&&(this.metadataTags.creationTime=new Date(1e3*(c-xo))),this.movieTimescale===0)throw new Error("Invalid mvhd box: timescale must not be 0.");e.skip(8+2*4),this.movieMatrix=of(e)}break;case"trak":{if(this.currentFragment||this.currentTrack)break;let o={id:-1,demuxer:this,trackBacking:null,disposition:{...Ve,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:si,internalCodecId:null,name:null,languageCode:le,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate:null};if(this.currentTrack=o,this.readContiguousBoxes(e.slice(a,n.contentSize)),o.id!==-1&&o.timescale!==-1&&o.info!==null&&o.sampleTableByteOffset!==-1){if(o.info.type==="video"&&o.info.width!==-1){let c=o;o.trackBacking=new Fo(c),this.tracks.push(o),this.idToTrack.set(o.id,o)}else if(o.info.type==="audio"&&o.info.numberOfChannels!==-1){let c=o;o.trackBacking=new Mo(c),this.tracks.push(o),this.idToTrack.set(o.id,o)}}this.currentTrack=null}break;case"tkhd":{let o=this.currentTrack;if(!o||this.currentFragment)break;let c=H(e),u=!!($t(e)&1);if(o.disposition.default=u,c===0)e.skip(8),o.id=B(e),e.skip(4),o.durationInMovieTimescale=B(e);else if(c===1)e.skip(16),o.id=B(e),e.skip(4),o.durationInMovieTimescale=Ge(e);else throw new Error(`Incorrect track header version ${c}.`);e.skip(2*4+2+2+2+2);let d=of(e);o.matrix=sr(d,this.movieMatrix)}break;case"elst":{let o=this.currentTrack;if(!o)break;let c=H(e);e.skip(3);let l=!1,u=0,d=B(e);for(let m=0;m<d;m++){let f=c===1?Ge(e):B(e),p=c===1?yf(e):Xr(e),h=wi(e);if(l){O._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(p===-1){u+=f;continue}if(h!==1){O._warn("Unsupported edit list entry: media rate must be 1.");break}o.editListPreviousSegmentDurations=u,o.editListOffset=p,l=!0}}break;case"mdhd":{let o=this.currentTrack;if(!o)break;let c=H(e);if(e.skip(3),c===0?(e.skip(8),o.timescale=B(e),o.durationInMediaTimescale=B(e)):c===1&&(e.skip(16),o.timescale=B(e),o.durationInMediaTimescale=Ge(e)),o.durationInMediaTimescale===2**(c===1?64:32)-1&&(o.durationInMediaTimescale=-1),o.timescale===0)throw new Error("Invalid mdhd box: timescale must not be 0.");let l=fe(e);if(l>0){o.languageCode="";for(let u=0;u<3;u++)o.languageCode=String.fromCharCode(96+(l&31))+o.languageCode,l>>=5;Ur(o.languageCode)||(o.languageCode=le)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let c=ae(e,4);c==="vide"?o.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Fs},avcType:null,avcCodecInfo:null,hevcType:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:c==="soun"&&(o.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let o=this.currentTrack;if(!o)break;o.sampleTableByteOffset=r,this.readContiguousBoxes(e.slice(a,n.contentSize))}break;case"stsd":{let o=this.currentTrack;if(!o||o.info===null||o.sampleTable)break;let c=H(e);e.skip(3);let l=B(e);for(let u=0;u<l;u++){let d=e.filePos,m=jr(e);if(!m)break;o.internalCodecId=m.name;let f=m.name.toLowerCase();if(o.info.type==="video"){e.skip(6*1+2+2+2+3*4),o.info.width=fe(e),o.info.height=fe(e),o.info.squarePixelWidth=o.info.width,o.info.squarePixelHeight=o.info.height,e.skip(50),o.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+m.totalSize-e.filePos));let p=f==="encv"?o.frmaCodecString:f;o.frmaCodecString=null,p==="avc1"||p==="avc3"?(o.info.codec="avc",o.info.avcType=p==="avc1"?1:3):p==="hvc1"||p==="hev1"?(o.info.codec="hevc",o.info.hevcType=p):p==="vp08"?o.info.codec="vp8":p==="vp09"?o.info.codec="vp9":p==="av01"?o.info.codec="av1":$r.includes(f)?(o.info.codec="prores",o.info.proresFormat=f):p===null?O._warn("Unknown encrypted video codec due to missing frma box."):O._warn(`Unsupported video codec (sample entry type '${m.name}').`)}else{e.skip(6*1+2);let p=fe(e);e.skip(3*2);let h=fe(e),y=fe(e);e.skip(2*2);let g=B(e)/65536,k=null;c===0&&p>0&&(p===1?(e.skip(4),y=8*B(e),e.skip(2*4)):p===2&&(e.skip(4),g=Oo(e),h=B(e),e.skip(4),y=B(e),k=B(e),e.skip(2*4))),o.info.numberOfChannels=h,o.info.sampleRate=g||o.timescale,o.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+m.totalSize-e.filePos));let T=f==="enca"?o.frmaCodecString:f;if(o.frmaCodecString=null,T!=="mp4a")if(T===".mp3")o.info.codec="mp3";else if(T==="opus")o.info.codec="opus",o.info.sampleRate=tt;else if(T==="flac")o.info.codec="flac";else if(T==="ulaw")o.info.codec="ulaw";else if(T==="alaw")o.info.codec="alaw";else if(T==="ac-3")o.info.codec="ac3";else if(T==="ec-3")o.info.codec="eac3";else if(Ha.includes(T))o.info.codec="dts",o.info.dtsFormat=T;else if(T==="mlpa")o.info.codec="truehd";else if(T==="twos")y===8?o.info.codec="pcm-s8":y===16?o.info.codec=o.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(O._warn(`Unsupported sample size ${y} for codec 'twos'.`),o.info.codec=null);else if(T==="sowt")y===8?o.info.codec="pcm-s8":y===16?o.info.codec="pcm-s16":(O._warn(`Unsupported sample size ${y} for codec 'sowt'.`),o.info.codec=null);else if(T==="raw ")o.info.codec="pcm-u8";else if(T==="in24")o.info.codec=o.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(T==="in32")o.info.codec=o.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(T==="fl32")o.info.codec=o.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(T==="fl64")o.info.codec=o.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(T==="ipcm"){let S=o.info.pcmSampleSize;o.info.pcmLittleEndian?S===16?o.info.codec="pcm-s16":S===24?o.info.codec="pcm-s24":S===32?o.info.codec="pcm-s32":(O._warn(`Invalid ipcm sample size ${S}.`),o.info.codec=null):S===16?o.info.codec="pcm-s16be":S===24?o.info.codec="pcm-s24be":S===32?o.info.codec="pcm-s32be":(O._warn(`Invalid ipcm sample size ${S}.`),o.info.codec=null)}else if(T==="fpcm"){let S=o.info.pcmSampleSize;o.info.pcmLittleEndian?S===32?o.info.codec="pcm-f32":S===64?o.info.codec="pcm-f64":(O._warn(`Invalid fpcm sample size ${S}.`),o.info.codec=null):S===32?o.info.codec="pcm-f32be":S===64?o.info.codec="pcm-f64be":(O._warn(`Invalid fpcm sample size ${S}.`),o.info.codec=null)}else if(T==="lpcm"&&k!==null){let S=y+7>>3,w=!!(k&1),A=!!(k&2),C=k&4?-1:0;y>0&&y<=64&&(w?y===32?o.info.codec=A?"pcm-f32be":"pcm-f32":y===64&&(o.info.codec=A?"pcm-f64be":"pcm-f64"):C&1<<S-1?S===1?o.info.codec="pcm-s8":S===2?o.info.codec=A?"pcm-s16be":"pcm-s16":S===3?o.info.codec=A?"pcm-s24be":"pcm-s24":S===4&&(o.info.codec=A?"pcm-s32be":"pcm-s32"):S===1&&(o.info.codec="pcm-u8")),o.info.codec===null&&O._warn("Unsupported PCM format.")}else T===null?O._warn("Unknown encrypted audio codec due to missing frma box."):O._warn(`Unsupported audio codec (sample entry type '${m.name}').`)}e.filePos=d+m.totalSize}}break;case"frma":{let o=this.currentTrack;if(!o)break;let l=ae(e,4).toLowerCase();o.frmaCodecString=l}break;case"schm":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=ae(e,4);c==="cenc"||c==="cens"||c==="cbcs"?o.encryptionInfo={scheme:c,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:O._warn(`Unsupported encryption scheme '${c}'.`)}break;case"tenc":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=H(e);e.skip(3),e.skip(1);let l=H(e);if(c>0?(o.encryptionInfo.defaultCryptByteBlock=l>>4,o.encryptionInfo.defaultSkipByteBlock=l&15):(o.encryptionInfo.defaultCryptByteBlock=0,o.encryptionInfo.defaultSkipByteBlock=0),o.encryptionInfo.defaultIsProtected=H(e)!==0,o.encryptionInfo.defaultPerSampleIvSize=H(e),o.encryptionInfo.defaultKid=ci(V(e,16)),o.encryptionInfo.defaultPerSampleIvSize>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");if(o.encryptionInfo.defaultIsProtected&&o.encryptionInfo.defaultPerSampleIvSize===0){let u=H(e);if(u>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");let d=new Uint8Array(16);d.set(V(e,u),0),o.encryptionInfo.defaultConstantIv=d}}break;case"avcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video"||n.contentSize===0)break;o.info.codecDescription=V(e,n.contentSize);let c=gr(o.info.codecDescription)?.sequenceParameterSets[0],l=c&&Gt(c);l&&cf(o,l.pixelAspectRatio)}break;case"hvcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video"||n.contentSize===0)break;o.info.codecDescription=V(e,n.contentSize);let c=vn(o.info.codecDescription)?.arrays.find(u=>u.nalUnitType===33)?.nalUnits[0],l=c&&Qi(c);l&&cf(o,l.pixelAspectRatio)}break;case"vpcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;e.skip(4);let c=H(e),l=H(e),u=H(e),d=u>>4,m=u>>1&7,f=u&1,p=H(e),h=H(e),y=H(e);o.info.vp9CodecInfo={profile:c,level:l,bitDepth:d,chromaSubsampling:m,videoFullRangeFlag:f,colourPrimaries:p,transferCharacteristics:h,matrixCoefficients:y}}break;case"av1C":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;e.skip(1);let c=H(e),l=c>>5,u=c&31,d=H(e),m=d>>7,f=d>>6&1,p=d>>5&1,h=d>>4&1,y=d>>3&1,g=d>>2&1,k=d&3,T=l===2&&f?p?12:10:f?10:8;e.skip(1);let S=V(e,n.contentSize-4),w=hi(S);o.info.av1CodecInfo={profile:l,level:u,tier:m,bitDepth:T,monochrome:h,chromaSubsamplingX:y,chromaSubsamplingY:g,chromaSamplePosition:k,videoFullRangeFlag:w?.videoFullRangeFlag??0,colourPrimaries:w?.colourPrimaries??2,transferCharacteristics:w?.transferCharacteristics??2,matrixCoefficients:w?.matrixCoefficients??2}}break;case"colr":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=ae(e,4);if(c!=="nclx"&&c!=="nclc")break;let l=fe(e),u=fe(e),d=fe(e),m;c==="nclx"&&(m=!!(H(e)&128)),o.info.colorSpace={primaries:Tt[l],transfer:wt[u],matrix:St[d],fullRange:m}}break;case"pasp":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=B(e),l=B(e);c>0&&l>0&&(o.info.squarePixelWidth=o.info.width,o.info.squarePixelHeight=o.info.height,c>l?o.info.squarePixelWidth=Math.round(o.info.width*c/l):o.info.squarePixelHeight=Math.round(o.info.height*l/c))}break;case"btrt":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=B(e),l=B(e);o.maxBitrate=c>0?c:null,o.avgBitrate=l>0?l:null}break;case"wave":this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"esds":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4);let{objectTypeIndication:c,decoderSpecificInfo:l}=Do(e);if(c===64||c===103?(o.info.codec="aac",o.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?o.info.codec="mp3":c===221?o.info.codec="vorbis":c===169?o.info.codec="dts":O._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),l&&(o.info.codecDescription=l,o.info.codec==="aac")){let u=xt(o.info.codecDescription);u.outputNumberOfChannels!==null&&(o.info.numberOfChannels=u.outputNumberOfChannels),u.outputSampleRate!==null&&(o.info.sampleRate=u.outputSampleRate)}}break;case"enda":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;o.info.pcmLittleEndian=!!(fe(e)&255)}break;case"pcmC":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4);let c=H(e);o.info.pcmLittleEndian=!!(c&1),o.info.pcmSampleSize=H(e)}break;case"srat":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4),o.info.sampleRate=B(e)}break;case"dOps":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(1);let c=H(e),l=fe(e),u=B(e),d=La(e),m=H(e),f=m!==0?V(e,n.contentSize-11):new Uint8Array(0),p=new Uint8Array(19+f.byteLength),h=new DataView(p.buffer);h.setUint32(0,1332770163,!1),h.setUint32(4,1214603620,!1),h.setUint8(8,1),h.setUint8(9,c),h.setUint16(10,l,!0),h.setUint32(12,u,!0),h.setInt16(16,d,!0),h.setUint8(18,m),p.set(f,19),o.info.codecDescription=p,o.info.numberOfChannels=c}break;case"dfLa":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(4);let c=127,l=128,u=e.filePos;for(;e.filePos<s;){let h=H(e),y=$t(e);if((h&c)===0){e.skip(10);let k=B(e),T=k>>>12,S=(k>>9&7)+1;o.info.sampleRate=T,o.info.numberOfChannels=S,e.skip(20)}else e.skip(y);if(h&l)break}let d=e.filePos;e.filePos=u;let m=V(e,d-u),f=new Uint8Array(4+m.byteLength);new DataView(f.buffer).setUint32(0,1716281667,!1),f.set(m,4),o.info.codecDescription=f}break;case"dac3":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=V(e,3),l=new K(c),u=l.readBits(2);l.skipBits(8);let d=l.readBits(3),m=l.readBits(1);u<3&&(o.info.sampleRate=Ki[u]),o.info.numberOfChannels=Ta[d]+m}break;case"dec3":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=V(e,n.contentSize),l=hm(c);if(!l){O._warn("Invalid dec3 box contents, ignoring.");break}let u=to(l);u!==null&&(o.info.sampleRate=u),o.info.numberOfChannels=ro(l)}break;case"ddts":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=V(e,Math.min(n.contentSize,no)),l=ym(c);if(!l){O._warn("Invalid ddts box contents, ignoring.");break}o.info.sampleRate=l.sampleRate,l.numberOfChannels!==null&&(o.info.numberOfChannels=l.numberOfChannels)}break;case"dmlp":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=B(e),l=c>>>28;if(l===15){O._warn("Invalid dmlp box contents, ignoring.");break}o.info.sampleRate=(l&8?44100:48e3)<<(l&7);let u=c>>>15&31,m=c&8191||u,f=0;for(let p=0;p<sf.length;p++)m&1<<p&&(f+=sf[p]);o.info.numberOfChannels=f}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=0,u=0;for(let d=0;d<c;d++){let m=B(e),f=B(e);o.sampleTable.sampleTimingEntries.push({startIndex:l,startDecodeTimestamp:u,count:m,delta:f}),l+=m,u+=m*f}}break;case"ctts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=0;for(let u=0;u<c;u++){let d=B(e),m=Xr(e);o.sampleTable.sampleCompositionTimeOffsets.push({startIndex:l,count:d,offset:m,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1}),l+=d}}break;case"stsz":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=B(e);if(c===0)for(let u=0;u<l;u++){let d=B(e);o.sampleTable.sampleSizes.push(d)}else o.sampleTable.sampleSizes.push(c);o.sampleTable.sampleCount=l}break;case"stz2":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),e.skip(3);let c=H(e),l=B(e);if(c!==4&&c!==8&&c!==16)throw new Error(`Invalid stz2 box: unsupported field size ${c}.`);let u=V(e,Math.ceil(l*c/8)),d=new K(u);for(let m=0;m<l;m++){let f=d.readBits(c);o.sampleTable.sampleSizes.push(f)}o.sampleTable.sampleCount=l}break;case"stss":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),o.sampleTable.keySampleIndices=[];let c=B(e);for(let l=0;l<c;l++){let u=B(e)-1;o.sampleTable.keySampleIndices.push(u)}o.sampleTable.keySampleIndices.sort((l,u)=>l-u),o.sampleTable.keySampleIndices[0]!==0&&o.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e),l=0;for(let d=0;d<c;d++){let m=B(e)-1,f=B(e),p=B(e),h=J(o.sampleTable.sampleToChunk);if(h&&m<=h.startChunkIndex){l++;continue}o.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:m,samplesPerChunk:f,sampleDescriptionIndex:p})}l>0&&O._warn(`Skipped ${l} invalid stsc entries whose chunk indices weren't strictly increasing.`);let u=0;for(let d=0;d<o.sampleTable.sampleToChunk.length;d++)if(o.sampleTable.sampleToChunk[d].startSampleIndex=u,d<o.sampleTable.sampleToChunk.length-1){let f=o.sampleTable.sampleToChunk[d+1].startChunkIndex-o.sampleTable.sampleToChunk[d].startChunkIndex;u+=f*o.sampleTable.sampleToChunk[d].samplesPerChunk}}break;case"stco":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e);for(let l=0;l<c;l++){let u=B(e);o.sampleTable.chunkOffsets.push(u)}}break;case"co64":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=B(e);for(let l=0;l<c;l++){let u=Ge(e);o.sampleTable.chunkOffsets.push(u)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mehd":{let o=H(e);e.skip(3);let c=o===1?Ge(e):B(e);this.movieDurationInTimescale=c}break;case"trex":{e.skip(4);let o=B(e),c=B(e),l=B(e),u=B(e),d=B(e);this.fragmentTrackDefaults.set(o,{trackId:o,defaultSampleDescriptionIndex:c,defaultSampleDuration:l,defaultSampleSize:u,defaultSampleFlags:d})}break;case"tfra":{let o=H(e);e.skip(3);let c=B(e),l=this.idToTrack.get(c);if(!l)break;let u=B(e),d=(u&48)>>4,m=(u&12)>>2,f=u&3,p=[H,fe,$t,B],h=p[d],y=p[m],g=p[f],k=B(e);for(let T=0;T<k;T++){let S=o===1?Ge(e):B(e),w=o===1?Ge(e):B(e);h(e);let A=y(e),C=g(e);A>=1&&C>=1&&l.fragmentLookupTable.push({timestamp:S,moofOffset:w,trunNumber:A,sampleNumber:C})}}break;case"moof":{if(this.currentFragment)break;this.currentFragment={moofOffset:r,moofSize:n.totalSize,implicitBaseDataOffset:r,trackData:new Map,psshBoxes:[],sampleCount:0};try{this.readContiguousBoxes(e.slice(a,n.contentSize))}catch(o){throw this.currentFragment=null,o}finally{this.currentTrack=null,this.currentFragmentTrackState=null}}break;case"traf":{if(!this.currentFragment||this.isReadingTraf)break;this.isReadingTraf=!0;try{this.readContiguousBoxes(e.slice(a,n.contentSize))}finally{this.isReadingTraf=!1}let o=this.currentFragmentTrackState;if(this.currentFragmentTrackState=null,this.currentTrack){b(o);let c=this.currentFragment.trackData.get(this.currentTrack.id);e:if(c){if(c.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}c.presentationTimestamps=c.samples.map((d,m)=>({presentationTimestamp:d.presentationTimestamp,sampleIndex:m})).sort((d,m)=>d.presentationTimestamp-m.presentationTimestamp);for(let d=0;d<c.presentationTimestamps.length;d++){let m=c.presentationTimestamps[d],f=c.samples[m.sampleIndex];if(c.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(c.firstKeyFrameTimestamp=f.presentationTimestamp),d<c.presentationTimestamps.length-1){let h=c.presentationTimestamps[d+1].presentationTimestamp-m.presentationTimestamp;f.duration=h}}let l=c.samples[c.presentationTimestamps[0].sampleIndex],u=c.samples[J(c.presentationTimestamps).sampleIndex];c.startTimestamp=l.presentationTimestamp,c.endTimestamp=u.presentationTimestamp+u.duration,c.endDecodeTimestamp=o.currentTimestamp,o.startTimestamp!==null&&(Io(c,o.startTimestamp),c.startTimestampIsFinal=!0),o.encryptionAuxInfo&&!c.samples[0].encryption&&(c.encryptionAuxInfo=o.encryptionAuxInfo)}this.currentTrack=null}}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let o=Po(V(e,n.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(o):this.currentTrack||this.psshBoxes.push(o)}break;case"tfhd":{if(!this.currentFragment||!this.isReadingTraf||this.currentFragmentTrackState)break;e.skip(1);let o=$t(e),c=!!(o&1),l=!!(o&2),u=!!(o&8),d=!!(o&16),m=!!(o&32),f=!!(o&65536),p=!!(o&131072),h=B(e),y=this.fragmentTrackDefaults.get(h),g={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:y?.defaultSampleDescriptionIndex??null,defaultSampleDuration:y?.defaultSampleDuration??null,defaultSampleSize:y?.defaultSampleSize??null,defaultSampleFlags:y?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null,currentOffset:null,currentTimestamp:0};this.currentFragmentTrackState=g,c?g.baseDataOffset=Ge(e):p&&(g.baseDataOffset=this.currentFragment.moofOffset),l&&(g.sampleDescriptionIndex=B(e)),u&&(g.defaultSampleDuration=B(e)),d&&(g.defaultSampleSize=B(e)),m&&(g.defaultSampleFlags=B(e)),f&&(g.defaultSampleDuration=0);let k=this.idToTrack.get(h);if(!k)break;if(this.currentFragment.trackData.has(h)){O._warn(`Multiple traf boxes for track ${h} in the same moof box; ignoring the samples of all but the first.`);break}this.currentTrack=k}break;case"tfdt":{if(!this.currentFragmentTrackState)break;let o=H(e);e.skip(3);let c=o===0?B(e):Ge(e);this.currentFragmentTrackState.startTimestamp=c}break;case"trun":{let o=this.currentFragmentTrackState;if(!o||!this.currentFragment)break;let c=this.currentTrack;e.skip(1);let l=$t(e),u=!!(l&1),d=!!(l&4),m=!!(l&256),f=!!(l&512),p=!!(l&1024),h=!!(l&2048),y=B(e),{defaultSampleDuration:g,defaultSampleSize:k,defaultSampleFlags:T}=o;if(y>0&&(!m&&g===null||!f&&k===null||!p&&T===null))throw new Error("Invalid trun box: sample values are missing and there are no defaults.");if(this.currentFragment.sampleCount+=y,this.currentFragment.sampleCount>2**20)throw new Error("Too many (> 2^20) samples in fragment.");let S=null;u&&(S=Xr(e));let w=null;d&&(w=B(e));let A=S!==null?o.baseDataOffset+S:o.currentOffset??o.baseDataOffset,C=null;c&&(C=this.currentFragment.trackData.get(c.id)??null,C||(C={track:c,startTimestamp:0,endTimestamp:0,endDecodeTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,trunSampleCounts:[],encryptionAuxInfo:null},this.currentFragment.trackData.set(c.id,C)),C.trunSampleCounts.push(y));for(let E=0;E<y;E++){let I;m?I=B(e):I=g;let x;f?x=B(e):x=k;let P;p?P=B(e):P=T,E===0&&w!==null&&(P=w);let v=0;h&&(v=Xr(e)),C?.samples.push({presentationTimestamp:o.currentTimestamp+v,duration:I,byteOffset:A,byteSize:x,isKeyFrame:!(P&65536),encryption:null}),A+=x,o.currentTimestamp+=I}o.currentOffset=A,this.currentFragment.implicitBaseDataOffset=A}break;case"saiz":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;if(e.skip(1),$t(e)&1){let f=ae(e,4),p=B(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let l=H(e),u=B(e),d=null;l===0&&u>0&&(d=V(e,u));let m=uf(o,this.currentFragmentTrackState);m.defaultSampleInfoSize=l,m.sampleSizes=d,m.sampleCount=u}break;case"saio":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=H(e);if($t(e)&1){let f=ae(e,4),p=B(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let u=B(e);if(u===0)break;u>1&&O._warn("Multiple saio entries are not supported; using the first offset only.");let d=c===0?B(e):Number(Ge(e));this.currentFragment&&(b(this.currentFragmentTrackState),d+=this.currentFragmentTrackState.baseDataOffset);let m=uf(o,this.currentFragmentTrackState);m.offset=d}break;case"senc":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=this.currentFragment?.trackData.get(o.id);if(!c)break;e.skip(1);let u=!!($t(e)&2),d=B(e),m=o.encryptionInfo.defaultPerSampleIvSize;if(m===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");for(let f=0;f<Math.min(d,c.samples.length);f++){let p=new Uint8Array(16);if(m>0)p.set(V(e,m),0);else if(o.encryptionInfo.defaultConstantIv)p.set(o.encryptionInfo.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let h=null;if(u){let g=fe(e);h=[];for(let k=0;k<g;k++){let T=fe(e),S=B(e);h.push({clearLen:T,protectedLen:S})}}let y=c.samples[f];y.encryption={iv:p,subsamples:h}}}break;case"udta":{let o=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(let{boxInfo:c,slice:l}of o){if(c.name!=="meta"&&!this.currentTrack){let u=l.filePos;this.metadataTags.raw??={},c.name[0]==="\xA9"?this.metadataTags.raw[c.name]??=Pt(l):this.metadataTags.raw[c.name]??=V(l,c.contentSize),l.filePos=u}switch(c.name){case"meta":l.skip(-c.headerSize),this.traverseBox(l);break;case"\xA9nam":this.currentTrack?this.currentTrack.name=Pt(l):this.metadataTags.title??=Pt(l);break;case"name":this.currentTrack?this.currentTrack.name=be.decode(V(l,c.contentSize)):this.metadataTags.title??=Pt(l);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Pt(l));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Pt(l));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Pt(l));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Pt(l));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Pt(l));break;case"\xA9day":if(!this.currentTrack){let u=Kt(Pt(l));u&&(this.metadataTags.date??=u)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Pt(l));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Pt(l));break}}}break;case"meta":{if(this.currentTrack)break;let c=B(e)!==0;this.currentMetadataKeys=new Map,c?this.readContiguousBoxes(e.slice(a,n.contentSize)):this.readContiguousBoxes(e.slice(a+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let o=B(e);for(let c=0;c<o;c++){let l=B(e);if(l<8)throw new Error("Invalid keys box: key size must be at least 8.");e.skip(4);let u=be.decode(V(e,l-8));this.currentMetadataKeys.set(c+1,u)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let o=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(let{boxInfo:c,slice:l}of o){let u=c.name,d=(u.charCodeAt(0)<<24)+(u.charCodeAt(1)<<16)+(u.charCodeAt(2)<<8)+u.charCodeAt(3);this.currentMetadataKeys.has(d)&&(u=this.currentMetadataKeys.get(d));let m=kf(l);switch(this.metadataTags.raw??={},this.metadataTags.raw[u]??=m,u){case"\xA9nam":case"titl":case"com.apple.quicktime.title":case"title":typeof m=="string"&&(this.metadataTags.title??=m);break;case"\xA9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof m=="string"&&(this.metadataTags.description??=m);break;case"\xA9ART":case"com.apple.quicktime.artist":case"artist":typeof m=="string"&&(this.metadataTags.artist??=m);break;case"\xA9alb":case"albm":case"com.apple.quicktime.album":case"album":typeof m=="string"&&(this.metadataTags.album??=m);break;case"aART":case"album_artist":typeof m=="string"&&(this.metadataTags.albumArtist??=m);break;case"\xA9cmt":case"com.apple.quicktime.comment":case"comment":typeof m=="string"&&(this.metadataTags.comment??=m);break;case"\xA9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof m=="string"&&(this.metadataTags.genre??=m);break;case"\xA9lyr":case"lyrics":typeof m=="string"&&(this.metadataTags.lyrics??=m);break;case"\xA9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof m=="string"){let f=Kt(m);f&&(this.metadataTags.date??=f)}break;case"tmpo":if(m instanceof Uint8Array&&m.length>=2){let f=z(m).getInt16(0,!1);f>0&&(this.metadataTags.beatsPerMinute??=f)}break;case"covr":case"com.apple.quicktime.artwork":m instanceof At?(this.metadataTags.images??=[],this.metadataTags.images.push({data:m.data,kind:"coverFront",mimeType:m.mimeType})):m instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:m,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof m=="string"){let f=m.split("/"),p=Number.parseInt(f[0],10),h=f[1]&&Number.parseInt(f[1],10);Number.isInteger(p)&&p>0&&(this.metadataTags.trackNumber??=p),h&&Number.isInteger(h)&&h>0&&(this.metadataTags.tracksTotal??=h)}break;case"trkn":if(m instanceof Uint8Array&&m.length>=6){let f=z(m),p=f.getUint16(2,!1),h=f.getUint16(4,!1);p>0&&(this.metadataTags.trackNumber??=p),h>0&&(this.metadataTags.tracksTotal??=h)}break;case"disc":case"disk":if(m instanceof Uint8Array&&m.length>=6){let f=z(m),p=f.getUint16(2,!1),h=f.getUint16(4,!1);p>0&&(this.metadataTags.discNumber??=p),h>0&&(this.metadataTags.discsTotal??=h)}break}}}break}return e.filePos=s,!0}},Ro=class{constructor(t){this.internalTrack=t;this.packetToSampleIndex=new WeakMap;this.packetToFragmentLocation=new WeakMap;this.nextEac3Frames=new WeakMap}getNumber(){let t=this.internalTrack.demuxer,e=this.internalTrack.trackBacking.getType(),r=0;for(let n of t.tracks)if(n.trackBacking.getType()===e&&r++,n===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){let t=this.internalTrack;return t.durationInMediaTimescale<=0||t.demuxer.isFragmented&&t.demuxer.getSampleTableForTrack(t).sampleCount>0?null:(b(t.trackBacking),((await t.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+t.durationInMediaTimescale/t.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){let e=await this.fetchPacketForSampleIndex(0,t);return e||!this.internalTrack.demuxer.isFragmented?e:this.fetchFirstFragmentedPacket(!1,t)}mapTimestampIntoTimescale(t){return Fe(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,e){let r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=eu(n,r),s=await this.fetchPacketForSampleIndex(a,e,r);if(!this.internalTrack.demuxer.isFragmented)return s;let o=await this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=X(l.presentationTimestamps,r,f=>f.presentationTimestamp),d=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,m=u!==-1&&r<l.endTimestamp;return{sampleIndex:d,correctSampleFound:m}},r,r,e);return!s||!o?s??o:s.timestamp>o.timestamp?s:o}async getNextPacket(t,e){let r=this.nextEac3Frames.get(t);if(r)return r;let n=this.packetToSampleIndex.get(t);if(n!==void 0){let s=await this.fetchPacketForSampleIndex(n+1,e);return s||!this.internalTrack.demuxer.isFragmented?s:this.fetchFirstFragmentedPacket(!1,e)}let a=this.packetToFragmentLocation.get(t);if(a===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,s=>{if(s===a.fragment){let o=s.trackData.get(this.internalTrack.id);if(a.sampleIndex+1<o.samples.length)return{sampleIndex:a.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}async getKeyPacket(t,e){let r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Yh(n,r),s=await this.fetchPacketForSampleIndex(a,e,r);if(!this.internalTrack.demuxer.isFragmented)return s;let o=await this.performFragmentedLookup(null,c=>{let l=c.trackData.get(this.internalTrack.id);if(!l)return{sampleIndex:-1,correctSampleFound:!1};let u=lr(l.presentationTimestamps,f=>l.samples[f.sampleIndex].isKeyFrame&&f.presentationTimestamp<=r),d=u!==-1?l.presentationTimestamps[u].sampleIndex:-1,m=u!==-1&&r<l.endTimestamp;return{sampleIndex:d,correctSampleFound:m}},r,r,e,!0);return!s||!o?s??o:s.timestamp>o.timestamp?s:o}async getNextKeyPacket(t,e){let r=this.nextEac3Frames.get(t);if(r)return r;let n=this.packetToSampleIndex.get(t);if(n!==void 0){let s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),o=eg(s,n),c=await this.fetchPacketForSampleIndex(o,e);return c||!this.internalTrack.demuxer.isFragmented?c:this.fetchFirstFragmentedPacket(!0,e)}let a=this.packetToFragmentLocation.get(t);if(a===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,s=>{if(s===a.fragment){let o=s.trackData.get(this.internalTrack.id);for(let c=a.sampleIndex+1;c<o.samples.length;c++)if(o.samples[c].isKeyFrame)return{sampleIndex:c,correctSampleFound:!0}}else{let o=s.trackData.get(this.internalTrack.id);if(o&&o.firstKeyFrameTimestamp!==null){let c=o.samples.findIndex(l=>l.isKeyFrame);return b(c!==-1),{sampleIndex:c,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}fetchFirstFragmentedPacket(t,e){return this.performFragmentedLookup(null,r=>{let a=r.trackData.get(this.internalTrack.id)?.samples.findIndex(s=>!t||s.isKeyFrame)??-1;return{sampleIndex:a,correctSampleFound:a!==-1}},-1/0,1/0,e)}async fetchPacketForSampleIndex(t,e,r=-1/0){if(t===-1)return null;let n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Zh(n,t);if(!a)return null;let s=this.internalTrack.demuxer.reader.fileSize;if(s!==null&&a.sampleOffset+a.sampleSize>s)return null;let o;if(e.metadataOnly&&this.internalTrack.info?.codec!=="eac3")o=Ae;else{let d=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);if(R(d)&&(d=await d),!d)return null;if(o=V(d,a.sampleSize),this.internalTrack.encryptionInfo){let m=null;if(this.internalTrack.encryptionAuxInfo){let f=await gf(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);t<f.length&&(m=f[t])}m??=df(this.internalTrack.encryptionInfo),m&&(o=await mf(this.internalTrack,m,o,null))}}let c=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=a.duration/this.internalTrack.timescale,u=new ee(o,a.isKeyFrame?"key":"delta",c,l,t,a.sampleSize);return this.internalTrack.info?.codec==="eac3"?this.splitEac3Sample(u,e,r,this.packetToSampleIndex,t):(this.packetToSampleIndex.set(u,t),u)}async fetchPacketInFragment(t,e,r,n){if(e===-1)return null;let s=t.trackData.get(this.internalTrack.id).samples[e];b(s);let o=this.internalTrack.demuxer.reader.fileSize;if(o!==null&&s.byteOffset+s.byteSize>o)return null;let c;if(r.metadataOnly&&this.internalTrack.info?.codec!=="eac3")c=Ae;else{let m=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(R(m)&&(m=await m),!m)return null;if(c=V(m,s.byteSize),this.internalTrack.encryptionInfo){let f=s.encryption??df(this.internalTrack.encryptionInfo);f&&(c=await mf(this.internalTrack,f,c,t))}}let l=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,u=s.duration/this.internalTrack.timescale,d=new ee(c,s.isKeyFrame?"key":"delta",l,u,t.moofOffset+e,s.byteSize);return this.internalTrack.info?.codec==="eac3"?this.splitEac3Sample(d,r,n,this.packetToFragmentLocation,{fragment:t,sampleIndex:e}):(this.packetToFragmentLocation.set(d,{fragment:t,sampleIndex:e}),d)}async performFragmentedLookup(t,e,r,n,a,s=!1){let{demuxer:o,fragmentLookupTable:c,fragmentPositionCache:l}=this.internalTrack,u=null,d=-1;if(t){let{sampleIndex:h,correctSampleFound:y}=e(t);if(y)return this.fetchPacketInFragment(t,h,a,r);h!==-1&&(u=t,d=h)}let m=X(c,r,h=>h.timestamp),f=X(l,r,h=>h.startTimestamp),p=1/0;for(;;){for(;m!==-1&&c[m].moofOffset>=p;)m--;for(;f!==-1&&(l[f].moofOffset>=p||s&&!l[f].hasKeyFrame);)f--;let h=Math.max(c[m]?.moofOffset??0,l[f]?.moofOffset??0)||null,y,g=null;t?h===null||t.moofOffset>=h?(y=t.moofOffset+t.moofSize,g=t):y=h:y=h??0;let k=g?g.moofOffset:y;for(;y<p;){if(g){let C=g.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>n)break;g=null}let T=o.fragmentSummaries.get(y);if(T&&!T.trackIds.has(this.internalTrack.id)){y+=T.moofSize;continue}let S=o.reader.requestSliceRange(y,Ot,kr);if(R(S)&&(S=await S),!S)break;let w=y,A=jr(S);if(!A)break;if(A.name==="moof"){if(g=await o.readFragment(w),!g)break;let{sampleIndex:C,correctSampleFound:E}=e(g);if(E)return this.fetchPacketInFragment(g,C,a,r);C!==-1&&(u=g,d=C)}y=w+A.totalSize}if(h===null||u&&u.moofOffset>=h)break;p=k,t=null}return u?this.fetchPacketInFragment(u,d,a,r):null}splitEac3Sample(t,e,r,n,a){let s=this.internalTrack.info;b(s?.type==="audio");let o=eo(t.data)??[{offset:0,size:t.data.byteLength,blockCount:6}],c=(r-this.internalTrack.editListOffset)/this.internalTrack.timescale,l=null,u=null,d=0;for(let m=0;m<o.length;m++){let f=o[m],p=t.timestamp+256*d/s.sampleRate,h=o.length===1?t.duration:256*f.blockCount/s.sampleRate,y=new ee(e.metadataOnly?Ae:t.data.subarray(f.offset,f.offset+f.size),"key",p,h,8*t.sequenceNumber+m,f.size);n.set(y,a),u&&this.nextEac3Frames.set(u,y),(m===0||p<=c)&&(l=y),u=y,d+=f.blockCount}return b(l),l}},Fo=class extends Ro{constructor(e){super(e);this.decoderConfigPromise=null}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}getTransformationMatrix(){return[...this.internalTrack.matrix]}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=r&&hr(r.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=r&&br(r.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!um(this.internalTrack.info.vp9CodecInfo))){let r=await this.getFirstPacket({}),n=r&&_n(r.data);n&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??n,videoFullRangeFlag:n.videoFullRangeFlag,colourPrimaries:n.colourPrimaries,transferCharacteristics:n.transferCharacteristics,matrixCoefficients:n.matrixCoefficients})}else if(this.internalTrack.info.codec==="av1"&&(!this.internalTrack.info.av1CodecInfo||!Qs(this.internalTrack.info.av1CodecInfo))){let r=await this.getFirstPacket({}),n=r&&hi(r.data);n&&(this.internalTrack.info.av1CodecInfo=n)}else if(this.internalTrack.info.codec==="prores"&&!this.internalTrack.info.proresCodecInfo){let r=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=r&&js(r.data)}if(!wn(this.internalTrack.info.colorSpace)){let r=Vo(this.internalTrack.info);this.internalTrack.info.colorSpace.primaries??=r.primaries,this.internalTrack.info.colorSpace.transfer??=r.transfer,this.internalTrack.info.colorSpace.matrix??=r.matrix,this.internalTrack.info.colorSpace.fullRange??=r.fullRange}let e={codec:Si(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};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},Mo=class extends Ro{constructor(e){super(e);this.decoderConfigPromise=null}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&ao(e.data)}return{codec:Ln(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},eu=(i,t)=>{if(i.sortedCompositionTimeOffsets)return pf(i,t,!1);{let e=X(i.sampleTimingEntries,t,n=>n.startDecodeTimestamp);if(e===-1)return-1;let r=i.sampleTimingEntries[e];return r.delta===0?r.startIndex+r.count-1:r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Yh=(i,t)=>{if(!i.keySampleIndices)return eu(i,t);if(i.sortedCompositionTimeOffsets)return pf(i,t,!0);{let e=eu(i,t),r=X(i.keySampleIndices,e,n=>n);return i.keySampleIndices[r]??-1}},Zh=(i,t)=>{if(t>=i.sampleCount)return null;let e=X(i.sampleTimingEntries,t,y=>y.startIndex),r=i.sampleTimingEntries[e],a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,s=X(i.sampleCompositionTimeOffsets,t,y=>y.startIndex),o=i.sampleCompositionTimeOffsets[s];o&&t-o.startIndex<o.count&&(a+=o.offset);let c=i.sampleSizes[Math.min(t,i.sampleSizes.length-1)],l=X(i.sampleToChunk,t,y=>y.startSampleIndex),u=i.sampleToChunk[l],d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),m=i.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,p=m;i.sampleSizes.length===1?p+=c*(t-f):p+=i.cumulativeSampleSizes[t]-i.cumulativeSampleSizes[f];let h=r.delta;if(i.sortedCompositionTimeOffsets){let y=Jh(i,t,a);y!==null&&(h=y-a)}return{presentationTimestamp:a,duration:h,sampleOffset:p,sampleSize:c,chunkOffset:m,isKeyFrame:i.keySampleIndices?Vr(i.keySampleIndices,t,y=>y)!==-1:!0}},pf=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=-1,a=-1/0,s=X(r,t,o=>o.startTimestamp);for(let o=s;o>=0;o--){let c=r[o];if(c.maxLastTimestamp<a)break;let l=c.lastTimestamp<=t?c.startIndex+c.count-1:hf(i,c,(d,m)=>m>t)-1;if(e){let d=X(i.keySampleIndices,l,m=>m);l=i.keySampleIndices[d]??-1}if(l<c.startIndex)continue;let u=tu(i,l)+c.offset;(u>a||u===a&&l>n)&&(n=l,a=u)}return n},Jh=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=X(r,e,s=>s.startTimestamp),a=r[n+1]?.startTimestamp??null;for(let s=n;s>=0;s--){let o=r[s];if(o.maxLastTimestamp<e)break;let c=hf(i,o,(u,d)=>d>e||d===e&&u>t);if(c===o.startIndex+o.count)continue;let l=tu(i,c)+o.offset;(a===null||l<a)&&(a=l)}return a},hf=(i,t,e)=>{let r=t.startIndex,n=t.startIndex+t.count;for(;r<n;){let a=Math.floor((r+n)/2);e(a,tu(i,a)+t.offset)?n=a:r=a+1}return r},tu=(i,t)=>{let e=X(i.sampleTimingEntries,t,n=>n.startIndex),r=i.sampleTimingEntries[e];return r.startDecodeTimestamp+(t-r.startIndex)*r.delta},eg=(i,t)=>{if(!i.keySampleIndices)return t+1;let e=X(i.keySampleIndices,t,r=>r);return i.keySampleIndices[e+1]??-1},Io=(i,t)=>{i.startTimestamp+=t,i.endTimestamp+=t,i.endDecodeTimestamp+=t;for(let e of i.samples)e.presentationTimestamp+=t;for(let e of i.presentationTimestamps)e.presentationTimestamp+=t},of=i=>[wi(i),wi(i),vo(i),wi(i),wi(i),vo(i),wi(i),wi(i),vo(i)],cf=(i,t)=>{let e=i.info;if(e.type!=="video")return;let{num:r,den:n}=t;!(r>0&&n>0)||r===n||(r>n?(e.squarePixelWidth=Math.round(e.width*r/n),e.squarePixelHeight=e.height):(e.squarePixelWidth=e.width,e.squarePixelHeight=Math.round(e.height*n/r)))},lf=(i,t)=>{for(;i.length>0&&J(i).startIndex>=t;)i.pop();let e=J(i);e&&(e.count=Math.min(e.count,t-e.startIndex))},uf=(i,t)=>t?t.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:i.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},gf=async(i,t,e)=>{if(e.resolved)return e.resolved;if(e.offset===null||e.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(e.defaultSampleInfoSize>0)r=e.defaultSampleInfoSize*e.sampleCount;else{b(e.sampleSizes);for(let o=0;o<e.sampleCount;o++)r+=e.sampleSizes[o]}let n=i.requestSlice(e.offset,r);if(R(n)&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");let a=t.defaultPerSampleIvSize;if(a===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");let s=[];for(let o=0;o<e.sampleCount;o++){let c=e.defaultSampleInfoSize>0?e.defaultSampleInfoSize:e.sampleSizes[o],l=new Uint8Array(16);if(a>0)l.set(V(n,a),0);else if(t.defaultConstantIv)l.set(t.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let u=null;if(c>a){let d=fe(n);u=[];for(let m=0;m<d;m++){let f=fe(n),p=B(n);u.push({clearLen:f,protectedLen:p})}}s.push({iv:l,subsamples:u})}return e.resolved=s,s},df=i=>i.defaultConstantIv?{iv:i.defaultConstantIv,subsamples:null}:null,mf=async(i,t,e,r)=>{b(i.encryptionInfo);let n=i.encryptionInfo;if(n.defaultKid===null)throw new Error("Invalid file: encrypted track is missing its tenc box.");let a=n.defaultKid,s,o=i.demuxer.decryptionKeyCache.get(a);if(o)s=await o;else{if(!i.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let c=(async()=>{let l=i.demuxer.psshBoxes;if(r){l=[...l,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(a));for(let d=0;d<l.length-1;d++)for(let m=d+1;m<l.length;m++)Eo(l[d],l[m])&&(l.splice(m,1),m--)}let u=await i.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:l});if(!(typeof u=="string"&&u.length===32&&Pd.test(u)||u instanceof Uint8Array&&u.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return u instanceof Uint8Array?u:Ed(u)})();i.demuxer.decryptionKeyCache.set(a,c),s=await c}return n.scheme==="cenc"||n.scheme==="cens"?tg(s,n,t,e):rg(s,n,t,e)},tg=async(i,t,e,r)=>{let n=new Uint8Array(16);n.set(e.iv,0);let a=await crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["decrypt"]),s=async p=>{let h=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},a,p);return new Uint8Array(h)};if(!e.subsamples)return s(r);b(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let o=bf(e.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock,r.length),c=0;for(let p of o)for(let h of p.perSubsample)c+=h.length;let l=new Uint8Array(c),u=0;for(let p of o)for(let h of p.perSubsample)l.set(r.subarray(h.offset,h.offset+h.length),u),u+=h.length;let d=await s(l),m=new Uint8Array(r),f=0;for(let p of o)for(let h of p.perSubsample)m.set(d.subarray(f,f+h.length),h.offset),f+=h.length;return m},rg=(i,t,e,r)=>{let n=new Na;n.init({key:i,iv:e.iv});let a=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(b(a!==null&&s!==null),!e.subsamples){let u=new Uint8Array(r),d=Math.floor(r.length/16);for(let m=0;m<d;m++){let f=m*16;n.in.set(r.subarray(f,f+16)),n.decrypt(),u.set(n.out,f)}return u}if(a===0&&s===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(r),c=bf(e.subsamples,a,s,r.length),l=new DataView(e.iv.buffer,e.iv.byteOffset,16);for(let u of c){n.iv[0]=l.getUint32(0,!1),n.iv[1]=l.getUint32(4,!1),n.iv[2]=l.getUint32(8,!1),n.iv[3]=l.getUint32(12,!1);for(let d of u.perSubsample){let m=d.length/16;for(let f=0;f<m;f++){let p=d.offset+f*16;n.in.set(r.subarray(p,p+16)),n.decrypt(),o.set(n.out,p)}}}return o},bf=(i,t,e,r)=>{let n=[],a=t!==0||e!==0,s=0;for(let o of i){if(s+o.clearLen+o.protectedLen>r)throw new Error("Invalid encryption info: subsamples exceed the sample size.");s+=o.clearLen;let c=[];if(!a)o.protectedLen>0&&c.push({offset:s,length:o.protectedLen}),s+=o.protectedLen;else{let l=o.protectedLen,u=s;for(;l>0&&!(l<16*t);){let d=16*t;c.push({offset:u,length:d}),u+=d,l-=d;let m=Math.min(16*e,l);u+=m,l-=m}s+=o.protectedLen}n.push({perSubsample:c})}return n};var Tr=class{constructor(t){this.value=t}},$i=class{constructor(t){this.value=t}},Hn=class{constructor(t){this.value=t}},Dt=class{constructor(t){this.value=t}};var au=[440786851,408125543],Wn=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],Wa=[...au,...Wn],Uo=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,ru=i=>i<1n<<8n?1:i<1n<<16n?2:i<1n<<24n?3:i<1n<<32n?4:i<1n<<40n?5:i<1n<<48n?6:i<1n<<56n?7:8,iu=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-(1<<20)&&i<1<<20?3:i>=-(1<<27)&&i<1<<27?4:i>=-(2**34)&&i<2**34?5:6,Ai=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)},zo=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap;this.dataOffsets=new WeakMap}writeByte(t){this.helperView.setUint8(0,t),this.writer.write(this.helper.subarray(0,1))}writeFloat32(t){this.helperView.setFloat32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(t){this.helperView.setFloat64(0,t,!1),this.writer.write(this.helper)}writeUnsignedInt(t,e=Uo(t)){let r=0;switch(e){case 6:this.helperView.setUint8(r++,t/2**40|0);case 5:this.helperView.setUint8(r++,t/2**32|0);case 4:this.helperView.setUint8(r++,t>>24);case 3:this.helperView.setUint8(r++,t>>16);case 2:this.helperView.setUint8(r++,t>>8);case 1:this.helperView.setUint8(r++,t);break;default:throw new Error("Bad unsigned int size "+e)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(t,e=ru(t)){let r=0;for(let n=e-1;n>=0;n--)this.helperView.setUint8(r++,Number(t>>BigInt(n*8)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(t,e=iu(t)){t<0&&(t+=2**(e*8)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=Ai(t)){if(t>=2**(7*e)-1)throw new Error(`EBML variable-size integer ${t} doesn't fit into ${e} bytes.`);let r=0;switch(e){case 1:this.helperView.setUint8(r++,128|t);break;case 2:this.helperView.setUint8(r++,64|t>>8),this.helperView.setUint8(r++,t);break;case 3:this.helperView.setUint8(r++,32|t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 4:this.helperView.setUint8(r++,16|t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 5:this.helperView.setUint8(r++,8|t/2**32&7),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;case 6:this.helperView.setUint8(r++,4|t/2**40&3),this.helperView.setUint8(r++,t/2**32|0),this.helperView.setUint8(r++,t>>24),this.helperView.setUint8(r++,t>>16),this.helperView.setUint8(r++,t>>8),this.helperView.setUint8(r++,t);break;default:throw new Error("Bad EBML varint size "+e)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(t){this.writer.write(new Uint8Array(t.split("").map(e=>e.charCodeAt(0))))}writeEBML(t){if(t!==null)if(t instanceof Uint8Array)this.writer.write(t);else if(Array.isArray(t))for(let e of t)this.writeEBML(e);else if(this.offsets.set(t,this.writer.getPos()),this.writeUnsignedInt(t.id),Array.isArray(t.data))if(t.size===void 0)this.writeVarInt(nu(t.data)),this.dataOffsets.set(t,this.writer.getPos()),this.writeEBML(t.data);else{let e=this.writer.getPos(),r=t.size===-1?1:t.size;t.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);let n=this.writer.getPos();if(this.dataOffsets.set(t,n),this.writeEBML(t.data),t.size!==-1){let a=this.writer.getPos()-n,s=this.writer.getPos();this.writer.seek(e),this.writeVarInt(a,r),this.writer.seek(s)}}else if(typeof t.data=="number"){let e=t.size??Uo(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if(typeof t.data=="bigint"){let e=t.size??ru(t.data);this.writeVarInt(e),this.writeUnsignedBigInt(t.data,e)}else if(typeof t.data=="string")this.writeVarInt(t.data.length),this.writeAsciiString(t.data);else if(t.data instanceof Uint8Array)this.writeVarInt(t.data.byteLength,t.size),this.writer.write(t.data);else if(t.data instanceof Tr)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof $i)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof Hn){let e=t.size??iu(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Dt){let e=Y.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else Z(t.data)}},nu=i=>{if(i===null)return 0;if(i instanceof Uint8Array)return i.byteLength;if(Array.isArray(i))return i.reduce((r,n)=>r+nu(n),0);let t,e;return Array.isArray(i.data)?(t=nu(i.data),e=i.size===void 0?Ai(t):i.size===-1?1:i.size):typeof i.data=="number"?(t=i.size??Uo(i.data),e=Ai(t)):typeof i.data=="bigint"?(t=i.size??ru(i.data),e=Ai(t)):typeof i.data=="string"?(t=i.data.length,e=Ai(t)):i.data instanceof Uint8Array?(t=i.data.byteLength,e=i.size??Ai(t)):i.data instanceof Tr?(t=4,e=1):i.data instanceof $i?(t=8,e=1):i.data instanceof Hn?(t=i.size??iu(i.data.value),e=Ai(t)):(b(i.data instanceof Dt),t=Y.encode(i.data.value).length,e=Ai(t)),Uo(i.id)+e+t},No=Date.UTC(2001,0,1),Tf=8,lt=2,Yt=2*Tf,su=i=>{if(i.remainingLength<1)return null;let t=H(i);if(i.skip(-1),t===0)return null;let e=1,r=128;for(;(t&r)===0;)e++,r>>=1;return i.remainingLength<e?null:e},qn=i=>{if(i.remainingLength<1)return null;let t=H(i);if(t===0)return null;let e=1,r=128;for(;(t&r)===0;)e++,r>>=1;if(i.remainingLength<e-1)return null;let n=t&r-1;for(let a=1;a<e;a++)n*=256,n+=H(i);return n},$=(i,t)=>{if(t>8)throw new Error("Bad unsigned int size "+t);let e=0;for(let r=0;r<t;r++)e*=256,e+=H(i);return e},ou=(i,t)=>{if(t>8)throw new Error("Bad unsigned int size "+t);let e=0n;for(let r=0;r<t;r++)e<<=8n,e+=BigInt(H(i));return e};var wf=(i,t)=>t===0?0n:BigInt.asIntN(8*t,ou(i,t)),Sf=i=>{let t=su(i);return t===null||i.remainingLength<t?null:$(i,t)},cu=i=>{let t=i.filePos,e=qn(i);if(e===null)return null;let r=i.filePos-t;if(e!==2**(7*r)-1)return e},Vt=i=>{b(i.remainingLength>=lt);let t=Sf(i);if(t===null)return null;let e=cu(i);return e===null?null:{id:t,size:e}},xi=(i,t)=>{let e=V(i,t),r="";for(let n=0;n<t&&e[n]!==0;n++)r+=String.fromCharCode(e[n]);return r},Yi=(i,t)=>{let e=V(i,t),r=0;for(;r<t&&e[r]!==0;)r+=1;return be.decode(e.subarray(0,r))},Zi=(i,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw new Error("Bad float size "+t);return t===4?Af(i):Oo(i)},Lo=async(i,t,e,r)=>{let n=new Set(e),a=t;for(;r===null||a<r;){let s=i.requestSliceRange(a,lt,Yt);if(R(s)&&(s=await s),!s)break;let o=Vt(s);if(!o)break;if(n.has(o.id))return{pos:a,found:!0};wr(o.size),a=s.filePos+o.size}return{pos:r!==null&&r>a?r:a,found:!1}},lu=async(i,t,e,r)=>{let a=new Set(e),s=t;for(;s<r;){let o=i.requestSliceRange(s,0,Math.min(65536,r-s));if(R(o)&&(o=await o),!o||o.length===0)break;let c=Math.max(o.length-Tf,1);for(let l=0;l<c;l++){o.filePos=s;let u=Sf(o);if(u!==null&&a.has(u))return s;s++}}return null},Be={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS",truehd:"A_TRUEHD","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 wr(i){if(i===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var Ho=i=>{let e=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){let r=[...new Set(i.codecStrings.filter(Boolean))];e+=`; codecs="${r.join(", ")}"`}return e};var uu=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],Cf=10*2**20,ig=64,Wo=class extends _e{constructor(e){super(e);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.currentProjection=null;this.currentTagTargetIsMovie=!0;this.currentSimpleTagName=null;this.currentAttachedFile=null;this.isWebM=!1;this.claimedSeekTargets=new Set;this.elementNestingDepth=0;this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(r=>r.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),r=await Promise.all(e.map(n=>n.getDecoderConfig().then(a=>a?.codec??null)));return Ho({isWebM:this.isWebM,hasVideo:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="video")),hasAudio:this.segments.some(n=>n.tracks.some(a=>a.info?.type==="audio")),codecStrings:r.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let r of this.segments)r.metadataTagsPromise||(this.reader.fileSize!==null?r.metadataTagsPromise=this.loadSegmentMetadata(r):r.metadataTagsPromise=Promise.resolve()),await r.metadataTagsPromise;let e={};for(let r of this.segments)e={...e,...r.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,lt,Yt);if(R(r)&&(r=await r),!r)break;let n=Vt(r);if(!n)break;let a=n.id,s=n.size,o=r.filePos;if(a===440786851){wr(s);let c=this.reader.requestSlice(o,s);if(R(c)&&(c=await c),!c)break;this.readContiguousElements(c)}else if(a===408125543){if(await this.readSegment(o,s),s===void 0||this.reader.fileSize===null)break}else if(a===524531317){if(this.reader.fileSize===null)break;s===void 0&&(s=(await Lo(this.reader,o,Wa,this.reader.fileSize)).pos-o);let c=J(this.segments);c&&(c.elementEndPos=o+s)}wr(s),e=o+s}if(this.segments.length===0)throw new Error("No Segment element found; the file is invalid or incomplete.")})()}async readSegment(e,r){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],idToTrack:new Map,cuePoints:[],dataStartPos:e,elementEndPos:r===void 0?null:e+r,clusterSeekStartPos:e,lastReadCluster:null,clusterSummaries:new Map,metadataTags:{},metadataTagsPromise:null},this.segments.push(this.currentSegment);let n=e,a=new Set;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let c=this.reader.requestSliceRange(n,lt,Yt);if(R(c)&&(c=await c),!c)break;let l=n,u=Vt(c);if(!u||!Wn.includes(u.id)&&u.id!==236){let h=await lu(this.reader,l+1,Wn,Math.min(this.currentSegment.elementEndPos??1/0,l+Cf));if(h){n=h;continue}else break}let{id:d,size:m}=u,f=c.filePos,p=uu.findIndex(h=>h.id===d);if(p!==-1){let h=uu[p].flag;this.currentSegment[h]=!0,d===290298740&&a.add(l-e),wr(m);let y=this.reader.requestSlice(f,m);R(y)&&(y=await y),y&&this.readContiguousElements(y)}else if(d===307544935||d===423732329){d===307544935?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,wr(m);let h=this.reader.requestSlice(f,m);R(h)&&(h=await h),h&&this.readContiguousElements(h)}else if(d===524531317){this.currentSegment.clusterSeekStartPos=l;break}if(m===void 0)break;n=f+m}if(this.reader.fileSize!==null)for(let c=0;c<this.currentSegment.seekEntries.length;c++){let l=this.currentSegment.seekEntries[c];if(l.id!==290298740||a.has(l.segmentPosition)||(a.add(l.segmentPosition),!this.claimSeekTarget(e+l.segmentPosition)))continue;let u=this.reader.requestSliceRange(e+l.segmentPosition,lt,Yt);if(R(u)&&(u=await u),!u)continue;let d=Vt(u);if(!d||d.id!==290298740)continue;let{size:m}=d;wr(m);let f=this.reader.requestSlice(u.filePos,m);R(f)&&(f=await f),f&&this.readContiguousElements(f)}if(this.currentSegment.seekEntries.sort((c,l)=>c.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let l=uu.find(h=>h.id===c.id);if(!l||this.currentSegment[l.flag]||!this.claimSeekTarget(e+c.segmentPosition))continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,lt,Yt);if(R(u)&&(u=await u),!u)continue;let d=Vt(u);if(!d)continue;let{id:m,size:f}=d;if(m!==l.id)continue;wr(f),this.currentSegment[l.flag]=!0;let p=this.reader.requestSlice(u.filePos,f);R(p)&&(p=await p),p&&this.readContiguousElements(p)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let c of this.currentSegment.tracks)c.defaultDurationNs!==null&&(c.defaultDuration=this.currentSegment.timestampFactor*c.defaultDurationNs/1e9),c.codecDelay=Math.round(this.currentSegment.timestampFactor*c.codecDelayNs/1e9);for(let c of this.currentSegment.cuePoints){let l=this.currentSegment.idToTrack.get(c.trackId);l&&l.cuePoints.push(c)}for(let c of this.currentSegment.tracks){let l=c.cuePoints;l.sort((d,m)=>d.time-m.time);let u=0;for(let d of l)(u===0||d.time!==l[u-1].time)&&(l[u++]=d);l.length=u}let s=null,o=-1/0;for(let c of this.currentSegment.tracks)c.cuePoints.length>o&&(o=c.cuePoints.length,s=c);for(let c of this.currentSegment.tracks)c.cuePoints.length===0&&(c.cuePoints=s.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let n=this.reader.requestSliceRange(e,lt,Yt);R(n)&&(n=await n),b(n);let a=e,s=Vt(n);b(s);let o=s.id;b(o===524531317);let c=s.size,l=n.filePos;c===void 0&&(c=(await Lo(this.reader,l,Wa,r.elementEndPos)).pos-l);let u=this.reader.requestSliceRange(l,0,c);R(u)&&(u=await u);let d={segment:r,elementStartPos:a,elementEndPos:l+c,dataStartPos:l,timestamp:-1,trackData:new Map};if(u){this.currentCluster=d;try{let m=this.readContiguousElements(u,Wa);d.elementEndPos=m}finally{this.currentCluster=null,this.currentBlock=null}}for(let[,m]of d.trackData){let f=m.track;b(m.blocks.length>0);let p=!1;for(let w=0;w<m.blocks.length;w++){let A=m.blocks[w];A.timestamp+=d.timestamp,p||=A.lacing!==0}m.presentationTimestamps=m.blocks.map((w,A)=>({timestamp:w.timestamp,blockIndex:A})).sort((w,A)=>w.timestamp-A.timestamp);for(let w=0;w<m.presentationTimestamps.length;w++){let A=m.presentationTimestamps[w],C=m.blocks[A.blockIndex];if(w<m.presentationTimestamps.length-1){let E=m.presentationTimestamps[w+1];C.duration=E.timestamp-C.timestamp}else C.duration===0&&f.defaultDuration!=null&&C.lacing===0&&(C.duration=Math.round(f.defaultDuration))}if(p&&(m.blocks=this.expandLacedBlocks(m.blocks,f),m.presentationTimestamps=m.blocks.map((w,A)=>({timestamp:w.timestamp,blockIndex:A})).sort((w,A)=>w.timestamp-A.timestamp)),f.info?.type==="audio"&&f.info.codec){let w=Ji.includes(f.info.codec);for(let A of m.blocks)(A.decoded||!w)&&(A.isKeyFrame=Rn(f.info.codec,A.data)==="key")}let h=m.presentationTimestamps.find(w=>m.blocks[w.blockIndex].isKeyFrame);h&&(m.firstKeyFrameTimestamp=h.timestamp);let y=m.blocks[m.presentationTimestamps[0].blockIndex],g=m.blocks[J(m.presentationTimestamps).blockIndex];m.startTimestamp=y.timestamp,m.endTimestamp=g.timestamp+g.duration;let k=X(f.clusterPositionCache,m.startTimestamp,w=>w.startTimestamp),T=f.clusterPositionCache[k],S=f.clusterPositionCache[k+1];(!T||T.elementStartPos<a)&&(!S||S.elementStartPos>a)&&f.clusterPositionCache.splice(k+1,0,{elementStartPos:d.elementStartPos,startTimestamp:m.startTimestamp,hasKeyFrame:m.firstKeyFrameTimestamp!==null})}return r.lastReadCluster=d,r.clusterSummaries.set(e,{elementEndPos:d.elementEndPos,trackIds:new Set(d.trackData.keys())}),d}getTrackDataInCluster(e,r){let n=e.trackData.get(r);if(!n){let a=e.segment.idToTrack.get(r);if(!a)return null;n={track:a,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(r,n)}return n}expandLacedBlocks(e,r){let n=[];for(let a of e){if(a.lacing===0){n.push(a);continue}let s=xe.tempFromBytes(a.data);if(s.length===0)throw new Error("Invalid laced block: no data.");let o=[],c=H(s)+1;switch(a.lacing){case 1:{let u=0;for(let d=0;d<c-1;d++){let m=0;for(;s.bufferPos<s.length;){let f=H(s);if(m+=f,f<255){o.push(m),u+=m;break}}}o.push(s.length-(s.bufferPos+u))}break;case 2:{let u=s.length-1,d=Math.floor(u/c);for(let m=0;m<c;m++)o.push(d)}break;case 3:{if(c===1){o.push(s.length-s.bufferPos);break}let u=qn(s);if(u===null)throw new Error("Invalid EBML lacing: bad frame size.");let d=u;o.push(d);let m=d;for(let f=1;f<c-1;f++){let p=s.bufferPos,h=qn(s);if(h===null)throw new Error("Invalid EBML lacing: bad frame size.");let y=h,k=(1<<(s.bufferPos-p)*7-1)-1,T=y-k;d+=T,o.push(d),m+=d}o.push(s.length-(s.bufferPos+m))}break;default:b(!1)}if(o.length!==c||o.some(u=>u<=0))throw new Error("Invalid block lacing: frame sizes don't match the block.");let l=a.duration||Math.round(c*(r.defaultDuration??0));for(let u=0;u<c;u++){let d=o[u],m=V(s,d),f=Math.floor(l*u/c),p=Math.floor(l*(u+1)/c);n.push({timestamp:a.timestamp+f,duration:p-f,isKeyFrame:a.isKeyFrame,data:m,lacing:0,decoded:a.decoded,postProcessed:!1,mainAdditional:a.mainAdditional})}}return n}async loadSegmentMetadata(e){for(let r of e.seekEntries){if(!(r.id===307544935&&!e.tagsSeen)){if(!(r.id===423732329&&!e.attachmentsSeen))continue}if(!this.claimSeekTarget(e.dataStartPos+r.segmentPosition))continue;let n=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,lt,Yt);if(R(n)&&(n=await n),!n)continue;let a=Vt(n);if(!a||a.id!==r.id)continue;let{size:s}=a;wr(s);let o=this.reader.requestSlice(n.filePos,s);if(R(o)&&(o=await o),o){b(!this.currentSegment),this.currentSegment=e;try{this.readContiguousElements(o)}finally{this.currentSegment=null}}r.id===307544935?e.tagsSeen=!0:r.id===423732329&&(e.attachmentsSeen=!0)}}claimSeekTarget(e){return this.claimedSeekTargets.has(e)?!1:(this.claimedSeekTargets.add(e),!0)}readContiguousElements(e,r){if(this.elementNestingDepth===ig)throw new Error("Invalid file: elements are nested too deeply.");this.elementNestingDepth++;try{for(;e.remainingLength>=lt;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}finally{this.elementNestingDepth--}}traverseElement(e,r){let n=Vt(e);if(!n||r&&r.includes(n.id))return!1;let{id:a,size:s}=n,o=e.filePos;if(wr(s),o+s>e.end)return!1;switch(a){case 17026:this.isWebM=xi(e,s)==="webm";break;case 19899:{if(!this.currentSegment)break;let c={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(c),this.readContiguousElements(e.slice(o,s)),(c.id===-1||c.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case 21419:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.id=$(e,s)}break;case 21420:{let c=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!c)break;c.segmentPosition=$(e,s)}break;case 2807729:{if(!this.currentSegment)break;let c=s===0?1e6:$(e,s);if(c===0)throw new Error("Invalid TimestampScale element: must not be 0.");this.currentSegment.timestampScale=c,this.currentSegment.timestampFactor=1e9/c}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=Zi(e,s)}break;case 17505:{if(!this.currentSegment)break;let c=wf(e,s);this.currentSegment.metadataTags.creationTime=new Date(No+Number(c/1000000n))}break;case 31657:{if(!this.currentSegment)break;this.currentSegment.metadataTags.title??=Yi(e,s)}break;case 174:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ve,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,codecDelay:0,codecDelayNs:0,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(c=>c.data?.type!=="decompress"||c.scope!==1||c.data.algorithm!==3)&&(O._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentSegment.idToTrack.has(this.currentTrack.id)&&(O._warn(`Track #${this.currentTrack.id} is defined more than once; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let c=this.currentTrack.codecId.indexOf("/"),l=c===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,c);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height;let u=this.currentTrack.info.displayWidth,d=this.currentTrack.info.displayHeight,m=this.currentTrack.info.stereoMode;if(u!==null&&[1,8,9,11].includes(m)&&(u*=2),d!==null&&[2,3,6,7].includes(m)&&(d*=2),this.currentTrack.info.displayUnit===0&&(u??=this.currentTrack.info.width,d??=this.currentTrack.info.height),this.currentTrack.info.displayUnit!==4&&u!==null&&d!==null){let p=u*this.currentTrack.info.height,h=d*this.currentTrack.info.width;p>0&&h>0&&(p>h?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*p/h):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*h/p))}if(this.currentTrack.codecId===Be.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Be.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(l===Be.vp8)this.currentTrack.info.codec="vp8";else if(l===Be.vp9)this.currentTrack.info.codec="vp9";else if(l===Be.av1)this.currentTrack.info.codec="av1";else if(l===Be.prores){let p=this.currentTrack.codecPrivate?be.decode(this.currentTrack.codecPrivate):"";$r.includes(p)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=p)}let f=this.currentTrack;this.currentTrack.trackBacking=new du(f),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}else if(this.currentTrack.info.type==="audio"){if(this.currentTrack.info.outputSampleRate!==null&&(this.currentTrack.info.sampleRate=this.currentTrack.info.outputSampleRate),l===Be.aac){if(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,!this.currentTrack.codecPrivate&&this.currentTrack.codecId!==Be.aac){let d=this.currentTrack.codecId.split("/")[2]??"",m=["MAIN","LC","SSR","LTP"].indexOf(d)+1;if(m===0)throw new Error(`Unknown Matroska AAC codec ID '${this.currentTrack.codecId}'.`);let f=this.currentTrack.codecId.endsWith("/SBR");f&&this.currentTrack.info.outputSampleRate===null&&(this.currentTrack.info.sampleRate*=2),this.currentTrack.info.codecDescription=ui({objectType:f?5:m,outputSampleRate:this.currentTrack.info.sampleRate,outputNumberOfChannels:this.currentTrack.info.numberOfChannels,programConfigElement:null})}}else this.currentTrack.codecId===Be.mp3?this.currentTrack.info.codec="mp3":l===Be.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=tt):l===Be.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):l===Be.dts?(this.currentTrack.info.codec="dts",this.currentTrack.codecId==="A_DTS/EXPRESS"?this.currentTrack.info.dtsFormat="dtse":this.currentTrack.codecId==="A_DTS/LOSSLESS"&&(this.currentTrack.info.dtsFormat="dtsl")):l===Be.truehd?this.currentTrack.info.codec="truehd":this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));let u=this.currentTrack;this.currentTrack.trackBacking=new mu(u),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}}this.currentTrack=null}break;case 215:{if(!this.currentTrack)break;this.currentTrack.id=$(e,s)}break;case 131:{if(!this.currentTrack)break;let c=$(e,s);c===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:0,stereoMode:0,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...Fs},alphaMode:!1,proresFormat:null}:c===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,outputSampleRate:null,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case 185:{if(!this.currentTrack)break;(s===0?1:$(e,s))||(this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.disposition.default=s===0||!!$(e,s)}break;case 21930:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!$(e,s)}break;case 21934:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!$(e,s)}break;case 21931:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!$(e,s)}break;case 21932:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!$(e,s)}break;case 21935:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!$(e,s)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=xi(e,s)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=V(e,s)}break;case 2352003:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=$(e,s)}break;case 22186:{if(!this.currentTrack)break;this.currentTrack.codecDelayNs=$(e,s)}break;case 21358:{if(!this.currentTrack)break;this.currentTrack.name=Yi(e,s)}break;case 2274716:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=s===0?"eng":xi(e,s),Ur(this.currentTrack.languageCode)||(this.currentTrack.languageCode=le)}break;case 2274717:{if(!this.currentTrack)break;let l=xi(e,s).split("-")[0];l?this.currentTrack.languageCode=l:this.currentTrack.languageCode=le,this.currentTrack.hasLanguageBcp47=!0}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=$(e,s)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=$(e,s)}break;case 21680:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=$(e,s)}break;case 21690:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=$(e,s)}break;case 21682:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=$(e,s)}break;case 21432:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.stereoMode=$(e,s)}break;case 21440:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=$(e,s)===1}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 21937:{if(this.currentTrack?.info?.type!=="video")break;let c=s===0?2:$(e,s),l=St[c];this.currentTrack.info.colorSpace.matrix=l}break;case 21945:{if(this.currentTrack?.info?.type!=="video")break;let c=$(e,s);this.currentTrack.info.colorSpace.fullRange=c===1||c===2?c===2:void 0}break;case 21946:{if(this.currentTrack?.info?.type!=="video")break;let c=s===0?2:$(e,s),l=wt[c];this.currentTrack.info.colorSpace.transfer=l}break;case 21947:{if(this.currentTrack?.info?.type!=="video")break;let c=s===0?2:$(e,s),l=Tt[c];this.currentTrack.info.colorSpace.primaries=l}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;let c=this.currentTrack.info,l={type:0,yaw:0,pitch:0,roll:0};if(this.currentProjection=l,this.readContiguousElements(e.slice(o,s)),this.currentProjection=null,l.type!==0)break;let u=d=>{try{return Math.round(Math.cos(ai(d)*Sl))}catch{return 1}};c.horizontalScale=u(l.yaw),c.verticalScale=u(l.pitch);try{c.rotation=ai(-l.roll)}catch{}}break;case 30321:{if(!this.currentProjection)break;this.currentProjection.type=$(e,s)}break;case 30323:{if(!this.currentProjection)break;this.currentProjection.yaw=Zi(e,s)}break;case 30324:{if(!this.currentProjection)break;this.currentProjection.pitch=Zi(e,s)}break;case 30325:{if(!this.currentProjection)break;this.currentProjection.roll=Zi(e,s)}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(o,s))}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;let c=s===0?8e3:Zi(e,s);if(!(c>0)||!Number.isFinite(c))throw new Error("Invalid SamplingFrequency element: must be a positive, finite number.");this.currentTrack.info.sampleRate=c}break;case 30901:{if(this.currentTrack?.info?.type!=="audio")break;let c=Zi(e,s);if(!(c>0)||!Number.isFinite(c))throw new Error("Invalid OutputSamplingFrequency element: must be a positive, finite number.");this.currentTrack.info.outputSampleRate=c}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;let c=s===0?1:$(e,s);if(c===0)throw new Error("Invalid Channels element: must not be 0.");this.currentTrack.info.numberOfChannels=c}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=$(e,s)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,s)),this.currentCueTime=null}break;case 179:this.currentCueTime=$(e,s);break;case 183:{if(this.currentCueTime===null||!this.currentSegment)break;let c={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(c),this.readContiguousElements(e.slice(o,s)),(c.trackId===-1||c.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case 247:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;c.trackId=$(e,s)}break;case 241:{let c=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!c)break;b(this.currentSegment),c.clusterPosition=this.currentSegment.dataStartPos+$(e,s)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=$(e,s)}break;case 163:{if(!this.currentCluster)break;let c=e.slice(o,s),l=qn(c);if(l===null||c.remainingLength<3)break;let u=this.getTrackDataInCluster(this.currentCluster,l);if(!u)break;let d=La(c),m=H(c),f=m>>1&3,p=!!(m&128),h=V(c,c.remainingLength),y=u.track.decodingInstructions.length>0;u.blocks.push({timestamp:d,duration:0,isKeyFrame:p,data:h,lacing:f,decoded:!y,postProcessed:!1,mainAdditional:null})}break;case 160:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,s)),this.currentBlock=null}break;case 161:{if(!this.currentCluster)break;let c=e.slice(o,s),l=qn(c);if(l===null||c.remainingLength<3)break;let u=this.getTrackDataInCluster(this.currentCluster,l);if(!u)break;let d=La(c),f=H(c)>>1&3,p=V(c,c.remainingLength),h=u.track.decodingInstructions.length>0;this.currentBlock={timestamp:d,duration:0,isKeyFrame:!0,data:p,lacing:f,decoded:!h,postProcessed:!1,mainAdditional:null},u.blocks.push(this.currentBlock)}break;case 30113:this.readContiguousElements(e.slice(o,s));break;case 166:{let c=this.currentBlock;if(!c)break;let l={addId:1,data:null};this.currentBlockAdditional=l,this.readContiguousElements(e.slice(o,s)),l.data&&l.addId===1&&(c.mainAdditional=l.data),this.currentBlockAdditional=null}break;case 165:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=V(e,s)}break;case 238:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=s===0?1:$(e,s)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=$(e,s)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case 29555:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,s));break;case 25536:this.readContiguousElements(e.slice(o,s));break;case 26826:(s===0?50:$(e,s))!==50&&(this.currentTagTargetIsMovie=!1);break;case 25541:case 25545:case 25540:case 25542:this.currentTagTargetIsMovie=!1;break;case 26568:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,s))}break;case 17827:this.currentSimpleTagName=Yi(e,s);break;case 17543:{if(!this.currentSimpleTagName)break;let c=Yi(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case 17541:{if(!this.currentSimpleTagName)break;let c=V(e,s);this.processTagValue(this.currentSimpleTagName,c)}break;case 24999:{if(!this.currentSegment||this.currentAttachedFile)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,s));let c=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(c.raw??={},c.raw[this.currentAttachedFile.fileUid.toString()]=new Lr(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let l=this.currentAttachedFile.fileName,u="unknown";if(l){let d=l.toLowerCase();d.startsWith("cover.")?u="coverFront":d.startsWith("back.")&&(u="coverBack")}c.images??=[],c.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:u,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case 18094:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=ou(e,s)}break;case 18030:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Yi(e,s)}break;case 18016:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=xi(e,s)}break;case 18012:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=V(e,s)}break;case 18046:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Yi(e,s)}break;case 28032:{let c=this.currentTrack;if(!c)break;this.readContiguousElements(e.slice(o,s)),c.decodingInstructions.sort((l,u)=>u.order-l.order)}break;case 25152:{let c=this.currentTrack;if(!c)break;let l={order:0,scope:1,data:null};this.currentDecodingInstruction=l,this.readContiguousElements(e.slice(o,s)),l.data&&c.decodingInstructions.push(l),this.currentDecodingInstruction=null}break;case 20529:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=$(e,s)}break;case 20530:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=s===0?1:$(e,s)}break;case 20532:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:0,settings:null},this.readContiguousElements(e.slice(o,s))}break;case 16980:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=$(e,s)}break;case 16981:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=V(e,s)}break;case 20533:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=o+s,!0}decodeBlockData(e,r){b(e.decodingInstructions.length>0);let n=r;for(let a of e.decodingInstructions)switch(b(a.data),a.data.type){case"decompress":switch(a.data.algorithm){case 3:if(a.data.settings&&a.data.settings.length>0){let s=a.data.settings,o=new Uint8Array(s.length+n.length);o.set(s,0),o.set(n,s.length),n=o}break;default:}break;default:}return n}processTagValue(e,r){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=r,typeof r=="string")switch(e.toLowerCase()){case"title":n.title??=r;break;case"description":n.description??=r;break;case"artist":n.artist??=r;break;case"album":n.album??=r;break;case"album_artist":n.albumArtist??=r;break;case"genre":n.genre??=r;break;case"bpm":{let a=Number.parseInt(r,10);Number.isInteger(a)&&a>0&&(n.beatsPerMinute??=a)}break;case"comment":n.comment??=r;break;case"lyrics":n.lyrics??=r;break;case"date":{let a=Kt(r);a&&(n.date??=a)}break;case"track_number":case"part_number":{let a=r.split("/"),s=Number.parseInt(a[0],10),o=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.trackNumber??=s),o&&Number.isInteger(o)&&o>0&&(n.tracksTotal??=o)}break;case"disc_number":case"disc":{let a=r.split("/"),s=Number.parseInt(a[0],10),o=a[1]&&Number.parseInt(a[1],10);Number.isInteger(s)&&s>0&&(n.discNumber??=s),o&&Number.isInteger(o)&&o>0&&(n.discsTotal??=o)}break}}getDurationFromMetadata(e){if(e.duration<=0)return null;let r=Math.min(...e.tracks.map(n=>n.codecDelay));return(e.duration-r)/e.timestampFactor}},qo=class{constructor(t){this.internalTrack=t;this.packetToClusterLocation=new WeakMap}getNumber(){let t=this.internalTrack.demuxer,e=this.internalTrack.trackBacking.getType(),r=0;for(let n of t.segments)for(let a of n.tracks)if(a.trackBacking.getType()===e&&r++,a===this.internalTrack)return r;b(!1)}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(t){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,t)}intoTimescale(t){return Fe(t*this.internalTrack.segment.timestampFactor)+this.internalTrack.codecDelay}async getPacket(t,e){let r=this.intoTimescale(t);return this.performClusterLookup(null,n=>{let a=n.trackData.get(this.internalTrack.id);if(!a)return{blockIndex:-1,correctBlockFound:!1};let s=X(a.presentationTimestamps,r,l=>l.timestamp),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<a.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,e)}async getNextPacket(t,e){let r=this.packetToClusterLocation.get(t);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,n=>{if(n===r.cluster){let a=n.trackData.get(this.internalTrack.id);if(r.blockIndex+1<a.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}async getKeyPacket(t,e){let r=this.intoTimescale(t);return this.performClusterLookup(null,n=>{let a=n.trackData.get(this.internalTrack.id);if(!a)return{blockIndex:-1,correctBlockFound:!1};let s=lr(a.presentationTimestamps,l=>a.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=r),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<a.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,e,!0)}async getNextKeyPacket(t,e){let r=this.packetToClusterLocation.get(t);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,n=>{if(n===r.cluster){let a=n.trackData.get(this.internalTrack.id);for(let s=r.blockIndex+1;s<a.blocks.length;s++)if(a.blocks[s].isKeyFrame)return{blockIndex:s,correctBlockFound:!0}}else{let a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){let s=a.blocks.findIndex(o=>o.isKeyFrame);return b(s!==-1),{blockIndex:s,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,e)}async fetchPacketInCluster(t,e,r){if(e===-1)return null;let a=t.trackData.get(this.internalTrack.id).blocks[e];if(b(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0),!a.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(a.data.length>=8&&a.data[4]===105&&a.data[5]===99&&a.data[6]===112&&a.data[7]===102)){let p=new Uint8Array(a.data.length+8);z(p).setUint32(0,p.length,!1),p[4]=105,p[5]=99,p[6]=112,p[7]=102,p.set(a.data,8),a.data=p}a.postProcessed=!0}let s=r.metadataOnly?Ae:a.data,{codecDelay:o,segment:c}=this.internalTrack,l=(a.timestamp-o)/c.timestampFactor,u=a.duration/c.timestampFactor,d={};a.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(d.alpha=r.metadataOnly?Ae:a.mainAdditional,d.alphaByteLength=a.mainAdditional.byteLength);let m=new ee(s,a.isKeyFrame?"key":"delta",l,u,t.dataStartPos+e,a.data.byteLength,d);return this.packetToClusterLocation.set(m,{cluster:t,blockIndex:e}),m}async performClusterLookup(t,e,r,n,a,s=!1){let{demuxer:o,segment:c,cuePoints:l,clusterPositionCache:u}=this.internalTrack,d=null,m=-1;if(t){let{blockIndex:y,correctBlockFound:g}=e(t);if(g)return this.fetchPacketInCluster(t,y,a);y!==-1&&(d=t,m=y)}let f=X(l,r,y=>y.time),p=X(u,r,y=>y.startTimestamp),h=1/0;for(;;){for(;f!==-1&&l[f].clusterPosition>=h;)f--;for(;p!==-1&&(u[p].elementStartPos>=h||s&&!u[p].hasKeyFrame);)p--;let y=Math.max(l[f]?.clusterPosition??0,u[p]?.elementStartPos??0)||null,g,k=null;t?y===null||t.elementStartPos>=y?(g=t.elementEndPos,k=t):g=y:g=y??c.clusterSeekStartPos;let T=k?k.elementStartPos:g;for(;(c.elementEndPos===null||g<=c.elementEndPos-lt)&&g<h;){if(k){let P=k.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>n)break;k=null}let S=c.clusterSummaries.get(g);if(S&&!S.trackIds.has(this.internalTrack.id)){g=S.elementEndPos;continue}let w=o.reader.requestSliceRange(g,lt,Yt);if(R(w)&&(w=await w),!w)break;let A=g,C=Vt(w);if(c.elementEndPos===null&&C&&au.includes(C.id)){c.elementEndPos=A;break}if(!C||!Wn.includes(C.id)&&C.id!==236){let P=await lu(o.reader,A+1,Wn,Math.min(c.elementEndPos??1/0,A+Cf));if(P){g=P;continue}else break}let E=C.id,I=C.size,x=w.filePos;if(E===524531317){k=await o.readCluster(A,c),I=k.elementEndPos-x;let{blockIndex:P,correctBlockFound:v}=e(k);if(v)return this.fetchPacketInCluster(k,P,a);P!==-1&&(d=k,m=P)}I===void 0&&(b(E!==524531317),I=(await Lo(o.reader,x,Wa,c.elementEndPos)).pos-x),g=x+I}if(y===null||d&&d.elementStartPos>=y)break;h=T,t=null}return d?this.fetchPacketInCluster(d,m,a):null}},du=class extends qo{constructor(e){super(e);this.decoderConfigPromise=null}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}getTransformationMatrix(){let e=this.internalTrack.info,r=sr(vs(e.horizontalScale,e.verticalScale),Tn(e.rotation));return Is(r,e.width,e.height)}async getColorSpace(){let e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=this.internalTrack.codecPrivate,r=this.internalTrack.info.codec==="av1"&&e?hi(e.subarray(4)):null,n=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"&&!r||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(n=await this.getFirstPacket({})),this.internalTrack.info.codec==="av1"&&n&&(r=hi(n.data));let s={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"&&n?hr(n.data):null,hevcType:"hev1",hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&n?br(n.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&n?_n(n.data):null,av1CodecInfo:r,proresCodecInfo:this.internalTrack.info.codec==="prores"&&n?js(n.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!wn(this.internalTrack.info.colorSpace)){let c=Vo(s);this.internalTrack.info.colorSpace.primaries??=c.primaries,this.internalTrack.info.colorSpace.transfer??=c.transfer,this.internalTrack.info.colorSpace.matrix??=c.matrix,this.internalTrack.info.colorSpace.fullRange??=c.fullRange}let o={codec:Si(s),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o})():null}},mu=class extends qo{constructor(e){super(e);this.decoderConfigPromise=null}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="dts"&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&ao(e.data)}return{codec:Ln({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}};var Sr=128,Et=10,Gn=["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"],Pf=(i,t)=>{let e=i.filePos;t.raw??={},t.raw.TAG??=V(i,Sr-3),i.filePos=e;let r=Kn(i,30);r&&(t.title??=r);let n=Kn(i,30);n&&(t.artist??=n);let a=Kn(i,30);a&&(t.album??=a);let s=Kn(i,4),o=Number.parseInt(s,10);Number.isInteger(o)&&o>0&&(t.date??=En(o));let c=V(i,30),l;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(t.trackNumber??=d),i.skip(-30),l=Kn(i,28),i.skip(2)}else i.skip(-30),l=Kn(i,30);l&&(t.comment??=l);let u=H(i);u<Gn.length&&(t.genre??=Gn[u])},Kn=(i,t)=>{let e=V(i,t),r=Li(e.indexOf(0),e.length),n=e.subarray(0,r),a="";for(let s=0;s<n.length;s++)a+=String.fromCharCode(n[s]);return a.trimEnd()},Ar=async(i,t)=>{let e=t;for(;;){let r=i.requestSlice(e,Et);if(R(r)&&(r=await r),!r)return e;let n=Yr(r);if(!n)return e;e=r.filePos+n.size}},Yr=i=>{let t=i.filePos,e=ae(i,3),r=H(i),n=H(i),a=H(i),s=B(i);if(e!=="ID3"||r===255||n===255||(s&2155905152)!==0)return i.filePos=t,null;let o=pa(s);return r===4&&a&16&&(o+=Et),{majorVersion:r,revision:n,flags:a,size:o}},Pi=(i,t,e)=>{if(![2,3,4].includes(t.majorVersion)){O._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}if(t.majorVersion===2&&t.flags&64){O._warn("Skipping compressed ID3v2.2 tag");return}let r=t.majorVersion===4&&t.flags&16?t.size-Et:t.size,n=V(i,r),a=new fu(t,n);if(t.flags&128&&t.majorVersion<=3&&a.ununsynchronizeAll(),t.flags&64){if(a.bytes.length<4)return;let c=a.readU32();t.majorVersion===3?a.pos+=c:a.pos+=pa(c)-4}let s=null,o=null;for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let c=a.readId3V2Frame();if(!c)break;let l=Math.min(a.pos+c.size,a.bytes.length),u=l,d=!1,m=!1,f=!1,p=!1,h=!1;if(t.majorVersion===3?(d=!!(c.flags&64),m=!!(c.flags&128),p=!!(c.flags&32)):t.majorVersion===4&&(p=!!(c.flags&64),d=!!(c.flags&4),m=!!(c.flags&8),f=!!(c.flags&2)||!!(t.flags&128),h=!!(c.flags&1)),d){O._warn(`Skipping encrypted ID3v2 frame ${c.id}`),a.pos=l;continue}if(m){O._warn(`Skipping compressed ID3v2 frame ${c.id}`),a.pos=l;continue}p&&(a.pos+=1),h&&(a.pos+=4),f&&(u=a.ununsynchronizeRegion(a.pos,u));let y=a.pos,g=k=>{if(u-a.pos<k)throw new Error(`Invalid ID3v2 ${c.id} frame: too short.`)};if(e.raw??={},c.id==="TXXX"||c.id==="TXX"){let k=e.raw[c.id]??={};g(1);let T=a.readId3V2TextEncoding(),S=a.readId3V2Text(T,u),w=a.readId3V2Text(T,u);k[S]??=w}else if(c.id[0]==="T")e.raw[c.id]??=a.readId3V2EncodingAndText(u);else{let k=a.readBytes(u-a.pos),T=e.raw[c.id];T instanceof Uint8Array?e.raw[c.id]=[T,k]:Array.isArray(T)?T.push(k):e.raw[c.id]??=k}switch(a.pos=y,c.id){case"TIT2":case"TT2":e.title??=a.readId3V2EncodingAndText(u);break;case"TIT3":case"TT3":e.description??=a.readId3V2EncodingAndText(u);break;case"TPE1":case"TP1":e.artist??=a.readId3V2EncodingAndText(u);break;case"TALB":case"TAL":e.album??=a.readId3V2EncodingAndText(u);break;case"TPE2":case"TP2":e.albumArtist??=a.readId3V2EncodingAndText(u);break;case"TRCK":case"TRK":{let T=a.readId3V2EncodingAndText(u).split("/"),S=Number.parseInt(T[0],10),w=T[1]&&Number.parseInt(T[1],10);Number.isInteger(S)&&S>0&&(e.trackNumber??=S),w&&Number.isInteger(w)&&w>0&&(e.tracksTotal??=w)}break;case"TPOS":case"TPA":{let T=a.readId3V2EncodingAndText(u).split("/"),S=Number.parseInt(T[0],10),w=T[1]&&Number.parseInt(T[1],10);Number.isInteger(S)&&S>0&&(e.discNumber??=S),w&&Number.isInteger(w)&&w>0&&(e.discsTotal??=w)}break;case"TCON":case"TCO":{let k=a.readId3V2EncodingAndText(u),T=/^\((\d+)\)/.exec(k);if(T){let S=Number.parseInt(T[1]);if(Gn[S]!==void 0){e.genre??=Gn[S];break}}if(T=/^\d+$/.exec(k),T){let S=Number.parseInt(T[0]);if(Gn[S]!==void 0){e.genre??=Gn[S];break}}e.genre??=k}break;case"TDRC":{let k=Kt(a.readId3V2EncodingAndText(u));k&&(e.date??=k)}break;case"TYER":case"TYE":{let k=a.readId3V2EncodingAndText(u),T=Number.parseInt(k,10);Number.isInteger(T)&&(s??=T)}break;case"TDAT":case"TDA":o??=a.readId3V2EncodingAndText(u);break;case"TBPM":case"TBP":{let k=a.readId3V2EncodingAndText(u),T=Number.parseInt(k,10);Number.isInteger(T)&&T>0&&(e.beatsPerMinute??=T)}break;case"USLT":case"ULT":{g(4);let k=a.readId3V2TextEncoding();a.pos+=3,a.readId3V2Text(k,u),e.lyrics??=a.readId3V2Text(k,u)}break;case"COMM":case"COM":{g(4);let k=a.readId3V2TextEncoding();a.pos+=3,a.readId3V2Text(k,u)===""&&(e.comment??=a.readId3V2Text(k,u))}break;case"APIC":case"PIC":{g(1);let k=a.readId3V2TextEncoding(),T;if(t.majorVersion===2){g(3);let C=a.readAscii(3);T=C==="PNG"?"image/png":C==="JPG"?"image/jpeg":"image/*"}else T=a.readId3V2Text(0,u);g(1);let S=a.readU8(),w=a.readId3V2Text(k,u).trimEnd(),A=u-a.pos;if(A>=0){let C=a.readBytes(A);e.images||(e.images=[]),e.images.push({data:C,mimeType:T,kind:S===3?"coverFront":S===4?"coverBack":"unknown",description:w})}}break;default:a.pos+=c.size;break}a.pos=l}if(s!==null){let c=En(s),l=/^(0[1-9]|[12]\d|3[01])(0[1-9]|1[0-2])$/.exec(o??"");if(l){let u=Number(l[1]),d=En(s,Number(l[2])-1,u);d.getUTCDate()===u&&(c=d)}Number.isNaN(c.getTime())||(e.date??=c)}},fu=class{constructor(t,e){this.header=t;this.bytes=e;this.pos=0;this.ownsBytes=!1;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let t=new Uint8Array(this.bytes.length),e=0;for(let r=0;r<this.bytes.length;r++){let n=this.bytes[r];t[e++]=n,n===255&&r!==this.bytes.length-1&&this.bytes[r+1]===0&&r++}this.bytes=t.subarray(0,e),this.view=z(this.bytes)}ununsynchronizeRegion(t,e){this.ownsBytes||(this.bytes=this.bytes.slice(),this.view=z(this.bytes),this.ownsBytes=!0);let r=t;for(let n=t;n<e;n++){let a=this.bytes[n];this.bytes[r++]=a,a===255&&n!==e-1&&this.bytes[n+1]===0&&n++}return r}readBytes(t){let e=this.bytes.subarray(this.pos,this.pos+t);return this.pos+=t,e}readU8(){let t=this.view.getUint8(this.pos);return this.pos+=1,t}readU16(){let t=this.view.getUint16(this.pos,!1);return this.pos+=2,t}readU24(){let t=this.view.getUint16(this.pos,!1),e=this.view.getUint8(this.pos+2);return this.pos+=3,t*256+e}readU32(){let t=this.view.getUint32(this.pos,!1);return this.pos+=4,t}readAscii(t){let e="";for(let r=0;r<t;r++)e+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=t,e}readId3V2Frame(){if(this.header.majorVersion===2){let t=this.readAscii(3);if(t==="\0\0\0")return null;let e=this.readU24();return{id:t,size:e,flags:0}}else{let t=this.readAscii(4);if(t==="\0\0\0\0")return null;let e=this.readU32(),r=(e&2155905152)===0,n=this.header.majorVersion===4&&r?pa(e):e,a=this.readU16(),s=this.pos,o=c=>{let l=s+c;if(l>this.bytes.length)return!1;if(l<=this.bytes.length-this.frameHeaderSize()){this.pos=l;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(r&&!o(n)){let c=this.header.majorVersion===4?e:pa(e);o(c)&&(n=c)}return this.pos=s,{id:t,size:n,flags:a}}}readId3V2TextEncoding(){let t=this.readU8();if(t>3)throw new Error(`Unsupported text encoding: ${t}`);return t}readId3V2Text(t,e){let r=this.pos,n=this.readBytes(e-this.pos);switch(t){case 0:{let a="";for(let s=0;s<n.length;s++){let o=n[s];if(o===0){this.pos=r+s+1;break}a+=String.fromCharCode(o)}return a}case 1:if(n[0]===255&&n[1]===254){let a=new oi("utf-16le"),s=Li(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else if(n[0]===254&&n[1]===255){let a=new oi("utf-16be"),s=Li(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(2,s))}else{if(n[0]===0&&n[1]===0)return this.pos=r+2,"";{let a=Li(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),be.decode(n.subarray(0,a))}}case 2:{let a=new oi("utf-16be"),s=Li(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);return this.pos=r+Math.min(s+2,n.length),a.decode(n.subarray(0,s))}case 3:{let a=Li(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),be.decode(n.subarray(0,a))}}}readId3V2EncodingAndText(t){if(this.pos>=t)return"";let e=this.readId3V2TextEncoding();return this.readId3V2Text(e,t)}},Ci=class{constructor(t){this.helper=new Uint8Array(8);this.helperView=z(this.helper);this.writer=t}writeId3V2Tag(t){let e=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let r=this.writer.getPos(),n=new Set;for(let{key:o,value:c}of qt(t))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),n.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),n.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),n.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),n.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),n.add("TPE2");break;case"trackNumber":{let l=t.tracksTotal!==void 0?`${c}/${t.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",l),n.add("TRCK")}break;case"discNumber":{let l=t.discsTotal!==void 0?`${c}/${t.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",l),n.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),n.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),n.add("TDRC");break;case"beatsPerMinute":this.writeId3V2TextFrame("TBPM",`${c}`),n.add("TBPM");break;case"lyrics":this.writeId3V2LyricsFrame(c),n.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),n.add("COMM");break;case"images":{let l={coverFront:3,coverBack:4,unknown:0};for(let u of c){let d=l[u.kind]??0,m=u.description??"";this.writeId3V2ApicFrame(u.mimeType,d,m,u.data)}n.add("APIC")}break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:Z(o)}if(t.raw)for(let o in t.raw){let c=t.raw[o];if(c==null||o.length!==4||n.has(o))continue;let l;if(typeof c=="string"){let u;if(Ht(c)){u=new Uint8Array(c.length+2),u[0]=0;for(let m=0;m<c.length;m++)u[m+1]=c.charCodeAt(m)}else{let m=Y.encode(c);u=new Uint8Array(m.byteLength+2),u[0]=3,u.set(m,1)}l=[u]}else if(c instanceof Uint8Array)l=[c];else if(Array.isArray(c)&&c.every(u=>u instanceof Uint8Array))l=c;else if(o==="TXXX"&&Us(c)){for(let u in c){let d=c[u],m=Ht(u)&&Ht(d),f=m?null:Y.encode(u),p=m?null:Y.encode(d),h=m?u.length:f.byteLength,y=m?d.length:p.byteLength,g=1+h+1+y+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(g),this.writeU16(0),this.writeU8(m?0:3),m?(this.writeIsoString(u),this.writeIsoString(d)):(this.writer.write(f),this.writeU8(0),this.writer.write(p),this.writeU8(0))}continue}else continue;for(let u of l)this.writeAscii(o),this.writeSynchsafeU32(u.byteLength),this.writeU16(0),this.writer.write(u)}let a=this.writer.getPos(),s=a-r;return this.writer.seek(e+6),this.writeSynchsafeU32(s),this.writer.seek(a),s+10}writeU8(t){this.helper[0]=t,this.writer.write(this.helper.subarray(0,1))}writeU16(t){this.helperView.setUint16(0,t,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(t){for(let e=0;e<t.length;e++)this.helper[e]=t.charCodeAt(e);this.writer.write(this.helper.subarray(0,t.length))}writeSynchsafeU32(t){this.writeU32(rm(t))}writeIsoString(t){let e=new Uint8Array(t.length+1);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);this.writer.write(e)}writeUtf8String(t){let e=Y.encode(t);this.writer.write(e),this.writeU8(0)}writeId3V2TextFrame(t,e){let r=Ht(e),a=1+(r?e.length:Y.encode(e).byteLength)+1;this.writeAscii(t),this.writeSynchsafeU32(a),this.writeU16(0),this.writeU8(r?0:3),r?this.writeIsoString(e):this.writeUtf8String(e)}writeId3V2LyricsFrame(t){let e=Ht(t),r=e?t.length:Y.encode(t).byteLength,n="",a=4+n.length+1+r+1;this.writeAscii("USLT"),this.writeSynchsafeU32(a),this.writeU16(0),this.writeU8(e?0:3),this.writeAscii("und"),e?(this.writeIsoString(n),this.writeIsoString(t)):(this.writeUtf8String(n),this.writeUtf8String(t))}writeId3V2CommentFrame(t){let e=Ht(t),r=e?t.length:Y.encode(t).byteLength,n="",a=4+n.length+1+r+1;this.writeAscii("COMM"),this.writeSynchsafeU32(a),this.writeU16(0),this.writeU8(e?0:3),this.writeU8(117),this.writeU8(110),this.writeU8(100),e?(this.writeIsoString(n),this.writeIsoString(t)):(this.writeUtf8String(n),this.writeUtf8String(t))}writeId3V2ApicFrame(t,e,r,n){let a=Ht(t)&&Ht(r),s=a?t.length:Y.encode(t).byteLength,o=a?r.length:Y.encode(r).byteLength,c=1+s+1+1+o+1+n.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(a?0:3),a?this.writeIsoString(t):this.writeUtf8String(t),this.writeU8(e),a?this.writeIsoString(r):this.writeUtf8String(r),this.writer.write(n)}};var qa=async(i,t,e,r)=>{let n=t;for(;;){let a=await Ko(i,n,t+e,r);if(!a)return null;let{header:s}=a,o=mi(s.mpegVersionId,s.channel),c=i.requestSlice(a.startPos+o,4);if(R(c)&&(c=await c),c){let d=B(c);if(d===qr||d===di)return a}let l=a.startPos+s.totalSize;if(l===i.fileSize)return a;if(l+Sr===i.fileSize){let d=i.requestSlice(l,3);if(R(d)&&(d=await d),d&&ae(d,3)==="TAG")return a}let u=await Ko(i,l,l+4);if(u&&u.header.channel===s.channel&&u.header.sampleRate===s.sampleRate)return a;n=a.startPos+1}},Ko=async(i,t,e,r=null)=>{let a=t;for(;e===null||a<e;){let s=e!==null?Math.min(65536,e-a):65536,o=i.requestSliceRange(a,4,s);if(R(o)&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,l=B(o),u=i.fileSize!==null?i.fileSize-a:null,d=fr(l,u);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&fi(d.header.channel)===fi(r.channel)))return{header:d.header,startPos:a};o.filePos=c+d.bytesAdvanced,a=o.filePos}}return null};var Go=32,Qo=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.firstFrameHeaderPos=null;this.xingFrameHeader=null;this.xingFrameHeaderPos=null;this.loadedSamples=[];this.metadataTags=null;this.xingData=null;this.trackBackings=[];this.readingMutex=new Ee;this.lastSampleLoaded=!1;this.lastLoadedPos=0;this.nextTimestampInSamples=0;this.primingDelay=0;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new pu(this)]})()}async advanceReader(){let e;if(this.lastLoadedPos===0){let l=await Ar(this.reader,0);e=await qa(this.reader,l,4096,null)}else if(e=await Ko(this.reader,this.lastLoadedPos,this.lastLoadedPos+2,this.firstFrameHeader),!e){if(this.firstFrameHeader){let u=this.reader.requestSlice(this.lastLoadedPos,5);if(R(u)&&(u=await u),u)for(let d=0;d<2;d++){u.filePos=this.lastLoadedPos+d;let{header:m}=fr(B(u),null);if(m&&m.sampleRate!==this.firstFrameHeader.sampleRate){O._warn(`The sample rate changes mid-stream (from ${this.firstFrameHeader.sampleRate} Hz to ${m.sampleRate} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}}}let l=await Ar(this.reader,this.lastLoadedPos+1);e=await qa(this.reader,l,2**16,this.firstFrameHeader)}if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=mi(r.mpegVersionId,r.channel),a=this.reader.requestSlice(e.startPos+n,4);if(R(a)&&(a=await a),a){let l=B(a);if(l===qr||l===di){if(this.xingFrameHeader||(this.xingFrameHeader=r,this.xingFrameHeaderPos=e.startPos),!this.xingData){let d=this.reader.requestSlice(e.startPos+n+4,8);if(R(d)&&(d=await d),d){let m=V(d,8),f=z(m),p=f.getUint32(0,!1);this.xingData={isVbr:l===qr,frameCount:p&1?f.getUint32(4,!1):null};let h=e.startPos+n+8+(p&1?4:0)+(p&2?4:0)+(p&4?100:0)+(p&8?4:0);if(!this.firstFrameHeader&&h+24<=e.startPos+r.totalSize){let y=this.reader.requestSlice(h,24);if(R(y)&&(y=await y),y){let g=V(y,24),k=String.fromCharCode(...g.subarray(0,4));(k==="LAME"||k==="Lavf"||k==="Lavc")&&(this.primingDelay=(g[21]<<4|g[22]>>4)+529,this.nextTimestampInSamples=-this.primingDelay)}}}}return}}let s=r.layer===1?this.reader.requestSlice(e.startPos+4+32,18):null;if(R(s)&&(s=await s),s){let l=B(s),u=fe(s);if(l===em&&u===1){if(this.xingFrameHeader||(this.xingFrameHeader=r,this.xingFrameHeaderPos=e.startPos),!this.xingData){s.skip(8);let d=B(s);this.xingData={isVbr:!0,frameCount:d}}return}}this.firstFrameHeader||(this.firstFrameHeader=r,this.firstFrameHeaderPos=e.startPos);let o=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,c={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:o,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(c),this.nextTimestampInSamples+=r.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0,n=!1;for(;;){let a=this.reader.requestSlice(r,Et);if(R(a)&&(a=await a),!a)break;let s=Yr(a);if(!s)break;n=!0;let o=this.reader.requestSlice(a.filePos,s.size);if(R(o)&&(o=await o),!o)break;Pi(o,s,this.metadataTags),r=a.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=Sr){let a=this.reader.requestSlice(this.reader.fileSize-Sr,Sr);R(a)&&(a=await a),b(a),ae(a,3)==="TAG"&&Pf(a,this.metadataTags)}return this.metadataTags}finally{e()}}},pu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getTimeResolution(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let t=this.demuxer;if(b(t.firstFrameHeader!==null),b(t.firstFrameHeaderPos!==null),t.xingData&&t.xingData.frameCount!==null)return(t.xingData.frameCount*t.firstFrameHeader.audioSamplesInFrame-t.primingDelay)/t.firstFrameHeader.sampleRate;if(!t.xingData?.isVbr&&t.reader.fileSize!==null){let e=t.reader.fileSize;if(e-t.firstFrameHeaderPos>=Sr){let a=t.reader.requestSlice(e-Sr,3);R(a)&&(a=await a),b(a),ae(a,3)==="TAG"&&(e-=Sr)}if(e-t.firstFrameHeaderPos>=Go){let a=t.reader.requestSlice(e-Go,Go);if(R(a)&&(a=await a),b(a),ae(a,8)==="APETAGEX"){a.skip(4);let s=Zt(a);a.skip(4);let c=(Zt(a)&1<<31)!==0;if(e-=s+(c?Go:0),e<t.firstFrameHeaderPos)throw new Error("Invalid APE tag size.")}}let r=tm(t.firstFrameHeader.lowSamplingFrequency,t.firstFrameHeader.layer,t.firstFrameHeader.bitrate,t.firstFrameHeader.sampleRate),n=(e-t.firstFrameHeaderPos)/r;return(Math.round(n)*t.firstFrameHeader.audioSamplesInFrame-t.primingDelay)/t.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return le}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.firstFrameHeader),fi(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Ve}}async getDecoderConfig(){return b(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:fi(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(t,e){if(t===-1)return null;let r=this.demuxer.loadedSamples[t];if(!r)return null;let n=this.demuxer.reader.fileSize;if(n!==null&&r.dataStart+r.dataSize>n)return null;let a;if(e.metadataOnly)a=Ae;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(R(s)&&(s=await s),!s)return null;a=V(s,r.dataSize)}return new ee(a,"key",r.timestamp,r.duration,t,r.dataSize)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=Vr(this.demuxer.loadedSamples,t.timestamp,s=>s.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let a=n+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,e)}finally{r()}}async getPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=this.getSampleRate(),a=Fe(t*n)/n;for(;;){let s=X(this.demuxer.loadedSamples,a,o=>o.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,e);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var Ka=1399285583,ag=79764919,Ef=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^ag:t<<1;Ef[i]=t>>>0&4294967295}var If=i=>{let t=z(i),e=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n<i.length;n++){let a=i[n];r=(r<<8^Ef[r>>>24^a])>>>0}return t.setUint32(22,e,!0),r},Ga=(i,t,e)=>{let r=0,n=null;if(i.length>0)if(t.codec==="vorbis"){b(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<<Bd(a-1))-1<<1,c=(i[0]&o)>>1;if(c>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let l=e??t.vorbisInfo.blocksizes[0],u=t.vorbisInfo.modeBlockflags[c];if(n=t.vorbisInfo.blocksizes[u],u===1){let d=(o|1)+1,m=i[0]&d?1:0;l=t.vorbisInfo.blocksizes[m]}r=l+n>>2}else t.codec==="opus"&&(r=Xs(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:n}},jo=i=>{let t="audio/ogg";if(i.codecStrings.length>0){let e=[...new Set(i.codecStrings)];t+=`; codecs="${e.join(", ")}"`}return t};var Zr=27,en=282,Xo=en+255*255,jn=i=>{let t=i.filePos;if(Zt(i)!==Ka)return null;i.skip(1);let r=H(i),n=_f(i),a=Zt(i),s=Zt(i),o=Zt(i),c=H(i);if(c===0||i.remainingLength<c)return null;let l=new Uint8Array(c);for(let f=0;f<c;f++)l[f]=H(i);let u=27+c,d=l.reduce((f,p)=>f+p,0),m=u+d;return{headerStartPos:t,totalSize:m,dataStartPos:t+u,dataSize:d,headerType:r,granulePosition:n,serialNumber:a,sequenceNumber:s,checksum:o,lacingValues:l}},vf=(i,t,e)=>{for(;i.filePos<t-3;){let r=Zt(i),n=r&255,a=r>>>8&255,s=r>>>16&255,o=r>>>24&255,c=79;if(!(n!==c&&a!==c&&s!==c&&o!==c)){if(i.skip(-4),r===Ka){if(e===void 0||i.filePos+18>i.end)return!0;i.skip(14);let l=Zt(i);if(i.skip(-18),l===e)return!0}i.skip(1)}}return!1};var Rf=64,sg=30,og=19,$o=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.bitstreams=[];this.trackBackings=[];this.metadataTags={};this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSliceRange(e,Zr,en);if(R(r)&&(r=await r),!r)break;let n=jn(r);if(!n||!!!(n.headerType&2))break;if(this.bitstreams.length===Rf)throw new Error(`Too many (> ${Rf}) logical bitstreams.`);this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let r of this.bitstreams){let n=await this.readPacket(r.bosPage,0);n&&(n.data.byteLength>=sg&&n.data[0]===1&&n.data[1]===118&&n.data[2]===111&&n.data[3]===114&&n.data[4]===98&&n.data[5]===105&&n.data[6]===115?await this.readVorbisMetadata(n,r):n.data.byteLength>=og&&n.data[0]===79&&n.data[1]===112&&n.data[2]===117&&n.data[3]===115&&n.data[4]===72&&n.data[5]===101&&n.data[6]===97&&n.data[7]===100&&await this.readOpusMetadata(n,r),r.codecInfo.codec!==null&&this.trackBackings.push(new hu(r,this)))}})()}async readVorbisMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let a=await this.readPacket(n.startPage,n.startSegmentIndex);if(!a||(n=await this.findNextPacketStart(a),!n))return;let s=await this.readPacket(n.startPage,n.startSegmentIndex);if(!s||a.data[0]!==3||s.data[0]!==5)return;let o=z(e.data),c=o.getUint8(11),l=o.getUint32(12,!0);if(c===0||l===0)throw new Error("Invalid Vorbis identification header: channel count and sample rate must not be 0.");let u=[],d=p=>{for(;u.push(Math.min(255,p)),!(p<255);)p-=255};d(e.data.length),d(a.data.length);let m=new Uint8Array(1+u.length+e.data.length+a.data.length+s.data.length);m[0]=2,m.set(u,1),m.set(e.data,1+u.length),m.set(a.data,1+u.length+e.data.length),m.set(s.data,1+u.length+e.data.length+a.data.length),r.codecInfo.codec="vorbis",r.description=m,r.lastMetadataPacket=s,r.numberOfChannels=c,r.sampleRate=l;let f=o.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:$s(s.data).modeBlockflags},ya(a.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,r){let n=await this.findNextPacketStart(e);if(!n)return;let a=await this.readPacket(n.startPage,n.startSegmentIndex);if(!a)return;r.codecInfo.codec="opus",r.description=e.data,r.lastMetadataPacket=a;let s=yr(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=tt,r.codecInfo.opusInfo={preSkip:s.preSkip},ya(a.data.subarray(8),this.metadataTags)}async readPacket(e,r){b(r<e.lacingValues.length);let n=0;for(let m=0;m<r;m++)n+=e.lacingValues[m];let a=e,s=n,o=r,c=[];e:for(;;){let m=this.reader.requestSlice(a.dataStartPos,a.dataSize);if(R(m)&&(m=await m),!m)return null;let f=V(m,a.dataSize);for(;;){if(o===a.lacingValues.length){c.push(f.subarray(n,s));break}let h=a.lacingValues[o];if(s+=h,h<255){c.push(f.subarray(n,s));break e}o++}let p=a.headerStartPos+a.totalSize;for(;;){let h=this.reader.requestSliceRange(p,Zr,en);if(R(h)&&(h=await h),!h)return null;let y=jn(h);if(!y)return null;if(a=y,a.serialNumber===e.serialNumber)break;p=a.headerStartPos+a.totalSize}n=0,s=0,o=0}let l=c.reduce((m,f)=>m+f.length,0);if(l===0)throw new Error("Invalid Ogg stream: empty packets are only allowed at the very end of a stream.");let u=new Uint8Array(l),d=0;for(let m=0;m<c.length;m++){let f=c[m];u.set(f,d),d+=f.length}return{data:u,endPage:a,endSegmentIndex:o}}async findNextPacketStart(e){let r=e.endPage,n=e.endSegmentIndex+1;if(n===r.lacingValues.length){if(!!(r.headerType&4))return null;let o=r.headerStartPos+r.totalSize;for(;;){let c=this.reader.requestSliceRange(o,Zr,en);if(R(c)&&(c=await c),!c)return null;let l=jn(c);if(!l)return null;if(l.serialNumber===r.serialNumber){r=l,n=0;break}o=l.headerStartPos+l.totalSize}}return!!(r.headerType&4)&&n===r.lacingValues.length-1&&r.lacingValues[n]===0?null:{startPage:r,startSegmentIndex:n}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return jo({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},hu=class{constructor(t,e){this.bitstream=t;this.demuxer=e;this.encodedPacketToMetadata=new WeakMap;this.sequentialScanCache=[];this.sequentialScanMutex=new Ee;this.firstTimestampInSamplesPromise=null;let r=t.codecInfo.codec;b(r),r==="vorbis"?this.internalSampleRate=t.sampleRate:r==="opus"?this.internalSampleRate=tt:(Z(r),b(!1))}getType(){return"audio"}getNumber(){let t=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return b(t!==-1),t+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return b(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 le}getDisposition(){return{...Ve,primary:!1}}granulePositionToTimestampInSamples(t){let e=this.bitstream.codecInfo.codec;if(b(e),e==="vorbis")return t;if(e==="opus")return b(this.bitstream.codecInfo.opusInfo),t-this.bitstream.codecInfo.opusInfo.preSkip;Z(e),b(!1)}createEncodedPacketFromOggPacket(t,e,r){if(!t)return null;let{durationInSamples:n,vorbisBlockSize:a}=Ga(t.data,this.bitstream.codecInfo,e.vorbisLastBlocksize),s=new ee(r.metadataOnly?Ae:t.data,"key",e.timestampInSamples/this.internalSampleRate,n/this.internalSampleRate,t.endPage.headerStartPos+t.endSegmentIndex,t.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:t,timestampInSamples:e.timestampInSamples,durationInSamples:n,vorbisLastBlockSize:e.vorbisLastBlocksize,vorbisBlockSize:a}),s}getFirstTimestampInSamples(){return this.firstTimestampInSamplesPromise??=(async()=>{let t=this.granulePositionToTimestampInSamples(0);b(this.bitstream.lastMetadataPacket);let e=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!e)return t;let r=null,n=0,a=null,s=null;for(;e;){let u=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);if(!u||(r??=u.endPage,u.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:d,vorbisBlockSize:m}=Ga(u.data,this.bitstream.codecInfo,s);n+=d,a??=d,s=m,e=await this.demuxer.findNextPacketStart(u)}if(!r)return t;b(a!==null);let o=r.granulePosition-n;if(r.granulePosition!==-1&&!(r.headerType&4))return t+o;let c=this.bitstream.codecInfo.codec;b(c);let l;return c==="vorbis"?l=-a:c==="opus"?l=0:(Z(c),b(!1)),t+Math.max(o,l)})()}async getFirstPacket(t){b(this.bitstream.lastMetadataPacket);let e=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!e)return null;let r=await this.getFirstTimestampInSamples(),n=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);return this.createEncodedPacketFromOggPacket(n,{timestampInSamples:r,vorbisLastBlocksize:null},t)}async getNextPacket(t,e){let r=this.encodedPacketToMetadata.get(t);if(!r)throw new Error("Packet was not created from this track.");let n=await this.demuxer.findNextPacketStart(r.packet);if(!n)return null;let a=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(n.startPage,n.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},e)}async getPacket(t,e){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(t,e);let r=Fe(t*this.internalSampleRate),n=await this.getFirstTimestampInSamples();if(r===n)return this.getFirstPacket(e);if(r<n)return null;b(this.bitstream.lastMetadataPacket);let a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,o=this.demuxer.reader.fileSize,c=[s];e:for(;s.headerStartPos+s.totalSize<o;){let T=s.headerStartPos,S=Math.floor((T+o)/2),w=S;for(;;){let A=Math.min(w+Xo,o-Zr),C=this.demuxer.reader.requestSlice(w,Math.max(A-w,0));if(R(C)&&(C=await C),!C||!vf(C,A,this.bitstream.serialNumber)){if(o<=S+Zr)break e;o=S+Zr;continue e}let E=C.filePos,I=this.demuxer.reader.requestSliceRange(E,Zr,en);R(I)&&(I=await I);let x=I&&jn(I);if(!x||x.serialNumber!==this.bitstream.serialNumber){w=E+4;continue}if(x.granulePosition===-1){w=x.headerStartPos+x.totalSize;continue}this.granulePositionToTimestampInSamples(x.granulePosition)>r||x.headerStartPos+x.totalSize>this.demuxer.reader.fileSize?o=x.headerStartPos:(s=x,c.push(x));continue e}}let l=a.startPage;for(let T of c){if(T.granulePosition===s.granulePosition)break;(!l||T.headerStartPos>l.headerStartPos)&&(l=T)}let u=l,d=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===s.granulePosition);){let T=u.headerStartPos+u.totalSize,S=this.demuxer.reader.requestSliceRange(T,Zr,en);R(S)&&(S=await S);let w=S&&jn(S);if(!w){u=s,d.push(s);break}u=w,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}let m=null,f,p,h=u,y=0;if(u.headerStartPos===a.startPage.headerStartPos)f=n,p=!0,m=0;else{b(u.granulePosition!==-1),f=0,p=!1;for(let w=u.lacingValues.length-1;w>=0;w--)if(u.lacingValues[w]<255){m=w+1;break}if(m===null)throw new Error("Invalid page with granule position: no packets end on this page.");y=m-1;let T={data:Ae,endPage:h,endSegmentIndex:y},S=await this.demuxer.findNextPacketStart(T);if(S){let w=Mf(d,u,m);b(w);let A=Ff(d,w.page,w.segmentIndex);A?(u=A.page,m=A.segmentIndex):(u=S.startPage,m=S.startSegmentIndex,f=this.granulePositionToTimestampInSamples(h.granulePosition),p=!0)}else for(;;){let w=Mf(d,u,m);if(!w)break;let A=Ff(d,w.page,w.segmentIndex);if(!A)break;if(u=A.page,m=A.segmentIndex,w.page.headerStartPos!==h.headerStartPos){h=w.page,y=w.segmentIndex;break}}}let g=null,k=null;for(;u!==null;){b(m!==null);let T=await this.demuxer.readPacket(u,m);if(!T)break;if(!(u.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let A=this.createEncodedPacketFromOggPacket(T,{timestampInSamples:f,vorbisLastBlocksize:k?.vorbisBlockSize??null},e);b(A);let C=this.encodedPacketToMetadata.get(A);if(b(C),!p&&T.endPage.headerStartPos===h.headerStartPos&&T.endSegmentIndex===y?(f=this.granulePositionToTimestampInSamples(h.granulePosition),p=!0,A=this.createEncodedPacketFromOggPacket(T,{timestampInSamples:f-C.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},e),b(A),C=this.encodedPacketToMetadata.get(A),b(C)):f+=C.durationInSamples,g=A,k=C,p&&(f>r||C.timestampInSamples===r))break}let w=await this.demuxer.findNextPacketStart(T);if(!w)break;u=w.startPage,m=w.startSegmentIndex}return g}async getPacketSequential(t,e){let r=await this.sequentialScanMutex.acquire();try{let n=Fe(t*this.internalSampleRate);t=n/this.internalSampleRate;let a=X(this.sequentialScanCache,n,c=>c.timestampInSamples),s;if(a!==-1){let c=this.sequentialScanCache[a];s=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},e)}else if(s=await this.getFirstPacket(e),s&&s.timestamp>t)return null;let o=0;for(;s&&s.timestamp<t;){let c=await this.getNextPacket(s,e);if(!c||c.timestamp>t)break;if(s=c,o++,o===100){o=0;let l=this.encodedPacketToMetadata.get(s);b(l),this.sequentialScanCache.length>0&&b(J(this.sequentialScanCache).timestampInSamples<=l.timestampInSamples),this.sequentialScanCache.push(l)}}return s}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}},Ff=(i,t,e)=>{let r=t,n=e;e:for(;;){for(n--,n;n>=0;n--)if(r.lacingValues[n]<255){n++;break e}if(b(n===-1),!(r.headerType&1)){n=0;break}let s=Il(i,o=>o.headerStartPos<r.headerStartPos);if(!s)return null;r=s,n=r.lacingValues.length}if(b(n!==-1),n===r.lacingValues.length){let a=i[i.indexOf(r)+1];b(a),r=a,n=0}return{page:r,segmentIndex:n}},Mf=(i,t,e)=>{if(e>0)return{page:t,segmentIndex:e-1};let r=Il(i,n=>n.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var Yo=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.dataSizeCapped=!1;this.dataSizeIsPlaceholder=!1;this.audioInfo=null;this.trackBackings=[];this.metadataTags={};this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);R(e)&&(e=await e),b(e);let r=ae(e,4),n=r!=="RIFX",a=r==="RF64",s=Jr(e,n),o=!a&&s===0,c=a||o||s===4294967295?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(ae(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let u=0,d=null,m=e.filePos;for(;c===null||m<c;){let p=this.reader.requestSlice(m,8);if(R(p)&&(p=await p),!p)break;let h=ae(p,4),y=Jr(p,n),g=p.filePos;if(a&&u===0&&h!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(h==="fmt ")await this.parseFmtChunk(g,y,n);else if(h==="data"){if(d??=y,(o&&d===0||!a&&d===4294967295)&&(d=Number.MAX_SAFE_INTEGER,y=d),this.dataSizeIsPlaceholder=d===Number.MAX_SAFE_INTEGER,a&&(y=d),this.dataStart=p.filePos,this.dataSize=Math.max(Math.min(d,(c??1/0)-this.dataStart),0),this.reader.fileSize===null)break}else if(h==="ds64"){let k=this.reader.requestSlice(g,y);if(R(k)&&(k=await k),!k)break;if(y<16)throw new Error('Invalid RF64 file: "ds64" chunk is too small.');let T=Math.min(bu(k,n),Number.MAX_SAFE_INTEGER);d=Math.min(bu(k,n),Number.MAX_SAFE_INTEGER),o=T===0,c=o?this.reader.fileSize:Math.min(T+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(g,y,n):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(g,y);m=g+y+(y&1),u++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');let f=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/f)*f,this.maybeCapDataSize(),this.trackBackings.push(new gu(this))})()}async parseFmtChunk(e,r,n){let a=this.reader.requestSlice(e,r);if(R(a)&&(a=await a),!a)return;if(r<14)throw new Error('Invalid WAVE file - "fmt " chunk is too small');let s=Qa(a,n),o=Qa(a,n),c=Jr(a,n);if(a.skip(6),o===0||c===0)throw new Error("Invalid WAVE file - channel count and sample rate must be positive");let l;if(r<16?l=8:l=Qa(a,n),r>=18&&s!==357){let d=Qa(a,n),m=r-18;if(Math.min(m,d)>=22&&s===65534){a.skip(6);let p=V(a,16);s=p[0]|p[1]<<8}}if((s===7||s===6)&&(l=8),s!==1&&s!==3&&s!==6&&s!==7)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and \u03BC-law are supported.`);if(s===1&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(s===3&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);let u=Math.ceil(l/8);this.audioInfo={format:s,numberOfChannels:o,sampleRate:c,sampleSizeInBytes:u,blockSizeInBytes:o*u}}async parseListChunk(e,r,n){if(r<4)return;let a=this.reader.requestSlice(e,r);if(R(a)&&(a=await a),!a)return;let s=ae(a,4);if(s!=="INFO"&&s!=="INF0")return;let o=a.filePos;for(;o<=e+r-8;){a.filePos=o;let c=ae(a,4),l=Jr(a,n);if(l>a.remainingLength)break;let u=V(a,l),d=u.indexOf(0),m=u.subarray(0,d===-1?u.length:d),f;try{f=Cd.decode(m)}catch{f="";for(let p of m)f+=String.fromCharCode(p)}switch(this.metadataTags.raw??={},this.metadataTags.raw[c]=f,c){case"INAM":case"TITL":this.metadataTags.title??=f;break;case"TIT3":this.metadataTags.description??=f;break;case"IART":this.metadataTags.artist??=f;break;case"IPRD":this.metadataTags.album??=f;break;case"IPRT":case"ITRK":case"TRCK":{let p=f.split("/"),h=Number.parseInt(p[0],10),y=p[1]&&Number.parseInt(p[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),y&&Number.isInteger(y)&&y>0&&(this.metadataTags.tracksTotal??=y)}break;case"ICRD":{let p=Kt(f);p&&(this.metadataTags.date??=p)}break;case"YEAR":{let p=Number.parseInt(f,10),h=En(p);p>0&&!Number.isNaN(h.getTime())&&(this.metadataTags.date??=h)}break;case"IGNR":case"GENR":this.metadataTags.genre??=f;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=f;break}o+=8+l+(l&1)}}async parseId3Chunk(e,r){if(r<Et)return;let n=this.reader.requestSlice(e,r);if(R(n)&&(n=await n),!n)return;let a=Yr(n);if(a){let s=r-Et;if(a.size=Math.min(a.size,s),a.size>0){let o=n.slice(e+Et,a.size);Pi(o,a,this.metadataTags)}}}getCodec(){if(b(this.audioInfo),this.audioInfo.format===7)return"ulaw";if(this.audioInfo.format===6)return"alaw";if(this.audioInfo.format===1){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===3){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}b(!1)}maybeCapDataSize(){if(b(this.audioInfo),this.dataSizeCapped)return;let e=this.reader.fileSize;e!==null&&(this.dataSize=Math.min(this.dataSize,An(e-this.dataStart,this.audioInfo.blockSizeInBytes)),this.dataSizeCapped=!0)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Xn=2048,gu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let t=this.demuxer.getCodec();return t?(b(this.demuxer.audioInfo),{codec:t,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return b(this.demuxer.dataSize!==-1),this.demuxer.maybeCapDataSize(),this.demuxer.dataSizeIsPlaceholder&&!this.demuxer.dataSizeCapped?null:this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return le}getDisposition(){return{...Ve}}async getPacketAtIndex(t,e){b(t>=0),b(this.demuxer.audioInfo);let r=this.demuxer.audioInfo.blockSizeInBytes;this.demuxer.maybeCapDataSize();let n=this.demuxer.reader.fileSize,a=t*Xn*r;if(a>=this.demuxer.dataSize)return null;let s=Math.min(Xn*r,this.demuxer.dataSize-a);if(n===null){let u=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,s);if(R(u)&&(u=await u),!u)return b(this.demuxer.reader.fileSize!==null),this.getPacketAtIndex(t,e)}let o;if(e.metadataOnly)o=Ae;else{let u=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,s);R(u)&&(u=await u),b(u),o=V(u,s)}let c=t*Xn/this.demuxer.audioInfo.sampleRate,l=s/r/this.demuxer.audioInfo.sampleRate;return new ee(o,"key",c,l,t,s)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getPacket(t,e){b(this.demuxer.audioInfo);let r=Math.floor(Math.min(Fe(t*this.demuxer.audioInfo.sampleRate)/Xn,(this.demuxer.dataSize-1)/(Xn*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;let n=await this.getPacketAtIndex(r,e);return n||this.getPacket(t,e)}getNextPacket(t,e){b(this.demuxer.audioInfo);let r=Math.round(t.timestamp*this.demuxer.audioInfo.sampleRate/Xn);return this.getPacketAtIndex(r+1,e)}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var rt=7,Ye=9,ja=async(i,t,e,r)=>{let n=(s,o)=>s.objectType===o.objectType&&s.samplingFrequencyIndex===o.samplingFrequencyIndex&&s.channelConfiguration===o.channelConfiguration,a=i.requestSliceRange(t,rt,e+Ye);if(R(a)&&(a=await a),!a)return null;for(let s=t;s<Math.min(t+e,a.end);s++){if(a.filePos=s,H(a)!==255)continue;a.filePos=s;let o=It(a);if(!o||r&&!n(o,r))continue;let c=s+o.frameLength;if(c===i.fileSize)return o;let l=i.requestSliceRange(c,rt,Ye);R(l)&&(l=await l);let u=l&&It(l);if(u&&n(o,u))return o}return null},It=i=>{let t=i.filePos;if(i.remainingLength<rt)return null;let e=V(i,rt),r=new K(e);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;let s=r.readBits(1),o=r.readBits(2)+1,c=r.readBits(4);if(c>=Xe.length)return null;r.skipBits(1);let l=r.readBits(3);r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let u=r.readBits(13);r.skipBits(11);let d=r.readBits(2)+1;if(d!==1)return null;let m=null;if(s===0){if(i.remainingLength<2)return null;m=fe(i)}return u<i.filePos-t?null:{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:m,startPos:t}};var Zo=1024,Jo=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.numberOfChannels=null;this.loadedSamples=[];this.metadataTags=null;this.trackBackings=[];this.readingMutex=new Ee;this.lastSampleLoaded=!1;this.lastLoadedPos=0;this.nextTimestampInSamples=0;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();let e=this.firstFrameHeader;if(b(e),e.channelConfiguration===0){let r=e.crcCheck===null?rt:Ye,n=this.reader.requestSlice(e.startPos+r,e.frameLength-r);if(R(n)&&(n=await n),!n)throw new Error("Invalid ADTS file: the first frame is cut off.");let a=mr(V(n,e.frameLength-r));if(!a)throw new Error("Invalid ADTS file: frames with channel configuration 0 must begin with a program config element.");this.numberOfChannels=Wr(a.programConfigElement)}else this.numberOfChannels=dr[e.channelConfiguration];this.trackBackings=[new yu(this)]})()}async advanceReader(){let e;if(this.lastLoadedPos===0){let a=await Ar(this.reader,0);e=await ja(this.reader,a,4096,null)}else{let a=this.reader.requestSliceRange(this.lastLoadedPos,rt,Ye);if(R(a)&&(a=await a),e=a&&It(a),!e){b(this.firstFrameHeader);let s=await Ar(this.reader,this.lastLoadedPos);e=await ja(this.reader,s,2**16,this.firstFrameHeader)}}if(!e){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&e.startPos+e.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader??=e;let r=Xe[this.firstFrameHeader.samplingFrequencyIndex];if(b(r!==void 0),e.samplingFrequencyIndex!==this.firstFrameHeader.samplingFrequencyIndex){O._warn(`The sample rate changes mid-stream (from ${r} Hz to ${Xe[e.samplingFrequencyIndex]} Hz), which isn't properly supported or handled by Mediabunny.`),this.lastSampleLoaded=!0;return}let n={timestamp:this.nextTimestampInSamples/r,duration:Zo/r,dataStart:e.startPos,dataSize:e.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=Zo,this.lastLoadedPos=e.startPos+e.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let r=0;for(;;){let n=this.reader.requestSlice(r,Et);if(R(n)&&(n=await n),!n)break;let a=Yr(n);if(!a)break;let s=this.reader.requestSlice(n.filePos,a.size);if(R(s)&&(s=await s),!s)break;Pi(s,a,this.metadataTags),r=n.filePos+a.size}return this.metadataTags}finally{e()}}},yu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return le}getCodec(){return"aac"}getInternalCodecId(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){return b(this.demuxer.numberOfChannels!==null),this.demuxer.numberOfChannels}getSampleRate(){b(this.demuxer.firstFrameHeader);let t=Xe[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return b(t!==void 0),t}getDisposition(){return{...Ve}}async getDecoderConfig(){return b(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(t,e){if(t===-1)return null;let r=this.demuxer.loadedSamples[t];if(!r)return null;let n=this.demuxer.reader.fileSize;if(n!==null&&r.dataStart+r.dataSize>n)return null;let a;if(e.metadataOnly)a=Ae;else{let s=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(R(s)&&(s=await s),!s)return null;a=V(s,r.dataSize)}return new ee(a,"key",r.timestamp,r.duration,t,r.dataSize)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=Vr(this.demuxer.loadedSamples,t.timestamp,s=>s.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");let a=n+1;for(;a>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(a,e)}finally{r()}}async getPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=this.getSampleRate(),a=Fe(t*n)/n;for(;;){let s=X(this.demuxer.loadedSamples,a,o=>o.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,e);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var ec=i=>i===0?null:i===1?192:i>=2&&i<=5?144*2**i:i===6?"uncommon-u8":i===7?"uncommon-u16":i>=8&&i<=15?2**i:null,Bf=(i,t)=>{switch(i){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},tc=i=>{let t=0,e=new K(V(i,1));for(;e.readBits(1)===1;)t++;if(t===0)return e.readBits(7);let r=[],n=t-1,a=new K(V(i,n)),s=8-t-1;for(let c=0;c<s;c++)r.unshift(e.readBits(1));for(let c=0;c<n;c++)for(let l=0;l<8;l++){let u=a.readBits(1);l<2||r.unshift(u)}return r.reduce((c,l,u)=>c+l*2**u,0)},rc=(i,t)=>{if(t==="uncommon-u16")return fe(i)+1;if(t==="uncommon-u8")return H(i)+1;if(typeof t=="number")return t;Z(t),b(!1)},Of=(i,t)=>t==="uncommon-u16"?fe(i):t==="uncommon-u16-10"?fe(i)*10:t==="uncommon-u8"?1e3*H(i):typeof t=="number"?t:null,Df=i=>{let e=0;for(let r of i){e^=r;for(let n=0;n<8;n++)(e&128)!==0?e=e<<1^7:e<<=1,e&=255}return e};var ic=class extends _e{constructor(e){super(e);this.loadedSamples=[];this.metadataPromise=null;this.trackBacking=null;this.metadataTags={};this.audioInfo=null;this.lastLoadedPos=null;this.blockingBit=null;this.readingMutex=new Ee;this.lastSampleLoaded=!1;this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),b(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let r=this.reader.requestSlice(e,Et);if(R(r)&&(r=await r),!r)break;let n=Yr(r);if(!n)break;let a=this.reader.requestSlice(r.filePos,n.size);R(a)&&(a=await a),b(a),Pi(a,n,this.metadataTags),e=r.filePos+n.size}for(e+=4;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(R(r)&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);b(r);let n=H(r),a=$t(r),s=(n&128)!==0;switch(n&127){case 0:{if(a<34)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let c=this.reader.requestSlice(e,a);if(R(c)&&(c=await c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let l=V(c,34),u=new K(l),d=u.readBits(16),m=u.readBits(16),f=u.readBits(24),p=u.readBits(24),h=u.readBits(20);if(h===0)throw new Error("Invalid StreamInfo block: sample rate is 0. Corrupted file.");let y=u.readBits(3)+1;u.readBits(5);let g=u.readBits(36);u.skipBits(16*8);let k=new Uint8Array(42);k.set(new Uint8Array([102,76,97,67]),0),k.set(new Uint8Array([128,0,0,34]),4),k.set(l,8),this.audioInfo={numberOfChannels:y,sampleRate:h,totalSamples:g,minimumBlockSize:d,maximumBlockSize:m,minimumFrameSize:f,maximumFrameSize:p,description:k},this.trackBacking=new ku(this);break}case 4:{let c=this.reader.requestSlice(e,a);if(R(c)&&(c=await c),!c)throw new Error(`Vorbis comment block at position ${e} exceeds the file. Corrupted file.`);ya(V(c,a),this.metadataTags);break}case 6:{let c=this.reader.requestSlice(e,a);if(R(c)&&(c=await c),!c)throw new Error(`Picture block at position ${e} exceeds the file. Corrupted file.`);try{let l=B(c),u=B(c),d=be.decode(V(c,u)),m=B(c),f=be.decode(V(c,m));c.skip(16);let p=B(c),h=V(c,p);this.metadataTags.images??=[],this.metadataTags.images.push({data:h,mimeType:d,kind:l===3?"coverFront":l===4?"coverBack":"unknown",description:f})}catch{}break}default:break}if(e+=a,s)break}if(this.lastLoadedPos=e,!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame(e){b(this.audioInfo);let r=6,n=16,a=10,s=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+n+2,o=this.audioInfo.minimumFrameSize||a,l=(this.audioInfo.maximumFrameSize||s)+n,u=await this.reader.requestSliceRange(e,r,l);if(!u)return null;let d=this.readFlacFrameHeader(u);if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-r)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(H(u)===255){let f=u.filePos,p=H(u),h=this.blockingBit===1?249:248;if(p!==h){u.filePos=f;continue}u.skip(-2);let y=u.filePos-e,g=this.readFlacFrameHeader(u);if(!g){u.filePos=f;continue}if(this.blockingBit===0){if(g.num-d.num!==1){u.filePos=f;continue}}else if(g.num-d.num!==d.blockSize){u.filePos=f;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:y,isLastFrame:!1}}}}readFlacFrameHeader(e){let r=e.filePos,n=V(e,4),a=new K(n);if(a.readBits(15)!==32764)return null;let o=a.readBits(1);if(this.blockingBit!==null&&o!==this.blockingBit)return null;let c=ec(a.readBits(4));if(!c)return null;b(this.audioInfo);let l=Bf(a.readBits(4),this.audioInfo.sampleRate);if(!l||(a.readBits(4),a.readBits(3),a.readBits(1)!==0))return null;let d=H(e);e.skip(-1);let f=4+Math.max(Math.clz32(~d<<24),1)+(c==="uncommon-u16"?2:c==="uncommon-u8"?1:0)+(l==="uncommon-u8"?1:typeof l=="number"?0:2)+1;if(r+f>e.end)return null;let p=tc(e),h=rc(e,c),y=Of(e,l);if(y===null||y!==this.audioInfo.sampleRate)return null;let g=e.filePos-r,k=H(e);e.skip(-g),e.skip(-1);let T=Df(V(e,g));return k!==T?null:(this.blockingBit=o,{num:p,blockSize:h,sampleRate:y})}async advanceReader(){await this.readMetadata(),b(this.lastLoadedPos!==null),b(this.audioInfo);let e=this.lastLoadedPos,r=await this.readNextFlacFrame(e);if(!r){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],s={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};if(this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(s),r.isLastFrame){this.lastSampleLoaded=!0;return}}},ku=class{constructor(t){this.demuxer=t}getType(){return"audio"}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return le}getTimeResolution(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return b(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Ve}}async getDecoderConfig(){return b(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(t,e){if(b(this.demuxer.audioInfo),t<0)return null;let r=await this.demuxer.readingMutex.acquire();try{let n=Fe(t*this.demuxer.audioInfo.sampleRate);for(;;){let a=X(this.demuxer.loadedSamples,n,o=>o.blockOffset);if(a===-1){if(this.demuxer.lastSampleLoaded)return null;await this.demuxer.advanceReader();continue}let s=this.demuxer.loadedSamples[a];if(s.blockOffset+s.blockSize<=n){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,e);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(a,e)}}finally{r()}}async getNextPacket(t,e){let r=await this.demuxer.readingMutex.acquire();try{let n=t.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,e)}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}async getPacketAtIndex(t,e){let r=this.demuxer.loadedSamples[t];if(!r)return null;let n;if(e.metadataOnly)n=Ae;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(R(o)&&(o=await o),!o)return null;n=V(o,r.byteSize)}b(this.demuxer.audioInfo);let a=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.blockSize/this.demuxer.audioInfo.sampleRate;return new ee(n,"key",a,s,t,r.byteSize)}async getFirstPacket(t){let e=await this.demuxer.readingMutex.acquire();try{for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,t)}finally{e()}}};var Ue=9e4,$n=2**33,ze=188;var nc=i=>{let t="video/MP2T",e=[...new Set(i.filter(Boolean))];return e.length>0&&(t+=`; codecs="${e.join(", ")}"`),t},Xa=i=>vl(Math.round(Ue*i),$n),ac=i=>{let t=60*Ue;return{reference:i>=$n-t?i-t-$n:i-t}},sc=(i,t)=>t.reference+vl(i-t.reference,$n);var Nf="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.",Vf=5,lg=1212435798,ug=1212436562,dg=1146376960,mg=new Set([133,134,162]),Uf=new Set,oc=class i extends _e{constructor(e){super(e);this.metadataPromise=null;this.elementaryStreams=[];this.trackBackingEntries=[];this.packetOffset=0;this.packetStride=-1;this.sectionEndPositions=[];this.seekChunkSize=5*1024*1024;this.minReferencePointByteDistance=-1;this.timestampWrapInfo=null;this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=ze+16+1,r=this.reader.requestSlice(0,e);R(r)&&(r=await r),b(r);let n=V(r,e);if(n[0]===71&&n[ze]===71)this.packetOffset=0,this.packetStride=ze;else if(n[0]===71&&n[ze+16]===71)this.packetOffset=0,this.packetStride=ze+16;else if(n[4]===71&&n[4+ze+4]===71)this.packetOffset=4,this.packetStride=ze+4;else throw new Error("Unreachable.");let a=256;this.minReferencePointByteDistance=a*this.packetStride;let s=this.packetOffset,o=null,c=!1,l=!1,u=null;for(;;){let d=await this.readPacketHeader(s);if(!d)break;if(d.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(l&&!this.elementaryStreams.some(g=>g.pid===d.pid&&!g.initialized)){s+=this.packetStride;continue}let m=this.elementaryStreams.some(g=>g.pid===d.pid),f=await this.readSection(s,!m,!l);if(!f)break;let p=32,h=!1;if(!l&&f.pid!==0&&(o===null||f.pid===o)&&!(f.payload[0]===0&&f.payload[1]===0&&f.payload[2]===1)){let k=new K(f.payload),T=k.readAlignedByte();k.skipBits(8*T),h=k.readBits(8)===2}if(f.pid===0&&!c){let g=new K(f.payload),k=g.readAlignedByte();g.skipBits(8*k),g.skipBits(14);let T=g.readBits(10),S=g.pos+8*T;for(g.skipBits(40);S-g.pos>p;){let w=g.readBits(16);g.skipBits(3);let A=g.readBits(13);if(w!==0){if(o!==null)throw new Error("Only files with a single program are supported.");o=A}}if(o===null)throw new Error("Program Association Table must link to a Program Map Table.");c=!0}else if(h){let g=new K(f.payload),k=g.readAlignedByte();g.skipBits(8*k),g.skipBits(12);let T=g.readBits(12),S=g.pos+8*T;g.skipBits(43);let w=g.readBits(13);g.skipBits(6);let A=g.readBits(10),C=g.pos+8*A,E=!1;for(;g.pos<C;){let I=g.readBits(8),x=g.readBits(8),P=g.pos+8*x;if(I===Vf&&x>=4){let v=g.readBits(32);E||=v===lg||v===ug}g.pos=P}for(g.pos=C;S-g.pos>p;){let I=g.readBits(8);g.skipBits(3);let x=g.readBits(13);g.skipBits(6);let P=g.readBits(10),v=g.pos+8*P,_=!1,M=!1,U=!1;for(;g.pos<v;){let G=g.readBits(8),me=g.readBits(8),ye=g.pos+8*me;if(G===106)_=!0;else if(G===122||G===204)M=!0;else if(G===123)U=!0;else if(G===Vf&&me>=4){let ke=g.readBits(32);U||=(ke&4294967040)===dg}g.pos=ye}let N=null,L=E&&mg.has(I)?130:I;switch(L){case 27:case 36:N={type:"video",codec:I===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:case 130:case 138:{let G;L===3||L===4?G="mp3":L===15?G="aac":L===129?G="ac3":L===135?G="eac3":G="dts",N={type:"audio",codec:G,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:M?N={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:_?N={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:U&&(N={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Uf.has(I)||(O._warn(`Note: MPEG-TS streams with stream_type 0x${I.toString(16)} are not currently supported.`),Uf.add(I))}N&&this.elementaryStreams.push({demuxer:this,pid:x,streamType:I,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:N,referencePesPackets:[]})}l=!0}else{let g=this.elementaryStreams.find(k=>k.pid===f.pid);e:if(g&&!g.initialized){if(!ei(this,f,!0))throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${g.pid}`);g.firstSection=f,g.canBeTrustedWithKeyPackets=f.randomAccessIndicator===1;let T=new tn(g,f.startPos);if(g.info.type==="video"){let S=0;for(;;){if(S===1&&this.input._initInput){if(!u){if(u=await this.input._initInput._getDemuxer(),u.constructor!==i)throw new Error("Init input must match the input's format.");await u.readMetadata()}let A=u.elementaryStreams.find(C=>C.pid===f.pid&&C.info.codec===g.info.codec&&C.initialized);if(A){g.info=A.info,g.initialized=!0;break e}}S++;let w=T;if(w.suppliedPacket=null,await T.markNextPacket(),g.info.codec==="avc"){if(!T.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(g.info.avcCodecInfo=hr(T.suppliedPacket.data),!g.info.avcCodecInfo)continue;let A=g.info.avcCodecInfo.sequenceParameterSets[0];b(A);let C=Gt(A);g.info.width=C.displayWidth,g.info.height=C.displayHeight;let E=C.pixelAspectRatio.num,I=C.pixelAspectRatio.den;g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=g.info.height,E>0&&I>0&&(E>I?g.info.squarePixelWidth=Math.round(g.info.width*E/I):g.info.squarePixelHeight=Math.round(g.info.height*I/E)),g.info.colorSpace={primaries:Tt[C.colourPrimaries],transfer:wt[C.transferCharacteristics],matrix:St[C.matrixCoefficients],fullRange:!!C.fullRangeFlag},g.info.reorderSize=C.maxDecFrameBuffering;break}else if(g.info.codec==="hevc"){if(!T.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(g.info.hevcCodecInfo=br(T.suppliedPacket.data),!g.info.hevcCodecInfo)continue;let C=g.info.hevcCodecInfo.arrays.find(P=>P.nalUnitType===33).nalUnits[0];b(C);let E=Qi(C);g.info.width=E.displayWidth,g.info.height=E.displayHeight;let I=E.pixelAspectRatio.num,x=E.pixelAspectRatio.den;g.info.squarePixelWidth=g.info.width,g.info.squarePixelHeight=g.info.height,I>0&&x>0&&(I>x?g.info.squarePixelWidth=Math.round(g.info.width*I/x):g.info.squarePixelHeight=Math.round(g.info.height*x/I)),g.info.colorSpace={primaries:Tt[E.colourPrimaries],transfer:wt[E.transferCharacteristics],matrix:St[E.matrixCoefficients],fullRange:!!E.fullRangeFlag},g.info.reorderSize=E.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}g.info.decoderConfig={codec:Si({width:g.info.width,height:g.info.height,codec:g.info.codec,codecDescription:null,colorSpace:g.info.colorSpace,avcType:1,avcCodecInfo:g.info.avcCodecInfo,hevcType:"hev1",hevcCodecInfo:g.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:g.info.width,codedHeight:g.info.height,colorSpace:g.info.colorSpace},(g.info.width!==g.info.squarePixelWidth||g.info.height!==g.info.squarePixelHeight)&&(g.info.decoderConfig.displayAspectWidth=g.info.squarePixelWidth,g.info.decoderConfig.displayAspectHeight=g.info.squarePixelHeight),g.initialized=!0}else{if(await T.markNextPacket(),!T.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${g.pid}`);if(g.info.codec==="aac"){let S=xe.tempFromBytes(T.suppliedPacket.data),w=It(S);if(!w)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");if(g.info.aacCodecInfo={isMpeg2:!1,objectType:w.objectType},w.channelConfiguration===0){let A=w.crcCheck===null?rt:Ye,C=mr(T.suppliedPacket.data.subarray(A,w.frameLength));if(!C)throw new Error("Invalid AAC audio stream; ADTS frames with channel configuration 0 must begin with a program config element.");g.info.numberOfChannels=Wr(C.programConfigElement)}else g.info.numberOfChannels=dr[w.channelConfiguration];g.info.sampleRate=Xe[w.samplingFrequencyIndex]}else if(g.info.codec==="mp3"){let S=B(xe.tempFromBytes(T.suppliedPacket.data)),w=fr(S,T.suppliedPacket.data.byteLength);if(!w.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");g.info.numberOfChannels=fi(w.header.channel),g.info.sampleRate=w.header.sampleRate}else if(g.info.codec==="ac3"){let S=Ys(T.suppliedPacket.data);if(!S)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(S.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");g.info.numberOfChannels=Ta[S.acmod]+S.lfeon,g.info.sampleRate=Ki[S.fscod]}else if(g.info.codec==="eac3"){let S=Js(T.suppliedPacket.data);if(!S)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let w=to(S);if(w===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");g.info.numberOfChannels=ro(S),g.info.sampleRate=w}else if(g.info.codec==="dts"){let S=xa(T.suppliedPacket.data);if(!S)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");g.info.numberOfChannels=S.numberOfChannels,g.info.sampleRate=S.sampleRate,S.core&&(g.info.dtsFormat=S.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");g.info.decoderConfig={codec:Ln({codec:g.info.codec,codecDescription:null,aacCodecInfo:g.info.aacCodecInfo,dtsFormat:g.info.dtsFormat}),numberOfChannels:g.info.numberOfChannels,sampleRate:g.info.sampleRate},g.initialized=!0}}}if(l&&this.elementaryStreams.every(g=>g.initialized))break;h?s=this.packetOffset:s+=this.packetStride}if(!l)throw c?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let d of this.elementaryStreams)d.initialized&&(d.info.type==="video"?this.trackBackingEntries.push(new Tu(d)):this.trackBackingEntries.push(new wu(d)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackingEntries.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return nc(e)}async readSection(e,r,n=!1){let a=e,s=e,o=[],c=0,l=null,u=!0,d=0;for(;;){let f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(!l)b(f.payloadUnitStartIndicator===1),l=f;else{if(f.pid!==l.pid)if(n){u=!1;break}else continue;if(f.payloadUnitStartIndicator===1)break}let p=!!(f.adaptationFieldControl&2),h=!!(f.adaptationFieldControl&1),y=0;if(p&&(y=1+f.body[0],f===l&&y>1&&(d=f.body[1]>>6&1)),h&&(y===0?(o.push(f.body),c+=f.body.byteLength):(o.push(f.body.subarray(y)),c+=f.body.byteLength-y)),a=s,!r&&c>=64){u=!1;break}if(Vr(this.sectionEndPositions,a,k=>k)!==-1){u=!1;break}}if(u){let f=X(this.sectionEndPositions,a,p=>p);this.sectionEndPositions.splice(f+1,0,a)}if(!l)return null;let m;if(o.length===1)m=o[0];else{let f=o.reduce((h,y)=>h+y.length,0);m=new Uint8Array(f);let p=0;for(let h of o)m.set(h,p),p+=h.length}return{startPos:e,pid:l.pid,payload:m,randomAccessIndicator:d}}async readPacketHeader(e){let r=this.reader.requestSlice(e,4);if(R(r)&&(r=await r),!r)return null;if(H(r)!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");let a=fe(r),s=a>>15,o=a>>14&1,c=a>>13&1,l=a&8191,u=H(r),d=u>>6,m=u>>4&3,f=u&15;return{payloadUnitStartIndicator:o,pid:l,adaptationFieldControl:m}}async readPacket(e){let r=this.reader.requestSlice(e,ze);if(R(r)&&(r=await r),!r)return null;let n=V(r,ze);if(n[0]!==71)throw new Error("Invalid TS packet sync byte; the file is likely corrupted.");let s=(n[1]<<8)+n[2],o=s>>15,c=s>>14&1,l=s>>13&1,u=s&8191,d=n[3],m=d>>6,f=d>>4&3,p=d&15;return{payloadUnitStartIndicator:c,pid:u,adaptationFieldControl:f,body:n.subarray(4)}}normalizeTimestamp(e){return this.timestampWrapInfo??=ac(e),sc(e,this.timestampWrapInfo)}},ei=(i,t,e)=>{if(t.payload.byteLength<3)return null;let r=new K(t.payload);if(r.readBits(24)!==1)return null;let a=r.readBits(8);if(r.skipBits(16),a===188||a===190||a===191||a===240||a===241||a===255||a===242||a===248)return null;r.skipBits(8);let s=r.readBits(2);r.skipBits(14);let o=null;if(s===2||s===3)o=0,r.skipBits(4),o+=r.readBits(3)*(1<<30),r.skipBits(1),o+=r.readBits(15)*32768,r.skipBits(1),o+=r.readBits(15),o=i.normalizeTimestamp(o);else if(e)throw new Error(Nf);return{sectionStartPos:t.startPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},cc=class i{constructor(t){this.elementaryStream=t;this.packetBuffers=new WeakMap;this.packetSectionStarts=new WeakMap}getNumber(){let t=this.elementaryStream.demuxer,e=this.elementaryStream.info.type,r=0;for(let n of t.trackBackingEntries)if(n.getType()===e&&r++,b(n instanceof i),n.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return le}getDisposition(){return{...Ve,primary:!1}}getTimeResolution(){return Ue}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(t,e,r){let n;return this.allPacketsAreKeyPackets()?n="key":n=t.randomAccessIndicator===1?"key":"delta",new ee(r.metadataOnly?Ae:t.data,n,t.pts/Ue,Math.max(e/Ue,0),t.sequenceNumber,t.data.byteLength)}async getFirstPacket(t){let e=this.elementaryStream.firstSection;b(e);let r=new tn(this.elementaryStream,e.startPos),n=new $a(this,r),a=await n.readNext();if(!a)return null;let s=this.createEncodedPacket(a.packet,a.duration,t);return this.packetBuffers.set(s,n),this.packetSectionStarts.set(s,a.packet.sectionStartPos),s}async getNextPacket(t,e){let r=this.packetBuffers.get(t);if(r){this.packetBuffers.delete(t);let d=await r.readNext();if(!d)return null;let m=this.createEncodedPacket(d.packet,d.duration,e);return this.packetBuffers.set(m,r),this.packetSectionStarts.set(m,d.packet.sectionStartPos),m}let n=this.packetSectionStarts.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");let a=this.elementaryStream.demuxer,s=n,o=this.getReorderSize(),c=n-a.packetStride;for(;o>0&&c>=a.packetOffset;){let d=await a.readPacketHeader(c);if(b(d),d.pid===this.elementaryStream.pid&&d.payloadUnitStartIndicator===1){let m=await a.readSection(c,!1);b(m);let f=ei(a,m,!1);f&&f.pts!==null&&(s=c,o--)}c-=a.packetStride}let l=new tn(this.elementaryStream,s);r=new $a(this,l);let u=t.sequenceNumber;for(;;){let d=await r.readNext();if(!d)return null;if(d.packet.sequenceNumber>u){let m=this.createEncodedPacket(d.packet,d.duration,e);return this.packetBuffers.set(m,r),this.packetSectionStarts.set(m,d.packet.sectionStartPos),m}}}async getNextKeyPacket(t,e){let r=t;for(;;){if(r=await this.getNextPacket(r,e),!r)return null;if(r.type==="key")return r}}getPacket(t,e){return this.doPacketLookup(t,!1,e)}getKeyPacket(t,e){return this.doPacketLookup(t,!0,e)}async doPacketLookup(t,e,r){let n=Fe(t*Ue),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:o}=a,c=this.elementaryStream.pid,l=async(T,S)=>{let w=T;for(;w<S;){let A=await a.readPacketHeader(w);if(!A)return null;if(A.pid===c&&A.payloadUnitStartIndicator===1){let C=await a.readSection(w,!1);if(!C)return null;let E=ei(a,C,!1);if(E&&E.pts!==null)return E}w+=a.packetStride}return null},u=this.elementaryStream.firstSection;b(u);let d=ei(a,u,!0);b(d);let m,f=this.elementaryStream.referencePesPackets,p=X(f,n,T=>T.pts),h=p!==-1?f[p]:null;if(h&&n-h.pts<Ue/2)m=h.sectionStartPos;else{let T=0;if(s.fileSize!==null&&n>=d.pts){let S=Math.ceil(s.fileSize/o);if(S>1){let w=0,A=S-1;for(T=w;w<=A;){let C=Math.floor((w+A)/2),E=An(C*o,a.packetStride)+d.sectionStartPos,I=E+o,x=await l(E,I);if(!x){A=C-1;continue}x.pts<=n?(T=C,w=C+1):A=C-1}}}m=An(T*o,a.packetStride)+d.sectionStartPos}let y=await l(m,s.fileSize??1/0);y||(y=d);let g=this.getReorderSize(),k=async(T,S)=>{let w=new tn(this.elementaryStream,T),A=new $a(this,w);for(;!((J(A.presentationOrderPackets)?.pts??-1/0)>=n||!await A.readNextPacket()););let C=lr(A.presentationOrderPackets,S);if(C===-1)return null;let E=A.presentationOrderPackets[C];A.decodeOrderPackets.splice(0,A.decodeOrderPackets.indexOf(E));let I=await A.readNext();b(I);let x=this.createEncodedPacket(I.packet,I.duration,r);return this.packetBuffers.set(x,A),this.packetSectionStarts.set(x,I.packet.sectionStartPos),x};if(!e||this.allPacketsAreKeyPackets()){e:for(;;){let T=y.sectionStartPos+a.packetStride;for(;;){let S=await a.readPacketHeader(T);if(!S)break e;if(S.pid===c&&S.payloadUnitStartIndicator===1){let w=await a.readSection(T,!1);if(w){let A=ei(a,w,!1);if(A&&A.pts!==null){if(A.pts>n)break e;y=A,Su(this.elementaryStream,y);break}}}T+=a.packetStride}}e:for(let T=0;T<g+1;T++){let S=y.sectionStartPos-a.packetStride;for(;S>=d.sectionStartPos;){let w=await a.readPacketHeader(S);if(!w)break e;if(w.pid===c&&w.payloadUnitStartIndicator===1){let A=await a.readSection(S,!1);if(A){let C=ei(a,A,!1);if(C&&C.pts!==null){y=C;break}}}S-=a.packetStride}if(S<d.sectionStartPos)break}return k(y.sectionStartPos,T=>T.pts<=n)}else{let T=m,S=null;for(;;){let w=null,A=T<=d.sectionStartPos,C;A?C=d:C=await l(T,S??s.fileSize??1/0);let E=!1,I=0,x=null;e:for(;C&&!(S!==null&&C.sectionStartPos>=S);){if(C.pts<=n){let v;if(this.elementaryStream.canBeTrustedWithKeyPackets)v=C.randomAccessIndicator===1;else{for(x??=new tn(this.elementaryStream,C.sectionStartPos);(!x.suppliedPacket||x.suppliedPacket.sectionStartPos<C.sectionStartPos)&&(x.suppliedPacket=null,await x.markNextPacket(),!!x.suppliedPacket););v=x.suppliedPacket?.sectionStartPos===C.sectionStartPos&&x.suppliedPacket.randomAccessIndicator===1}v&&(w=C)}if(C.pts>n&&(E=!0),E&&(I++,I>g))break;let P=C.sectionStartPos+a.packetStride;for(;;){let v=await a.readPacketHeader(P);if(!v)break e;if(v.pid===c&&v.payloadUnitStartIndicator===1){let _=await a.readSection(P,!1);if(_){let M=ei(a,_,!1);if(M&&M.pts!==null){C=M,Su(this.elementaryStream,C);break}}}P+=a.packetStride}}if(w){let P=w;if(I===0)e:for(let _=0;_<g+1;_++){let M=P.sectionStartPos-a.packetStride;for(;M>=d.sectionStartPos;){let U=await a.readPacketHeader(M);if(!U)break e;if(U.pid===c&&U.payloadUnitStartIndicator===1){let N=await a.readSection(M,!1);if(N){let L=ei(a,N,!1);if(L&&L.pts!==null){P=L;break}}}M-=a.packetStride}if(M<d.sectionStartPos)break}let v=await k(P.sectionStartPos,_=>_.pts<=n&&_.randomAccessIndicator===1);if(v)return v}if(A)return null;S=T,T=Math.max(An(T-d.sectionStartPos-o,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},Tu=class extends cc{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}getTransformationMatrix(){return[...si]}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return b(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},wu=class extends cc{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return b(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},Su=(i,t)=>{let e=i.referencePesPackets,r=X(e,t.sectionStartPos,a=>a.sectionStartPos),n=i.demuxer.minReferencePointByteDistance;if(r>=0){let a=e[r];if(t.pts<=a.pts||t.sectionStartPos-a.sectionStartPos<n)return!1}if(r<e.length-1){let a=e[r+1];if(a.pts<t.pts||a.sectionStartPos-t.sectionStartPos<n)return!1}return e.splice(r+1,0,{sectionStartPos:t.sectionStartPos,pts:t.pts,randomAccessIndicator:t.randomAccessIndicator}),!0},tn=class{constructor(t,e){this.reachedEnd=!1;this.isInPesPacket=!1;this.pesHeaderBytesLeft=0;this.pesDataBytesLeft=0;this.currentPos=0;this.endPos=0;this.scratch=new Uint8Array(2**16);this.scratchStartPos=0;this.pesPackets=[];this.pesPacketDataStartPositions=[];this.lastSuppliedPesPacket=null;this.nextPts=null;this.suppliedPacket=null;this.elementaryStream=t,this.pid=t.pid,this.demuxer=t.demuxer,this.nextTsPacketPos=e}ensureBuffered(t){let e=this.endPos-this.currentPos;return e>=t?t:this.bufferData(t-e).then(()=>Math.min(this.endPos-this.currentPos,t))}async bufferData(t){let e=this.endPos+t;for(;this.endPos<e&&!this.reachedEnd;){let r=this.nextTsPacketPos,n=await this.demuxer.readPacket(r);if(!n){this.reachedEnd=!0;break}if(this.nextTsPacketPos+=this.demuxer.packetStride,n.pid!==this.pid)continue;if(n.payloadUnitStartIndicator===1){this.isInPesPacket=!1;let d=await this.demuxer.readSection(r,!1);b(d);let m=ei(this.demuxer,d,!1);if(!m)continue;let f=new K(d.payload);f.skipBits(32);let p=f.readBits(16),h=6;f.skipBits(16);let y=f.readBits(8);this.pesHeaderBytesLeft=f.pos/8+y,this.pesDataBytesLeft=p>0?Math.max(h+p-this.pesHeaderBytesLeft,0):1/0,this.isInPesPacket=!0,this.pesPackets.push(m),this.pesPacketDataStartPositions.push(this.endPos)}if(!this.isInPesPacket||!(n.adaptationFieldControl&1))continue;let a=n.body,s=n.adaptationFieldControl&2?1+a[0]:0,o=Math.min(this.pesHeaderBytesLeft,Math.max(a.byteLength-s,0));this.pesHeaderBytesLeft-=o,s+=o;let c=Math.min(a.byteLength,s+this.pesDataBytesLeft);if(c<=s)continue;let l=c-s;this.pesDataBytesLeft-=l;let u=this.endPos-this.scratchStartPos;if(u+l>this.scratch.byteLength){let d=new Uint8Array(2*this.scratch.byteLength);d.set(this.scratch.subarray(0,u)),this.scratch=d}this.scratch.set(a.subarray(s,c),u),this.endPos+=l}}readBytes(t){let e=this.currentPos-this.scratchStartPos;return this.currentPos+=t,this.scratch.subarray(e,e+t)}readU8(){return this.scratch[this.currentPos++-this.scratchStartPos]}seekTo(t){b(t>=this.scratchStartPos),this.currentPos=t}skip(t){this.seekTo(this.currentPos+t)}async markNextPacket(){b(!this.suppliedPacket);let t=this.elementaryStream;if(t.info.type==="video"){let e=t.info.codec,r=1024;if(e!=="avc"&&e!=="hevc")throw new Error("Unhandled.");let n=e==="avc"?1:2,a=null,s=!1,o=0;for(;;){let c=this.ensureBuffered(r);if(R(c)&&(c=await c),c===0)break;let l=this.currentPos,u=this.readBytes(c),d=u.byteLength,m=0;for(;m<d;){let f=u.indexOf(0,m);if(f===-1||f>=d)break;m=f;let p=l+m;if(m+3>=d){this.seekTo(p);break}let h=u[m+1],y=u[m+2],g=u[m+3],k=0;if(h===0&&y===0&&g===1?k=4:h===0&&y===1&&(k=3),k===0){m++;continue}let T=p;a??=T;let S=m+k,w=S+n;if(w+1>d){this.seekTo(p);break}let A=u[S],C,E,I,x;if(e==="avc")C=pr(A),E=C===1||C===2||C===5,I=C===6||C===7||C===8||C===9,x=C===9;else{if(C=Qt(A),((A&1)<<5|u[S+1]>>3)>0){m+=k;continue}E=C<=9||C>=16&&C<=21,I=C>=32&&C<=35||C===39||C>=41&&C<=44||C>=48&&C<=55,x=C===35}let P=!1;if(E){let v;if(e==="avc"){let _=new K(u.subarray(w)),M;try{M=D(_)}catch{M=null}if(M===null||_.getBitsLeft()<0){this.seekTo(p);break}v=!s||M<=o,o=M}else v=u[w]>>7===1;v&&(s?P=!0:s=!0)}else I&&s?P=!0:x&&(a=T);if(P){let v=T-a;return this.seekTo(a),this.supplyPacket(v,0)}m+=k}if(c<r)break}if(s){b(a!==null);let c=this.endPos-a;return this.seekTo(a),this.supplyPacket(c,0)}}else{let e=t.info.codec,r=128;for(;;){let n=this.ensureBuffered(r);R(n)&&(n=await n);let a=this.currentPos;for(;this.currentPos-a<n;){let s=this.readU8();if(e==="aac"){if(s!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(Ye);if(R(c)&&(c=await c),c<Ye)return;let l=this.readBytes(Ye),u=It(xe.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);return R(d)&&(d=await d),this.supplyPacket(d,Zo*Ue/t.info.sampleRate)}else this.seekTo(o+1)}else if(e==="mp3"){if(s!==255)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(4);if(R(c)&&(c=await c),c<4)return;let l=this.readBytes(4),u=z(l).getUint32(0),d=fr(u,null);if(d.header){this.seekTo(o);let m=this.ensureBuffered(d.header.totalSize);R(m)&&(m=await m);let f=d.header.audioSamplesInFrame*Ue/t.info.sampleRate;return this.supplyPacket(m,f)}else this.seekTo(o+1)}else if(e==="ac3"){if(s!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(R(c)&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let u=l[4]>>6,d=l[4]&63;if(u===3||d>37){this.seekTo(o+1);continue}let m=fm[3*d+u];b(m!==void 0),this.seekTo(o),c=this.ensureBuffered(m),R(c)&&(c=await c);let f=pm*Ue/t.info.sampleRate;return this.supplyPacket(c,f)}else if(e==="eac3"){if(s!==11)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(5);if(R(c)&&(c=await c),c<5)return;let l=this.readBytes(5);if(l[0]!==11||l[1]!==119){this.seekTo(o+1);continue}let d=(((l[2]&7)<<8|l[3])+1)*2,f=l[4]>>6===3?3:l[4]>>4&3,p=Zs[f];for(;;){this.seekTo(o);let g=d+4,k=this.ensureBuffered(g);if(R(k)&&(k=await k),k<g)break;this.seekTo(o+d);let T=this.readBytes(4);if(T[0]!==11||T[1]!==119||T[2]>>6!==1)break;d+=2*(((T[2]&7)<<8|T[3])+1)}this.seekTo(o),c=this.ensureBuffered(d),R(c)&&(c=await c);let y=p*256*Ue/t.info.sampleRate;return this.supplyPacket(c,y)}else if(e==="dts"){if(s!==127&&s!==100)continue;this.skip(-1);let o=this.currentPos,c=this.ensureBuffered(Aa);if(R(c)&&(c=await c),c<Aa)return;let l=this.readBytes(Aa),u=Wl(l),d=u?null:Ca(l);if(!u&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);let h=Math.min(d.frameSize,gm),y=this.ensureBuffered(h);R(y)&&(y=await y),d=Ca(this.readBytes(y))??d}let m=u?u.frameSize:d.frameSize;if(u){let h=Math.ceil(u.frameSize/4)*4;for(;;){this.seekTo(o);let y=h+io,g=this.ensureBuffered(y);if(R(g)&&(g=await g),g<y)break;this.seekTo(o+h);let k=Ca(this.readBytes(io));if(!k)break;h+=k.frameSize,m=h}}let f=u?.sampleCount??d.asset?.sampleCount;if(f===void 0){this.seekTo(o+1);continue}this.seekTo(o),c=this.ensureBuffered(m),R(c)&&(c=await c);let p=f*Ue/t.info.sampleRate;return this.supplyPacket(c,p)}else throw new Error("Unhandled.")}if(n<r)break}}}supplyPacket(t,e){let r=lr(this.pesPacketDataStartPositions,p=>p<=this.currentPos);b(r!==-1);let n=this.pesPackets[r],a=this.pesPacketDataStartPositions[r],s;if(this.lastSuppliedPesPacket===n)b(this.nextPts!==null),s=this.nextPts;else{if(n.pts===null)throw new Error(Nf);s=n.pts,Su(this.elementaryStream,n)}this.lastSuppliedPesPacket=n,this.nextPts=s+e;let o=n.sectionStartPos,c=o+(this.currentPos-a),l=this.readBytes(t).slice(),u=n.randomAccessIndicator;if(u===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")u=1;else if(this.elementaryStream.info.decoderConfig){let p=gi(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,l)==="key";u=Number(p)}}let d=Math.round(s);this.suppliedPacket={pts:d,intrinsicDuration:Math.round(s+e)-d,data:l,sequenceNumber:c,sectionStartPos:o,randomAccessIndicator:u};let m=this.currentPos-this.scratchStartPos;this.scratch.copyWithin(0,m,this.endPos-this.scratchStartPos),this.scratchStartPos=this.currentPos;let f=lr(this.pesPacketDataStartPositions,p=>p<=this.currentPos);this.pesPackets.splice(0,f),this.pesPacketDataStartPositions.splice(0,f)}},$a=class{constructor(t,e){this.decodeOrderPackets=[];this.reorderBuffer=[];this.presentationOrderPackets=[];this.reachedEnd=!1;this.lastDuration=0;this.backing=t,this.context=e,this.reorderSize=t.getReorderSize(),b(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let t=this.decodeOrderPackets[0],e=this.presentationOrderPackets.indexOf(t),r;for(e!==-1&&e<this.presentationOrderPackets.length-1?(r=this.presentationOrderPackets[e+1].pts-t.pts,this.lastDuration=r):t.intrinsicDuration>0?r=t.intrinsicDuration:e>0?r=t.pts-this.presentationOrderPackets[e-1].pts:r=this.lastDuration,this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let n=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(n))break;this.presentationOrderPackets.shift()}return{packet:t,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let t;return this.context.suppliedPacket?t=this.context.suppliedPacket:(await this.context.markNextPacket(),t=this.context.suppliedPacket),this.context.suppliedPacket=null,t?(this.decodeOrderPackets.push(t),this.processPacketThroughReorderBuffer(t),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let t=this.decodeOrderPackets[0];for(b(t);;){let e=this.presentationOrderPackets.indexOf(t);if(e!==-1&&e<=this.presentationOrderPackets.length-2||this.decodeOrderPackets.length>4*(this.reorderSize+1)||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(t){if(this.reorderBuffer.push(t),this.reorderBuffer.length>this.reorderSize){let e=0;for(let n=1;n<this.reorderBuffer.length;n++)this.reorderBuffer[n].pts<this.reorderBuffer[e].pts&&(e=n);let r=this.reorderBuffer[e];this.presentationOrderPackets.push(r),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((t,e)=>t.pts-e.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}};var Cr="application/vnd.apple.mpegurl",Au="#EXT-X-STREAM-INF:",xu="#EXT-X-I-FRAME-STREAM-INF:",Cu="#EXT-X-MEDIA:",Zn="#EXT-X-DEFINE:",Ya="#EXTINF:",Pu="#EXT-X-MAP:",Eu="#EXT-X-KEY:",Iu="#EXT-X-MEDIA-SEQUENCE:",vu="#EXT-X-BYTERANGE:",_u="#EXT-X-PROGRAM-DATE-TIME:",Lf="#EXT-X-DISCONTINUITY",Ru="#EXT-X-DISCONTINUITY-SEQUENCE:",Fu="#EXT-X-TARGETDURATION:",Hf="#EXT-X-ENDLIST",Mu="#EXT-X-PLAYLIST-TYPE:",Wf="#EXT-X-I-FRAMES-ONLY",zt="com.apple.streaming.transportStreamTimestamp",lc=i=>i.length===0||i.startsWith("#")&&!i.startsWith("#EXT"),xr=class{constructor(t,e){this._attributes={};let r="",n="",a=!1,s=!1,o=!1,c=()=>{if(!r)return;let l=r.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,l)&&O._warn(`Duplicate AttributeName "${l}"; using last value`);let u=o||n.startsWith("0x")||n.startsWith("0X");this._attributes[l]=u&&e?e.substitute(n):n,r="",n="",a=!1,o=!1};for(let l=0;l<t.length;l++){let u=t[l];u==='"'?(a&&!s&&n.length===0&&(o=!0),s=!s):u==="="&&!a&&!s?a=!0:u===","&&!s?c():a?n+=u:r+=u}if(s)throw new Error("Invalid M3U8 file; unterminated quoted-string AttributeValue.");c()}get(t){return this._attributes[t.toLowerCase()]??null}getAsNumber(t){let e=this.get(t);if(e===null)return null;let r=Number(e);return Number.isFinite(r)?r:null}merge(t){Object.assign(this._attributes,t._attributes)}},fg=/^[A-Za-z0-9_-]+$/,pg=/\{\$([A-Za-z0-9_-]+)\}/g,hg=2**26,Yn=class{constructor(t,e){this.playlistPath=t;this.importedVariables=e;this.variables=new Map;this.totalSubstitutedLength=0}define(t){let e=new xr(t,this),r=e.get("name"),n=e.get("import"),a=e.get("queryparam");if([r,n,a].filter(o=>o!==null).length!==1)throw new Error("Invalid #EXT-X-DEFINE tag; exactly one of NAME, IMPORT, or QUERYPARAM must be present.");if(r!==null){let o=e.get("value");if(o===null)throw new Error("Invalid #EXT-X-DEFINE tag; NAME requires VALUE.");this.set(r,o)}else if(n!==null){let o=this.importedVariables?.get(n);if(o===void 0)throw new Error(`Invalid #EXT-X-DEFINE tag; cannot import undefined variable "${n}".`);this.set(n,o)}else if(a!==null){let o=Ld(this.playlistPath,a);if(o===null)throw new Error(`Invalid #EXT-X-DEFINE tag; query parameter "${a}" is missing.`);this.set(a,o)}}substitute(t){return t.replaceAll(pg,(e,r)=>{let n=this.variables.get(r);if(n===void 0)throw new Error(`Invalid M3U8 file; variable "${r}" is referenced before being defined.`);if(this.totalSubstitutedLength+=n.length,this.totalSubstitutedLength>hg)throw new Error("Invalid M3U8 file; variable substitution produces an excessive amount of data.");return n})}get(t){return this.variables.get(t)}set(t,e){if(!fg.test(t))throw new Error(`Invalid #EXT-X-DEFINE tag; invalid variable name "${t}".`);if(this.variables.has(t))throw new Error(`Invalid #EXT-X-DEFINE tag; variable "${t}" is already defined.`);this.variables.set(t,e)}};var uc=class{constructor(t,e,r){this.nextInputCacheAge=0;this.inputCache=[];this.trackBackingsPromise=null;this.firstSegment=null;this.hasOnlyKeyPackets=!1;this.learnedSegmentTimestampOffset=null;this.segmentMediaOffsets=new WeakMap;this.input=t,this.path=e,this.trackDeclarations=r}async getDurationFromMetadata(t){let e=await this.getSegmentAt(1/0,{skipLiveWait:t.skipLiveWait});return e?e.timestamp+await this.getFirstSegmentTimestampOffset()+e.duration:null}async getUnixTimeForTimestamp(t){let e=await this.getSegmentAt(t,{skipLiveWait:!0});if(e??=await this.getFirstSegment({}),!e||e.unixEpochTimestamp===null)return null;let r=t-(e.timestamp+await this.getFirstSegmentTimestampOffset());return e.unixEpochTimestamp+r}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let t=[];if(this.trackDeclarations){for(let e of this.trackDeclarations)if(e.type==="video"){let r=Wi(t,n=>n.getType()==="video")+1;t.push(new mc(this,e,r))}else if(e.type==="audio"){let r=Wi(t,n=>n.getType()==="audio")+1;t.push(new fc(this,e,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let r=await this.getInputForSegment(this.firstSegment.initSegment??this.firstSegment).getTracks();for(let n of r)if(n.type==="video"){let a=Wi(t,s=>s.getType()==="video")+1;t.push(new mc(this,{type:"video"},a))}else if(n.type==="audio"){let a=Wi(t,s=>s.getType()==="audio")+1;t.push(new fc(this,{type:"audio"},a))}}return t})()}getMediaOffset(t,e){let r=this.segmentMediaOffsets.get(t);return r||(r=(async()=>{let n=await this.getRawTimestampOffset(e);if(n===null)return t.timestamp;let a=n+await this.getMediaOffsetForDiscontinuity(t.discontinuityNumber),s=this.getTimestampWrapPeriod();if(s<1/0){let o=await Za(e);if(o!==null){let c=o+a;a+=s*Math.round((t.timestamp-c)/s)}}return a})(),this.segmentMediaOffsets.set(t,r),r)}dispose(){for(let t of this.inputCache)t.input.dispose();this.inputCache.length=0}},Za=async i=>{let t=await i.getTracks(),e=[...t.filter(r=>r.type==="video"),...t.filter(r=>r.type!=="video")];for(let r of e){let n=await r.getFirstTimestampOrNull();if(n!==null)return n}return null},dc=class{constructor(t,e,r){this.packetInfos=new WeakMap;this.hydrationPromise=null;this.metadataInputTrack=null;this.segmentedInput=t,this.decl=e,this.number=r}hydrate(){return this.hydrationPromise??=(async()=>{let t=await this.getFirstSegment(),e=null;if(t.initSegment)e=(await this.segmentedInput.getInputForSegment(t.initSegment).getTracks()).find(n=>n.type===this.decl.type&&n.number===this.number)??null;else{let r=t;for(;r&&(e=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(s=>s.type===this.decl.type&&s.number===this.number)??null,!e);)r=await this.segmentedInput.getNextSegment(r,{})}if(!e)throw new Error("No matching track found in underlying media data.");this.metadataInputTrack=e})()}getType(){return this.decl.type}getNumber(){return this.number}delegate(t){return this.metadataInputTrack?t():this.hydrate().then(t)}async getDecoderConfig(){return this.delegate(()=>this.metadataInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.segmentedInput.hasOnlyKeyPackets||(this.metadataInputTrack._backing.getHasOnlyKeyPackets?.()??null))}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.metadataInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.metadataInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.metadataInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.metadataInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.metadataInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.metadataInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){let t=await this.getFirstSegment();return t.unixEpochTimestamp===t.timestamp}getUnixTimeForTimestamp(t){return this.segmentedInput.getUnixTimeForTimestamp(t)}getBitrate(){return this.delegate(()=>this.metadataInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.metadataInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(t){return this.segmentedInput.getDurationFromMetadata(t)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(t,e,r){b(t.sequenceNumber>=0);let n=await this.getFirstSegment(),a=await this.segmentedInput.getMediaOffset(e,r.input),s=e.timestamp-n.timestamp,o=t.clone({timestamp:Mt(t.timestamp+a,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+t.sequenceNumber});return this.packetInfos.set(o,{segment:e,track:r,sourcePacket:t}),o}async getFirstPacket(t){let e=await this.getFirstSegment();this.segmentedInput.getMediaOffsetForDiscontinuity(e.discontinuityNumber).catch(()=>{});let r=e;for(;r;){let s=(await this.segmentedInput.getInputForSegment(r).getTracks()).find(o=>o.type===this.decl.type&&o.number===this.number);if(s){let o=await s._backing.getFirstPacket(t);if(o)return this.createAdjustedPacket(o,r,s)}r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:t.skipLiveWait})}return null}async getFirstSegment(){if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");return this.segmentedInput.firstSegment}getNextPacket(t,e){return this._getNextInternal(t,e,!1)}getNextKeyPacket(t,e){return this._getNextInternal(t,e,!0)}async _getNextInternal(t,e,r){let n=this.packetInfos.get(t);if(!n)throw new Error("Packet was not created from this track.");let a=r?await n.track._backing.getNextKeyPacket(n.sourcePacket,e):await n.track._backing.getNextPacket(n.sourcePacket,e);if(a)return this.createAdjustedPacket(a,n.segment,n.track);let s=n.segment;for(;;){let o=await this.segmentedInput.getNextSegment(s,{skipLiveWait:e.skipLiveWait});if(!o)return null;let u=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(m=>m.type===n.track.type&&m.number===n.track.number);if(!u){s=o;continue}let d=await u._backing.getFirstPacket(e);if(d&&r&&d.type!=="key"&&(d=await u._backing.getNextKeyPacket(d,e)),!d){s=o;continue}return this.createAdjustedPacket(d,o,u)}}getPacket(t,e){return this._getPacketInternal(t,e,!1)}getKeyPacket(t,e){return this._getPacketInternal(t,e,!0)}async _getPacketInternal(t,e,r){let n=await this.segmentedInput.getSegmentAt(t,{skipLiveWait:e.skipLiveWait});if(n??=await this.segmentedInput.getFirstSegment({}),!n)return null;for(this.segmentedInput.getMediaOffsetForDiscontinuity(n.discontinuityNumber).catch(()=>{});n;){let a=this.segmentedInput.getInputForSegment(n),o=(await a.getTracks()).find(f=>f.type===this.decl.type&&f.number===this.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(n,a),l=this.segmentedInput.learnedSegmentTimestampOffset===null?await o._backing.getFirstPacket({...e,metadataOnly:!0}):null;if(l){let f=l.timestamp+c;this.segmentedInput.learnedSegmentTimestampOffset=f-n.timestamp;let p=t-f;if(p<-n.duration||p>=2*n.duration){let h=await this.segmentedInput.getSegmentAt(t,{skipLiveWait:e.skipLiveWait});if(h!==n){n=h;continue}}}let u=qf(t,c,await o.getTimeResolution()),d=r?await o._backing.getKeyPacket(u,e):await o._backing.getPacket(u,e);if(!d){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let m=r?await o._backing.getPacket(u,{...e,metadataOnly:!0}):d;if(b(m),u>=m.timestamp+m.duration){let f=await this.segmentedInput.getNextSegment(n,{skipLiveWait:e.skipLiveWait});if(f){let p=this.segmentedInput.getInputForSegment(f),y=(await p.getTracks()).find(k=>k.type===this.decl.type&&k.number===this.number),g=y?await y._backing.getFirstPacket({...e,metadataOnly:!0}):null;if(g&&r&&g.type!=="key"&&(g=await y._backing.getNextKeyPacket(g,{...e,metadataOnly:!0})),g){let k=await this.segmentedInput.getMediaOffset(f,p),T=qf(t,k,await y.getTimeResolution());if(g.timestamp<=T){n=f;continue}}}}return this.createAdjustedPacket(d,n,o)}return null}},qf=(i,t,e)=>(Math.floor(Fe(e*i))-Math.round(e*t))/e,mc=class extends dc{getType(){return"video"}getCodec(){return this.delegate(()=>this.metadataInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.metadataInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.metadataInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.metadataInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.metadataInputTrack._backing.getSquarePixelHeight())}getTransformationMatrix(){return this.delegate(()=>this.metadataInputTrack._backing.getTransformationMatrix())}async getColorSpace(){return this.delegate(()=>this.metadataInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.metadataInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.metadataInputTrack._backing.getDecoderConfig())}},fc=class extends dc{getType(){return"audio"}getCodec(){return this.delegate(()=>this.metadataInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.metadataInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.metadataInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.metadataInputTrack._backing.getDecoderConfig())}};var Kf=wd(Bu(),1);Cn();var Gf=typeof Kf<"u"?Kf:void 0,Du=0,Vu=1/0,Qe=class extends st{constructor(){super();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(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new ge;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Du,Vu),e=this._getFileSize(),b(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new ge;let e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,r){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new es(this,e,r)}_dispatchRead(e,r){this.onread?.(e,r),this._emit("read",{start:e,end:r})}ref(){return new Ei(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},Ei=class{constructor(t){this._freed=!1;if(t._disposed)throw new Error("Cannot ref a disposed source.");t._incrementRefCount(),t._refFinalizationRegistry?.register(this,t,this),this._source=t}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");let t=this.source;b(t._refCount>0),t._decrementRefCount(),t._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},it=class extends Qe{constructor(e,r){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof r!="function")throw new TypeError("requestHandler must be a function.");super();this.rootPath=e;this.requestHandler=r}_resolveRequest(e){let r=this.requestHandler(e),n=a=>{if(!(a instanceof Qe||a instanceof Ei))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=a instanceof Qe?a.ref():a;return s.source._usedForHls||=this._usedForHls,s};return R(r)?r.then(n):n(r)}},Uu=(i,t)=>i.path===t.path,Jn=class extends it{constructor(){super(...arguments);this._root=null;this._rootRequest=null;this._removeRootReadListener=null}_read(e,r,n,a){if(!this._root){if(!this._rootRequest){let o=this._resolveRequest({path:this.rootPath,isRoot:!0}),c=l=>{let u=l instanceof Qe?l.ref():l;return this._root=u,this._rootRequest=null,this._removeRootReadListener=u.source.on("read",({start:d,end:m})=>{this._dispatchRead(d,m)}),u};R(o)?this._rootRequest=o.then(c):(c(o),b(this._root))}if(this._rootRequest)return this._rootRequest.then(()=>this._read(e,r,n,a))}let s=this._root.source;return r>(s._getFileSize()??1/0)?null:s._read(e,r,n,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?(this._removeRootReadListener(),this._root.free()):this._rootRequest&&this._rootRequest.then(e=>{this._removeRootReadListener(),e.free()}).catch(()=>{})}},pc=class extends Qe{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super();this._onreadCalled=!1;this._bytes=Q(e),this._view=z(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},Qf=typeof FinalizationRegistry<"u"?new FinalizationRegistry(i=>{i.cancel().catch(()=>{})}):null,hc=class extends Qe{constructor(e,r={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.useStreamReader!==void 0&&typeof r.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super();this._readers=new WeakMap;this._blob=e,this._options=r,this._orchestrator=new Ja({maxCacheSize:r.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:n=>{let a=this._readers.get(n);a&&(this._readers.delete(n),Qf?.unregister(n),a.cancel().catch(()=>{}))},prefetchProfile:zu.fileSystem,handleUnhandledError:r.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,r,n,a){return this._orchestrator.read(e,r,n,a)}async _runWorker(e){b(e.strictTarget);let r=this._readers.get(e);for(r===void 0&&("stream"in this._blob&&!et()&&this._options.useStreamReader!==!1?(r=this._blob.slice(e.currentPos).stream().getReader(),Qf?.register(e,r,e)):r=null,this._readers.set(e,r));e.currentPos<e.targetPos&&!e.aborted;)if(r){let{done:n,value:a}=await r.read();if(n)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}else{let n=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+n.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(n))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await r?.cancel().catch(()=>{})}_dispose(){this._orchestrator.dispose()}},gg=.5*2**20,bg=(i,t,e)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(e instanceof Request?e.url:e,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==window.location.origin)return O._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**(i-2),16)},jf=new Set,gc=class i extends it{constructor(e,r={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.requestInit!==void 0&&(!r.requestInit||typeof r.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(r.getRetryDelay!==void 0&&typeof r.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(r.parallelism!==void 0&&(!Number.isInteger(r.parallelism)||r.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(r.fetchFn!==void 0&&typeof r.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");let n=e instanceof Request?e.url:e instanceof URL?e.href:e;super(n,o=>new i(o.path,{...this._options,requestInit:this._requestInit}));this._offset=0;this._length=null;this._fileSizeDetermined=!1;this._sequentialBacking=null;this._abortControllers=new Map;this._sequentialAbortController=null;this._url=e,this._options=r,this._getRetryDelay=r.getRetryDelay??bg,this._requestInit={...r.requestInit};let a=null;if(r.requestInit?.headers){let o={...Cs(r.requestInit.headers)},c=Object.keys(o).find(l=>l.toLowerCase()==="range");c!==void 0&&(a=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){let o=e,c=e.headers.get("Range");c!==null&&(a??=c,o=new Request(e),o.headers.delete("Range"),this._url=o),this._requestInit={cache:o.cache,credentials:o.credentials,integrity:o.integrity,keepalive:o.keepalive,mode:o.mode==="navigate"?void 0:o.mode,redirect:o.redirect,referrer:o.referrer,referrerPolicy:o.referrerPolicy,...this._requestInit},this._requestInit.headers=Os({headers:o.headers},this._requestInit).headers}if(a!==null){let o=kg(a);o&&(this._offset=o.offset,this._length=o.length)}let s=2;this._orchestrator=new Ja({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??s,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:o=>{this._abortControllers.get(o)?.abort(),this._abortControllers.delete(o)},prefetchProfile:zu.network,handleUnhandledError:r.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;let e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:ne(e-this._offset,0,this._length??1/0)}_read(e,r,n,a){if(this._length!==null&&r>this._length)return null;let s=this._offset,o=this._sequentialBacking?this._sequentialBacking._read(s+e,s+r):this._orchestrator.read(s+e,s+r,Math.max(s+n,s),s+Math.min(a,this._length??1/0)),c=l=>l?(l.offset-=this._offset,l):null;return R(o)?o.then(c):c(o)}async _runWorker(e){let r=0,n=this._length!==null?this._offset+this._length-1:"";for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}let a=new AbortController;this._abortControllers.set(e,a);let s=await Rl(this._options.fetchFn??fetch,this._url,Os(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-${n}`},signal:a.signal}),this._getRetryDelay,()=>a.signal.aborted),o=s.status===416?/^bytes \*\/(\d+)$/.exec(s.headers.get("Content-Range")??""):null,c=null;if(o?c=Number(o[1]):s.status===416&&e.currentPos>e.startPos&&(c=e.currentPos),c!==null&&c<=e.currentPos){s.body?.cancel().catch(()=>{}),this._orchestrator.fileSize===null&&this._orchestrator.supplyFileSize(c),this._fileSizeDetermined=!0,this._orchestrator.onWorkerFinished(e);return}if(!s.ok)throw s.body?.cancel().catch(()=>{}),new Error(`Error fetching ${this.rootPath}: ${s.status} ${s.statusText}`);s.redirected&&(this.rootPath=s.url);e:if(this._orchestrator.fileSize===null&&!s.headers.has("Content-Encoding")&&(s.status===206||s.type==="basic")){let d=s.headers.get("Content-Range");if(d){let f=/\/(\d+)/.exec(d);if(f){this._orchestrator.supplyFileSize(Number(f[1]));break e}}let m=s.headers.get("Content-Length");if(m){let f=s.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(f+Number(m))}}if(this._fileSizeDetermined=!0,!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(s.status!==206){if(this._sequentialBacking){s.body.cancel().catch(()=>{});return}if(!this._usedForHls){let d=new URL(s.url||(this._url instanceof Request?this._url.url:this._url),typeof window<"u"?window.location.href:void 0);d.origin!=="null"&&!(d.pathname.endsWith(".m3u8")||d.pathname.endsWith(".m3u"))&&(jf.has(d.origin)||(O._warn(`HTTP server (origin ${d.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),jf.add(d.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(s.body,a);return}let l=s.body.getReader(),u=e.currentPos;for(;;){if(e.currentPos>=e.targetPos||e.aborted){a.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let d;try{d=await l.read()}catch(p){if(a.signal.aborted)throw p;let h=this._getRetryDelay(++r,p,this._url);if(h!==null){O._error("Error while reading response stream. Attempting to resume.",p),await Nr(1e3*h);break}else throw p}if(e.aborted)continue;let{done:m,value:f}=d;if(m){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(!e.strictTarget&&(e.currentPos===u||s.headers.has("Content-Encoding"))){this._orchestrator.onWorkerFinished(e);return}if(e.currentPos>u)break;r++;let p=new Error("Range response ended without delivering any data."),h=this._getRetryDelay(r,p,this._url);if(h===null)throw p;O._error("Retrying range request that ended without delivering any data."),await Nr(1e3*h);break}r=0,this._dispatchResourceRead(e.currentPos,e.currentPos+f.length),this._orchestrator.supplyWorkerData(e,f)}}}_transitionToSequentialMode(e,r){this._sequentialAbortController=r;let n=e.getReader(),a=0,s=0,o=0,c=new ReadableStream({pull:async d=>{for(;;){let m;try{m=await n.read()}catch(p){if(this._disposed)throw p;let h=this._getRetryDelay(++o,p,this._url);if(h===null)throw p;O._error("Error while reading response stream. Attempting to resume.",p),await Nr(1e3*h),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();let y=await Rl(this._options.fetchFn??fetch,this._url,Os(this._requestInit,{headers:{Range:`bytes=${a}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!y.ok)throw y.body?.cancel().catch(()=>{}),new Error(`Error fetching ${this.rootPath}: ${y.status} ${y.statusText}`);if(!y.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");n=y.body.getReader(),s=y.status===206?0:a;continue}if(m.done){d.close();return}let f=m.value;if(s>0){let p=Math.min(s,f.length);if(s-=p,f=f.subarray(p),f.length===0)continue}if(o=0,f.length!==0){a+=f.length,d.enqueue(f);return}}},cancel:()=>n.cancel().catch(()=>{})}),l=new rn(c,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});l._endIndex=this._orchestrator.fileSize,l._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",l.on("read",({start:d,end:m})=>this._dispatchResourceRead(d,m)),this._sequentialBacking=l;let u=new Set;for(let d of this._orchestrator.workers){for(let m of d.pendingSlices)u.add(m);d.aborted=!0,d.pendingSlices.length=0}for(let d of this._orchestrator.queuedReads)for(let m of d.pendingSlices)u.add(m);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(let[,d]of this._abortControllers)d.abort();this._abortControllers.clear();for(let d of u){let m=l._read(d.start,d.start+d.bytes.length);R(m)?m.then(f=>{f?(b(f.offset===d.start),d.resolve(f.bytes)):d.resolve(null)},f=>d.reject(f)):(b(m===null),d.resolve(null))}}_dispatchResourceRead(e,r){let n=Math.max(e-this._offset,0),a=Math.min(r-this._offset,this._length??1/0);n<a&&this._dispatchRead(n,a)}_dispose(){this._orchestrator.dispose();for(let[,e]of this._abortControllers)e.abort();this._abortControllers.clear(),this._sequentialAbortController?.abort(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}},yg=/^bytes=(\d+)-(\d*)$/,kg=i=>{let t=yg.exec(i.trim());if(!t)return null;let e=Number(t[1]),r=t[2]===""?null:Number(t[2]);return r!==null&&r<e?null:{offset:e,length:r!==null?r-e+1:null}},Ou=null;typeof FinalizationRegistry<"u"&&(Ou=new FinalizationRegistry(i=>{i.close()}));var bc=class i extends it{constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Gf.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,n=>new i(n.path,r));this._fileHandle=null;this._customSource=new ea({getSize:async()=>{let n=await Gf.fs.open(e,"r");if(this._disposed)throw n.close(),new ge;return this._fileHandle=n,Ou?.register(this,n,this),(await n.stat()).size},read:async(n,a)=>{b(this._fileHandle);let s=new Uint8Array(a-n),o=0;for(;o<s.length;){let c=await this._fileHandle.read(s,o,s.length-o,n+o);if(c.bytesRead===0)throw new Error(`File ended at byte ${n+o}, before byte ${a} was read; it was likely truncated while being read.`);o+=c.bytesRead}return s},maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:r.handleUnhandledError}),this._customSource.on("read",({start:n,end:a})=>this._dispatchRead(n,a))}_read(e,r,n,a){return this._customSource._read(e,r,n,a)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._disposed=!0,this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Ou?.unregister(this))}},ea=class extends Qe{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.handleUnhandledError!==void 0&&typeof e.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!Ie(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super();this._readers=new Set;this._pendingSize=null;this._options=e,this._orchestrator=new Ja({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:zu[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,r,n,a){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,r,n,a);let s=this._pendingSize??this._options.getSize();if(R(s))return this._pendingSize=s,s.then(o=>{if(!Number.isInteger(o)||o<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");if(this._disposed)throw new ge;return this._orchestrator.fileSize=o,r>o?null:this._orchestrator.read(e,r,n,a)});if(!Number.isInteger(s)||s<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=s,r>s?null:this._orchestrator.read(e,r,n,a)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let r=e.currentPos,n=e.targetPos,a=this._options.read(e.currentPos,n);if(R(a)&&(a=await a),e.aborted){a instanceof ReadableStream&&await a.cancel().catch(()=>{});break}if(a instanceof Uint8Array){if(a=Q(a),a.length!==n-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${a.length}.`);this._dispatchRead(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}else if(a instanceof ReadableStream){let s=a.getReader();this._readers.add(s);try{for(;e.currentPos<n&&!e.aborted;){let{done:o,value:c}=await s.read();if(o){if(e.currentPos<n)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-r} bytes, but got ${e.currentPos-r}`);break}if(!(c instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;let l=Q(c);this._dispatchRead(e.currentPos,e.currentPos+l.length),this._orchestrator.supplyWorkerData(e,l)}}finally{this._readers.delete(s),s.cancel().catch(()=>{}),s.releaseLock()}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){this._orchestrator.dispose();for(let e of this._readers)e.cancel().catch(()=>{});this._readers.clear(),this._options.dispose?.()}},$f=ea,rn=class extends Qe{constructor(e,r={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.handleUnhandledError!==void 0&&typeof r.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(r.maxCacheSize!==void 0&&(!Ie(r.maxCacheSize)||r.maxCacheSize<0))throw new 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._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.";this._stream=e,this._maxCacheSize=r.maxCacheSize??32*2**20,this._handleUnhandledError=r.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,r){if(this._endIndex!==null&&r>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,r);let n=X(this._cache,e,d=>d.start),a=n!==-1?this._cache[n]:null;if(a&&a.start<=e&&r<=a.end)return{bytes:a.bytes,view:a.view,offset:a.start};let s=e,o=[];if(n!==-1)for(let d=n;d<this._cache.length;d++){let m=this._cache[d];if(m.start>=r)break;let f=Math.max(e,m.start);f>s&&this._throwDueToCacheMiss();let p=Math.min(r,m.end);f<p&&(o.push({start:f,bytes:m.bytes.subarray(f-m.start,p-m.start)}),s=p)}if(s===r)return Xf(e,r,o);this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:c,resolve:l,reject:u}=te();return this._pendingSlices.push({start:e,end:r,parts:o,resolve:l,reject:u}),this._targetIndex=Math.max(this._targetIndex,r),this._pulling||(this._pulling=!0,this._pull().catch(d=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(m=>m.reject(d)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(d);else throw d})),c}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:r}=await this._reader.read();if(e){for(let s of this._pendingSlices)s.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,a=this._currentIndex+r.byteLength;this._dispatchRead(n,a);for(let s=0;s<this._pendingSlices.length;s++){let o=this._pendingSlices[s],c=Math.max(n,o.start),l=Math.min(a,o.end);c<l&&(o.parts.push({start:c,bytes:r.subarray(c-n,l-n)}),l===o.end&&(o.resolve(Xf(o.start,o.end,o.parts)),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:n,end:a,bytes:r,view:z(r),age:0});this._cache.length>0;){let s=this._cache[0];if(this._maxRequestedIndex-s.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=r.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new ge);this._pendingSlices.length=0,this._cache.length=0,(this._reader??this._stream).cancel().catch(()=>{})}},Xf=(i,t,e)=>{let r=new Uint8Array(t-i);for(let n of e)r.set(n.bytes,n.start-i);return{bytes:r,view:z(r),offset:i}},zu={none:(i,t)=>({start:i,end:t}),fileSystem:(i,t)=>(i=Math.floor((i-65536)/65536)*65536,t=Math.ceil((t+65536)/65536)*65536,{start:i,end:t}),network:(i,t,e)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(let n of e){let s=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(Ds(i,t,s,n.targetPos)){let o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);t=Math.max(t,n.startPos+u)}}return t=Math.max(t,i+gg),{start:i,end:t}}},Ja=class{constructor(t){this.options=t;this.fileSize=null;this.nextAge=0;this.workers=[];this.cache=[];this.currentCacheSize=0;this.disposed=!1;this.queuedReads=[]}read(t,e,r,n){b(!this.disposed);let a=this.options.prefetchProfile(t,e,this.workers),s=Math.max(a.start,r),o=Math.min(a.end,this.fileSize??1/0,n);b(s<=t&&e<=o);let c=null,l=X(this.cache,t,w=>w.start),u=l!==-1?this.cache[l]:null;u&&u.start<=t&&e<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});let d=X(this.cache,s,w=>w.start),m=c?null:new Uint8Array(e-t),f=0,p=s,h=[];if(d!==-1){for(let w=d;w<this.cache.length;w++){let A=this.cache[w];if(A.start>=o)break;if(A.end<=s)continue;let C=Math.max(s,A.start),E=Math.min(o,A.end);if(b(C<=E),p<C&&h.push({start:p,end:C}),p=E,m){let I=Math.max(t,A.start),x=Math.min(e,A.end);if(I<x){let P=I-t;m.set(A.bytes.subarray(I-A.start,x-A.start),P),P===f&&(f=x-t)}}A.age=this.nextAge++}p<o&&h.push({start:p,end:o})}else h.push({start:s,end:o});if(m&&f>=m.length&&(c={bytes:m,view:z(m),offset:t}),h.length===0)return b(c),c;let{promise:y,resolve:g,reject:k}=te(),T=[];for(let w of h){let A=Math.max(t,w.start),C=Math.min(e,w.end);A===w.start&&C===w.end?T.push(w):A<C&&T.push({start:A,end:C})}let S=m&&{start:t,bytes:m,holes:T,resolve:g,reject:k};e:for(let w of h){for(let E of this.workers)if(this.checkHoleAgainstWorker(E,w,S?[S]:[])){this.checkQueuedReadsAgainstWorker(E);continue e}let A=w.end<o||this.fileSize!==null,C=this.createWorker(w.start,w.end,A);if(C)S&&(C.pendingSlices=[S]),this.runWorker(C);else{let E=X(this.queuedReads,w.start,x=>x.hole.start),I=E!==-1?this.queuedReads[E]:null;for(I&&w.start<=I.hole.end?(I.hole.end=Math.max(I.hole.end,w.end),I.strictTarget&&=A,S&&I.pendingSlices.push(S)):(E++,I={hole:{start:w.start,end:w.end},strictTarget:A,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(E,0,I));E+1<this.queuedReads.length;){let x=this.queuedReads[E+1];if(x.hole.start>I.hole.end)break;I.hole.end=Math.max(I.hole.end,x.hole.end),I.pendingSlices.push(...x.pendingSlices),I.strictTarget&&=x.strictTarget,I.age=Math.min(I.age,x.age),this.queuedReads.splice(E+1,1)}}}return c?y.catch(w=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(w);else throw w}):(b(m),c=y.then(w=>w&&{bytes:w,view:z(w),offset:t})),c}checkHoleAgainstWorker(t,e,r){if(Ds(e.start-131072,e.start,t.currentPos,t.targetPos)){t.targetPos=Math.max(t.targetPos,e.end);for(let a=0;a<r.length;a++){let s=r[a];t.pendingSlices.includes(s)||t.pendingSlices.push(s)}return t.running||this.runWorker(t),!0}return!1}checkQueuedReadsAgainstWorker(t){let e=!1;for(let r=0;r<this.queuedReads.length;r++){let n=this.queuedReads[r];if(this.checkHoleAgainstWorker(t,n.hole,n.pendingSlices))this.queuedReads.splice(r,1),r--,e=!0;else if(e)break}}createWorker(t,e,r){if(this.workers.length>=this.options.maxWorkerCount){let a=null,s=null;for(let o=0;o<this.workers.length;o++){let c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!a||c.age<a.age)&&(s=o,a=c)}if(a)b(s!==null),b(a.pendingSlices.length===0),this.workers.splice(s,1),this.options.onIdleWorkerRemoved?.(a);else return null}let n={startPos:t,currentPos:t,targetPos:e,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(n),n}runWorker(t){b(!t.running),b(t.currentPos<t.targetPos),t.running=!0,t.age=this.nextAge++,this.options.runWorker(t).catch(e=>{if(t.running=!1,t.pendingSlices.length>0)t.pendingSlices.forEach(r=>r.reject(e)),t.pendingSlices.length=0;else if(!t.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(e);else throw e}).finally(()=>{if(!t.running&&this.queuedReads.length>0){let e=0;for(let a=1;a<this.queuedReads.length;a++)this.queuedReads[a].age<this.queuedReads[e].age&&(e=a);let r=this.queuedReads[e],n=this.createWorker(r.hole.start,r.hole.end,r.strictTarget);if(!n)return;this.queuedReads.splice(e,1),n.pendingSlices=r.pendingSlices,this.runWorker(n)}})}supplyWorkerData(t,e){b(!t.aborted);let r=t.currentPos,n=r+e.length;this.insertIntoCache({start:r,end:n,bytes:e,view:z(e),age:this.nextAge++}),t.currentPos+=e.length,t.currentPos>t.targetPos&&(t.targetPos=t.currentPos,this.checkQueuedReadsAgainstWorker(t));for(let a=0;a<t.pendingSlices.length;a++){let s=t.pendingSlices[a],o=Math.max(r,s.start),c=Math.min(n,s.start+s.bytes.length);o<c&&s.bytes.set(e.subarray(o-r,c-r),o-s.start);for(let l=0;l<s.holes.length;l++){let u=s.holes[l];r<=u.start&&n>u.start&&(u.start=n),u.end<=u.start&&(s.holes.splice(l,1),l--)}s.holes.length===0&&(s.resolve(s.bytes),t.pendingSlices.splice(a,1),a--)}for(let a=0;a<this.workers.length;a++){let s=this.workers[a];t===s||s.running||Ds(r,n,s.currentPos,s.targetPos)&&(this.workers.splice(a,1),this.options.onIdleWorkerRemoved?.(s),a--)}}supplyFileSize(t){b(this.fileSize===null),this.fileSize=t;for(let e of this.workers){e.targetPos=Math.min(e.targetPos,t),e.strictTarget=!0;for(let r=0;r<e.pendingSlices.length;r++){let n=e.pendingSlices[r];for(let a of n.holes)if(a.end>t){n.resolve(null),e.pendingSlices.splice(r,1),r--;break}}}for(let e=0;e<this.queuedReads.length;e++){let r=this.queuedReads[e];for(let n=0;n<r.pendingSlices.length;n++){let a=r.pendingSlices[n];a.start+a.bytes.length>t&&(a.resolve(null),r.pendingSlices.splice(n,1),n--)}r.hole.start>=t?(this.queuedReads.splice(e,1),e--):(r.hole.end=Math.min(r.hole.end,t),r.strictTarget=!0)}}signalWorkerStoppedRunning(t){t.running=!1,t.aborted||(t.pendingSlices.length=0)}onWorkerFinished(t){let e=this.workers.indexOf(t);b(e!==-1),t.running=!1,this.workers.splice(e,1),this.options.onIdleWorkerRemoved?.(t),this.fileSize===null&&this.supplyFileSize(t.currentPos);for(let r of t.pendingSlices)r.start+r.bytes.length>t.currentPos&&r.resolve(null)}insertIntoCache(t){if(this.options.maxCacheSize===0)return;let e=X(this.cache,t.start,r=>r.start)+1;if(e>0){let r=this.cache[e-1];if(r.end>=t.end)return;if(r.end>t.start){let n=new Uint8Array(t.end-r.start);n.set(r.bytes,0),n.set(t.bytes,t.start-r.start),this.currentCacheSize+=t.end-r.end,r.bytes=n,r.view=z(n),r.end=t.end,e--,t=r}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length}else this.cache.splice(e,0,t),this.currentCacheSize+=t.bytes.length;for(let r=e+1;r<this.cache.length;r++){let n=this.cache[r];if(t.end<=n.start)break;if(t.end>=n.end){this.cache.splice(r,1),this.currentCacheSize-=n.bytes.length,r--;continue}let a=new Uint8Array(n.end-t.start);a.set(t.bytes,0),a.set(n.bytes,n.start-t.start),this.currentCacheSize-=t.end-n.start,t.bytes=a,t.view=z(a),t.end=n.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,n=this.cache[0];for(let a=1;a<this.cache.length;a++){let s=this.cache[a];s.age<n.age&&(r=a,n=s)}if(this.currentCacheSize-n.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=n.bytes.length}}dispose(){for(let t of this.workers){for(let e of t.pendingSlices)e.reject(new ge);t.pendingSlices.length=0,t.aborted=!0,t.running||this.options.onIdleWorkerRemoved?.(t)}for(let t of this.queuedReads)for(let e of t.pendingSlices)e.reject(new ge);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}};var es=class extends Qe{constructor(e,r,n){super();this._ref=null;this._removeReadListener=null;if(e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=r,this._length=n??null}_getFileSize(){if(this._length!==null)return this._length;let e=this._baseSource._getFileSize();return e==null?e:Math.max(e-this._offset,0)}_read(e,r,n,a){if(this._length!==null&&r>this._length)return null;let s=this._baseSource._getFileSize(),o=typeof s=="number"&&this._offset+r>s?null:this._baseSource._read(this._offset+e,this._offset+r,this._offset+n,this._offset+Math.min(a,this._length??1/0)),c=l=>{if(!l){if(this._length!==null){let u=this._offset+this._length;throw new Error(`Underlying data too short, expected a length of at least ${u} bytes.`)}return null}return l.offset-=this._offset,l};return R(o)?o.then(c):c(o)}_dispose(){this._ref?.free(),this._removeReadListener?.()}ref(){return this._ref||(this._ref=this._baseSource.ref(),this._removeReadListener=this._baseSource.on("read",({start:e,end:r})=>{let n=Math.max(e-this._offset,0),a=Math.min(r-this._offset,this._length??1/0);n<a&&this._dispatchRead(n,a)})),super.ref()}};var Tg=/^0[xX][0-9a-fA-F]+$/,wg=/^data:.*;base64,/i,Yf=1e9,ts=class extends uc{constructor(e,r,n,a){super(e.input,r,n);this.segments=[];this.nextLines=null;this.currentUpdateSegmentsPromise=null;this.streamHasEnded=!1;this.neverRemovesSegments=!1;this.lastSegmentUpdateTime=-1/0;this.refreshInterval=5;this.segmentTimestampOffsetPromise=null;this.rootPath=r,this.demuxer=e,this.nextLines=a}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await Nr(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,r=Math.max(0,1e3*this.refreshInterval-e);return r<=50?0:r}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){var S=[];try{let E=yt(S,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}));let I=new Ii(E.source);let x=I.requestSliceRange(0,0,64);R(x)&&(x=await x);if(x&&!be.decode(V(x,x.length)).trimStart().startsWith("#EXTM3U"))throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");let P=await I.requestEntireFile();b(P);e=yc(P,P.length,{ignore:lc});E.source instanceof it&&(this.rootPath=E.source.rootPath)}catch(w){var A=w,C=!0}finally{kt(S,A,C)}}let r=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1&&(this.segments.length===0||this.segments[0].unixEpochTimestamp===this.segments[0].timestamp),n=new Yn(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),a=!1,s=0,o=null,c=null,l=null,u=0,d=0,m=null,f=null,p=null,h=null,y=null,g=J(this.segments)??null,k=E=>{let I=E.indexOf("@"),x=Number(I===-1?E:E.slice(0,I));if(!Number.isInteger(x)||x<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${E}'.`);let P=null;if(I!==-1&&(P=Number(E.slice(I+1)),!Number.isInteger(P)||P<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${E}'.`);return{length:x,offset:P}},T=E=>{if(u=E,g&&(b(g.sequenceNumber!==null),g.sequenceNumber<E)){let I=(E-g.sequenceNumber)*g.duration;s=g.timestamp+I,m=g.firstSegment??g,f=g.initSegment,y=g.lastProgramDateTimeSeconds,o=g.unixEpochTimestamp!==null?g.unixEpochTimestamp+I:null,g=null}};for(let E=0;E<e.length;E++){let I=e[E];if(!a){if(I!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");a=!0;continue}if(!I.startsWith("#")){if(!g){if(c===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let x=l;if(x&&x.method==="AES-128"&&!x.iv){let M=new Uint8Array(Xt),U=z(M);U.setUint32(8,Math.floor(u/2**32)),U.setUint32(12,u),x={...x,iv:M}}let v={path:ve(this.rootPath,n.substitute(I)),offset:h?.offset??0,length:h?.length??null};m&&m.discontinuityNumber!==d&&(m=null);let _={index:this.segments.length,timestamp:s,unixEpochTimestamp:o,discontinuityNumber:d,firstSegment:m,sequenceNumber:u,location:v,duration:c,encryption:x,initSegment:f,lastProgramDateTimeSeconds:y};m??=_,s+=c,o!==null&&(o+=c),this.segments.push(_)}c=null,h===null?p=null:h=null,T(u+1)}if(I.startsWith(Ya)){if(g)continue;let x=I.slice(Ya.length),P=x.indexOf(","),v=P===-1?x:x.slice(0,P),_=Number(v);if(!Number.isFinite(_)||_<0||_>Yf)throw new Error(`Invalid #EXTINF tag duration '${v}'.`);c=_}else if(I.startsWith(Zn))n.define(I.slice(Zn.length));else if(I.startsWith(Pu)){let x=new xr(I.slice(Pu.length),n),P=x.get("uri");if(!P)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let v=x.get("byterange"),_=null;if(v!==null&&(_=k(v)),_&&_.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){let U={path:ve(this.rootPath,P),offset:_?.offset??0,length:_?.length??null};if(l?.method==="AES-128"&&!l.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");f={index:-1,timestamp:s,unixEpochTimestamp:o,discontinuityNumber:d,firstSegment:null,sequenceNumber:null,location:U,duration:0,encryption:l,initSegment:null,lastProgramDateTimeSeconds:y}}}else if(I.startsWith(Eu)){let x=new xr(I.slice(Eu.length),n),P=x.get("method");if(P==="NONE")l=null;else if(P==="AES-128"){let v=x.get("uri");if(!v)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let _=null,M=x.get("iv");if(M){if(!Tg.test(M))throw new Error(`Unsupported IV format '${M}'.`);let N=M.slice(2);N=N.padStart(2*Xt,"0"),N=N.slice(-2*Xt),_=new Uint8Array(Xt);for(let L=0;L<Xt;L++){let G=2*L;_[L]=parseInt(N.slice(G,G+2),16)}}let U=x.get("keyformat")??"identity";if(U!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");l={method:"AES-128",keyUri:ve(this.rootPath,v),iv:_,keyFormat:U}}else if(P==="SAMPLE-AES"||P==="SAMPLE-AES-CTR"){let v=x.get("uri");if(!v)throw new Error(`Invalid #EXT-X-KEY: ${P} requires a URI attribute.`);if((x.get("keyformat")??"identity")==="identity")throw new 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 M=null;if(wg.test(v)){let U=v.indexOf(","),N=Hi(v.slice(U+1));if(N.length>=8&&N[4]===112&&N[5]===115&&N[6]===115&&N[7]===104){let L=z(N).getUint32(0);M=Po(N.subarray(8,Math.min(L,N.length)))}}l={method:P,psshBox:M}}else throw new Error(`Unsupported encryption method '${P}'. If you think this method should be supported, please raise an issue.`)}else if(I.startsWith(Iu)){let x=I.slice(Iu.length),P=Number(x);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${x}'.`);T(P)}else if(I.startsWith(vu)){let x=k(I.slice(vu.length));if(x.offset===null){if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");x.offset=p}h=x,p=x.offset+x.length}else if(I.startsWith(_u)){if(g)continue;let x=I.slice(_u.length),P=Date.parse(x);if(!Number.isFinite(P))continue;let v=P/1e3;if(y===v)continue;if(y===null&&this.segments.length>0){let _=v-s;for(let M of this.segments)M.unixEpochTimestamp=M.timestamp+_,r&&(M.timestamp=M.unixEpochTimestamp)}y=v,o=v,r&&(s=v)}else if(I===Lf)m=null,d++;else if(I.startsWith(Ru)){let x=I.slice(Ru.length),P=Number(x);if(!Number.isSafeInteger(P)||P<0)throw new Error(`Invalid EXT-X-DISCONTINUITY-SEQUENCE value '${x}'.`);d=P}else if(I.startsWith(Fu)){let x=I.slice(Fu.length),P=Number(x);if(!Number.isFinite(P)||P<0||P>Yf)throw new Error(`Invalid EXT-X-TARGETDURATION value '${x}'.`);this.refreshInterval=ne(P,.5,3600)}else if(I===Wf)this.hasOnlyKeyPackets=!0;else if(I===Hf){this.streamHasEnded=!0;break}else if(I.startsWith(Mu)){let x=I.slice(Mu.length).toLowerCase();x==="vod"&&(this.streamHasEnded=!0),(x==="vod"||x==="event")&&(this.neverRemovesSegments=!0)}}if(!a)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&!this.streamHasEnded&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,r){this.segments.length===0&&!this.streamHasEnded&&!(r.skipLiveWait&&this.getRemainingWaitTimeMs()>0)&&await this.runUpdateSegments();let n=e-(this.learnedSegmentTimestampOffset??0),a=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let s=X(this.segments,n,c=>c.timestamp);if(s===-1)return null;if(s<this.segments.length-1||this.streamHasEnded||a)return this.segments[s];let o=this.segments[s];if(n<o.timestamp+o.duration)return o;await this.runUpdateSegments(),r.skipLiveWait&&(a=!0)}}async getNextSegment(e,r){let n=e.index;b(n!==-1);let a=n+1,s=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(a<this.segments.length)return this.segments[a];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),r.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){let r=e.index;return b(r!==-1),this.segments[r-1]??null}getInputForSegment(e){let r=e,n=this.inputCache.find(l=>l.segment===r);if(n)return n.age=this.nextInputCacheAge++,n.input;let a=null;r.initSegment?(a=this.getInputForSegment(r.initSegment),a.getTracks().catch(()=>{})):r.firstSegment&&(a=this.getInputForSegment(r.firstSegment));let s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(l=>{if(!r.encryption||!(r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR")||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(l);let u=l.psshBoxes,{psshBox:d}=r.encryption;return(d.keyIds===null||d.keyIds.includes(l.keyId))&&!u.some(m=>Eo(m,d))&&(u=[...u,d]),this.input._formatOptions.isobmff.resolveKeyId({...l,psshBoxes:u})})}},o=new vi({source:new Jn(r.location.path,async l=>{b(l.isRoot);let u={...l,isRoot:!1},d,m=r.location.offset>0||r.location.length!==null;if(!r.encryption||r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(u),m){let p=d.source.slice(r.location.offset,r.location.length??void 0).ref();d.free(),d=p}}else if(r.encryption.method==="AES-128"){let f=r.encryption;b(f.iv);let p=await this.input._getSourceCached(u);if(m){let k=p.source.slice(r.location.offset,r.location.length??void 0).ref();p.free(),p=k}let h=new Ii(p.source),y=af(h,async()=>{var w=[];try{let g=yt(w,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},Zf));let k=new Ii(g.source);let T=await k.requestSlice(0,Xt);if(!T)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");let S=V(T,Xt);return{key:S,iv:f.iv}}catch(A){var C=A,E=!0}finally{kt(w,C,E)}},()=>{p.free()});d=new rn(y).ref()}else b(!1);return d}),formats:this.input._formats.filter(l=>!(l instanceof nn)),initInput:a??void 0,formatOptions:s});if(o._onFormatDetermined=l=>{if((r.encryption?.method==="SAMPLE-AES"||r.encryption?.method==="SAMPLE-AES-CTR")&&!l._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:r,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let l=li(this.inputCache,u=>u.age);b(l!==-1),this.inputCache.splice(l,1)}return o}async getLiveRefreshInterval(){return!this.streamHasEnded&&this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}getMediaOffsetForDiscontinuity(e){return this.demuxer.getMediaOffsetForDiscontinuity(e)}getFirstSegmentTimestampOffset(){return this.segmentTimestampOffsetPromise??=(async()=>{let e=this.demuxer.getReferenceSegmentedInput();if(this===e)return 0;let[r,n]=await Promise.all([this.getFirstSegment(),e.getFirstSegment()]);if(b(r),n&&(this.listsAllSegments()&&e.listsAllSegments()||r.unixEpochTimestamp===r.timestamp&&n.unixEpochTimestamp===n.timestamp))return 0;let a=this.getInputForSegment(r);if(this.getMediaOffsetForDiscontinuity(r.discontinuityNumber).catch(()=>{}),await this.getRawTimestampOffset(a)===null)return 0;let s=await Za(a);if(s===null)throw new Error("The playlist's first segment contains no media.");let o=await this.getMediaOffset(r,a),c=s+o-r.timestamp;return this.learnedSegmentTimestampOffset??=c,c})()}listsAllSegments(){return this.segments[0].sequenceNumber===0||this.neverRemovesSegments}async getRawTimestampOffset(e){if((await e.getFormat()).supportsTimestampedMediaData)return 0;let a=(await e.getMetadataTags()).raw?.PRIV;for(let s of Bt(a)){if(!(s instanceof Uint8Array)||s.length!==zt.length+1+8||be.decode(s.subarray(0,zt.length))!==zt||s[zt.length]!==0)continue;let o=z(s),c=o.getUint32(zt.length+1),l=o.getUint32(zt.length+5);if(c>1)continue;let u=2**32*c+l;return sc(u,ac(u))/Ue-await e.getFirstTimestamp()}return null}getTimestampWrapPeriod(){return $n/Ue}};var Sg=256,Ag=256,Tc=class extends _e{constructor(e){super(e);this.metadataPromise=null;this.trackBackings=null;this.internalTracks=null;this.segmentedInputs=[];this.hasMasterPlaylist=!0;this.masterPlaylistVariables=null;this.mediaOffsets=new Map}readMetadata(){return this.metadataPromise??=(async()=>{b(this.input._rootSource instanceof it);let e=await this.input._reader.requestEntireFile();b(e);let r=yc(e,e.length,{ignore:lc}),{rootPath:n}=this.input._rootSource,a=new Yn(n,null),s=[],o=[];for(let d=1;d<r.length;d++){let m=r[d];if(m.startsWith(Zn))a.define(m.slice(Zn.length));else if(m.startsWith(Au)){let f=d,p=r[++d];if(p===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");p=a.substitute(p);let h=ve(n,p),y=new xr(m.slice(Au.length),a);if(y.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");s.push({fullPath:h,attributes:y,lineNumber:f,hasOnlyKeyPackets:!1})}else if(m.startsWith(xu)){let f=new xr(m.slice(xu.length),a),p=f.get("uri");if(p===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(f.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let y=ve(n,p);s.push({fullPath:y,attributes:f,lineNumber:d,hasOnlyKeyPackets:!0})}else if(m.startsWith(Cu)){let f=new xr(m.slice(Cu.length),a);if(f.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(f.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let y=null,g=f.get("uri");g!==null&&(y=ve(n,g)),o.push({fullPath:y,attributes:f,lineNumber:d})}else if(m.startsWith(Ya)){let f=new ts(this,n,null,r);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}if(s.length>Sg||o.length>Ag)throw new Error("Unsupported M3U8 file; too many variant streams or media tags.");this.masterPlaylistVariables=a;let c=await Promise.all(s.map(async(d,m)=>{let f=[],p=d.attributes.get("codecs"),h;if(p)h=p.split(",").map(x=>x.trim());else{let P=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),v=await Promise.all(P.map(async _=>({track:_,codec:await _.getCodec()})));h=await Promise.all(v.filter(_=>_.codec!==null).map(_=>_.track.getDecoderConfig().then(M=>M.codec)))}let y=d.attributes.get("video"),g=d.attributes.get("audio"),k=h.some(x=>ue.includes(ct(x))),T=h.some(x=>pe.includes(ct(x)));if(y!==null&&!k){let x=o.find(P=>{let v=P.attributes.get("group-id"),_=P.attributes.get("type");return v===y&&_.toLowerCase()==="video"});e:if(x){let P=x.attributes.get("uri");if(P===null)break e;let v=ve(n,P),U=(await this.getSegmentedInputForPath(v).getTrackBackings()).find(L=>L.getType()==="video");if(!U||await U.getCodec()===null)break e;let N=await U.getDecoderConfig().then(L=>L?.codec??null);b(N!==null),h.push(N)}}if(g!==null&&!T){let x=o.find(P=>{let v=P.attributes.get("group-id"),_=P.attributes.get("type");return v===g&&_.toLowerCase()==="audio"});e:if(x){let P=x.attributes.get("uri");if(P===null)break e;let v=ve(n,P),U=(await this.getSegmentedInputForPath(v).getTrackBackings()).find(L=>L.getType()==="audio");if(!U||await U.getCodec()===null)break e;let N=await U.getDecoderConfig().then(L=>L?.codec??null);b(N!==null),h.push(N)}}h=[...new Set(h)];let S=d.attributes.getAsNumber("bandwidth");b(S!==null);let w=d.attributes.getAsNumber("average-bandwidth"),A=d.attributes.get("name"),C=async(x,P,v)=>{let _=new Set(x.map(G=>ct(G)));if(_.size===1){let[G]=_;return b(G),{codec:G,fullCodecString:x.length===1?x[0]:null}}let U=(await this.getSegmentedInputForPath(P).getTrackBackings()).filter(G=>G.getType()===v);if(U.length!==1)throw new Error(`Unsupported M3U8 file; a variant stream lists several ${v} codecs, but its media doesn't contain exactly one ${v} track.`);let N=await U[0].getCodec();if(N===null)return null;let L=await U[0].getDecoderConfig();return b(L),{codec:N,fullCodecString:L.codec}},E=h.filter(x=>ue.includes(ct(x))),I=h.filter(x=>pe.includes(ct(x)));for(let x of h)if(x===E[0]){let P=o.filter(v=>v.attributes.get("group-id")===y&&v.attributes.get("type").toLowerCase()==="video");if(P.length===0){let v=d.attributes.get("resolution"),_=null,M=null;if(v){let N=v.match(/^(\d+)x(\d+)$/);N&&(_=Number(N[1]),M=Number(N[2]))}let U=await C(E,d.fullPath,"video");U&&f.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:le,lineNumber:d.lineNumber,fullPath:d.fullPath,codec:U.codec,fullCodecString:U.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:S,averageBitrate:w,name:A,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:_,height:M}})}else{let v=await Promise.all(P.map(_=>C(E,_.fullPath??d.fullPath,"video")));for(let _=0;_<P.length;_++){let M=P[_],U=v[_];if(!U)continue;let N=M.attributes.get("resolution")??d.attributes.get("resolution"),L=null,G=null;if(N){let me=N.match(/^(\d+)x(\d+)$/);me&&(L=Number(me[1]),G=Number(me[2]))}f.push({demuxer:this,backingTrack:null,default:kc(M.attributes),autoselect:kc(M.attributes)||Jf(M.attributes),languageCode:ep(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,codec:U.codec,fullCodecString:U.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:M.fullPath===null?S:null,averageBitrate:M.fullPath===null?w:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:L,height:G}})}}}else if(x===I[0]){let P=o.filter(v=>v.attributes.get("group-id")===g&&v.attributes.get("type").toLowerCase()==="audio");if(P.length===0){let v=await C(I,d.fullPath,"audio");if(v){let _=d.attributes.get("channels");f.push({demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:le,lineNumber:d.lineNumber,fullPath:d.fullPath,codec:v.codec,fullCodecString:v.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:S,averageBitrate:w,name:A,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:tp(_)}})}}else{let v=await Promise.all(P.map(_=>C(I,_.fullPath??d.fullPath,"audio")));for(let _=0;_<P.length;_++){let M=P[_],U=v[_];if(!U)continue;let N=M.attributes.get("channels")??d.attributes.get("channels");f.push({demuxer:this,backingTrack:null,default:kc(M.attributes),autoselect:kc(M.attributes)||Jf(M.attributes),languageCode:ep(M.attributes.get("language")),lineNumber:M.lineNumber,fullPath:M.fullPath??d.fullPath,codec:U.codec,fullCodecString:U.fullCodecString,pairingMask:1n<<BigInt(m),peakBitrate:M.fullPath===null?S:null,averageBitrate:M.fullPath===null?w:null,name:M.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:tp(N)}})}}}return f})),l=[],u=d=>{let m=l.find(f=>f.fullPath===d.fullPath&&f.info.type===d.info.type);m?(m.pairingMask|=d.pairingMask,m.default||=d.default,m.autoselect||=d.autoselect,m.lineNumber=Math.min(m.lineNumber,d.lineNumber),d.peakBitrate!==null&&(m.peakBitrate=Math.max(m.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(m.averageBitrate=Math.max(m.averageBitrate??-1/0,d.averageBitrate)),m.languageCode===le&&(m.languageCode=d.languageCode)):l.push(d)};for(let d of c)for(let m of d)u(m);l.sort((d,m)=>d.lineNumber-m.lineNumber),this.trackBackings=[];for(let d of l)d.info.type==="video"?this.trackBackings.push(new Sc(d)):this.trackBackings.push(new Ac(d));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),b(this.trackBackings),this.trackBackings}getMediaOffsetForDiscontinuity(e){let r=this.mediaOffsets.get(e);return r||(r=(async()=>{let n=this.getReferenceSegmentedInput(),a=await n.getFirstSegment();for(;a&&a.discontinuityNumber<e;)a=await n.getNextSegment(a,{});if(!a||a.discontinuityNumber!==e)throw new Error(`The reference playlist contains no segment in discontinuity ${e}, so the discontinuity can't be synchronized across tracks. If you think this is a bug, please raise an issue and include the playlist.`);let s=n.getInputForSegment(a),o=await n.getRawTimestampOffset(s)??0,c=await Za(s);if(c===null)throw new Error("The reference playlist's segment contains no media.");return a.timestamp-(o+c)})(),this.mediaOffsets.set(e,r),r)}getReferenceSegmentedInput(){if(!this.hasMasterPlaylist)return this.segmentedInputs[0];b(this.internalTracks);let e=this.internalTracks.filter(o=>!o.hasOnlyKeyPackets),r=e.length>0?e:this.internalTracks,n=r.filter(o=>o.info.type==="video"),a=n.length>0?n:r,s=li(a,o=>o.peakBitrate??1/0);return b(s!==-1),this.getSegmentedInputForPath(a[s].fullPath)}getSegmentedInputForPath(e){let r=this.segmentedInputs.find(a=>a.path===e);if(r)return r;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(s=>s.fullPath===e).map(s=>({type:s.info.type}))),r=new ts(this,e,n,null),this.segmentedInputs.push(r),r}async getMetadataTags(){return{}}async getMimeType(){return Cr}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},wc=class{constructor(t){this.internalTrack=t;this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let t=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),e=null,n=(await t.getTrackBackings()).filter(a=>a.getType()===this.getType());if(n.length===1)e=n[0];else if(this instanceof Sc){for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}else{b(this instanceof Ac);for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}if(!e)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=e})()}delegate(t){return this.internalTrack.backingTrack?t():this.hydrate().then(t)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...Ve,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){b(this.internalTrack.demuxer.internalTracks);let t=this.internalTrack.info.type,e=0;for(let r of this.internalTrack.demuxer.internalTracks)if(r.info.type===t&&e++,r===this.internalTrack)break;return e}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(t){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(t))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(t){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(t)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(t){return this.prefetchReferencePlaylist(),await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(t)}async getPacket(t,e){return this.prefetchReferencePlaylist(),await this.hydrate(),this.internalTrack.backingTrack.getPacket(t,e)}async getKeyPacket(t,e){return this.prefetchReferencePlaylist(),await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(t,e)}async getNextPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(t,e)}async getNextKeyPacket(t,e){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(t,e)}prefetchReferencePlaylist(){this.internalTrack.demuxer.getReferenceSegmentedInput().getFirstSegment().catch(()=>{})}},Sc=class extends wc{constructor(t){super(t)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return this.internalTrack.codec}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(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){if(await this.hydrate(),await this.backingVideoTrack.getCodec()!==this.getCodec())throw new Error("The codec in the playlist doesn't match the codec of the media data.");return this.backingVideoTrack.getDecoderConfig()}},Ac=class extends wc{constructor(t){super(t)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return this.internalTrack.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){if(await this.hydrate(),await this.backingAudioTrack.getCodec()!==this.getCodec())throw new Error("The codec in the playlist doesn't match the codec of the media data.");return this.backingAudioTrack.getDecoderConfig()}},kc=i=>{let t=i.get("default");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},Jf=i=>{let t=i.get("autoselect");if(t===null)return!1;let e=t.toUpperCase();if(e==="YES")return!0;if(e==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},ep=i=>{if(i===null)return le;let t=i.split("-")[0];return t||le},tp=i=>{if(i===null)return null;let[t,e]=i.split("/");if(e!==void 0&&e!=="-")return null;let r=Number(t);return Number.isInteger(r)&&r>0?r:null};var nt=class{constructor(){this._isIsobmff=!1}},ta=class extends nt{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);if(R(r)&&(r=await r),!r)return null;let n=B(r),a=ae(r,4);if(a!=="ftyp"&&a!=="styp")return null;if(n===1){let s=e._reader.requestSlice(16,4);return R(s)&&(s=await s),s?ae(s,4):null}return ae(r,4)}_createDemuxer(e){return new _o(e)}get supportsTimestampedMediaData(){return!0}},rs=class extends ta{async _getMatchPosition(t){let e=await this._getMajorBrand(t);if(e!==null)return e!=="qt "?0:null;let r=0;for(let n=0;n<10;n++){let a=t._reader.requestSlice(r,8);if(R(a)&&(a=await a),!a)return null;let s=B(a),o=8;if(s===1){let l=t._reader.requestSlice(r+8,8);if(R(l)&&(l=await l),!l)return null;s=Ge(l),o=16}if(s<o)return null;let c=ae(a,4);if(c==="moof"||c==="sidx"||c==="moov"||c==="mdat")return 0;if(c==="emsg"||c==="prft"||c==="free"||c==="skip"||c==="wide")r+=s;else return null}return null}get name(){return"MP4"}get mimeType(){return"video/mp4"}},is=class extends ta{async _getMatchPosition(t){return await this._getMajorBrand(t)==="qt "?0:null}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},ra=class extends nt{async isSupportedEBMLOfDocType(t,e){let r=t._reader.requestSlice(0,Yt);if(R(r)&&(r=await r),!r)return!1;let n=su(r);if(n===null||n<1||n>8||$(r,n)!==440786851)return!1;let s=cu(r);if(typeof s!="number")return!1;let o=t._reader.requestSlice(r.filePos,s);if(R(o)&&(o=await o),!o)return!1;let c=r.filePos;for(;o.filePos<=c+s-lt;){let l=Vt(o);if(!l)break;let{id:u,size:d}=l,m=o.filePos;if(d===void 0||m+d>c+s||d>8&&u!==17026)return!1;switch(u){case 17143:if($(o,d)!==1)return!1;break;case 17026:if(xi(o,d)!==e)return!1;break;case 17029:if($(o,d)>4)return!1;break}o.filePos=m+d}return!0}async _getMatchPosition(t){return await this.isSupportedEBMLOfDocType(t,"matroska")?0:null}_createDemuxer(t){return new Wo(t)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}get supportsTimestampedMediaData(){return!0}},ns=class extends ra{async _getMatchPosition(t){return await this.isSupportedEBMLOfDocType(t,"webm")?0:null}get name(){return"WebM"}get mimeType(){return"video/webm"}},as=class extends nt{async _getMatchPosition(t){let e=await Ar(t._reader,0),r=await qa(t._reader,e,4096,null);return r?r.startPos===e?0:r.startPos:null}_createDemuxer(t){return new Qo(t)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}get supportsTimestampedMediaData(){return!1}},ss=class extends nt{async _getMatchPosition(t){let e=t._reader.requestSlice(0,12);if(R(e)&&(e=await e),!e)return null;let r=ae(e,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?null:(e.skip(4),ae(e,4)==="WAVE"?0:null)}_createDemuxer(t){return new Yo(t)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}get supportsTimestampedMediaData(){return!1}},os=class extends nt{async _getMatchPosition(t){let e=t._reader.requestSlice(0,4);return R(e)&&(e=await e),e&&ae(e,4)==="OggS"?0:null}_createDemuxer(t){return new $o(t)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}get supportsTimestampedMediaData(){return!0}},cs=class extends nt{async _getMatchPosition(t){let e=await Ar(t._reader,0),r=t._reader.requestSlice(e,4);return R(r)&&(r=await r),r&&ae(r,4)==="fLaC"?0:null}get name(){return"FLAC"}get mimeType(){return"audio/flac"}get supportsTimestampedMediaData(){return!1}_createDemuxer(t){return new ic(t)}},ls=class extends nt{async _getMatchPosition(t){let e=await Ar(t._reader,0),r=await ja(t._reader,e,4096,null);return r?r.startPos===e?0:r.startPos:null}_createDemuxer(t){return new Jo(t)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}get supportsTimestampedMediaData(){return!1}},us=class extends nt{async _getMatchPosition(t){let e=ze+16+1,r=t._reader.requestSlice(0,e);if(R(r)&&(r=await r),!r)return null;let n=V(r,e);return n[0]===71&&n[ze]===71||n[0]===71&&n[ze+16]===71||n[4]===71&&n[4+ze+4]===71?0:null}_createDemuxer(t){return new oc(t)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}get supportsTimestampedMediaData(){return!0}},nn=class extends nt{async _getMatchPosition(t){let e=t._reader.requestSlice(0,7);if(R(e)&&(e=await e),!e||!(ae(e,7)==="#EXTM3U"))return null;if(!(t._rootSource instanceof it))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return t._rootSource._usedForHls=!0,0}_createDemuxer(t){return new Tc(t)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Cr}get supportsTimestampedMediaData(){return!0}},xc=new rs,Cc=new is,Nu=new ra,Lu=new ns,Pc=new as,Hu=new ss,Wu=new os,Ec=new ls,qu=new cs,Ic=new us,vc=new nn,rp=[vc,xc,Cc,Nu,Lu,Hu,Wu,qu,Pc,Ec,Ic],ip=[vc,xc,Cc,Pc,Ec,Ic],np=(i,t)=>{if(!i||typeof i!="object")throw new TypeError(`${t}, when provided, must be an object.`);if(i.isobmff!==void 0){if(!i.isobmff||typeof i.isobmff!="object")throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(i.isobmff.resolveKeyId!==void 0&&typeof i.isobmff.resolveKeyId!="function")throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(i.hls!==void 0){if(!i.hls||typeof i.hls!="object")throw new TypeError(`${t}.hls, when provided, must be an object.`);if(i.hls.offsetTimestampsByDateTime!==void 0&&typeof i.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};var an=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(i.skipLiveWait!==void 0&&typeof i.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},ti=i=>{if(!Ie(i))throw new TypeError("timestamp must be a number.")},Ku=(i,t,e)=>e.verifyKeyPackets?t.then(async r=>{if(!r||r.type==="delta")return r;let n=await i.determinePacketType(r);return n&&(r.type=n),r}):t,ut=class{constructor(t){if(!(t instanceof Ri))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(an(t),this._track.input._disposed)throw new ge;return Ku(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){an(t);let e=await this.getFirstPacket(t);return e?e.type==="key"?e:this.getNextKeyPacket(e,t):null}async getPacket(t,e={}){if(ti(t),an(e),this._track.input._disposed)throw new ge;return Ku(this._track,this._track._backing.getPacket(t,e),e)}async getNextPacket(t,e={}){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(an(e),this._track.input._disposed)throw new ge;return Ku(this._track,this._track._backing.getNextPacket(t,e),e)}async getKeyPacket(t,e={}){if(ti(t),an(e),this._track.input._disposed)throw new ge;if(!e.verifyKeyPackets)return this._track._backing.getKeyPacket(t,e);let r=await this._track._backing.getKeyPacket(t,e);for(;r;){if(b(r.type==="key"),await this._track.determinePacketType(r)!=="delta")return r;let a=1/await this._track.getTimeResolution(),s;for(;s=await this._track._backing.getKeyPacket(r.timestamp-a,e),!(!s||s.timestamp<r.timestamp);)a*=2;r=s}return null}async getNextKeyPacket(t,e={}){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(an(e),this._track.input._disposed)throw new ge;if(!e.verifyKeyPackets)return this._track._backing.getNextKeyPacket(t,e);let r=await this._track._backing.getNextKeyPacket(t,e);for(;r;){if(b(r.type==="key"),await this._track.determinePacketType(r)!=="delta")return r;r=await this._track._backing.getNextKeyPacket(r,e)}return null}packets(t,e,r={}){if(t!==void 0&&!(t instanceof ee))throw new TypeError("startPacket must be an EncodedPacket.");if(t!==void 0&&t.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(e!==void 0&&!(e instanceof ee))throw new TypeError("endPacket must be an EncodedPacket.");if(an(r),this._track.input._disposed)throw new ge;let n=[],{promise:a,resolve:s}=te(),{promise:o,resolve:c}=te(),l=!1,u=!1,d=null,m=!1,f=()=>{if(n.length>=128)return!0;if(n.length<8)return!1;let h=1/0,y=-1/0;for(let g of n)h=Math.min(h,g.timestamp),y=Math.max(y,g.timestamp);return y-h>=1};(async()=>{let h=t??await this.getFirstPacket(r);for(;h&&!u&&!this._track.input._disposed&&!(e&&h.sequenceNumber>=e?.sequenceNumber);){if(f()){({promise:o,resolve:c}=te()),await o;continue}n.push(h),s(),{promise:a,resolve:s}=te(),h=await this.getNextPacket(h,r)}l=!0,s()})().catch(h=>{m||(d=h,m=!0,s())});let p=this._track;return{async next(){for(;;){if(p.input._disposed)throw new ge;if(u)return{value:void 0,done:!0};if(m)throw d;if(n.length>0){let h=n.shift();return c(),{value:h,done:!1}}else{if(l)return{value:void 0,done:!0};await a}}},async return(){return u=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},ap=4,ds=class{constructor(t,e){this.onSample=t;this.onError=e;this.onDequeue=null}},ia=class{mediaSamplesInRange(t=-1/0,e=1/0,r){ti(t),ti(e);let n=[],a=!1,s=null,{promise:o,resolve:c}=te(),{promise:l,resolve:u}=te(),d=!1,m=!1,f=!1,p=null,h=null,y=!1,g={...r,verifyKeyPackets:!0,metadataOnly:!1},k=this._track,T=()=>{s?.close(),s=null;for(let w of n)w.close();n.length=0},S=()=>{f=!0,m=!0,u(),c()};return k.input._disposed||k.input._disposeCallbacks.add(S),(async()=>{p=await this._createDecoder(v=>{if(u(),v.timestamp>=e&&(m=!0),m){v.close();return}s&&(v.timestamp>t?(n.push(s),a=!0):s.close()),v.timestamp>=t&&(n.push(v),a=!0),s=a?null:v,n.length>0&&(c(),{promise:o,resolve:c}=te())},v=>{y||(h=v,y=!0,c())}),p.onDequeue=()=>u();let w=this._createPacketSink(),A=await this._getPreRollDuration(),C=await w.getPacket(t,g),E=await w.getKeyPacket((C?.timestamp??t)-A,g)??await w.getFirstKeyPacket(g),I=E,P=w.packets(E??void 0,void 0,g);for(await P.next();I&&!m&&!this._track.input._disposed;){if(n.length+p.getDecodeQueueSize()>=ap){({promise:l,resolve:u}=te()),await l;continue}p.decode(I);let v=await P.next();if(v.done)break;I=v.value}await P.return(),!f&&!this._track.input._disposed&&await p.flush(),!a&&s&&(n.push(s),s=null),d=!0,c()})().catch(w=>{y||(h=w,y=!0,c())}).finally(()=>{k.input._disposeCallbacks.delete(S),p?.close(),k.input._disposed&&T()}),{async next(){for(;;){if(k.input._disposed)throw S(),T(),new ge;if(f)return{value:void 0,done:!0};if(y)throw S(),T(),h;if(n.length>0){let w=n.shift();return u(),{value:w,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return S(),T(),{value:void 0,done:!0}},async throw(w){throw await this.return(),w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,e){vd(t);let r=Id(t),n=[],a=[],{promise:s,resolve:o}=te(),{promise:c,resolve:l}=te(),u=!1,d=!1,{promise:m,resolve:f}=te(),p=null,h=null,y=!1,g=E=>{a.push(E),o(),{promise:s,resolve:o}=te()},k=null,T=E=>{for(let I=0;I<E;I++)g(k&&(I<E-1?k.clone():k));E===0&&k?.close(),k=null},S={...e,verifyKeyPackets:!0,metadataOnly:!1},w=this._track,A=()=>{k?.close(),k=null;for(let E of a)E?.close();a.length=0},C=()=>{d=!0,f(),l(),o()};return w.input._disposed||w.input._disposeCallbacks.add(C),(async()=>{p=await this._createDecoder(L=>{if(l(),d){L.close();return}let G=0;for(;n.length>0&&L.timestamp-n[0]>1e-10;)G++,n.shift();T(G),k=L},L=>{y||(h=L,y=!0,o())}),p.onDequeue=()=>l();let E=this._createPacketSink(),I=await this._getPreRollDuration(),x=null,P=-1/0,v=null,_=null,M=-1,U=async()=>{b(v),b(p);let L=_;for(L||(L=v,p.decode(L));L.sequenceNumber<M;){for(;a.length+p.getDecodeQueueSize()>=ap&&!d;)({promise:c,resolve:l}=te()),await c;if(d)break;let G=await E.getNextPacket(L,S);if(!G)throw new Error("Internal error: couldn't get next packet when one was expected.");p.decode(G),L=G}_=L},N=async()=>{b(p),await p.flush(),T(n.length),n.length=0};try{for(;;){let L=r.next();L.catch(()=>{});let G=await Promise.race([L,m]);if(!G||G.done)break;let me=G.value;if(ti(me),d||this._track.input._disposed)break;let ye=await E.getPacket(me,S),ke=ye&&await E.getKeyPacket(ye.timestamp-I,S);if(ye&&!ke){let Ze=await E.getFirstKeyPacket(S);Ze&&Ze.timestamp<=ye.timestamp&&(ke=Ze)}if(!ye||!ke){x&&await N(),g(null),x=null;continue}(!x||ke.sequenceNumber>M+1||me<P)&&(x&&await N(),v=ke,_=null,M=-1),n.push(me),M=Math.max(ye.sequenceNumber,M),x=ye,P=me,await U()}}finally{r.return().catch(()=>{})}!d&&!this._track.input._disposed&&await N(),u=!0,o()})().catch(E=>{y||(h=E,y=!0,o())}).finally(()=>{w.input._disposeCallbacks.delete(C),p?.close(),w.input._disposed&&A()}),{async next(){for(;;){if(w.input._disposed)throw C(),A(),new ge;if(d)return{value:void 0,done:!0};if(y)throw C(),A(),h;if(a.length>0){let E=a.shift();return b(E!==void 0),l(),{value:E,done:!1}}else if(!u)await s;else return{value:void 0,done:!0}}},async return(){return C(),A(),{value:void 0,done:!0}},async throw(E){throw await this.return(),E},[Symbol.asyncIterator](){return this}}}},Gu=class extends ds{constructor(e,r,n,a,s,o,c){super(e,r);this.codec=n;this.decoderConfig=a;this.rotation=s;this.flip=o;this.timeResolution=c;this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new ni;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];this.currentPacketIndex=0;this.raslSkipped=!1;this.alphaDecoder=null;this.alphaHadKeyframe=!1;this.colorQueue=[];this.alphaQueue=[];this.merger=null;this.decodedAlphaChunkCount=0;this.alphaDecoderQueueSize=0;this.nullAlphaFrameQueue=[];this.currentAlphaPacketIndex=0;this.alphaRaslSkipped=!1;this.finalSamples=[];this.mergeAlphaPromises=[];this.flushing=!1;this.frameCopyContext=null;let l=bi.find(u=>u.supports(n,a));if(l)this.customDecoder=new l,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=u=>{if(!(u instanceof $e))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(u)},this.customDecoder.onError=u=>{r(u)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(u=>r(u));else{let u=m=>{if(this.alphaQueue.length>0){let f=this.alphaQueue.shift();b(f!==void 0),this.mergeAlpha(m,f)}else this.colorQueue.push(m)};if(Ni()){if(n==="avc"&&this.decoderConfig.description){let m=gr(Q(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){let f=Gt(m.sequenceParameterSets[0]);f&&f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"});let p=!1;for(let h=0;h<m.sequenceParameterSets.length;h++){let y=Gt(m.sequenceParameterSets[h]);y&&y.maxDecFrameBuffering!==0&&y.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[h]=Hl(y),p=!0)}p&&(this.decoderConfig={...this.decoderConfig,description:In(m)})}}wn(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}let d=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:m=>{try{u(this.copyFrameIfNeeded(m))}catch(f){this.onError(f)}},error:m=>{m.stack=d,this.onError(m)}}),this.decoder.addEventListener("dequeue",()=>{this.onDequeue?.()}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0)+this.finalSamples.length)}decode(e){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()});else{if(b(this.decoder),!et()){let r=mm(this.codec,e.data);for(let n=0;n<r;n++)El(this.inputTimestamps,e.timestamp,a=>a)}if(Ni()&&this.currentPacketIndex===0){let r=this.fixFirstPacketDataForChromium(e.data);r&&(e=e.clone({data:r}))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new Qu),!this.alphaDecoder){let n=s=>{if(this.colorQueue.length>0){let o=this.colorQueue.shift();b(o!==void 0),this.mergeAlpha(o,s)}else this.alphaQueue.push(s);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let o=this.colorQueue.shift();b(o!==void 0),this.mergeAlpha(o,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},a=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:s=>{try{n(this.copyFrameIfNeeded(s))}catch(o){this.onError(o)}},error:s=>{s.stack=a,this.onError(s)}}),this.alphaDecoder.addEventListener("dequeue",()=>{this.onDequeue?.()}),this.alphaDecoder.configure({...this.decoderConfig,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"}})}let r=gi(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=r==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}if(Ni()&&this.currentAlphaPacketIndex===0){let n=this.fixFirstPacketDataForChromium(e.sideData.alpha);n&&(e=e.clone({sideData:{...e.sideData,alpha:n}}))}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}fixFirstPacketDataForChromium(e){if(this.codec==="avc"){let r=[],n=!1;for(let a of Nl(e,this.decoderConfig)){let s=pr(e[a.offset]);if(n||=s>=1&&s<=5,s===9){if(n)break;r.length=0}s>=20&&s<=31||r.push(e.subarray(a.offset,a.offset+a.length))}if(!this.decoderConfig.description)for(let a=0;a<r.length;a++){let s=r[a];if(pr(s[0])!==7)continue;let o=Gt(s);o&&o.maxDecFrameBuffering!==0&&o.bitstreamRestrictionFlag!==1&&(r[a]=Hl(o))}return sm(r,this.decoderConfig)}else return this.codec==="hevc"?lm(e,this.decoderConfig):null}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of ha(e,this.decoderConfig)){let n=Qt(e[r.offset]);if(n===8||n===9)return!0}return!1}sampleHandler(e){if(et()){if(this.sampleQueue.length>0&&e.timestamp>=J(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}El(this.sampleQueue,e,r=>r.timestamp)}else{let r=this.inputTimestamps.shift();b(r!==void 0),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,r){let n=te();this.mergeAlphaPromises.push(n.promise);let a={sample:null};this.finalSamples.push(a);try{if(!r)a.sample=new $e(e);else{b(this.merger);let s=await this.merger.merge(e,r);a.sample=new $e(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){for(Sn(this.finalSamples,a);this.finalSamples.length>0&&this.finalSamples[0].sample!==null;)this.finalSamples.shift().sample.close();this.onError(s)}finally{Sn(this.mergeAlphaPromises,n.promise),n.resolve()}}copyFrameIfNeeded(e){if(!Ni()||!Vd())return e;let r=e.visibleRect,n=r.width,a=r.height;if(!this.frameCopyContext){let c;if(typeof OffscreenCanvas<"u"?c=new OffscreenCanvas(n,a).getContext("2d",{alpha:!1}):c=document.createElement("canvas").getContext("2d",{alpha:!1}),!c)throw new Error("The '2d' canvas context is required to decode video on Chromium for Android.");this.frameCopyContext=c}let s=this.frameCopyContext.canvas;(s.width!==n||s.height!==a)&&(s.width=n,s.height=a),this.frameCopyContext.drawImage(e,0,0,n,a),this.flushing&&this.frameCopyContext.getImageData(0,0,1,1);let o=new VideoFrame(s,{timestamp:e.timestamp,duration:e.duration??void 0,displayWidth:e.displayWidth,displayHeight:e.displayHeight});return e.close(),o}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),this.flushing=!0,await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.flushing=!1,await Promise.all(this.mergeAlphaPromises),this.inputTimestamps.length=0,this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),et()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()).catch(e=>this.onError(e)):(b(this.decoder),this.decoder.state!=="closed"&&this.decoder.close(),this.alphaDecoder&&this.alphaDecoder.state!=="closed"&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Qu=class{constructor(){this.workers=[];this.nextWorkerIndex=0;this.pendingRequests=new Map;this.nextRequestId=0}merge(t,e){if(this.workers.length===0){let s=ne(navigator.hardwareConcurrency,1,4);for(let o=0;o<s;o++){let c=Pn("color-alpha-merger",xg);c.addEventListener("message",l=>{let u=l.data,d=this.pendingRequests.get(u.id);if(!d){"frame"in u&&u.frame.close();return}this.pendingRequests.delete(u.id),"error"in u?d.reject(new Error(u.error)):d.resolve(u.frame)}),c.addEventListener("error",l=>{let u=new Error(l.message||"Color/alpha merge worker error.");for(let d of this.pendingRequests.values())d.reject(u);this.pendingRequests.clear()}),this.workers.push(c)}}let r=this.nextRequestId++,n=te();this.pendingRequests.set(r,n);let a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:r,color:t,alpha:e},{transfer:[t,e]}),n.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let t=new Error("Color/alpha merger closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},xg=()=>{let i=null,t=null,e=Promise.resolve();self.addEventListener("message",c=>{let{id:l,color:u,alpha:d}=c.data;e=e.then(async()=>{try{let m=await r(u,d);self.postMessage({id:l,frame:m},{transfer:[m]})}catch(m){self.postMessage({id:l,error:m.message})}finally{u.close(),d.close()}})});let r=async(c,l)=>{let u=c.format,d=l.format;if(!u||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let m=u.includes("P10"),f=u.includes("P12"),p=d.includes("P10"),h=d.includes("P12");if(p!==m||h!==f)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${u}', alpha: '${d}').`);if(u==="RGBX"||u==="RGBA"||u==="BGRX"||u==="BGRA")return await n(c,l,u);if(u==="I420"||u==="I420P10"||u==="I420P12"||u==="I422"||u==="I422P10"||u==="I422P12"||u==="I444"||u==="I444P10"||u==="I444P12")return await a(c,l,u);if(u==="NV12")return await s(c,l);throw new Error(`CPU color/alpha merging does not support format '${u}'.`)},n=async(c,l,u)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=d*m,p=new Uint8Array(f*4);await c.copyTo(p);let h=await o(l,d,m,1);for(let k=0,T=3;k<f;k++,T+=4)p[T]=h[k];let g={format:u==="RGBX"||u==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:m,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,g)},a=async(c,l,u)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=u.includes("P10"),p=u.includes("P12"),h=f||p?2:1,y,g;u.startsWith("I420")?(y=Math.ceil(d/2),g=Math.ceil(m/2)):u.startsWith("I422")?(y=Math.ceil(d/2),g=m):(y=d,g=m);let k=d*m,T=y*g,S=k*h,w=T*h,A=k*h,C=S+2*w+A,E=new Uint8Array(C);await c.copyTo(E);let I=await o(l,d,m,h),x=S+2*w;E.set(I,x);let v={format:u.slice(0,4)+"A"+u.slice(4),codedWidth:d,codedHeight:m,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[E.buffer]};return new VideoFrame(E,v)},s=async(c,l)=>{let u=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,m=u*d,f=Math.ceil(u/2),p=Math.ceil(d/2),h=f*p,y=c.allocationSize();(!t||t.byteLength!==y)&&(t=new Uint8Array(y)),await c.copyTo(t);let g=new Uint8Array(m+2*h+m);g.set(t.subarray(0,m),0);let k=m,T=m+h,S=m;for(let C=0;C<h;C++)g[k+C]=t[S+C*2],g[T+C]=t[S+C*2+1];let w=await o(l,u,d,1);g.set(w,m+2*h);let A={format:"I420A",codedWidth:u,codedHeight:d,displayWidth:c.displayWidth,displayHeight:c.displayHeight,colorSpace:c.colorSpace.toJSON(),timestamp:c.timestamp,duration:c.duration??void 0,transfer:[g.buffer]};return new VideoFrame(g,A)},o=async(c,l,u,d)=>{let m=c.allocationSize();(!i||i.byteLength!==m)&&(i=new Uint8Array(m)),await c.copyTo(i);let f=c.format;if(f==="RGBA"||f==="BGRA"||f==="RGBX"||f==="BGRX"){let p=f==="RGBA"||f==="RGBX"?0:2,h=l*u;for(let y=0;y<h;y++)i[y]=i[y*4+p];return i.subarray(0,h)}else{let p=i.subarray(0,l*u*d);if(c.colorSpace.fullRange===!1){let h=f.includes("P12")?12:f.includes("P10")?10:8,y=16<<h-8,g=235<<h-8,k=(1<<h)-1,T=d===2?new Uint16Array(p.buffer,0,l*u):p;for(let S=0;S<T.length;S++){let w=Math.round((T[S]-y)*k/(g-y));T[S]=Math.min(Math.max(w,0),k)}}return p}}},sp=i=>{if(!i||typeof i!="object")throw new TypeError("decoderOptions must be an object.");if(i.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i.optimizeForLatency!==void 0&&typeof i.optimizeForLatency!="boolean")throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")},_i=class extends ia{constructor(t,e={}){if(!(t instanceof Pr))throw new TypeError("videoTrack must be an InputVideoTrack.");sp(e),super(),this._track=t,this._decoderOptions=e}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(xn("VideoDecoder")):new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getRotation(),a=await this._track.getFlip(),s=await this._track.getDecoderConfig(),o=await this._track.getTimeResolution();return b(r&&s),s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Gu(t,e,r,s,n,a,o)}_createPacketSink(){return new ut(this._track)}async _getPreRollDuration(){return 0}async getSample(t,e={}){ti(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},_c=class{constructor(t,e={}){this._rotation=0;this._flip=!1;this._initPromise=null;this._nextCanvasIndex=0;if(!(t instanceof Pr))throw new TypeError("videoTrack must be an InputVideoTrack.");if(e&&typeof e!="object")throw new TypeError("options must be an object.");if(e.alpha!==void 0&&typeof e.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotation!==void 0&&![0,90,180,270].includes(e.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(e.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&ki(e.crop,"options."),e.poolSize!==void 0&&(typeof e.poolSize!="number"||!Number.isInteger(e.poolSize)||e.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");e.decoderOptions!==void 0&&sp(e.decoderOptions),this._videoTrack=t,this._alpha=e.alpha??!1,this._options=e,this._fit=e.fit??"fill",this._videoSampleSink=new _i(t,e.decoderOptions),this._canvasPool=Array.from({length:e.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let t=this._options,e=this._videoTrack,r=t.rotation??await e.getRotation(),n=t.flip??await e.getFlip(),a=await e.getSquarePixelWidth(),s=await e.getSquarePixelHeight(),[o,c]=r%180===0?[a,s]:[s,a],l=t.crop;l&&(l=Mn(l,o,c));let[u,d]=l?[l.width,l.height]:[o,c],m=u/d;t.width!==void 0&&t.height===void 0?(u=t.width,d=Math.round(u/m)):t.width===void 0&&t.height!==void 0?(d=t.height,u=Math.round(d*m)):t.width!==void 0&&t.height!==void 0&&(u=t.width,d=t.height),this._width=u,this._height=d,this._rotation=r,this._flip=n,this._crop=l})()}_videoSampleToWrappedCanvas(t){let e=this._width,r=this._height,n=this._canvasPool[this._nextCanvasIndex],a=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=e,n.height=r):n=new OffscreenCanvas(e,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let s=n.getContext("2d",{alpha:this._alpha||Wt()});b(s);try{return t._drawWithFitAndMipmapping(n,s,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&Wt()}),{canvas:n,timestamp:t.timestamp,duration:t.duration}}finally{t.close()}}async getCanvas(t,e){ti(t),await this._ensureInit();let r=await this._videoSampleSink.getSample(t,e);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(t,e,r){await this._ensureInit(),yield*ma(this._videoSampleSink.samples(t,e,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,e){await this._ensureInit(),yield*ma(this._videoSampleSink.samplesAtTimestamps(t,e),r=>r&&this._videoSampleToWrappedCanvas(r))}},ju=class extends ds{constructor(e,r,n,a){super(e,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new ni;this.customDecoderQueueSize=0;this.currentTimestamp=null;this.expectedFirstTimestamp=null;this.timestampOffset=0;this.packetsSinceFlush=0;this.inputTimestampShift=0;this.referencePacketIndex=n==="vorbis"?1:0;let s=n==="opus"&&a.description?yr(Q(a.description)).preSkip/tt:0,o=l=>{if(l.numberOfFrames===0){l.close();return}let u=l.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp+s-u),u+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(u-this.currentTimestamp)>=l.duration)&&(this.currentTimestamp=u);let d=this.currentTimestamp;this.currentTimestamp+=l.duration;let m=a.sampleRate;l.setTimestamp(Math.round(d*m)/m),e(l)},c=yi.find(l=>l.supports(n,a));if(c)this.customDecoder=new c,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=l=>{if(!(l instanceof Ce))throw new TypeError("The argument passed to onSample must be an AudioSample.");o(l)},this.customDecoder.onError=l=>{r(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>r(l));else{let l=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:u=>{try{o(new Ce(u))}catch(d){this.onError(d)}},error:u=>{u.stack=l,this.onError(u)}}),this.decoder.addEventListener("dequeue",()=>{this.onDequeue?.()}),this.decoder.configure(a)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(b(this.decoder),this.decoder.decodeQueueSize)}decode(e){if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()});else{b(this.decoder),this.packetsSinceFlush===0&&(this.inputTimestampShift=-e.timestamp),this.packetsSinceFlush===this.referencePacketIndex&&(this.expectedFirstTimestamp=e.timestamp),this.packetsSinceFlush++;let r=e.clone({timestamp:e.timestamp+this.inputTimestampShift});this.decoder.decode(r.toEncodedAudioChunk())}}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.packetsSinceFlush=0,this.inputTimestampShift=0,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()).catch(e=>this.onError(e)):(b(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}},Xu=class extends ds{constructor(e,r,n){super(e,r);this.decoderConfig=n;this.currentTimestamp=null;b(se.includes(n.codec)),this.codec=n.codec;let{dataType:a,sampleSize:s,littleEndian:o}=Me(this.codec);switch(this.inputSampleSize=s,s){case 1:a==="unsigned"?this.readInputValue=(c,l)=>c.getUint8(l)-2**7:a==="signed"?this.readInputValue=(c,l)=>c.getInt8(l):a==="ulaw"?this.readInputValue=(c,l)=>wm(c.getUint8(l)):a==="alaw"?this.readInputValue=(c,l)=>Am(c.getUint8(l)):b(!1);break;case 2:a==="unsigned"?this.readInputValue=(c,l)=>c.getUint16(l,o)-2**15:a==="signed"?this.readInputValue=(c,l)=>c.getInt16(l,o):b(!1);break;case 3:a==="unsigned"?this.readInputValue=(c,l)=>Ui(c,l,o)-2**23:a==="signed"?this.readInputValue=(c,l)=>_d(c,l,o):b(!1);break;case 4:a==="unsigned"?this.readInputValue=(c,l)=>c.getUint32(l,o)-2**31:a==="signed"?this.readInputValue=(c,l)=>c.getInt32(l,o):a==="float"?this.readInputValue=(c,l)=>c.getFloat32(l,o):b(!1);break;case 8:a==="float"?this.readInputValue=(c,l)=>c.getFloat64(l,o):b(!1);break;default:Z(s),b(!1)}switch(s){case 1:a==="ulaw"||a==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,l,u)=>c.setUint8(l,u+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,l,u)=>c.setInt16(l,u,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u<<8,!0);break;case 4:this.outputSampleSize=4,a==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,l,u)=>c.setInt32(l,u,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,l,u)=>c.setFloat32(l,u,!0);break;default:Z(s),b(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=z(e.data),n=Math.floor(e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize);if(n===0)return;let a=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(a),o=new DataView(s);for(let m=0;m<n*this.decoderConfig.numberOfChannels;m++){let f=m*this.inputSampleSize,p=m*this.outputSampleSize,h=this.readInputValue(r,f);this.writeOutputValue(o,p,h)}let c=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=e.timestamp);let l=this.currentTimestamp;this.currentTimestamp+=c;let u=this.decoderConfig.sampleRate,d=new Ce({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:u,numberOfFrames:n,timestamp:Mt(l,u),_doNotCopy:!0});this.onSample(d)}async flush(){this.currentTimestamp=null}close(){}},sn=class extends ia{constructor(t){if(!(t instanceof Er))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=t}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof AudioDecoder>"u"?new Error(xn("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),n=await this._track.getDecoderConfig();return b(r&&n),se.includes(n.codec)?new Xu(t,e,n):new ju(t,e,r,n)}_createPacketSink(){return new ut(this._track)}async _getPreRollDuration(){let t=await this._track.getPreRollDuration();return b(t!==null),t}async getSample(t,e={}){ti(t);for await(let r of this.mediaSamplesAtTimestamps([t],e))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(t,e,r={}){return this.mediaSamplesInRange(t,e,r)}samplesAtTimestamps(t,e={}){return this.mediaSamplesAtTimestamps(t,e)}},Rc=class{constructor(t){if(!(t instanceof Er))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new sn(t)}_audioSampleToWrappedArrayBuffer(t){try{return{buffer:t.toAudioBuffer(),timestamp:t.timestamp,duration:t.duration}}finally{t.close()}}async getBuffer(t,e){ti(t);let r=await this._audioSampleSink.getSample(t,e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(t,e,r){return ma(this._audioSampleSink.samples(t,e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(t,e){return ma(this._audioSampleSink.samplesAtTimestamps(t,e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}};var Ri=class i{constructor(t,e){this.input=t,this._backing=e}isVideoTrack(){return this instanceof Pr}isAudioTrack(){return this instanceof Er}get id(){let t=this.input._trackBackingsCache;b(t);let e=t.indexOf(this._backing);return b(e!==-1),e+1}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Te(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Te(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Te(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Te(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(t){return this._backing.getUnixTimeForTimestamp(t)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Te(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return await this.getFirstTimestampOrNull()??0}async getFirstTimestampOrNull(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??null}async computeDuration(t){return await this.computeDurationOrNull(t)??0}async computeDurationOrNull(t){let e=await this._backing.getPacket(1/0,{metadataOnly:!0,...t});return e?Mt(e.timestamp+e.duration,await this.getTimeResolution()):null}async getDurationFromMetadata(t={}){return this._backing.getDurationFromMetadata(t)}async computePacketStats(t=1/0,e){let r=new ut(this),n=1/0,a=-1/0,s=0,o=0;for await(let l of r.packets(void 0,void 0,{metadataOnly:!0,...e})){if(s>=t&&l.timestamp>=a&&a>n)break;n=Math.min(n,l.timestamp),a=Math.max(a,l.timestamp+l.duration),s++,o+=l.byteLength}let c=a-n;return{packetCount:s,averagePacketRate:s>0?Number((s/c).toPrecision(16)):0,averageBitrate:o>0?Number((8*o/c).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an InputTrack.");return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(t){return this.input.getTracks(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPairableVideoTracks(t){return this.input.getVideoTracks(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPairableAudioTracks(t){return this.input.getAudioTracks(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableVideoTrack(t){return this.input.getPrimaryVideoTrack(Fi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableAudioTrack(t){return this.input.getPrimaryAudioTrack(Fi({filter:e=>e.canBePairedWith(this)},t))}async hasPairableTrack(t){t&&=$u(t);let e=await this.input.getTracks();for(let r of e)if(this.canBePairedWith(r)&&(!t||await t(r)))return!0;return!1}hasPairableVideoTrack(t){return t&&=$u(t),this.hasPairableTrack(async e=>e.isVideoTrack()&&(!t||await t(e)))}hasPairableAudioTrack(t){return t&&=$u(t),this.hasPairableTrack(async e=>e.isAudioTrack()&&(!t||await t(e)))}},Te=(i,t,e)=>{if(R(i))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${e}()' instead.`);return i},$u=i=>{if(i!==void 0&&typeof i!="function")throw new TypeError("predicate, when provided, must be a function.");return i?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return n},r=i(t);return R(r)?r.then(e):e(r)}:void 0},Pr=class extends Ri{constructor(e,r){super(e,r);this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Te(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Te(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Te(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Di(await this._backing.getTransformationMatrix())}get rotation(){return Di(Te(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return Al(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Te(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Te(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=op(await this.getSquarePixelWidth()*await this.getCodedHeight(),await this.getSquarePixelHeight()*await this.getCodedWidth())}get pixelAspectRatio(){return this._pixelAspectRatioCache??=op(Te(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Te(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),Te(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Te(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio"))}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let a=Te(e,"displayWidth","getDisplayWidth");if(a!==null)return a}let n=Di(Te(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Te(n,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let a=Te(e,"displayHeight","getDisplayHeight");if(a!==null)return a}let n=Di(Te(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Te(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.transfer==="pq"||e.transfer==="hlg"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let r=await this._backing.getCodec();return b(r!==null),bi.some(a=>a.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return O._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let r=await this.getCodec();if(r===null)return null;let n=await this.getDecoderConfig();return b(n),gi(r,n,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!Ie(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");let r=await this.getTimeResolution(),n=e.targetPacketCount??256,a=new ut(this),s=[],o=-1/0,c=0;for await(let P of a.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=n&&P.timestamp>=o)break;s.push(P.timestamp),o=Math.max(o,P.timestamp),c++}let l=new Float64Array(s.length);for(let P=0;P<s.length;P++)l[P]=Math.round(s[P]*r);l.sort();let u=1;for(let P=1;P<l.length;P++)l[P]!==l[u-1]&&(l[u++]=l[P]);if(u<2)return{underlyingFrameRate:null,bestGuessFrameRate:r,minFrameRate:r,maxFrameRate:r,averageFrameRate:r,medianFrameRate:r,frameRateIsConstant:!0,probedPacketCount:c};let d=l.subarray(0,u),m=Cg(d,r),f=m??r,p=m!==null?r/m:null,h=new Map,y=1/0,g=-1/0,k=0;for(let P=1;P<u;P++){let v=d[P]-d[P-1],_=p!==null?Math.max(1,Math.round(v/p)):v;h.set(_,(h.get(_)??0)+1),y=Math.min(y,_),g=Math.max(g,_),k+=_}let T=u-1,S=[...h.keys()].sort((P,v)=>P-v),w=T-1>>1,A=T>>1,C=0,E=0,I=0;for(let P of S)if(I+=h.get(P),C===0&&I>w&&(C=P),I>A){E=P;break}let x=(f/C+f/E)/2;return{underlyingFrameRate:m,bestGuessFrameRate:m!==null?m:Pg(x),minFrameRate:f/g,maxFrameRate:f/y,averageFrameRate:f*T/k,medianFrameRate:x,frameRateIsConstant:m!==null&&y===1&&g===1,probedPacketCount:c}}},op=(i,t)=>i===0||t===0?{num:1,den:1}:zr({num:i,den:t}),Er=class extends Ri{constructor(t,e){super(t,e)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Te(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){let t=await this._backing.getCodec();return await this._backing.getHasOnlyKeyPackets?.()??(t===null||!Ji.includes(t))}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Te(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Te(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let t=await this._backing.getMetadataCodecParameterString?.();return t??(await this._backing.getDecoderConfig())?.codec??null}async getPreRollDuration(){let t=await this._backing.getCodec();if(t===null)return null;let e=await this._backing.getDecoderConfig();return b(e),Mc(t,e)}async canDecode(){try{let t=await this._backing.getDecoderConfig();if(!t)return!1;let e=await this._backing.getCodec();return b(e!==null),yi.some(r=>r.supports(e,t))||se.includes(t.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0}catch(t){return O._error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");let e=await this.getCodec();return e===null?null:Rn(e,t.data)}},lp=i=>i??1/0,ms=i=>-(i??-1/0),Mi=i=>-i,na=i=>{if(typeof i!="object"||!i)throw new TypeError("query must be an object.");if(i.filter!==void 0&&typeof i.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(i.sortBy!==void 0&&typeof i.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:i.filter?t=>{let e=n=>{if(typeof n!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return n},r=i.filter(t);return R(r)?r.then(e):e(r)}:void 0,sortBy:i.sortBy?t=>{let e=n=>{if(typeof n!="number"&&(!Array.isArray(n)||!n.every(a=>typeof a=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return n},r=i.sortBy(t);return R(r)?r.then(e):e(r)}:void 0}},Fi=(i,t)=>({filter:i?.filter||t?.filter?e=>{let r=i?.filter?.(e)??!0,n=a=>a===!1?!1:t?.filter?.(e)??!0;return R(r)?r.then(n):n(r)}:void 0,sortBy:i?.sortBy||t?.sortBy?e=>{let r=i?.sortBy?.(e)??[],n=t?.sortBy?.(e)??[],a=(s,o)=>[...Array.isArray(s)?s:[s],...Array.isArray(o)?o:[o]];return R(r)||R(n)?Promise.all([r,n]).then(([s,o])=>a(s,o)):a(r,n)}:void 0}),Fc=async(i,t)=>{let e=i;if(t?.filter){let s=i.map(c=>t.filter(c));if(s.some(c=>R(c))){let c=await Promise.all(s);e=i.filter((l,u)=>c[u])}else e=i.filter((c,l)=>s[l])}if(!t?.sortBy)return e;let r=e.map(s=>t.sortBy(s)),a=r.some(s=>R(s))?await Promise.all(r):r;return e.map((s,o)=>({track:s,sortValue:a[o]})).sort((s,o)=>{let c=Array.isArray(s.sortValue)?s.sortValue:[s.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){let m=c[d]??0,f=l[d]??0;if(m!==f)return m-f}return 0}).map(s=>s.track)},Cg=(i,t)=>{let n=1.000000001,a=1e3,s=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(i.length<2)return null;let o=new Float64Array(i.length-1);for(let E=1;E<i.length;E++){let I=i[E]-i[E-1];if(!(I>0))return null;o[E-1]=I}let c=o.slice();c.sort();let l=c[Math.floor(c.length*.05)],u=1;for(let E=0;E<6;E++){let I=0,x=0;for(let v of o){let _=Math.max(1,Math.round(v/l));Math.abs(v-_*l)>=n+_*u||(I+=v,x+=_)}if(x===0)return null;let P=I/x;if(u=1/Math.min(x,a),Math.abs(P-l)<=1e-12*Math.max(1,l)){l=P;break}l=P}let d=0,m=0,f=0;for(let E of o){let I=Math.max(1,Math.round(E/l));Math.abs(E-I*l)>=n+I*u||(d++,m+=E,f+=I)}if(d/o.length<.98)return null;l=m/f;let p=1/Math.min(f,a),h=Math.max(Number.EPSILON,l-p),y=l+p,g=t/y,k=t/h,T=t/l,S=null,w=1/0;for(let E of s){if(E<g||E>k)continue;let I=Math.abs(E/T-1);I<w&&(S=E,w=I)}if(S===null){let E=cp(h,y,1e6),I=cp(g,k,1e6);if(I&&(!E||I.den<E.den||I.den===E.den&&I.num<=E.num))S=I.num/I.den;else if(E)S=t*E.den/E.num;else return null}let A=t/S,C=0;for(let E of o){let I=Math.max(1,Math.round(E/A));Math.abs(E-I*A)<n&&C++}return C/o.length<.98?null:S},cp=(i,t,e)=>{for(let r=1;r<=e;r++){let n=Math.floor(i*r)+1;if(n/r<t)return zr({num:n,den:r})}return null},Pg=i=>{let t=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],e=[12,15,20,24,25,30,48,50,60,100,120,144,240],r=5e-4,n=.025;for(let o of t)if(Math.abs(o/i-1)<=r)return o;let a=i,s=1/0;for(let o of e){let c=Math.abs(o/i-1);c<=n&&c<s&&(a=o,s=c)}return a};Cn();var Eg=1,Zf=2,vi=class i extends st{constructor(e){super();this._demuxerPromise=null;this._format=null;this._trackBackingsCache=null;this._backingToTrack=new Map;this._disposed=!1;this._disposeCallbacks=new Set;this._nextSourceCacheAge=0;this._sourceRefs=[];this._sourceCache=[];this._sourceCachePromises=[];this._onFormatDetermined=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof nt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Qe||e.source instanceof Ei))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Qe&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof i))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&np(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Qe?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get disposed(){return this._disposed}get _rootSource(){if(this._disposed)throw new ge;return this._rootRef.source}async _getSourceUncached(e){b(this._rootSource instanceof it);let r=await this._rootSource._resolveRequest(e);return this._emit("source",{source:r.source,request:e,isRoot:e.isRoot}),r}_getSourceCached(e,r=Eg){let n=this._sourceCache.find(o=>o.cacheGroup===r&&Uu(o.request,e));if(n)return n.age=this._nextSourceCacheAge++,Promise.resolve(n.sourceRef.source.ref());let a=this._sourceCachePromises.find(o=>o.cacheGroup===r&&Uu(o.request,e));if(a)return a.promise.then(o=>o.sourceRef.source.ref());let s=(async()=>{let o;try{o=await this._getSourceUncached(e)}finally{let d=this._sourceCachePromises.findIndex(m=>m.request===e);b(d!==-1),this._sourceCachePromises.splice(d,1)}if(this._disposed)throw o.free(),new ge;if(Wi(this._sourceCache,d=>d.cacheGroup===r&&d.sourceRef.source._refCount===1)>=4){let d=li(this._sourceCache,f=>f.cacheGroup===r&&f.sourceRef.source._refCount===1?f.age:1/0);b(d!==-1);let m=this._sourceCache[d];this._sourceCache.splice(d,1),m.sourceRef.free(),Sn(this._sourceRefs,m.sourceRef)}return this._sourceRefs.push(o),{request:e,sourceRef:o,age:this._nextSourceCacheAge++,cacheGroup:r}})();return this._sourceCachePromises.push({request:e,cacheGroup:r,promise:s}),s.then(o=>{let c=o.sourceRef.source.ref();return this._sourceCache.push(o),c})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new Ii(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});let e=null,r=1/0;for(let n of this._formats){let a=await n._getMatchPosition(this);if(a!==null&&a<r&&(e=n,r=a,a===0))break}if(!e)throw new aa;return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),b(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof aa)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let r=e.filter(s=>s!==null);if(r.length===0)return 0;let n=await Promise.all(r.map(s=>s.getFirstTimestampOrNull())),a=Math.min(...n.map(s=>s??1/0));return a===1/0?0:a}async computeDuration(e,r){e??=await this.getTracks();let n=e.filter(o=>o!==null);if(n.length===0)return 0;let a=await Promise.all(n.map(o=>o.computeDurationOrNull(r))),s=Math.max(...a.map(o=>o??-1/0));return s===-1/0?0:s}async getDurationFromMetadata(e,r){e??=await this.getTracks();let n=e.filter(o=>o!==null),s=(await Promise.all(n.map(o=>o.getDurationFromMetadata(r)))).filter(o=>o!==null);return s.length===0?null:Math.max(...s)}async getTracks(e){e&&=na(e);let n=(await this._getTrackBackings()).map(a=>this._wrapBackingAsTrack(a));return Fc(n,e)}async getVideoTracks(e){e&&=na(e);let n=(await this.getTracks()).filter(a=>a.isVideoTrack());return Fc(n,e)}async getAudioTracks(e){e&&=na(e);let n=(await this.getTracks()).filter(a=>a.isAudioTrack());return Fc(n,e)}async getPrimaryVideoTrack(e){e&&=na(e);let r=Fi(e,{sortBy:async a=>[Mi((await a.getDisposition()).default),Mi(await a.hasPairableAudioTrack()),Mi(!await a.hasOnlyKeyPackets()),ms(await a.getBitrate())]});return(await this.getVideoTracks(r))[0]??null}async getPrimaryAudioTrack(e){e&&=na(e);let r=await this.getPrimaryVideoTrack(),n=Fi(e,{sortBy:async s=>[Mi(!r||s.canBePairedWith(r)),Mi((await s.getDisposition()).default),ms(await s.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let r=this._backingToTrack.get(e);if(r)return r;let a=e.getType()==="video"?new Pr(this,e):new Er(this,e);return this._backingToTrack.set(e,a),a}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._disposeCallbacks)e();this._disposeCallbacks.clear();for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._sourceCache.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},aa=class extends Error{constructor(t="Input has an unsupported or unrecognizable format."){super(t),this.name="UnsupportedInputFormatError"}},ge=class extends Error{constructor(t="Input has been disposed."){super(t),this.name="InputDisposedError"}};var Ii=class{constructor(t){this.source=t}get fileSize(){let t=this.source._getFileSize();if(t===void 0)throw new Error("Reading file size too early; read required first.");return t}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(t,e){if(this.source._disposed)throw new ge;if(t<0||this.fileSizeNonStrict!==null&&t+e>this.fileSizeNonStrict)return null;if(e===0){let a=new Uint8Array(0);return new xe(a,z(a),0,t,t)}let r=t+e,n=this.source._read(t,r,Du,Vu);return R(n)?n.then(a=>a?new xe(a.bytes,a.view,a.offset,t,r):null):n?new xe(n.bytes,n.view,n.offset,t,r):null}requestSliceRange(t,e,r){if(this.source._disposed)throw new ge;if(t<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(t,ne(this.fileSizeNonStrict-t,e,r));{let n=this.requestSlice(t,r),a=s=>s||(b(this.fileSizeNonStrict!==null),this.requestSlice(t,ne(this.fileSizeNonStrict-t,e,r)));return R(n)?n.then(a):a(n)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let t=1024;return(async()=>{let e=[],r=0;for(;;){if(e.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let s=this.requestSliceRange(r,0,t);if(R(s)&&(s=await s),!s||s.length===0)break;let o=V(s,s.length);e.push(o),r+=s.length}let n=new Uint8Array(r),a=0;for(let s of e)n.set(s,a),a+=s.length;return new xe(n,z(n),0,0,r)})()}},xe=class i{constructor(t,e,r,n,a){this.bytes=t;this.view=e;this.offset=r;this.start=n;this.end=a;this.bufferPos=n-r}static tempFromBytes(t){return new i(t,z(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(t){this.bufferPos=t-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(t){this.bufferPos+=t}slice(t,e=this.end-t){if(t<this.start||t+e>this.end)throw new RangeError("Slicing outside of original slice.");return new i(this.bytes,this.view,this.offset,t,t+e)}},dt=(i,t)=>{if(t<0||i.filePos<i.start||i.filePos+t>i.end)throw new RangeError(`Tried reading [${i.filePos}, ${i.filePos+t}), but slice is [${i.start}, ${i.end}). This is likely an internal error, please report it alongside the file that caused it.`)},V=(i,t)=>{dt(i,t);let e=i.bytes.subarray(i.bufferPos,i.bufferPos+t);return i.bufferPos+=t,e},H=i=>(dt(i,1),i.view.getUint8(i.bufferPos++)),Qa=(i,t)=>{dt(i,2);let e=i.view.getUint16(i.bufferPos,t);return i.bufferPos+=2,e},fe=i=>{dt(i,2);let t=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,t},$t=i=>{dt(i,3);let t=Ui(i.view,i.bufferPos,!1);return i.bufferPos+=3,t},La=i=>{dt(i,2);let t=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,t},Jr=(i,t)=>{dt(i,4);let e=i.view.getUint32(i.bufferPos,t);return i.bufferPos+=4,e},B=i=>{dt(i,4);let t=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,t},Zt=i=>{dt(i,4);let t=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,t},Xr=i=>{dt(i,4);let t=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,t},Ig=i=>{dt(i,4);let t=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,t},bu=(i,t)=>{let e,r;return t?(e=Jr(i,!0),r=Jr(i,!0)):(r=Jr(i,!1),e=Jr(i,!1)),r*4294967296+e},Ge=i=>{let t=B(i),e=B(i);return t*4294967296+e},yf=i=>{let t=Xr(i),e=B(i);return t*4294967296+e},_f=i=>{let t=Zt(i);return Ig(i)*4294967296+t},Af=i=>{dt(i,4);let t=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,t},Oo=i=>{dt(i,8);let t=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,t},ae=(i,t)=>{dt(i,t);let e="";for(let r=0;r<t;r++)e+=String.fromCharCode(i.bytes[i.bufferPos++]);return e},yc=(i,t,e)=>be.decode(V(i,t)).split(`
|
|
15
|
+
`).map(a=>a.trim()).filter(a=>a.length>0&&!e?.ignore?.(a));var Ot=8,kr=16,jr=i=>{let t=B(i),e=ae(i,4),r=8;t===1&&(t=Ge(i),r=16);let a=t-r;return a<0?null:{name:e,totalSize:t,headerSize:r,contentSize:a}},wi=i=>Xr(i)/65536,vo=i=>Xr(i)/1073741824,Yu=i=>{let t=0;for(let e=0;e<4;e++){t<<=7;let r=H(i);if(t|=r&127,(r&128)===0)break}return t},Do=i=>{if(H(i)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");Yu(i),i.skip(2);let e=H(i),r=(e&128)!==0,n=(e&64)!==0,a=(e&32)!==0;if(r&&i.skip(2),n){let d=H(i);i.skip(d)}if(a&&i.skip(2),H(i)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");let o=Yu(i),c=i.filePos,l=H(i);i.skip(12);let u=null;if(o>i.filePos-c){if(H(i)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");let m=Yu(i);u=V(i,m)}return{objectTypeIndication:l,decoderSpecificInfo:u}},Pt=i=>{let t=fe(i);return i.skip(2),t=Math.min(t,i.remainingLength),be.decode(V(i,t))},kf=i=>{let t=jr(i);if(!t||t.name!=="data"||t.contentSize<8||i.remainingLength<8)return null;let e=B(i);i.skip(4);let r=V(i,t.contentSize-8);switch(e){case 1:return be.decode(r);case 2:return new oi("utf-16be").decode(r);case 13:return new At(r,"image/jpeg");case 14:return new At(r,"image/png");case 27:return new At(r,"image/bmp");default:return r}};var on=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._nominalBitrate=null}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closingPromise)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(t){}close(){if(this._closingPromise)return;let t=this._connectedTrack;if(!t)throw new Error("Cannot call close without connecting the source to an output track.");if(t.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),!(t.output.state==="finalizing"||t.output.state==="finalized")&&await t.output._muxer.onTrackClose(t)})(),this._closingPromise.catch(()=>{})}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=this._flushAndClose(t)}},Ir=class extends on{constructor(t){if(super(),!ue.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${ue.join(", ")}.`);this._codec=t}},td=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},ri=class extends Ir{constructor(t){super(t)}add(t,e){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),td(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},ps=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.encoderConfig=null;this.encodersReclaimed=!1;this.muxer=null;this.lastMultipleOfKeyFrameInterval=null;this.emittedEncoderPackets=0;this.chunkTimestampsAreShiftedByDuration=!1;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.addMutex=new Ee;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new ni;this.customEncoderQueueSize=0;this.defaultEncodeOptions={};this.alphaEncoder=null;this.splitter=null;this.splitterCreationFailed=!1;this.alphaFrameQueue=[];this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e,r){let n=t,a=null;try{if(this.checkForEncoderError(),a=await this.addMutex.acquire(),this.closed)return;let s=this.encodingConfig,o=s.sizeChangeBehavior??"deny",c=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(c=!0,o==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${t.codedWidth}x${t.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.flip!==void 0||s.transform?.crop!==void 0||s.transform?.alpha==="discard"||s.transform?.force===!0||c&&o!=="passThrough"){let m=s.transform?.width,f=s.transform?.height,p=s.transform?.fit??"fill";o!=="deny"&&o!=="passThrough"&&(p=o),c&&o!=="passThrough"&&(b(this.outputWidth),b(this.outputHeight),m=this.outputWidth,f=this.outputHeight);let h=await t.transform({width:m,height:f,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,flip:s.transform?.flip,fit:p,alpha:s.transform?.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=h.displayWidth,this.outputHeight=h.displayHeight),e&&t.close(),t=h,e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let d=s.transform?.frameRate;if(d!==void 0){let m=t.timestamp+t.duration,f=_l(t.timestamp,d);if(this.frameRateLastSample!==null)if(f<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=m;return}else await this.padFrameRate(f,r);if(t===n){let p=t.clone();e&&t.close(),t=p,e=!0}t.setTimestamp(f),t.setDuration(1/d),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=f,this.frameRateLastEndTimestamp=m}await this.processAndEncode(t,r)}finally{a?.(),e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,n;if(r.transform?.process){let a=r.transform.process(t);if(R(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);let s=[];try{for(let o of a)o instanceof $e?s.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?s.push(new $e(o)):s.push(new $e(o,{timestamp:t.timestamp,duration:t.duration}))}catch(o){for(let c of s)c!==t&&c.close();for(let c of a)(c instanceof $e&&c!==t||typeof VideoFrame<"u"&&c instanceof VideoFrame)&&c.close();throw o}n=s}else n=[t];try{for(let a of n){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),b(this.encoderInitialized),this.closed)break;this.encodersReclaimed&&this.recreateWebCodecsEncoders();let s=this.encodingConfig.keyFrameInterval??2,o=Math.floor(a.timestamp/s),c={...this.defaultEncodeOptions,...a.encodeOptions,...e},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:s===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(a),this.customEncoder){this.customEncoderQueueSize++;let u=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).catch(m=>this.setError(m)).finally(()=>{this.customEncoderQueueSize--,u.close()});this.customEncoderQueueSize>=4&&await d}else{b(this.encoder);let u=a.toVideoFrame(),d=X(this.preciseTimings,u.timestamp,f=>f.microsecondTimestamp),m=d!==-1?this.preciseTimings[d]:null;if(m&&m.microsecondTimestamp===u.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(u,l)}finally{u.close()}}else{this.splitter||(this.splitter=new rd);let{colorFrame:p,alphaFrame:h}=await this.splitter.split(u);this.alphaFrameQueue.push(h);try{this.encoder.encode(p,l)}finally{p.close()}}else try{this.encoder.encode(u,l)}finally{u.close()}this.encoder.encodeQueueSize>=4&&await new Promise(f=>this.encoder.addEventListener("dequeue",f,{once:!0}))}await this.lastMuxerPromise}}finally{for(let a of n)a!==t&&a.close()}}async padFrameRate(t,e){let r=this.encodingConfig.transform.frameRate;b(this.frameRateLastSample);let n=Math.round((t-this.frameRateLastTimestamp)*r);for(let l=1;l<n;l++){var a=[];try{let u=yt(a,this.frameRateLastSample.clone());u.setTimestamp(this.frameRateLastTimestamp+l/r);u.setDuration(1/r);await this.processAndEncode(u,e)}catch(s){var o=s,c=!0}finally{kt(a,o,c)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let e=Ti(this.encodingConfig.quality,this.encodingConfig.bitrate);b(e!==void 0);let r=Xl({...this.encodingConfig,quality:e,width:t.codedWidth,height:t.codedHeight,squarePixelWidth:t.squarePixelWidth,squarePixelHeight:t.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),n=null,a;for(let o of r){let c=o.config;if(this.encodingConfig.onEncoderConfig?.(c),a=On.find(u=>u.supports(this.encodingConfig.codec,c)),a){n=o;break}if(typeof VideoEncoder>"u")continue;if(c.alpha="discard",this.encodingConfig.alpha==="keep"&&(c.latencyMode="quality"),(c.width%2===1||c.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${c.width}x${c.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(c)).supported){n=o;break}}catch{}}if(!n){if(typeof VideoEncoder>"u")throw new Error(xn("VideoEncoder"));let o=r[0].config,c=r.map(({config:l,quantizer:u})=>u!==null?`quantizer ${u}`:`${l.bitrate} bps`);throw new Error(`This specific encoder configuration (${o.codec}, ${c.join(" / ")}, ${o.width}x${o.height}, hardware acceleration: ${o.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}let s=n.config;n.quantizer!==null?this.defaultEncodeOptions=Yl(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=s.bitrate??null,a?(this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof ee))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");td(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(l=>{this.setError(l)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init()):(this.encoderConfig=s,this.encodingConfig.codec==="avc"&&Wt()&&(this.chunkTimestampsAreShiftedByDuration=await vg()),this.createWebCodecsEncoders()),b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(e=>this.setError(e))}createWebCodecsEncoders(){let t=this.encoderConfig;b(t);let e=[],r=[],n=0,a=0,s=(c,l)=>{if(Ud(c)){this.encodersReclaimed=!0;return}c.stack=l,this.setError(c)},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(c,l)=>{try{if(!this.alphaEncoder){this.addPacket(c,null,l);return}let u=this.alphaFrameQueue.shift();b(u!==void 0),u?(this.alphaEncoder.encode(u,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),a++,u.close(),e.push({chunk:c,meta:l})):a===0?this.addPacket(c,null,l):(r.push(n+a),e.push({chunk:c,meta:l}))}catch(u){this.setError(u)}},error:c=>s(c,o)}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){let c=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(l,u)=>{try{a--;let d=e.shift();for(b(d!==void 0),this.addPacket(d.chunk,l,d.meta),n++;r.length>0&&r[0]===n;){r.shift();let m=e.shift();b(m!==void 0),this.addPacket(m.chunk,null,m.meta)}}catch(d){this.setError(d)}},error:l=>s(l,c)}),this.alphaEncoder.configure(t)}}addPacket(t,e,r){let n={};if(e){let d=new Uint8Array(e.byteLength);e.copyTo(d),n.alpha=d}let a=ee.fromEncodedChunk(t,n),s=this.encoderConfig;if(b(s),r?.decoderConfig&&(r.decoderConfig.codec=Si({width:s.width,height:s.height,codec:this.encodingConfig.codec,codecDescription:r.decoderConfig.description?Q(r.decoderConfig.description):null,colorSpace:r.decoderConfig.colorSpace??null,avcType:s.codec.includes("avc1.")?1:s.codec.includes("avc3.")?3:null,avcCodecInfo:this.encodingConfig.codec==="avc"&&!r.decoderConfig.description?hr(a.data):null,hevcType:s.codec.includes("hev1.")?"hev1":s.codec.includes("hvc1.")?"hvc1":null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?br(a.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?_n(a.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?hi(a.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&r.decoderConfig.description&&Wt())){let d=gr(Q(r.decoderConfig.description)),m=d?.sequenceParameterSets[0];if(m&&m[0]===m[1]){b(d),m=m.subarray(1);let f=d.pictureParameterSets[0];f&&(f=f.subarray(1));let p=In({...d,sequenceParameterSets:[m],pictureParameterSets:f?[f]:[]});r.decoderConfig.description=p}}let o=t.timestamp;this.chunkTimestampsAreShiftedByDuration&&(o-=t.duration??0,a=a.clone({timestamp:o/1e6}));let c=X(this.preciseTimings,o,d=>d.microsecondTimestamp),l=c!==-1?this.preciseTimings[c]:null,u=null;this.emittedEncoderPackets===0&&a.type==="delta"&&r?.decoderConfig&&(u=gi(this.encodingConfig.codec,r.decoderConfig,a.data)),(l&&l.microsecondTimestamp===o||u!==null)&&(a=a.clone({timestamp:l?.timestampIsValid?l.timestamp:void 0,duration:l?.durationIsValid?l.duration:void 0,type:u??void 0})),td(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,r),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch(d=>{this.setError(d)}),this.emittedEncoderPackets++}recreateWebCodecsEncoders(){b(this.encoder),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.alphaFrameQueue.length=0,this.encodersReclaimed=!1,this.lastMultipleOfKeyFrameInterval=null,this.createWebCodecsEncoders()}async flushAndClose(t){await this.ensureEncoderPromise?.catch(()=>{});try{if(!t){this.checkForEncoderError();let e=await this.addMutex.acquire();try{if(this.frameRateLastSample){let r=this.encodingConfig.transform.frameRate,n=_l(this.frameRateLastEndTimestamp,r);await this.padFrameRate(n)}}finally{e()}}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(e=>this.setError(e)):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await Nr(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&(this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}t||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.addMutex.pending+(this.encoder?.encodeQueueSize??0)}checkForEncoderError(){if(this.errorSet)throw this.error}},up=null,vg=()=>up??=(async()=>{let i=null,t=new VideoEncoder({output:e=>{i??=e.timestamp},error:()=>{}});try{t.configure({codec:"avc1.64001f",width:1280,height:720});let e=new VideoFrame(new Uint8Array(1280*720*1.5),{format:"I420",codedWidth:1280,codedHeight:720,timestamp:0,duration:500});t.encode(e,{keyFrame:!0}),e.close(),await t.flush()}catch{return up=null,!1}finally{t.state!=="closed"&&t.close()}return i===500})(),rd=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){this.worker||(this.worker=Pn("color-alpha-splitter",_g),this.worker.addEventListener("message",n=>{let a=n.data,s=this.pendingRequests.get(a.id);s&&(this.pendingRequests.delete(a.id),"error"in a?s.reject(new Error(a.error)):s.resolve({colorFrame:a.colorFrame,alphaFrame:a.alphaFrame}))}),this.worker.addEventListener("error",n=>{let a=new Error(n.message||"Color/alpha splitter worker error.");for(let s of this.pendingRequests.values())s.reject(a);this.pendingRequests.clear()}));let e=this.nextRequestId++,r=te();return this.pendingRequests.set(e,r),this.worker.postMessage({id:e,sourceFrame:t},{transfer:[t]}),r.promise}close(){this.worker?.terminate(),this.worker=null;let t=new Error("Color/alpha splitter closed.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}},_g=()=>{let i=null,t=Promise.resolve();self.addEventListener("message",a=>{let{id:s,sourceFrame:o}=a.data;t=t.then(async()=>{try{let{colorFrame:c,alphaFrame:l}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:s,error:c.message})}finally{o.close()}})});let e=async a=>{let s=a.format;if(!s)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");let o=a.allocationSize();if((!i||i.byteLength!==o)&&(i=new Uint8Array(o)),await a.copyTo(i),s==="RGBA"||s==="BGRA")return r(i,s,a);if(s==="I420A"||s==="I420AP10"||s==="I420AP12"||s==="I422A"||s==="I422AP10"||s==="I422AP12"||s==="I444A"||s==="I444AP10"||s==="I444AP12")return n(i,s,a);throw new Error(`CPU color/alpha splitting does not support format '${s}'.`)},r=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=c*l,d=Math.ceil(c/2),m=Math.ceil(l/2),f=u+d*m*2,p=new Uint8Array(f);for(let k=0,T=3;k<u;k++,T+=4)p[k]=a[T];p.fill(128,u);let h=new VideoFrame(a,{format:s==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),y={format:"I420",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[p.buffer]},g=new VideoFrame(p,y);return{colorFrame:h,alphaFrame:g}},n=(a,s,o)=>{let c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=s.includes("P10"),d=s.includes("P12"),m=u||d?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(l/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=l):(f=c,p=l);let h=c*l,y=f*p,g=h*m,k=y*m,T=h*m,S=g+k*2,w=s.replace("A",""),A=Math.ceil(c/2),C=Math.ceil(l/2),E=A*C,I=E*m,x=T+2*I,P=new Uint8Array(x),v=S;P.set(a.subarray(v,v+T),0);let _=T,M=u?512:d?2048:128;m===1?P.fill(M,_):new Uint16Array(P.buffer,_,2*E).fill(M);let U=u?"I420P10":d?"I420P12":"I420",N=new VideoFrame(a.subarray(0,S),{format:w,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:o.colorSpace}),L={format:U,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[P.buffer]},G=new VideoFrame(P,L);return{colorFrame:N,alphaFrame:G}}},cn=class extends Ir{constructor(t){ko(t),super(t.codec),this._encoder=new ps(this,t)}add(t,e){if(!(t instanceof $e))throw new TypeError("videoSample must be a VideoSample.");return this._ensureValidAdd(),this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Bc=class extends Ir{constructor(t,e){if(!(typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ko(e),super(e.codec),this._encoder=new ps(this,e),this._canvas=t}add(t,e=0,r){if(!Number.isFinite(t))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(e)||e<0)throw new TypeError("duration must be a non-negative number.");this._ensureValidAdd();let n=new $e(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Oc=class extends Ir{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(ko(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(!Number.isFinite(n.frameRate)||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a finite positive number or null.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");r={...r,latencyMode:"realtime"};super(r.codec);this._abortController=null;this._workerTrackId=null;this._workerListener=null;this._promiseWithResolvers=te();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new ps(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||O._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let r=null,n=null,a=null,s=0,o=!1,c=null,l=0,u=()=>{if(b(e!==null),!this._lastVideoFrame)return;b(a!==null),b(n!==null);let f=performance.now();for(;f-a>1e3/e;){a+=1e3/e;let p=n+s/e,h=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*p,duration:1e6/e});m(h,f)}};e!==null&&(this._timerHandle=Gd(u,4));let d=f=>{if(this._closingPromise){f.close();return}if(e===null)m(f);else{let p=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=f):(n=f.timestamp/1e6,m(f.clone(),p),a=p,this._lastVideoFrame=f)}},m=(f,p=performance.now())=>{if(o||this._closingPromise||this._connectedTrack.output.state!=="started"){f.close();return}s++;let h=f.timestamp/1e6;if(this._paused){if(r!==null){if(c!==null&&this._options.timestampBase!=="unix"){let k=h-c;l-=k}c=h}f.close();return}if(r===null){r=h;let g,k=this._options.timestampBase??"synced-zero";if(k==="unix")g=Date.now()/1e3;else if(k==="zero")g=0;else{let T=this._connectedTrack.output;T._firstMediaStreamTimestamp===null?(T._firstMediaStreamTimestamp=p/1e3,g=0):g=p/1e3-T._firstMediaStreamTimestamp}l=g-r}if(c=h,this._encoder.getQueueSize()>=8){f.close();return}let y=new $e(f,{timestamp:h+l});this._encoder.add(y,!0).catch(g=>{o=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(g),this._workerTrackId!==null&&ed({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let f=new MediaStreamTrackProcessor({track:this._track}),p=new WritableStream({write:d});f.readable.pipeTo(p,{signal:this._abortController.signal}).catch(h=>{h instanceof DOMException&&h.name==="AbortError"||this._promiseWithResolvers.reject(h)})}else if(await Og()){this._workerTrackId=Mg++;let p=this._track.clone();ed({type:"videoTrack",trackId:this._workerTrackId,track:p},[p]),this._workerListener=h=>{let y=h.data;y.type==="videoFrame"&&y.trackId===this._workerTrackId?d(y.videoFrame):y.type==="error"&&y.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(y.error)},Nt.addEventListener("message",this._workerListener)}else if(e!==null){let p=document.createElement("video");p.style.position="fixed",p.style.left="-10000px",p.style.top="-10000px",p.style.width="1px",p.style.height="1px",p.style.opacity="0",p.style.pointerEvents="none",p.muted=!0,p.srcObject=new MediaStream([this._track]),document.body.appendChild(p),this._videoElement=p,p.addEventListener("loadeddata",()=>{if(o||!this._videoElement)return;let h=new VideoFrame(p,{timestamp:1e3*performance.now()});d(h),h.close()},{once:!0}),p.play().catch(h=>{o=!0,this._promiseWithResolvers.reject(h)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&Qd(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(b(this._workerListener),ed({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{let n=a=>{let s=a.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(b(this._workerListener),Nt.removeEventListener("message",this._workerListener),Nt.removeEventListener("message",n),r())};Nt.addEventListener("message",n)}))}finally{await this._encoder.flushAndClose(e)}}},vr=class extends on{constructor(t){if(super(),!pe.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${pe.join(", ")}.`);this._codec=t}},ii=class extends vr{constructor(t){super(t)}add(t,e){if(!(t instanceof ee))throw new TypeError("packet must be an EncodedPacket.");if(t.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(e!==void 0&&(!e||typeof e!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,t,e)}},fs=2048,hs=class{constructor(t,e){this.source=t;this.encodingConfig=e;this.ensureEncoderPromise=null;this.encoderInitialized=!1;this.encoder=null;this.muxer=null;this.lastNumberOfChannels=null;this.lastSampleRate=null;this.addMutex=new Ee;this.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.pcmMeta=null;this.pcmStartTimestamp=0;this.pcmEmittedFrames=0;this.pcmReadBuffer=new ArrayBuffer(0);this.pcmScratchView=null;this.pcmScratchFrames=0;this.customEncoder=null;this.customEncoderCallSerializer=new ni;this.customEncoderQueueSize=0;this.lastEndSampleIndex=null;this.resampler=null;this.error=null;this.errorSet=!1;this.lastMuxerPromise=Promise.resolve();this.closed=!1}setError(t){this.errorSet||(this.error=t,this.errorSet=!0)}async add(t,e){let r=null;try{if(this.checkForEncoderError(),r=await this.addMutex.acquire(),this.closed)return;if(this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(t.numberOfChannels!==this.lastNumberOfChannels||t.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${t.numberOfChannels} channels at ${t.sampleRate} Hz.`)}else this.lastNumberOfChannels=t.numberOfChannels,this.lastSampleRate=t.sampleRate;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new Ao({targetNumberOfChannels:n.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:n.transform.sampleRate??t.sampleRate,onSample:async s=>{await this.processAndEncode(s,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{r?.(),e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&Um(t.format)!==r.transform.sampleFormat){let n=zm(t,r.transform.sampleFormat);e&&t.close(),t=n,e=!0}if(r.transform?.process)try{let n=r.transform.process(t);if(R(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(let a of n)if(!(a instanceof Ce))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(let a of n)await this.encodeSample(a,a!==t)}finally{for(let a of n)a instanceof Ce&&a!==t&&a.close()}}finally{e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(t.numberOfFrames===0||(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(t),this.encoderInitialized||await this.ensureEncoderPromise),b(this.encoderInitialized),this.closed))return;{let r=Math.round(t.timestamp*t.sampleRate),n=Math.round((t.timestamp+t.duration)*t.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let a=r-this.lastEndSampleIndex;if(a>=64){let s=Ct(t.format)*t.numberOfChannels,o=new Uint8Array(s*Math.min(a,t.sampleRate));(t.format==="u8"||t.format==="u8-planar")&&o.fill(2**7);let c=a;for(;c>0;){let l=Math.min(c,t.sampleRate),u=new Ce({data:o.subarray(0,s*l),_doNotCopy:!0,format:t.format,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:l,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(u,!0),c-=l}}this.lastEndSampleIndex+=t.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(t),this.customEncoder){this.customEncoderQueueSize++;let r=t.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).catch(a=>this.setError(a)).finally(()=>{this.customEncoderQueueSize--,r.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(t,e);else{b(this.encoder),this.checkForEncoderError();let r=t.toAudioData();try{this.encoder.encode(r)}finally{r.close()}e&&t.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.lastMuxerPromise}}finally{e&&t.close()}}async doPcmEncoding(t,e){b(this.outputSampleSize),b(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:n,sampleRate:a,timestamp:s}=t;this.pcmMeta||(this.pcmMeta={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}},this.pcmStartTimestamp=s);let o=t.format==="s32"||t.format==="s32-planar",c=o?"s32":"f32",l=o?1/2147483648:1,u=t.allocationSize({planeIndex:0,format:c});this.pcmReadBuffer.byteLength<u&&(this.pcmReadBuffer=new ArrayBuffer(u));let d=o?new Int32Array(this.pcmReadBuffer,0,u/4):new Float32Array(this.pcmReadBuffer,0,u/4);t.copyTo(d,{planeIndex:0,format:c}),e&&t.close();let m=0;for(;m<n;){this.pcmScratchView??=new DataView(new ArrayBuffer(fs*r*this.outputSampleSize));let f=Math.min(fs-this.pcmScratchFrames,n-m),p=this.pcmScratchFrames*r,h=m*r;for(let y=0;y<f*r;y++)this.writeOutputValue(this.pcmScratchView,(p+y)*this.outputSampleSize,d[h+y]*l);this.pcmScratchFrames+=f,m+=f,this.pcmScratchFrames===fs&&await this.emitPcmScratchPacket()}}async emitPcmScratchPacket(){b(this.outputSampleSize),b(this.pcmScratchView),b(this.pcmMeta?.decoderConfig);let{numberOfChannels:t,sampleRate:e}=this.pcmMeta.decoderConfig,r=this.pcmScratchFrames*t*this.outputSampleSize,n=new ee(new Uint8Array(this.pcmScratchView.buffer,0,r),"key",this.pcmStartTimestamp+this.pcmEmittedFrames/e,this.pcmScratchFrames/e);this.pcmEmittedFrames+=this.pcmScratchFrames,this.pcmScratchView=null,this.pcmScratchFrames=0,this.encodingConfig.onEncodedPacket?.(n,this.pcmMeta),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,this.pcmMeta)}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let{format:e,numberOfChannels:r,sampleRate:n,timestamp:a}=t,s=Ti(this.encodingConfig.quality,this.encodingConfig.bitrate),o=$l({numberOfChannels:r,sampleRate:n,...this.encodingConfig,quality:s});this.encodingConfig.onEncoderConfig?.(o),this.source._nominalBitrate=o.bitrate??null;let c=Dn.find(l=>l.supports(this.encodingConfig.codec,o));if(c)this.customEncoder=new c,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(l,u)=>{if(!(l instanceof ee))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(u!==void 0&&(!u||typeof u!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(l,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u).catch(d=>{this.setError(d)})},this.customEncoder.onError=l=>{this.setError(l)},await this.customEncoder.init();else if(se.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(xn("AudioEncoder"));let l;try{l=(await AudioEncoder.isConfigSupported(o)).supported??!1}catch{l=!1}if(!l)throw new Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let d=await Rg(this.encodingConfig.codec,o.codec)/o.sampleRate,m=0,f=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(p,h)=>{try{if(h?.decoderConfig&&(mp(this.encodingConfig.codec,o,h.decoderConfig),this.encodingConfig.codec==="opus"&&h.decoderConfig.description)){let g=Q(h.decoderConfig.description);m=yr(g).preSkip/tt}let y=ee.fromEncodedChunk(p);y=y.clone({timestamp:Mt(y.timestamp-d-m,o.sampleRate),duration:p.duration!=null?Mt(y.duration,o.sampleRate):void 0}),Wt()&&(m=0),this.encodingConfig.onEncodedPacket?.(y,h),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,y,h).catch(g=>{this.setError(g)})}catch(y){this.setError(y)}},error:p=>{p.stack=f,this.setError(p)}}),this.encoder.configure(o),this.encodingConfig.codec==="aac"&&et()&&dp(this.encoder,e,r,n,a)}b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})(),this.ensureEncoderPromise.catch(e=>this.setError(e))}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Me(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,ne(Math.round(o*128)+128,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,ne(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=ne(Math.round(o*32768),-32768,32767);a.setUint8(s,Tm(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=ne(Math.round(o*32768),-32768,32767);a.setUint8(s,Sm(c))}:b(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,ne(Math.round(o*32768)+32768,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,ne(Math.round(o*32768),-32768,32767),n):b(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>zi(a,s,ne(Math.round(o*8388608)+8388608,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Rd(a,s,ne(Math.round(o*8388608),-8388608,8388607),n):b(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,ne(Math.round(o*2147483648)+2147483648,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,ne(Math.round(o*2147483648),-2147483648,2147483647),n):e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat32(s,o,n):b(!1);break;case 8:e==="float"?this.writeOutputValue=(a,s,o)=>a.setFloat64(s,o,n):b(!1);break;default:Z(r),b(!1)}}async flushAndClose(t){await this.ensureEncoderPromise?.catch(()=>{});try{if(!t){this.checkForEncoderError();let e=await this.addMutex.acquire();try{this.resampler&&await this.resampler.finalize(),this.pcmScratchFrames>0&&await this.emitPcmScratchPacket()}finally{e()}}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()).catch(e=>this.setError(e)):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}t||(await this.lastMuxerPromise,this.checkForEncoderError())}getQueueSize(){return this.customEncoder?this.addMutex.pending+this.customEncoderQueueSize:this.isPcmEncoder?this.addMutex.pending:this.addMutex.pending+(this.encoder?.encodeQueueSize??0)}checkForEncoderError(){if(this.errorSet)throw this.error}},Zu=new Map,Rg=(i,t)=>{let e=Zu.get(t);return e||(e=(async()=>{let a={codec:t,numberOfChannels:1,sampleRate:48e3,...So(i)},s=4096,o=2*s,c="f32-planar",l=[],u=null,d=null,m=-1/0,f=0,p=null,h=new AudioEncoder({output:(k,T)=>{T?.decoderConfig&&(u??=T.decoderConfig),l.push(k)},error:k=>{p??=k}}),y=new AudioDecoder({output:k=>{let T=new Float32Array(k.numberOfFrames);k.copyTo(T,{planeIndex:0,format:c}),k.close();for(let S=0;S<T.length;S++)T[S]>m&&(m=T[S],d=f+S);f+=T.length},error:k=>{p??=k}});try{h.configure(a),i==="aac"&&et()&&dp(h,c,1,48e3,0);let k=new Float32Array(1*o);k[s]=1;let T=new AudioData({data:k,format:c,numberOfChannels:1,numberOfFrames:o,sampleRate:48e3,timestamp:0});h.encode(T),T.close(),await h.flush(),b(u),mp(i,a,u),y.configure(u);for(let S of l)y.decode(S);await y.flush()}catch(k){throw p??k}finally{h.state!=="closed"&&h.close(),y.state!=="closed"&&y.close()}b(d!==null);let g=Math.round(l[0].timestamp/1e6*48e3);return d-s+g})(),Zu.set(t,e),e.catch(()=>Zu.delete(t)),e)},dp=(i,t,e,r,n)=>{let s=Ct(t),o=new Uint8Array(s*1024*e);(t==="u8"||t==="u8-planar")&&o.fill(2**7);let c=new AudioData({data:o,format:t,numberOfChannels:e,numberOfFrames:1024,sampleRate:r,timestamp:Math.round(1e6*(n-1024/r))});i.encode(c),c.close()},mp=(i,t,e)=>{if(i==="aac"){if(e.description&&e.description.byteLength>0&&Q(e.description)[0]===3){let{decoderSpecificInfo:n}=Do(xe.tempFromBytes(Q(e.description)));e.description=n??void 0}let r=!1;if(!e.description||e.description.byteLength<2?r=!0:r=xt(Q(e.description)).objectType===0,r){let n=Number(J(t.codec.split(".")));e.description=ui({objectType:n,outputNumberOfChannels:e.numberOfChannels,outputSampleRate:e.sampleRate,programConfigElement:null})}}},sa=class extends vr{constructor(t){To(t),super(t.codec),this._encoder=new hs(this,t)}add(t){if(!(t instanceof Ce))throw new TypeError("audioSample must be an AudioSample.");return this._ensureValidAdd(),this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Dc=class extends vr{constructor(e,r={}){if(To(e),typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.startTimestamp!==void 0&&!Number.isFinite(r.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(e.codec);this._addMutex=new Ee;this._encoder=new hs(this,e),this._accumulatedTime=r.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");this._ensureValidAdd();let r=Ce._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;let n=await this._addMutex.acquire();try{for(let a of r)await this._encoder.add(a,!0)}finally{n()}}async _flushAndClose(e){return e||(await this._addMutex.acquire())(),this._encoder.flushAndClose(e)}},Vc=class extends vr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(To(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.timestampBase!==void 0&&n.timestampBase!=="synced-zero"&&n.timestampBase!=="zero"&&n.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(r.codec);this._abortController=null;this._audioContext=null;this._scriptProcessorNode=null;this._promiseWithResolvers=te();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new hs(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||O._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,r=!1,n=null,a=0,s=o=>{if(r||this._closingPromise||this._connectedTrack.output.state!=="started"){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let u=c-n;a-=u}n=c}o.close();return}if(e===null){e=o.timestamp;let l,u=this._options.timestampBase??"synced-zero";if(u==="unix")l=Date.now()/1e3;else if(u==="zero")l=0;else{let d=this._connectedTrack.output;d._firstMediaStreamTimestamp===null?(d._firstMediaStreamTimestamp=performance.now()/1e3,l=0):l=performance.now()/1e3-d._firstMediaStreamTimestamp}a=l-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(l=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(l),this._audioContext&&this._audioContext.state!=="closed"&&this._audioContext.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:l=>s(new Ce(l))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(l=>{l instanceof DOMException&&l.name==="AbortError"||this._promiseWithResolvers.reject(l)})}else{let o=window.AudioContext||window.webkitAudioContext;this._audioContext=new o({sampleRate:this._track.getSettings().sampleRate});let c=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),c.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let l=0;this._scriptProcessorNode.onaudioprocess=u=>{let d=Ce._fromAudioBuffer(u.inputBuffer,l);l+=u.inputBuffer.duration;for(let m of d)s(m)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(b(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.close())}finally{await this._encoder.flushAndClose(e)}}},Fg=()=>{let i=(r,n)=>{n?self.postMessage(r,{transfer:n}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let t=new Map,e=new Map;self.addEventListener("message",r=>{let n=r.data;switch(n.type){case"videoTrack":{e.set(n.trackId,n.track);let a=new MediaStreamTrackProcessor({track:n.track}),s=new WritableStream({write:c=>{if(!e.has(n.trackId)){c.close();return}i({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;t.set(n.trackId,o),a.readable.pipeTo(s,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{let a=t.get(n.trackId);a&&(a.abort(),t.delete(n.trackId)),e.get(n.trackId)?.stop(),e.delete(n.trackId),i({type:"trackStopped",trackId:n.trackId})}break;default:Z(n)}})},Mg=0,Nt=null,Bg=()=>{Nt=Pn("media-stream-track-processor",Fg)},Ju=null,Og=async()=>Ju!==null?Ju:(Nt||Bg(),new Promise(i=>{b(Nt);let t=e=>{let r=e.data;r.type==="support"&&(Ju=r.supported,Nt.removeEventListener("message",t),i(r.supported))};Nt.addEventListener("message",t)})),ed=(i,t)=>{b(Nt),t?Nt.postMessage(i,t):Nt.postMessage(i)},ln=class extends on{constructor(t){if(super(),!qe.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${qe.join(", ")}.`);this._codec=t}},Uc=class extends ln{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new so({codec:e,output:(r,n)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,r,n).catch(a=>{this._setError(a)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}};var ue=["avc","hevc","vp9","av1","vp8","prores"],se=["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"],Jt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts","truehd"],pe=[...Jt,...se],qe=["webvtt"],Ji=["truehd"],ga=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],fp=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Gi=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],zc=[{maxPictureSize:147456,maxHSize:2048,maxVSize:1152,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxHSize:2816,maxVSize:1584,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxHSize:4352,maxVSize:2448,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxHSize:5504,maxVSize:3096,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxHSize:6144,maxVSize:3456,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:8912896,maxHSize:8192,maxVSize:4352,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxHSize:16384,maxVSize:8704,maxBitrate:8e8,tier:"H",level:19}],pp=".01.01.01.01.00",hp=".0.110.01.01.01.0",$r=["ap4x","ap4h","apch","apcn","apcs","apco"],Ha=["dtsc","dtsh","dtsl","dtse"],Dg=[{fourCc:"apco",bitrate:45e6,alpha:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],po=(i,t,e,r,n)=>{if(i==="avc"){let a=et(),s=a?66:100,o=Math.ceil(t/16)*Math.ceil(e/16),c=ga.find(f=>o<=f.maxMacroblocks&&r<=f.maxBitrate)??J(ga),l=c?c.level:0,u=s.toString(16).padStart(2,"0"),d=a?"40":"00",m=l.toString(16).padStart(2,"0");return`avc1.${u}${d}${m}`}else if(i==="hevc"){let a="",o="6",c=t*e,l=fp.find(d=>c<=d.maxPictureSize&&r<=d.maxBitrate)??J(fp);return`hvc1.${a}1.${o}.${l.tier}${l.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",s=t*e,o=Gi.find(l=>s<=l.maxPictureSize&&r<=l.maxBitrate)??J(Gi);return`vp09.${a}.${o.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let s=t*e,o=zc.find(u=>s<=u.maxPictureSize&&t<=u.maxHSize&&e<=u.maxVSize&&r<=u.maxBitrate)??J(zc);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(i==="prores"){let s=Math.pow(t*e/2073600,.95),o=Dg.filter(u=>u.alpha===n),c=o[0].fourCc,l=1/0;for(let{fourCc:u,bitrate:d}of o){let m=Math.abs(d*s-r);m<l&&(l=m,c=u)}return c}else Z(i)}throw new TypeError(`Unhandled codec '${String(i)}'.`)},gp=i=>{let t=i.split("."),e=Number(t[1]),r=Number(t[2]),n=Number(t[3]),a=t[4]?Number(t[4]):1;return[1,1,e,2,1,r,3,1,n,4,1,a]},Nc=i=>{let t=i.split("."),n=(1<<7)+1,a=Number(t[1]),s=t[2],o=Number(s.slice(0,-1)),c=(a<<5)+o,l=s.slice(-1)==="H"?1:0,u=Number(t[3]),d=u===8?0:1,m=u===12?1:0,f=t[4]?Number(t[4]):0,p=t[5]?Number(t[5][0]):1,h=t[5]?Number(t[5][1]):1,y=t[5]?Number(t[5][2]):0,g=(l<<7)+(d<<6)+(m<<5)+(f<<4)+(p<<3)+(h<<2)+y;return[n,c,g,0]},Si=i=>{let{codec:t,codecDescription:e,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:a,vp9CodecInfo:s,av1CodecInfo:o,proresFormat:c}=i;if(t==="avc"){if(b(i.avcType!==null),n){let l=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${i.avcType}.${ci(l)}`}if(!e||e.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${i.avcType}.${ci(e.subarray(1,4))}`}else if(t==="hevc"){b(i.hevcType!==null);let l,u,d,m,f,p;if(a)l=a.generalProfileSpace,u=a.generalProfileIdc,d=Pl(a.generalProfileCompatibilityFlags),m=a.generalTierFlag,f=a.generalLevelIdc,p=[...a.generalConstraintIndicatorFlags];else{if(!e||e.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let y=z(e),g=y.getUint8(1);l=g>>6&3,u=g&31,d=Pl(y.getUint32(2)),m=g>>5&1,f=y.getUint8(12),p=[];for(let k=0;k<6;k++)p.push(y.getUint8(6+k))}let h=`${i.hevcType}.`;for(h+=["","A","B","C"][l]+u,h+=".",h+=d.toString(16).toUpperCase(),h+=".",h+=m===0?"L":"H",h+=f;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(h+=".",h+=p.map(y=>y.toString(16).toUpperCase()).join(".")),h}else{if(t==="vp8")return"vp8";if(t==="vp9"){let l=i.width*i.height,u=J(Gi).level;for(let S of Gi)if(l<=S.maxPictureSize){u=S.level;break}if(!s)return`vp09.00.${u.toString().padStart(2,"0")}.08`;let d=s.profile.toString().padStart(2,"0"),m=(s.level===0?u:s.level).toString().padStart(2,"0"),f=s.bitDepth.toString().padStart(2,"0"),p=s.chromaSubsampling.toString().padStart(2,"0"),h=s.colourPrimaries.toString().padStart(2,"0"),y=s.transferCharacteristics.toString().padStart(2,"0"),g=s.matrixCoefficients.toString().padStart(2,"0"),k=s.videoFullRangeFlag.toString().padStart(2,"0"),T=`vp09.${d}.${m}.${f}.${p}`;return T+=`.${h}.${y}.${g}.${k}`,T.endsWith(pp)&&(T=T.slice(0,-pp.length)),T}else if(t==="av1"){if(!o){let S=i.width*i.height,w=J(zc).level;for(let A of zc)if(S<=A.maxPictureSize&&i.width<=A.maxHSize&&i.height<=A.maxVSize){w=A.level;break}return`av01.0.${w.toString().padStart(2,"0")}M.08`}let l=o.profile,u=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",m=o.bitDepth.toString().padStart(2,"0"),f=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),h,y,g,k;Qs(o)?(h=o.colourPrimaries,y=o.transferCharacteristics,g=o.matrixCoefficients,k=o.videoFullRangeFlag):(h=r?.primaries?_t[r.primaries]:1,y=r?.transfer?Rt[r.transfer]:1,g=r?.matrix?Ft[r.matrix]:1,k=r?.fullRange?1:0);let T=`av01.${l}.${u}${d}.${m}`;return T+=`.${f}.${p.toString().padStart(3,"0")}`,T+=`.${h.toString().padStart(2,"0")}`,T+=`.${y.toString().padStart(2,"0")}`,T+=`.${g.toString().padStart(2,"0")}`,T+=`.${k}`,T.endsWith(hp)&&(T=T.slice(0,-hp.length)),T}else{if(t==="prores")return c??"apch";t!==null&&Z(t)}}throw new TypeError(`Unhandled codec '${t}'.`)},Vo=i=>{switch(i.codec){case"avc":{let t=i.avcCodecInfo?.sequenceParameterSets[0];if(!t&&i.codecDescription&&(t=gr(i.codecDescription)?.sequenceParameterSets[0]),t){let e=Gt(t);if(e)return{primaries:Tt[e.colourPrimaries],transfer:wt[e.transferCharacteristics],matrix:St[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=i.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0];if(!t&&i.codecDescription&&(t=vn(i.codecDescription)?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0]),t){let e=Qi(t);if(e)return{primaries:Tt[e.colourPrimaries],transfer:wt[e.transferCharacteristics],matrix:St[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(i.vp9CodecInfo)return{primaries:Tt[i.vp9CodecInfo.colourPrimaries],transfer:wt[i.vp9CodecInfo.transferCharacteristics],matrix:St[i.vp9CodecInfo.matrixCoefficients],fullRange:!!i.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(i.av1CodecInfo)return{primaries:Tt[i.av1CodecInfo.colourPrimaries],transfer:wt[i.av1CodecInfo.transferCharacteristics],matrix:St[i.av1CodecInfo.matrixCoefficients],fullRange:!!i.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(i.proresCodecInfo)return{primaries:Tt[i.proresCodecInfo.colourPrimaries],transfer:wt[i.proresCodecInfo.transferCharacteristics],matrix:i.proresCodecInfo.matrixCoefficients===0?void 0:St[i.proresCodecInfo.matrixCoefficients],fullRange:i.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},ho=i=>{if(i==="aac")return"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(i==="ac3")return"ac-3";if(i==="eac3")return"ec-3";if(i==="dts")return"dtsc";if(i==="truehd")return"mlpa";if(se.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},Ln=i=>{let{codec:t,codecDescription:e,aacCodecInfo:r,dtsFormat:n}=i;if(t==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let a;return r.objectType!==null?a=r.objectType:a=xt(e).objectType,`mp4a.40.${a}`}}else{if(t==="mp3")return"mp3";if(t==="opus")return"opus";if(t==="vorbis")return"vorbis";if(t==="flac")return"flac";if(t==="ac3")return"ac-3";if(t==="eac3")return"ec-3";if(t==="dts")return n??"dtsc";if(t==="truehd")return"mlpa";if(t&&se.includes(t))return t}throw new TypeError(`Unhandled codec '${t}'.`)},Em=i=>{},Im=i=>{switch(i.codec){case"flac":{let t=Hi("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");return i.sampleRate>=1<<20||i.numberOfChannels>8?!1:(t[18]=i.sampleRate>>>12,t[19]=i.sampleRate>>>4,t[20]=(i.sampleRate&15)<<4|i.numberOfChannels-1<<1,t)}case"vorbis":{let t=Hi("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),e=z(t);return e.setUint8(15,i.numberOfChannels),e.setUint32(16,i.sampleRate,!0),t}default:return}},Mc=(i,t)=>{switch(i){case"aac":{if(!t.description)return 1024/t.sampleRate;let e=xt(Q(t.description));if(e.coreSampleRate===null)throw new Error("Invalid AAC sampling frequency index.");return e.frameLength/e.coreSampleRate}case"opus":return id;case"mp3":{let{sampleRate:e,numberOfChannels:r}=t,n=e>=32e3,a=n?1152:576,s=n?32e3:8e3,o=n?511:255,c=n?r===1?17:32:r===1?9:17,u=Math.floor(a/8*s/e)-4-c;return(1+Math.ceil(o/u))*a/e}case"vorbis":{b(t.description);let e=Q(t.description),r=1,n=2;for(;n>0;)e[r++]<255&&n--;return(1<<(e[r+28]>>4))/2/t.sampleRate}case"ac3":case"eac3":return 256/t.sampleRate;case"dts":return 512/t.sampleRate;case"flac":case"truehd":case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":case"pcm-u8":case"pcm-s8":case"ulaw":case"alaw":return 0;default:Z(i),b(!1)}},bp=(i,t)=>{switch(i){case"aac":return 1024;case"opus":return .02*t;case"mp3":return 576;case"vorbis":return 256;case"flac":return 1152;case"ac3":return 1536;case"eac3":return 256;case"dts":return 512;case"truehd":return 40;case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":case"pcm-u8":case"pcm-s8":case"ulaw":case"alaw":return fs;default:Z(i),b(!1)}},tt=48e3,id=.4,yp=/^pcm-([usf])(\d+)(be)?$/,Me=i=>{if(b(se.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let t=yp.exec(i);b(t);let e;t[1]==="u"?e="unsigned":t[1]==="s"?e="signed":e="float";let r=Number(t[2])/8,n=t[3]!=="be",a=i==="pcm-u8"?2**7:0;return{dataType:e,sampleSize:r,littleEndian:n,silentValue:a}},ct=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":$r.includes(i)?"prores":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"||i==="mp4a.40.34"?"mp3":i.startsWith("mp4a.40.")||i==="mp4a.67"?"aac":i==="opus"||i==="Opus"?"opus":i==="vorbis"?"vorbis":i==="flac"||i==="fLaC"?"flac":i==="ac-3"||i==="ac3"?"ac3":i==="ec-3"||i==="eac3"?"eac3":Ha.includes(i)?"dts":i==="mlpa"?"truehd":i==="ulaw"?"ulaw":i==="alaw"?"alaw":yp.test(i)?i:i==="webvtt"?"webvtt":null,Jm=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},So=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},Vg=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...$r],Ug=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,zg=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ng=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Lg=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,_r=(i,t)=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Vg.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectWidth)||i.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectHeight)||i.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectWidth!==void 0!=(i.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(i.decoderConfig.description!==void 0&&!Dr(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){let{colorSpace:e}=i.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(_t);if(e.primaries!=null&&!r.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let n=Object.keys(Rt);if(e.transfer!=null&&!n.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${n.join(", ")}.`);let a=Object.keys(Ft);if(e.matrix!=null&&!a.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!Ug.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!zg.test(i.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!Ng.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(i.decoderConfig.codec.startsWith("av01")){if(!Lg.test(i.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if($r.some(e=>i.decoderConfig.codec.startsWith(e))&&!$r.some(e=>i.decoderConfig.codec===e))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${$r.join(", ")}.`);if(t!==null&&ct(i.decoderConfig.codec)!==t)throw new TypeError(`Video chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Hg=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts","mlpa"],Re=(i,t)=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Hg.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!Dr(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.40.42","mp4a.67"].includes(i.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("ac-3")||i.decoderConfig.codec.startsWith("ac3")){if(i.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(i.decoderConfig.codec.startsWith("ec-3")||i.decoderConfig.codec.startsWith("eac3")){if(i.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(i.decoderConfig.codec.startsWith("dts")){if(!Ha.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${Ha.join(", ")}.`)}else if(i.decoderConfig.codec.startsWith("mlpa")){if(i.decoderConfig.codec!=="mlpa")throw new TypeError('Audio chunk metadata decoder configuration codec string for TrueHD must be "mlpa".')}else if((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!se.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${se.join(", ")}).`);if(t!==null&&ct(i.decoderConfig.codec)!==t)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${i.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},Lc=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};var Pe=class{constructor(t){this.mutex=new Ee;this.trackPacketOrderValidators=new WeakMap;this.output=t}async onTrackClose(t){}validateTimestamp(t,e,r){let n=this.trackPacketOrderValidators.get(t);n||(n=new oa,this.trackPacketOrderValidators.set(t,n));let a=r?"key":"delta";if(n.digest(e,a))return;if(n.maxTimestamp===null)throw new Error("First packet must be a key packet.");let s=a==="key"?n.maxTimestamp:n.maxTimestampBeforeLastKeyPacket;throw new Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${e}s, but largest timestamp is ${s}s.`)}},oa=class{constructor(){this.maxTimestamp=null;this.maxTimestampBeforeLastKeyPacket=null}check(t,e){if(this.maxTimestamp===null)return e==="key";let r=e==="key"?this.maxTimestamp:this.maxTimestampBeforeLastKeyPacket;return r===null||t>=r}digest(t,e){return this.check(t,e)?(e==="key"&&(this.maxTimestampBeforeLastKeyPacket=this.maxTimestamp),this.maxTimestamp=Math.max(this.maxTimestamp??-1/0,t),!0):!1}},Hc=class extends Pe{async start(){}async getMimeType(){return"application/x-black-hole"}async addEncodedVideoPacket(){}async addEncodedAudioPacket(){}async addSubtitleCue(){}async finalize(){}};var Wc=class extends Pe{constructor(e,r){super(e);this.header=null;this.headerBitstream=null;this.inputIsAdts=null;this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0),Hr(this.output._metadataTags)||new Ci(this.writer).writeId3V2Tag(this.output._metadataTags)}finally{e()}}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.validateTimestamp(e,r.timestamp,r.type==="key"),this.inputIsAdts===null){Re(n,e.source._codec);let s=n?.decoderConfig?.description;if(s){let o=xt(Q(s)),c=zs(o);this.header=c.header,this.headerBitstream=c.bitstream}this.inputIsAdts=!s}if(this.inputIsAdts){let s=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,s)}else{b(this.header);let s=r.data.byteLength+this.header.byteLength;Ns(this.headerBitstream,s);let o=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(r.data),this.format._options.onFrame){let c=new Uint8Array(s);c.set(this.header,0),c.set(r.data,this.header.byteLength),this.format._options.onFrame(c,o)}}await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.inputIsAdts===null)throw new Error("Cannot finalize an empty ADTS file: not a single packet was added.");e()}};var kp=new Uint8Array([102,76,97,67]),Wg=38,qg=34,qc=2**24-1,Kc=class extends Pe{constructor(e,r){super(e);this.metadataWritten=!1;this.frameCount=0;this.minimumBlockSize=1/0;this.maximumBlockSize=0;this.lastBlockSize=null;this.minimumFrameSize=1/0;this.maximumFrameSize=0;this.totalSamples=0;this.sampleRate=null;this.channels=null;this.bitsPerSample=null;this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(kp);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Re({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.applyDecoderConfig(r.metadata.decoderConfig))}finally{e()}}applyDecoderConfig(e){b(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;let r=new K(Q(e.description));r.skipBits(167),this.bitsPerSample=r.readBits(5)+1,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}writeHeader({bitsPerSample:e,minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:a,maximumFrameSize:s,sampleRate:o,channels:c,totalSamples:l}){b(this.writer.getPos()===4);let u=!Hr(this.output._metadataTags),d=new K(new Uint8Array(4));d.writeBits(1,+!u),d.writeBits(7,0),d.writeBits(24,qg),this.writer.write(d.bytes);let m=new K(new Uint8Array(18));m.writeBits(16,r),m.writeBits(16,n),m.writeBits(24,a),m.writeBits(24,s),m.writeBits(20,o),m.writeBits(3,c-1),m.writeBits(5,e-1),m.writeBits(36,l<2**36?l:0),this.writer.write(m.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=Y.encode(e.mimeType),n=Y.encode(e.description??""),a=32+r.length+n.length+e.data.length;if(a>qc)throw new Error(`Picture is too big for FLAC: its metadata block would take ${a} bytes, but FLAC metadata blocks can take at most ${qc} bytes.`);let s=new Uint8Array(a),o=0,c=z(s);c.setUint32(o,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),o+=4,c.setUint32(o,r.length),o+=4,s.set(r,o),o+=r.length,c.setUint32(o,n.length),o+=4,s.set(n,o),o+=n.length,o+=16,c.setUint32(o,e.data.length),o+=4,s.set(e.data,o),o+=e.data.length,b(o===a);let l=new K(new Uint8Array(4));l.writeBits(1,0),l.writeBits(7,6),l.writeBits(24,a),this.writer.write(l.bytes),this.writer.write(s)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(Wg+kp.byteLength),Hr(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let a of e)this.writePictureBlock(a);let r=ka(new Uint8Array(0),this.output._metadataTags,!1);if(r.length>qc)throw new Error(`Metadata tags are too big for FLAC: their Vorbis comment block would take ${r.length} bytes, but FLAC metadata blocks can take at most ${qc} bytes.`);let n=new K(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,4),n.writeBits(24,r.length),this.writer.write(n.bytes),this.writer.write(r),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),this.sampleRate===null&&(Re(n,e.source._codec),b(n),b(n.decoderConfig),this.applyDecoderConfig(n.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=xe.tempFromBytes(r.data);s.skip(2);let o=V(s,2),c=new K(o),l=ec(c.readBits(4));if(l===null)throw new Error("Invalid FLAC frame: Invalid block size.");tc(s);let u=rc(s,l);this.format._options.appendOnly||(this.lastBlockSize!==null&&(this.minimumBlockSize=Math.min(this.minimumBlockSize,this.lastBlockSize)),this.frameCount++,this.maximumBlockSize=Math.max(this.maximumBlockSize,u),this.lastBlockSize=u,this.minimumFrameSize=Math.min(this.minimumFrameSize,r.data.length),this.maximumFrameSize=Math.max(this.maximumFrameSize,r.data.length),this.totalSamples+=u);let d=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,d),await this.writer.flush()}finally{a()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.sampleRate===null)throw new Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let r=this.minimumBlockSize,n=this.maximumBlockSize,a=this.minimumFrameSize,s=this.maximumFrameSize;this.frameCount===0?(r=16,n=65535,a=0,s=0):this.frameCount===1&&(n=Math.max(n,16),r=n),b(this.channels!==null),b(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:r,maximumBlockSize:n,minimumFrameSize:a,maximumFrameSize:s,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:this.totalSamples})}e()}};var un=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.offsets=new WeakMap}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,Math.floor(t/2**32),!1),this.helperView.setUint32(4,t,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(t){for(let e=0;e<t.length;e++)this.helperView.setUint8(e%8,t.charCodeAt(e)),e%8===7&&this.writer.write(this.helper);t.length%8!==0&&this.writer.write(this.helper.subarray(0,t.length%8))}writeBox(t){if(this.offsets.set(t,this.writer.getPos()),t.contents&&!t.children)this.writeBoxHeader(t,t.size??t.contents.byteLength+8),this.writer.write(t.contents);else{let e=this.writer.getPos();if(this.writeBoxHeader(t,0),t.contents&&this.writer.write(t.contents),t.children)for(let a of t.children)a&&this.writeBox(a);let r=this.writer.getPos(),n=t.size??r-e;this.writer.seek(e),this.writeBoxHeader(t,n),this.writer.seek(r)}}writeBoxHeader(t,e){this.writeU32(t.largeSize?1:e),this.writeAscii(t.type),t.largeSize&&this.writeU64(e)}measureBoxHeader(t){return 8+(t.largeSize?8:0)}patchBox(t){let e=this.offsets.get(t);b(e!==void 0);let r=this.writer.getPos();this.writer.seek(e),this.writeBox(t),this.writer.seek(r)}measureBox(t){if(t.contents&&!t.children)return this.measureBoxHeader(t)+t.contents.byteLength;{let e=this.measureBoxHeader(t);if(t.contents&&(e+=t.contents.byteLength),t.children)for(let r of t.children)r&&(e+=this.measureBox(r));return e}}},j=new Uint8Array(8),vt=new DataView(j.buffer),we=i=>[(i%256+256)%256],W=i=>(vt.setUint16(0,i,!1),[j[0],j[1]]),gs=i=>(vt.setInt16(0,i,!1),[j[0],j[1]]),Ap=i=>(vt.setUint32(0,i,!1),[j[1],j[2],j[3]]),F=i=>(vt.setUint32(0,i,!1),[j[0],j[1],j[2],j[3]]),tr=i=>(vt.setInt32(0,i,!1),[j[0],j[1],j[2],j[3]]),rr=i=>(vt.setUint32(0,Math.floor(i/2**32),!1),vt.setUint32(4,i,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),Tp=i=>(vt.setInt32(0,Math.floor(i/2**32),!1),vt.setUint32(4,i,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),Kg=i=>(vt.setFloat64(0,i,!1),[j[0],j[1],j[2],j[3],j[4],j[5],j[6],j[7]]),xp=i=>(vt.setInt16(0,2**8*i,!1),[j[0],j[1]]),Lt=i=>(vt.setInt32(0,2**16*i,!1),[j[0],j[1],j[2],j[3]]),nd=i=>(vt.setInt32(0,2**30*i,!1),[j[0],j[1],j[2],j[3]]),ad=(i,t)=>{let e=[],r=i;do{let n=r&127;r>>=7,e.length>0&&(n|=128),e.push(n),t!==void 0&&t--}while(r>0||t);return e.reverse()},oe=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,n)=>i.charCodeAt(n));return t&&e.push(0),e},Cp=i=>[Lt(i[0]),Lt(i[1]),nd(i[2]),Lt(i[3]),Lt(i[4]),nd(i[5]),Lt(i[6]),Lt(i[7]),nd(i[8])],q=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),re=(i,t,e,r,n)=>q(i,[we(t),Ap(e),r??[]],n),Pp=i=>i.isQuickTime?q("ftyp",[oe("qt "),F(512),oe("qt ")]):i.fragmented?i.cmaf?q("ftyp",[oe("iso5"),F(512),oe("iso5"),oe("iso6"),oe("mp41"),oe("cmfc"),oe("dash")]):q("ftyp",[oe("iso5"),F(512),oe("iso5"),oe("iso6"),oe("mp41")]):q("ftyp",[oe("isom"),F(512),oe("isom"),i.holdsAvc?oe("avc1"):[],oe("mp41")]),od=()=>q("styp",[oe("iso5"),F(0),oe("iso5"),oe("iso6"),oe("mp41"),oe("cmfc"),oe("dash")]),cd=(i,t)=>{b(t<2**31);let e=Math.max(0,i.minWrittenTimestamp),r=Math.max(0,i.maxWrittenEndTimestamp-e);Number.isFinite(r)||(r=0);let n=ce(r,mt);if(n>=2**32)throw new Error("CMAF segments must be shorter than 20.712612 hours.");return re("sidx",1,0,[F(1),F(mt),rr(ce(e,mt)),rr(0),W(0),W(1),F(t),F(n),F(0)])},bs=i=>({type:"mdat",largeSize:i}),Ep=i=>({type:"free",size:i}),ca=i=>q("moov",void 0,[Gg(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>Qg(t,i.creationTime)),i.isFragmented?Mb(i.trackDatas):null,Hb(i)]),Gg=(i,t)=>{let e=Math.max(0,...t.map(s=>Math.max(0,ce(dn(s),mt)+ce(s.startTimestampOffset??0,mt)))),r=Math.max(0,...t.map(s=>s.track.id))+1,n=!or(i)||!or(e),a=n?rr:F;return re("mvhd",+n,0,[a(i),a(i),F(mt),a(e),Lt(1),xp(1),Array(10).fill(0),Cp(si),Array(24).fill(0),F(r)])},Qg=(i,t)=>{let e=zp(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset!==0;return q("trak",void 0,[jg(i,t),r?Xg(i):null,$g(i,t),e.name!==void 0?q("udta",void 0,[q("name",[...Y.encode(e.name)])]):null])},jg=(i,t)=>{let e=Math.max(0,ce(dn(i),mt)+ce(i.startTimestampOffset??0,mt)),r=!or(t)||!or(e),n=r?rr:F,a;if(i.type==="video"&&i.track.metadata.transformationMatrix)a=i.track.metadata.transformationMatrix;else if(i.type==="video"){let{rotation:c,flip:l}=i.track.metadata,u=sr(Tn(c??0),vs(l?-1:1,1));a=Is(u,i.info.width,i.info.height)}else a=si;let s=2;i.track.metadata.disposition?.default!==!1&&(s|=1);let o=i.type==="video"?0:i.type==="audio"?1:i.type==="subtitle"?2:Z(i);return re("tkhd",+r,s,[n(t),n(t),F(i.track.id),F(0),n(e),Array(8).fill(0),W(0),W(o),xp(i.type==="audio"?1:0),W(0),Cp(a),Lt(i.type==="video"?i.info.width:0),Lt(i.type==="video"?i.info.height:0)])},Xg=i=>{let t=i.startTimestampOffset;if(b(t!==null),t>0){let e=ce(t,mt),r=ce(dn(i),mt),n=!or(e)||!or(r),a=n?rr:F,s=n?Tp:tr;return q("edts",void 0,[re("elst",n?1:0,0,[F(2),a(e),s(-1),Lt(1),a(r),s(0),Lt(1)])])}else{let e=ce(-t,i.timescale),r=Math.max(0,ce(dn(i),mt)+ce(t,mt)),n=!xl(e)||!or(r),a=n?rr:F,s=n?Tp:tr;return q("edts",void 0,[re("elst",n?1:0,0,[F(1),a(r),s(e),Lt(1)])])}},$g=(i,t)=>q("mdia",void 0,[Yg(i,t),ld(!0,Zg[i.type],Jg[i.type],void 0,i.muxer.isQuickTime),eb(i)]),Yg=(i,t)=>{let e=ce(dn(i),i.timescale),r=!or(t)||!or(e),n=r?rr:F;return re("mdhd",+r,0,[n(t),n(t),F(i.timescale),n(e),W(Up(i.track.metadata.languageCode??le)),W(0)])},Zg={video:"vide",audio:"soun",subtitle:"text"},Jg={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ld=(i,t,e,r="\0\0\0\0",n=!1)=>re("hdlr",0,0,[i?oe("mhlr"):F(0),oe(t),oe(r),F(0),F(0),n?[we(e.length),oe(e)]:oe(e,!0)]),eb=i=>q("minf",void 0,[nb[i.type](),ab(),cb(i)]),tb=()=>re("vmhd",0,1,[W(0),W(0),W(0),W(0)]),rb=()=>re("smhd",0,0,[W(0),W(0)]),ib=()=>re("nmhd",0,0),nb={video:tb,audio:rb,subtitle:ib},ab=()=>q("dinf",void 0,[sb()]),sb=()=>re("dref",0,0,[F(1)],[ob()]),ob=()=>re("url ",0,1),cb=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return q("stbl",void 0,[lb(i),Pb(i),t?Rb(i):null,t?Fb(i):null,Ib(i),vb(i),_b(i),Eb(i),..._p(i.samples,!1)])},lb=i=>{let t;if(i.type==="video")t=ub(Qb(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){let e=Vp(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime);b(e),t=gb(e,i)}else i.type==="subtitle"&&(t=xb($b[i.track.source._codec],i));return b(t),re("stsd",0,0,[F(1)],[t])},ub=(i,t)=>q(i,[Array(6).fill(0),W(1),W(0),W(0),Array(12).fill(0),W(t.info.width),W(t.info.height),F(4718592),F(4718592),F(0),W(1),we(Kr.length),oe(Kr),Array(31-Kr.length).fill(0),W(t.info.hasAlphaChannel?32:24),gs(65535)],[jb[t.track.source._codec]?.(t)??null,db(t),Rs(t.info.decoderConfig.colorSpace)?null:mb(t),ud(t)]),ud=i=>i.avgBitrate===0&&i.maxBitrate===0?null:q("btrt",[F(0),F(i.maxBitrate),F(i.avgBitrate)]),db=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:q("pasp",[F(i.info.pixelAspectRatio.num),F(i.info.pixelAspectRatio.den)]),mb=i=>{let t=i.info.decoderConfig.colorSpace;return q("colr",[oe(i.muxer.isQuickTime?"nclc":"nclx"),W(t?.primaries!=null?_t[t.primaries]:2),W(t?.transfer!=null?Rt[t.transfer]:2),W(t?.matrix!=null?Ft[t.matrix]:2),i.muxer.isQuickTime?[]:we((t?.fullRange?1:0)<<7)])},fb=i=>i.info.decoderConfig&&q("avcC",[...Q(i.info.decoderConfig.description)]),pb=i=>i.info.decoderConfig&&q("hvcC",[...Q(i.info.decoderConfig.description)]),wp=i=>{if(!i.info.decoderConfig)return null;let t=i.info.decoderConfig,e=t.codec.split("."),r=Number(e[1]),n=Number(e[2]),a=e[3]?Number(e[3]):8,s=e[4]?Number(e[4]):1,o=e[8]?Number(e[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(s<<1)+o,l=e[5]?Number(e[5]):t.colorSpace?.primaries?_t[t.colorSpace.primaries]:1,u=e[6]?Number(e[6]):t.colorSpace?.transfer?Rt[t.colorSpace.transfer]:1,d=e[7]?Number(e[7]):t.colorSpace?.matrix?Ft[t.colorSpace.matrix]:1;return re("vpcC",1,0,[we(r),we(n),we(c),we(l),we(u),we(d),W(0)])},hb=i=>q("av1C",Nc(i.info.decoderConfig.codec)),gb=(i,t)=>{let e=0,r,n=16,a=t.info.sampleRate,s=Xb(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,o=se.includes(t.track.source._codec);if(o){let c=t.track.source._codec,{sampleSize:l}=Me(c);n=8*l}else if(t.track.source._codec==="flac"){let c=t.info.decoderConfig?.description;b(c);let l=new K(Q(c));for(l.skipBits(167),n=l.readBits(5)+1;a>=2**16;)a=Math.floor(a/2)}if(t.muxer.isQuickTime&&t.track.source._codec!=="truehd"&&(e=t.info.sampleRate<2**16&&t.info.numberOfChannels<=2?1:2),e===0)r=[Array(6).fill(0),W(1),W(e),W(0),F(0),W(t.info.numberOfChannels),W(n),W(0),W(0),t.track.source._codec==="truehd"?F(t.info.sampleRate):[W(a<2**16?a:0),W(0)]];else if(e===1){let c=o?0:-2;r=[Array(6).fill(0),W(1),W(e),W(0),F(0),W(t.info.numberOfChannels),W(Math.min(n,16)),gs(c),W(0),W(t.info.sampleRate<2**16?t.info.sampleRate:0),W(0),o?[F(1),F(n/8),F(t.info.numberOfChannels*n/8)]:[F(0),F(0),F(0)],F(2)]}else if(e===2){let c=0;if(o){let{dataType:l,littleEndian:u}=Me(t.track.source._codec);l!=="ulaw"&&l!=="alaw"&&(i="lpcm",s=null,c=(l==="float"?1:0)|(u?0:2)|(l==="signed"?4:0)|8)}r=[Array(6).fill(0),W(1),W(e),W(0),F(0),W(3),W(16),gs(-2),W(0),F(65536),F(72),Kg(t.info.sampleRate),F(t.info.numberOfChannels),F(2130706432),o?[F(n),F(c),F(t.info.numberOfChannels*n/8),F(1)]:[F(0),F(0),F(0),F(0)]]}else Z(e),b(!1);return q(i,r,[(i==="ipcm"||i==="fpcm")&&t.info.sampleRate>=2**16?bb(t):null,s,ud(t)])},bb=i=>re("srat",0,0,[F(i.info.sampleRate)]),sd=i=>{let t;switch(i.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let e=[...we(t),...we(21),...Ap(0),...F(i.maxBitrate),...F(i.avgBitrate)];if(i.info.decoderConfig.description){let r=Q(i.info.decoderConfig.description);e=[...e,...we(5),...ad(r.byteLength),...r]}return e=[...W(1),...we(0),...we(4),...ad(e.length),...e,...we(6),...we(1),...we(2)],e=[...we(3),...ad(e.length),...e],re("esds",0,0,e)},Rr=i=>q("wave",void 0,[yb(i),i.track.source._codec==="ac3"?Ip(i):i.track.source._codec==="eac3"?vp(i):kb(i),q("\0\0\0\0")]),yb=i=>q("frma",[oe(Vp(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime))]),kb=i=>{let{littleEndian:t}=Me(i.track.source._codec);return q("enda",[W(+t)])},Tb=i=>{let t=i.info.numberOfChannels,e=312,r=i.info.sampleRate,n=0,a=0,s=new Uint8Array(0),o=i.info.decoderConfig?.description;if(o){b(o.byteLength>=18);let c=Q(o),l=yr(c);t=l.outputChannelCount,e=l.preSkip,r=l.inputSampleRate,n=l.outputGain,a=l.channelMappingFamily,l.channelMappingTable&&(s=l.channelMappingTable)}return q("dOps",[we(0),we(t),W(e),F(r),gs(n),we(a),...s])},wb=i=>{let t=i.info.decoderConfig?.description;b(t);let e=Q(t);return re("dfLa",0,0,[...e.subarray(4)])},Fr=i=>{let{littleEndian:t,sampleSize:e}=Me(i.track.source._codec),r=+t;return re("pcmC",0,0,[we(r),we(8*e)])},Ip=i=>{b(i.info.primingPacket);let t=Ys(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");let e=new Uint8Array(3),r=new K(e);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),q("dac3",[...e])},vp=i=>{b(i.info.primingPacket);let t=Js(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let e=16;for(let s of t.substreams)e+=23,s.numDepSub>0?e+=9:e+=1;let r=Math.ceil(e/8),n=new Uint8Array(r),a=new K(n);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let s of t.substreams)a.writeBits(2,s.fscod),a.writeBits(5,s.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,s.bsmod),a.writeBits(3,s.acmod),a.writeBits(1,s.lfeon),a.writeBits(3,0),a.writeBits(4,s.numDepSub),s.numDepSub>0?a.writeBits(9,s.chanLoc):a.writeBits(1,0);return q("dec3",[...n])},Sb=i=>{b(i.info.primingPacket);let t=xa(i.info.primingPacket.data);if(!t)throw new Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return q("ddts",[...km(t)])},Ab=i=>{b(i.info.primingPacket);let t=i.info.primingPacket.data;if(Rn("truehd",t)!=="key")throw new Error("Couldn't extract TrueHD stream info from the audio packet. Ensure the first packet is an access unit carrying a major sync.");let e=z(t),r=e.getUint32(8),n=e.getUint16(18)&32767;return q("dmlp",[F(r),W(n<<1),F(0)])},xb=(i,t)=>q(i,[Array(6).fill(0),W(1)],[Yb[t.track.source._codec](t),ud(t)]),Cb=i=>q("vttC",[...Y.encode(i.info.config.description)]);var Pb=i=>re("stts",0,0,[F(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[F(t.sampleCount),F(t.sampleDelta)])]),Eb=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return re("stss",0,0,[F(t.length),t.map(([e])=>F(e+1))])},Ib=i=>re("stsc",0,0,[F(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[F(t.firstChunk),F(t.samplesPerChunk),F(1)])]),vb=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:t}=Me(i.track.source._codec);return re("stsz",0,0,[F(t*i.info.numberOfChannels),F(i.samples.reduce((e,r)=>e+ce(r.duration,i.timescale),0))])}return re("stsz",0,0,[F(0),F(i.samples.length),i.samples.map(t=>F(t.size))])},_b=i=>i.finalizedChunks.length>0&&J(i.finalizedChunks).offset>=2**32?re("co64",0,0,[F(i.finalizedChunks.length),i.finalizedChunks.map(t=>rr(t.offset))]):re("stco",0,0,[F(i.finalizedChunks.length),i.finalizedChunks.map(t=>F(t.offset))]),Rb=i=>re("ctts",1,0,[F(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[F(t.sampleCount),tr(t.sampleCompositionTimeOffset)])]),Fb=i=>{if(b(i.compositionTimeOffsetTable.length>0),i.samples.length===0)return null;let t=1/0,e=-1/0,r=1/0,n=-1/0;for(let s=0;s<i.compositionTimeOffsetTable.length;s++){let o=i.compositionTimeOffsetTable[s];t=Math.min(t,o.sampleCompositionTimeOffset),e=Math.max(e,o.sampleCompositionTimeOffset)}for(let s=0;s<i.samples.length;s++){let o=i.samples[s];r=Math.min(r,ce(o.timestamp,i.timescale)),n=Math.max(n,ce(o.timestamp+o.duration,i.timescale))}let a=Math.max(-t,0);return n>=2**31?null:re("cslg",0,0,[tr(a),tr(t),tr(e),tr(r),tr(n)])},_p=(i,t)=>{let e=[];for(let a of i)if(e.length===0)e.push({sampleCount:1,prerollSamples:a.prerollSamples});else{let s=e[e.length-1];s.prerollSamples===a.prerollSamples?s.sampleCount++:e.push({sampleCount:1,prerollSamples:a.prerollSamples})}let r=e.filter(a=>a.prerollSamples!==0);if(r.length===0)return[];let n=t?65537:1;return[re("sgpd",1,0,[oe("roll"),F(2),F(r.length),...r.map(a=>gs(a.prerollSamples))]),re("sbgp",0,0,[oe("roll"),F(e.length),...e.map(a=>[F(a.sampleCount),F(a.prerollSamples!==0?n++:0)])])]},Mb=i=>q("mvex",void 0,i.map(Bb)),Bb=i=>re("trex",0,0,[F(i.track.id),F(1),F(0),F(0),F(0)]),dd=(i,t)=>q("moof",void 0,[Ob(i),...t.map(Db)]),Ob=i=>re("mfhd",0,0,[F(i)]),Rp=i=>{let t=0,e=0,r=0,n=0,a=i.type==="delta";return e|=+a,a?t|=1:t|=2,t<<24|e<<16|r<<8|n},Db=i=>q("traf",void 0,[Vb(i),Ub(i),zb(i),..._p(i.currentChunk.samples,!0)]),Vb=i=>{b(i.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let e=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:e.timescaleUnitsToNextSample,size:e.size,flags:Rp(e)};return re("tfhd",0,t,[F(i.track.id),F(r.duration),F(r.size),F(r.flags)])},Ub=i=>(b(i.currentChunk),re("tfdt",1,0,[rr(ce(i.currentChunk.samples[0].decodeTimestamp,i.timescale))])),zb=i=>{b(i.currentChunk);let t=i.currentChunk.offset-i.currentChunk.moofOffset||0;b(xl(t));let e=i.currentChunk.samples.map(y=>y.timescaleUnitsToNextSample),r=i.currentChunk.samples.map(y=>y.size),n=i.currentChunk.samples.map(Rp),a=i.currentChunk.samples.map(y=>ce(y.timestamp-y.decodeTimestamp,i.timescale)),s=new Set(e),o=new Set(r),c=new Set(n),l=new Set(a),u=c.size===2&&n.lastIndexOf(n[0])===0,d=s.size>1,m=o.size>1,f=!u&&c.size>1,p=l.size>1||[...l].some(y=>y!==0),h=0;return h|=1,h|=4*+u,h|=256*+d,h|=512*+m,h|=1024*+f,h|=2048*+p,re("trun",1,h,[F(i.currentChunk.samples.length),tr(t),u?F(n[0]):[],i.currentChunk.samples.map((y,g)=>[d?F(e[g]):[],m?F(r[g]):[],f?F(n[g]):[],p?tr(a[g]):[]])])},Fp=i=>q("mfra",void 0,[...i.map(Nb),Lb()]),Nb=i=>re("tfra",1,0,[F(i.track.id),F(63),F(i.tfraEntries.length),i.tfraEntries.map(e=>[rr(ce(e.timestamp,i.timescale)),rr(e.moofOffset),F(e.trafIndex+1),F(1),F(e.sampleIndex+1)])]),Lb=()=>re("mfro",0,0,[F(0)]),Mp=()=>q("vtte"),Bp=(i,t,e,r,n)=>q("vttc",void 0,[n!==null?q("vsid",[tr(n)]):null,e!==null?q("iden",[...Y.encode(e)]):null,t!==null?q("ctim",[...Y.encode(co(t))]):null,r!==null?q("sttg",[...Y.encode(r)]):null,q("payl",[...Y.encode(i)])]),Op=i=>q("vtta",[...Y.encode(i)]),Hb=i=>{let t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){let n=Kb(r);n&&t.push(n)}else if(e==="mdta"){let n=Gb(r);n&&t.push(n)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&Wb(t,i.output._metadataTags);return t.length===0?null:q("udta",void 0,t)},Wb=(i,t)=>{for(let{key:e,value:r}of qt(t))switch(e){case"title":i.push(Mr("\xA9nam",r));break;case"description":i.push(Mr("\xA9des",r));break;case"artist":i.push(Mr("\xA9ART",r));break;case"album":i.push(Mr("\xA9alb",r));break;case"albumArtist":i.push(Mr("albr",r));break;case"genre":i.push(Mr("\xA9gen",r));break;case"date":i.push(Mr("\xA9day",r.toISOString().slice(0,10)));break;case"comment":i.push(Mr("\xA9cmt",r));break;case"lyrics":i.push(Mr("\xA9lyr",r));break;case"raw":break;case"creationTime":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:Z(e)}if(t.raw)for(let e in t.raw){let r=t.raw[e];r==null||e.length!==4||i.some(n=>n.type===e)||(typeof r=="string"?i.push(Mr(e,r)):r instanceof Uint8Array&&i.push(q(e,Array.from(r))))}},Mr=(i,t)=>{let e=Y.encode(t);return q(i,[W(e.length),W(Up("und")),Array.from(e)])},Sp={"image/jpeg":13,"image/png":14,"image/bmp":27},qb=new Set(["HMMT","loci","chpl"]),Dp=(i,t)=>{let e=[];for(let{key:r,value:n}of qt(i))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:er(n)});break;case"description":e.push({key:t?"description":"\xA9des",value:er(n)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:er(n)});break;case"album":e.push({key:t?"album":"\xA9alb",value:er(n)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:er(n)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:er(n)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:er(n)});break;case"beatsPerMinute":t||e.push({key:"tmpo",value:q("data",[F(21),F(0),W(n)])});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:er(n)});break;case"date":e.push({key:t?"date":"\xA9day",value:er(n.toISOString().slice(0,10))});break;case"images":for(let a of n)a.kind==="coverFront"&&e.push({key:"covr",value:q("data",[F(Sp[a.mimeType]??0),F(0),Array.from(a.data)])});break;case"trackNumber":if(t){let a=i.tracksTotal!==void 0?`${n}/${i.tracksTotal}`:n.toString();e.push({key:"track",value:er(a)})}else e.push({key:"trkn",value:q("data",[F(0),F(0),W(0),W(n),W(i.tracksTotal??0),W(0)])});break;case"discNumber":t||e.push({key:"disk",value:q("data",[F(0),F(0),W(0),W(n),W(i.discsTotal??0),W(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;case"creationTime":break;default:Z(r)}if(i.raw)for(let r in i.raw){let n=i.raw[r];n==null||!t&&(r.length!==4||qb.has(r))||e.some(a=>a.key===r)||(typeof n=="string"?e.push({key:r,value:er(n)}):n instanceof Uint8Array?e.push({key:r,value:q("data",[F(0),F(0),Array.from(n)])}):n instanceof At&&e.push({key:r,value:q("data",[F(Sp[n.mimeType]??0),F(0),Array.from(n.data)])}))}return e},Kb=i=>{let t=Dp(i,!1);return t.length===0?null:re("meta",0,0,void 0,[ld(!1,"mdir","","appl"),q("ilst",void 0,t.map(e=>q(e.key,void 0,[e.value])))])},Gb=i=>{let t=Dp(i,!0);return t.length===0?null:q("meta",void 0,[ld(!1,"mdta",""),re("keys",0,0,[F(t.length)],t.map(e=>q("mdta",[...Y.encode(e.key)]))),q("ilst",void 0,t.map((e,r)=>{let n=String.fromCharCode(...F(r+1));return q(n,void 0,[e.value])}))])},er=i=>q("data",[F(1),F(0),...Y.encode(i)]),Qb=(i,t)=>{switch(i){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return t}},jb={avc:fb,hevc:pb,vp8:wp,vp9:wp,av1:hb,prores:null},Vp=(i,t,e)=>{switch(i){case"aac":return"mp4a";case"mp3":return e?".mp3":"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3";case"dts":return t;case"truehd":return"mlpa"}if(e)switch(i){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(i){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Xb=(i,t)=>{switch(i){case"aac":return sd;case"mp3":return t?null:sd;case"opus":return Tb;case"vorbis":return sd;case"flac":return wb;case"ac3":return t?Rr:Ip;case"eac3":return t?Rr:vp;case"dts":return Sb;case"truehd":return Ab}if(t)switch(i){case"pcm-s24":return Rr;case"pcm-s24be":return Rr;case"pcm-s32":return Rr;case"pcm-s32be":return Rr;case"pcm-f32":return Rr;case"pcm-f32be":return Rr;case"pcm-f64":return Rr;case"pcm-f64be":return Rr}else switch(i){case"pcm-s16":return Fr;case"pcm-s16be":return Fr;case"pcm-s24":return Fr;case"pcm-s24be":return Fr;case"pcm-s32":return Fr;case"pcm-s32be":return Fr;case"pcm-f32":return Fr;case"pcm-f32be":return Fr;case"pcm-f64":return Fr;case"pcm-f64be":return Fr}return null},$b={webvtt:"wvtt"},Yb={webvtt:Cb},Up=i=>{b(i.length===3);let t=0;for(let e=0;e<3;e++)t<<=5,t+=i.charCodeAt(e)-96;return t};var Br=class{constructor(t,e){this.finalized=!1;this.started=!1;this.pos=0;this.trackedWrites=null;this.trackedStart=-1;this.trackedEnd=-1;if(t._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");if(t._closed)throw new Error("Can't create a Writer for a Target that has already been closed.");this.target=t,t._setMonotonicity(e),t._writerAcquired=!0}start(){b(!this.started),this.target._start(),this.started=!0}write(t){b(this.started&&!this.finalized),this.maybeTrackWrites(t),this.target._write(t,this.pos),this.pos+=t.byteLength}seek(t){this.pos=t}getPos(){return this.pos}async flush(){return b(this.started&&!this.finalized),this.target._flush()}async finalize(){b(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(t){if(!this.trackedWrites)return;let e=this.getPos();if(e<this.trackedStart){if(e+t.byteLength<=this.trackedStart)return;t=t.subarray(this.trackedStart-e),e=this.trackedStart}let r=e+t.byteLength-this.trackedStart,n=this.trackedWrites.byteLength;for(;n<r;)n*=2;if(n!==this.trackedWrites.byteLength){let a=new Uint8Array(n);a.set(this.trackedWrites,0),this.trackedWrites=a}this.trackedWrites.set(t,e-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,e+t.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}};var Np=wd(Bu(),1);var Lp=typeof Np<"u"?Np:void 0,Oe=class extends st{constructor(){super(...arguments);this._writerAcquired=!1;this._closed=!1;this._monotonicity=null;this.onwrite=null}_close(){return this._closed=!0,this._release()}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,r){this.onwrite?.(e,r),this._emit("write",{start:e,end:r})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new ys(this,e)}},md=2**16,fd=2**32,Bi=class extends Oe{constructor(e={}){super();this.buffer=null;this._maxPos=0;if(!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(md,{maxByteLength:fd})}catch{this._buffer=new ArrayBuffer(md),this._supportsResize=!1}else this._buffer=new ArrayBuffer(md);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){b(this._buffer),b(this._bytes);let r=this._buffer.byteLength;for(;r<e;)r*=2;if(r!==this._buffer.byteLength){if(r>fd)throw new Error(`ArrayBuffer exceeded maximum size of ${fd} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(r);else{let n=new ArrayBuffer(r),a=new Uint8Array(n);a.set(this._bytes,0),this._buffer=n,this._bytes=a}}}_start(){}_write(e,r){b(this._bytes),this._ensureSize(r+e.byteLength),this._bytes.set(e,r),this._maxPos=Math.max(this._maxPos,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){}async _finalize(){b(this._buffer),"transferToFixedLength"in this._buffer?this.buffer=this._buffer.transferToFixedLength(this._maxPos):this.buffer=this._buffer.slice(0,this._maxPos),this._buffer=null,this._bytes=null,this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _release(){}_getSlice(e,r){return b(this._bytes),this._bytes.slice(e,r)}},Zb=2**24,Jb=2,la=class extends Oe{constructor(e,r={}){super();this._sections=[];this._lastWriteEnd=0;this._lastFlushEnd=0;this._streamWriter=null;this._writeError=null;this._chunks=[];if(!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(r!=null&&typeof r!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(r.chunked!==void 0&&typeof r.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(r.chunkSize!==void 0&&(!Number.isInteger(r.chunkSize)||r.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=r,this._chunked=r.chunked??!1,this._chunkSize=r.chunkSize??Zb}_start(){this._streamWriter=this._writable.getWriter()}_write(e,r){if(r>this._lastWriteEnd){let n=r-this._lastWriteEnd;this._write(new Uint8Array(n),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:r}),this._lastWriteEnd=Math.max(this._lastWriteEnd,r+e.byteLength),this._dispatchWrite(r,r+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(b(this._streamWriter),this._sections.length===0)return;let e=[],r=[...this._sections].sort((n,a)=>n.start-a.start);e.push({start:r[0].start,size:r[0].data.byteLength});for(let n=1;n<r.length;n++){let a=e[e.length-1],s=r[n];s.start<=a.start+a.size?a.size=Math.max(a.size,s.start+s.data.byteLength-a.start):e.push({start:s.start,size:s.data.byteLength})}for(let n of e){n.data=new Uint8Array(n.size);for(let a of this._sections)n.start<=a.start&&a.start<n.start+n.size&&n.data.set(a.data,a.start-n.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(n.data,n.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&n.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:n.data,position:n.start}).catch(a=>{this._writeError??=a}),this._lastFlushEnd=n.start+n.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,r){for(;;){let n=this._chunks.findIndex(l=>l.start<=r&&r<l.start+this._chunkSize);n===-1&&(n=this._createChunk(r));let a=this._chunks[n],s=r-a.start,o=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));a.data.set(o,s);let c={start:s,end:s+o.byteLength};if(this._insertSectionIntoChunk(a,c),a.written[0].start===0&&a.written[0].end===this._chunkSize&&(a.shouldFlush=!0),this._chunks.length>Jb){for(let l=0;l<this._chunks.length-1;l++)this._chunks[l].shouldFlush=!0;this._tryToFlushChunks()}if(o.byteLength===e.byteLength)break;e=e.subarray(o.byteLength),r+=o.byteLength}}_insertSectionIntoChunk(e,r){let n=0,a=e.written.length-1,s=-1;for(;n<=a;){let o=Math.floor(n+(a-n+1)/2);e.written[o].start<=r.start?(n=o+1,s=o):a=o-1}for(e.written.splice(s+1,0,r),(s===-1||e.written[s].end<r.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){let n={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(n),this._chunks.sort((a,s)=>a.start-s.start),this._chunks.indexOf(n)}_tryToFlushChunks(e=!1){b(this._streamWriter);for(let r=0;r<this._chunks.length;r++){let n=this._chunks[r];if(!(!n.shouldFlush&&!e)){for(let a of n.written){let s=n.start+a.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");let o=a.start!==0||a.end!==n.data.byteLength,c;o&&et()?c=n.data.slice(a.start,a.end):c=n.data.subarray(a.start,a.end),this._streamWriter.write({type:"write",data:c,position:s}).catch(l=>{this._writeError??=l}),this._lastFlushEnd=n.start+a.end}this._chunks.splice(r--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;b(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _release(){let e=this._streamWriter??this._writable.getWriter();e.desiredSize!==null&&await e.close()}},Gc=class extends Oe{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new la(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:r=>{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return b(r.position===this._nextWritePos),this._nextWritePos+=r.data.byteLength,b(this._writer),this._writer.write(r.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}_flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}_release(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Qc=class extends Oe{constructor(e,r={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(!Lp.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super();this._fileHandle=null;let n=new WritableStream({start:async()=>{this._fileHandle=await Lp.fs.open(e,"w")},write:async a=>{b(this._fileHandle),await this._fileHandle.write(a.data,0,a.data.byteLength,a.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new la(n,{chunked:!0,...r})}_start(){this._streamTarget._start()}_write(e,r){this._streamTarget._write(e,r),this._dispatchWrite(r,r+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _release(){try{await this._streamTarget._close()}finally{await this._fileHandle?.close(),this._fileHandle=null}}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Oi=class extends Oe{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _release(){}},ys=class extends Oe{constructor(t,e){super(),this._baseTarget=t,this._offset=e}_start(){}_write(t,e){this._baseTarget._write(t,this._offset+e),this._dispatchWrite(e,e+t.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _release(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}},ft=class{constructor(t,e){this.rootPath=t;this.getTarget=e;if(typeof t!="string")throw new TypeError("rootPath must be a string.");if(typeof e!="function")throw new TypeError("getTarget must be a function.")}};var mt=57600,Hp=.5,zp=i=>{let t={},e=i.track;return e.metadata.name!==void 0&&(t.name=e.metadata.name),t},ce=(i,t,e=!0)=>{let r=i*t;return e?Math.round(r):r},dn=i=>{if(i.samples.length===0)return 0;let t=1/0,e=-1/0;for(let r=0;r<i.samples.length;r++){let n=i.samples[r];n.timestamp<t&&(t=n.timestamp),n.timestamp+n.duration>e&&(e=n.timestamp+n.duration)}return t===1/0?0:e-t},jc=class extends Pe{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new Bi;this.auxWriter=new Br(this.auxTarget,!1);this.auxBoxWriter=new un(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.closedTracks=new Set;this.allTracksKnown=te();this.finalizedChunks=[];this.wroteFragmentedHeader=!1;this.nextFragmentNumber=1;this.maxWrittenTimestamp=-1/0;this.minWrittenTimestamp=1/0;this.maxWrittenEndTimestamp=-1/0;this.segmentHeaderSize=null;this.format=r,this.formatOptions={...r._options},this.isQuickTime=r instanceof fn,this.isCmaf=r instanceof mn,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof mn?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();try{let r=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime;if(this.creationTime=r?Math.floor(r.getTime()/1e3)+xo:0,r&&this.creationTime<=0)throw new Error("creationTime must be after 1904-01-01T00:00:00Z for MP4/QuickTime files.");if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(a=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="in-memory"||this.formatOptions.fastStart==="fragmented":a instanceof Bi),this.boxWriter=new un(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof Bi?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let a=await this.output._getInitTarget(),s=new Br(a,!0);s.start(),this.initWriter=s,this.initBoxWriter=new un(s)}let n=this.output.tracks.some(a=>a.isVideoTrack()&&a.source._codec==="avc");{let a=this.initBoxWriter??this.boxWriter;if(b(a),this.formatOptions.onFtyp&&a.writer.startTrackingWrites(),a.writeBox(Pp({isQuickTime:this.isQuickTime,holdsAvc:n,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:s,start:o}=a.writer.stopTrackingWrites();this.formatOptions.onFtyp(s,o)}this.ftypSize=a.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve")for(let a of this.output.tracks){if(a.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.");if(a.metadata.maximumPacketCount>2**32-1)throw new Error(`Track #${a.id} has a maximumPacketCount of ${a.metadata.maximumPacketCount}, which exceeds the maximum of ${2**32-1} packets per track that a non-fragmented file can hold.`)}else this.isFragmented||(b(this.writer),b(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=bs(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let a of this.output.tracks)a.isVideoTrack()&&a.metadata.decoderConfig?this.getVideoTrackData(a,a.metadata.primingPacket??null,{decoderConfig:a.metadata.decoderConfig}):a.isAudioTrack()&&a.metadata.decoderConfig&&this.getAudioTrackData(a,a.metadata.primingPacket??null,{decoderConfig:a.metadata.decoderConfig})}finally{e()}}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Co({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(p=>p.track===e);if(a)return a;_r(n,e.source._codec),b(n),b(n.decoderConfig);let s={...n.decoderConfig};b(s.codedWidth!==void 0),b(s.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!s.description){if(!r)throw new Error("No AVC description provided; you must therefore provide a priming packet.");let p=hr(r.data);if(!p)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=In(p),o=!0}else if(e.source._codec==="hevc"&&!s.description){if(!r)throw new Error("No HEVC description provided; you must therefore provide a priming packet.");let p=br(r.data);if(!p)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=cm(p),o=!0}let c=Od(1/(e.metadata.frameRate??mt),1e6).den,l=s.displayAspectWidth,u=s.displayAspectHeight,d=l===void 0||u===void 0?{num:1,den:1}:zr({num:l*s.codedHeight,den:u*s.codedWidth}),m=s.codec==="ap4h"||s.codec==="ap4x",f={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:o,hasAlphaChannel:m},timescale:c,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,tfraEntries:[],compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((p,h)=>p.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),f}getAudioTrackData(e,r,n){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;Re(n,e.source._codec),b(n),b(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let l=It(xe.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u,d=null;if(l.channelConfiguration===0){let m=l.crcCheck===null?rt:Ye,f=mr(r.data.subarray(m));if(!f)throw new Error("ADTS frames with channel configuration 0 must begin with a program config element.");d=f.programConfigElement,u=Wr(d)}else u=dr[l.channelConfiguration];s.description=ui({objectType:l.objectType,outputSampleRate:Xe[l.samplingFrequencyIndex],outputNumberOfChannels:u,programConfigElement:d}),o=!0}if(!r){if(e.source._codec==="ac3"||e.source._codec==="eac3")throw new Error("AC-3/E-AC-3 require a priming packet.");if(e.source._codec==="dts")throw new Error("DTS requires a priming packet.");if(e.source._codec==="truehd")throw new Error("TrueHD requires a priming packet.")}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&se.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r,pendingEac3Packets:[],preroll:{packetCount:0,accumulatedAudioSamples:0,audioSampleDurationHistory:[]}},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,tfraEntries:[],compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Lc(r),b(r),b(r.config);let a={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,tfraEntries:[],compactlyCodedChunkTable:[],avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n),o=r.data;if(s.info.requiresAnnexBTransformation){let l=[...pi(o)].map(u=>o.subarray(u.offset,u.offset+u.length));if(l.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=Gs(l,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type,0);await this.registerSample(s,c)}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let f=It(xe.tempFromBytes(o));if(!f)throw new Error("Expected ADTS frame, didn't get one.");let p=f.crcCheck===null?rt:Ye;if(o=o.subarray(p),f.channelConfiguration===0){let h=mr(o);h&&(o=o.subarray(h.size))}}if(this.validateTimestamp(s.track,r.timestamp,r.type==="key"),e.source._codec==="eac3"){let f=eo(o),p=f?f.reduce((g,k)=>g+k.blockCount,0):6,h=s.info.pendingEac3Packets,y=h.reduce((g,k)=>g+k.blockCount,0)+p;if(y>6)throw new Error("E-AC-3 frames must add up to exactly six blocks to be muxed into MP4 samples.");h.push({packet:r,blockCount:p}),y===6&&await this.writePendingEac3Packets(s);return}let c=r.timestamp,l=r.duration;if(s.info.requiresPcmTransformation){let p=Me(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(l=o.byteLength/p/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let h=c-s.info.expectedNextPcmPacketTimestamp;if(h<.01)c=s.info.expectedNextPcmPacketTimestamp;else{let y=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,h);c=s.info.expectedNextPcmPacketTimestamp+y}}s.info.expectedNextPcmPacketTimestamp=c+l}let{preroll:u}=s.info,d=0;if(e.source._codec==="aac"||e.source._codec==="vorbis")d=-Math.min(1,u.packetCount);else if(e.source._codec==="mp3")d=-Math.min(2,u.packetCount);else if(e.source._codec==="opus"){let f=Math.round(id*tt);d=-u.audioSampleDurationHistory.length;let p=Xs(o);for(u.accumulatedAudioSamples+=p.durationInSamples,u.audioSampleDurationHistory.push(p.durationInSamples);u.accumulatedAudioSamples-u.audioSampleDurationHistory[0]>=f;)u.accumulatedAudioSamples-=u.audioSampleDurationHistory.shift(),b(u.audioSampleDurationHistory.length>0)}u.packetCount++;let m=this.createSampleForTrack(s,o,c,l,r.type,d);await this.registerSample(s,m)}finally{a()}}async padWithSilence(e,r,n){let a=ce(n,e.timescale),{sampleSize:s,silentValue:o}=Me(e.info.decoderConfig.codec),c=s*e.info.numberOfChannels,l=new Uint8Array(c*Math.min(a,e.timescale)).fill(o);for(let u=0;u<a;u+=e.timescale){let d=Math.min(a-u,e.timescale),m=this.createSampleForTrack(e,l.subarray(0,c*d),r+u/e.timescale,d/e.timescale,"key",0);await this.registerSample(e,m)}return a/e.timescale}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);if(this.validateTimestamp(s.track,r.timestamp,!0),e.source._codec==="webvtt"){let o=ce(r.timestamp,s.timescale)/s.timescale,c=ce(r.timestamp+r.duration,s.timescale)/s.timescale;c>o&&s.cueQueue.push({cue:r,start:o,end:c}),await this.processWebVTTCues(s,o)}}finally{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].start);let n=new Set([]);for(let{start:u,end:d}of e.cueQueue)b(u<=r),b(e.lastCueEndTimestamp<=d),n.add(Math.max(u,e.lastCueEndTimestamp)),n.add(d);let a=[...n].sort((u,d)=>u-d),s=a[0],o=a[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let u=Mp();this.auxBoxWriter.writeBox(u);let d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),m=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key",0);await this.registerSample(e,m),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let u=0;u<e.cueQueue.length;u++){let{cue:d,start:m,end:f}=e.cueQueue[u];if(m>=o)break;Fn.lastIndex=0;let p=Fn.test(d.text),h=e.cueToSourceId.get(d);if(h===void 0&&o<f&&(h=e.nextSourceId++,e.cueToSourceId.set(d,h)),d.notes){let g=Op(d.notes);this.auxBoxWriter.writeBox(g)}let y=Bp(d.text,p?s:null,d.identifier??null,d.settings??null,h??null);this.auxBoxWriter.writeBox(y),f===o&&e.cueQueue.splice(u--,1)}let c=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,c,s,o-s,"key",0);await this.registerSample(e,l),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,n,a,s,o){return{timestamp:n,decodeTimestamp:n,duration:a,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:ce(a,e.timescale),prerollSamples:o}}processTimestamps(e,r){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){b(!this.isFragmented),e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp;let l=0;for(let u=0;u<e.timestampProcessingQueue.length;u++){let d=e.timestampProcessingQueue[u],m=ce(d.duration,e.timescale);l+=m}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:l,sampleDelta:1});else{let u=J(e.timeToSampleTable);u.sampleCount+=l}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue,a=n.map(l=>l.timestamp).sort((l,u)=>l-u),s=ce(a[0],e.timescale);this.isFragmented?e.startTimestampOffset??=Math.min(a[0],0):e.startTimestampOffset??=a[0];let o;e.lastTimescaleUnits===null?o=s:(b(e.lastSample),o=Math.round(e.lastTimescaleUnits)+e.lastSample.timescaleUnitsToNextSample);let c=0;for(let l=0;l<n.length;l++){let u=n[l],d=o+ce(a[l],e.timescale)-s;u.decodeTimestamp=d/e.timescale;let m=ce(u.timestamp,e.timescale)-d,f=ce(u.duration,e.timescale);if(e.lastTimescaleUnits!==null){b(e.lastSample);let p=ce(u.decodeTimestamp,e.timescale,!1),h=Math.round(p-e.lastTimescaleUnits);if(b(h>=0),e.lastTimescaleUnits+=h,e.lastSample.timescaleUnitsToNextSample=h,c=h,!this.isFragmented){let y=J(e.timeToSampleTable);if(b(y),y.sampleCount===1){y.sampleDelta=h;let k=e.timeToSampleTable[e.timeToSampleTable.length-2];k&&k.sampleDelta===h&&(k.sampleCount++,e.timeToSampleTable.pop(),y=k)}else y.sampleDelta!==h&&(y.sampleCount--,e.timeToSampleTable.push(y={sampleCount:1,sampleDelta:h}));y.sampleDelta===f?y.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:f});let g=J(e.compositionTimeOffsetTable);b(g),g.sampleCompositionTimeOffset===m?g.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:m})}}else e.lastTimescaleUnits=ce(u.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:f}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:m}));e.lastSample=u}if(e.timestampProcessingQueue.length=0,b(e.lastSample),b(e.lastTimescaleUnits!==null),r){let l=ce(r.timestamp,e.timescale);e.lastSample.timescaleUnitsToNextSample=Math.max(l-Math.round(e.lastTimescaleUnits),c)}}async registerSample(e,r){r.type==="key"&&this.processTimestamps(e,r),e.timestampProcessingQueue.push(r),e.sampleQueue.push(r),await this.interleaveSamples()}async addSampleToTrack(e,r){if(!this.isFragmented&&(e.samples.push(r),this.fastStart==="reserve")){let a=e.track.metadata.maximumPacketCount;if(b(a!==void 0),e.samples.length>a)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${a}). Either add fewer packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);let a=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let s=this.trackDatas.every(c=>{if(e===c)return r.type==="key";let l=c.sampleQueue[0];return l?l.type==="key":this.closedTracks.has(c.track)}),o=this.wroteFragmentedHeader||this.trackDatas.every(c=>c.startTimestampOffset!==null||this.closedTracks.has(c.track));a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&o&&(n=!0,await this.finalizeFragment())}else n=a>=Hp}if(n){if(!this.isFragmented){let a=this.trackDatas.filter(s=>s.currentChunk&&r.timestamp-s.currentChunk.startTimestamp>=Hp).sort((s,o)=>s.currentChunk.startTimestamp-o.currentChunk.startTimestamp);for(let s of a)await this.finalizeCurrentChunk(s)}e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}}b(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,r.timestamp+r.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){b(!this.isFragmented),b(this.writer);let r=e.currentChunk;b(r),e.currentChunk=null,e.finalizedChunks.push(r);let n=r.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(n=r.samples.reduce((a,s)=>a+ce(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||J(e.compactlyCodedChunkTable).samplesPerChunk!==n)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:n}),this.fastStart==="in-memory"){r.offset=0,this.finalizedChunks.push(r);return}r.offset=this.writer.getPos();for(let a of r.samples)b(a.data),this.writer.write(a.data),a.data=null;r.samples.length=0,await this.writer.flush()}async interleaveSamples(e=!1){if(!(!e&&!this.allTracksAreKnown())){this.fastStart==="reserve"&&!this.mdat&&await this.createFastStartReserveMdat();e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!this.closedTracks.has(s.track))break e;s.sampleQueue.length>0&&s.sampleQueue[0].timestamp<n&&(r=s,n=s.sampleQueue[0].timestamp)}if(!r)break;let a=r.sampleQueue.shift();await this.addSampleToTrack(r,a)}}}async finalizeFragment(e=!this.isCmaf){if(b(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let p=this.initBoxWriter??this.boxWriter;b(p),this.formatOptions.onMoov&&p.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let h=ca(this);if(p.writeBox(h),this.formatOptions.onMoov){let{data:y,start:g}=p.writer.stopTrackingWrites();this.formatOptions.onMoov(y,g)}if(this.isCmaf){b(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new un(this.writer);let y=this.boxWriter.measureBox(od()),g=this.boxWriter.measureBox(cd(this,0));this.segmentHeaderSize=y+g,this.writer.seek(this.segmentHeaderSize)}}b(this.writer),b(this.boxWriter);let r=this.trackDatas.filter(p=>p.currentChunk);if(r.length===0){e&&await this.writer.flush();return}let n=this.nextFragmentNumber++,a=dd(n,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+Ot,l=1/0;for(let p=0;p<r.length;p++){let h=r[p];b(h.currentChunk),b(h.startTimestampOffset!==null),l=Math.min(l,h.currentChunk.startTimestamp),h.currentChunk.offset=c,h.currentChunk.moofOffset=s,h.currentChunk.startTimestamp-=h.startTimestampOffset;for(let y of h.currentChunk.samples)c+=y.size,y.timestamp-=h.startTimestampOffset,y.decodeTimestamp-=h.startTimestampOffset}let u=c-o,d=u>=2**32;if(d){for(let p of r)p.currentChunk.offset+=kr-Ot;u+=kr-Ot}if(J(r).currentChunk.offset-s>=2**31)throw new Error("The data of a fragment's track must start less than 2 GiB after its moof box; use shorter fragments.");this.formatOptions.onMoof&&this.writer.startTrackingWrites();let m=dd(n,r);if(this.boxWriter.writeBox(m),this.formatOptions.onMoof){let{data:p,start:h}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(p,h,l)}b(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=bs(d);f.size=u,this.boxWriter.writeBox(f),this.writer.seek(o+(d?kr:Ot));for(let p of r)for(let h of p.currentChunk.samples)this.writer.write(h.data),h.data=null;if(this.formatOptions.onMdat){let{data:p,start:h}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(p,h)}for(let p=0;p<r.length;p++){let h=r[p];if(b(h.currentChunk),!this.isCmaf){let y=h.currentChunk.samples.findIndex(g=>g.type==="key");y!==-1&&h.tfraEntries.push({timestamp:h.currentChunk.samples[y].timestamp,moofOffset:s,trafIndex:p,sampleIndex:y})}h.currentChunk=null}e&&await this.writer.flush()}async createFastStartReserveMdat(){b(this.writer),b(this.boxWriter),this.ensureOneEnabledTrack();let e=ca(this),n=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;b(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=bs(!0),this.boxWriter.writeBox(this.mdat)}computeSampleTableSizeUpperBound(){b(this.fastStart==="reserve");let e=0;for(let r of this.trackDatas){let n=r.track.metadata.maximumPacketCount;b(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n,r.type==="audio"&&(e+=2*n,e+=8*n)}return e}async onTrackClose(e){let r=await this.mutex.acquire();try{let n=this.trackDatas.find(a=>a.track===e);n?.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),n?.type==="audio"&&n.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(n),this.closedTracks.add(e),n&&this.processTimestamps(n),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveSamples()}finally{r()}}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let r=this.trackDatas.filter(a=>a.type===e);if(r.length===0)continue;if(!r.some(a=>a.track.metadata.disposition?.default!==!1)){let a=r[0];a.track.metadata.disposition={...a.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){b(this.isFragmented);let e=await this.mutex.acquire();try{for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async writePendingEac3Packets(e){let r=e.info.pendingEac3Packets.map(o=>o.packet);e.info.pendingEac3Packets.length=0;let n=r[0].data;if(r.length>1){n=new Uint8Array(r.reduce((c,l)=>c+l.data.byteLength,0));let o=0;for(let c of r)n.set(c.data,o),o+=c.data.byteLength}let a=r.reduce((o,c)=>o+c.duration,0),s=this.createSampleForTrack(e,n,r[0].timestamp,a,"key",0);await this.registerSample(e,s)}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack();for(let r of this.trackDatas)r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),r.type==="audio"&&r.info.pendingEac3Packets.length>0&&await this.writePendingEac3Packets(r),this.closedTracks.add(r.track),this.processTimestamps(r);if(await this.interleaveSamples(!0),this.isFragmented)await this.finalizeFragment(!1);else{let r=this.trackDatas.filter(n=>n.currentChunk).sort((n,a)=>n.currentChunk.startTimestamp-a.currentChunk.startTimestamp);for(let n of r)await this.finalizeCurrentChunk(n);for(let n of this.trackDatas){let a=dn(n);if(a>0){let l=0;for(let u of n.samples)l+=u.size;n.avgBitrate=Math.round(8*l/a)}else n.avgBitrate=0;let s=0,o=0,c=0;for(let l=0;l<n.samples.length;l++){let u=n.samples[l];for(o+=u.size;u.decodeTimestamp-n.samples[s].decodeTimestamp>=1;)o-=n.samples[s].size,s++;c=Math.max(c,o)}if(n.maxBitrate=8*c,n.startTimestampOffset!==null)for(let l=0;l<n.samples.length;l++){let u=n.samples[l];u.timestamp-=n.startTimestampOffset,u.decodeTimestamp-=n.startTimestampOffset}}}if(b(this.writer),b(this.boxWriter),this.fastStart==="in-memory"){this.mdat=bs(!1);let r,n=null;for(;;){let s=this.boxWriter.measureBox(ca(this)),o=this.boxWriter.measureBox(this.mdat),c=s+o;if(c===n)break;n=c,r=o;let l=this.writer.getPos()+c;for(let u of this.finalizedChunks){u.offset=l;for(let{data:d}of u.samples)b(d),l+=d.byteLength,r+=d.byteLength}r>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let a=ca(this);if(this.boxWriter.writeBox(a),this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let s of this.finalizedChunks){for(let o of s.samples)b(o.data),this.writer.write(o.data),o.data=null;await this.writer.flush()}if(this.formatOptions.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;if(r>=2**31)throw new Error("CMAF segments must be smaller than 2 GiB, as their sidx box can't index anything larger.");this.writer.seek(0),this.boxWriter.writeBox(od()),this.boxWriter.writeBox(cd(this,r))}else{let r=this.writer.getPos(),n=Fp(this.trackDatas);this.boxWriter.writeBox(n);let a=this.writer.getPos()-r;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(a)}else{b(this.mdat);let r=this.boxWriter.offsets.get(this.mdat);b(r!==void 0);let n=this.writer.getPos()-r;if(this.mdat.size=n,this.mdat.largeSize=n>=2**32,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(s,o)}let a=ca(this);if(this.fastStart==="reserve"){b(this.ftypSize!==null);let s=this.boxWriter.offsets.get(this.mdat)-this.ftypSize,o=this.boxWriter.measureBox(a);if(o+8>s)throw new Error(`The moov box (${o} bytes) plus a free box (8 bytes) exceed the space reserved for them (${s} bytes) with fastStart: 'reserve'. This is a bug; please report it.`);this.writer.seek(this.ftypSize+o),this.boxWriter.writeBox(Ep(s-o)),this.writer.seek(this.ftypSize)}if(this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a),this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}};var ey=-(2**15),ty=2**15-1,Wp=6,ry=6,iy={video:1,audio:2,subtitle:17},Xc=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.closedTracks=new Set;this.allTracksKnown=te();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.tagsElement=null;this.attachmentsElement=null;this.segmentDuration=null;this.cues=null;this.currentClusterBlocks=[];this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.endTimestamp=-1/0;this.warnedAboutTooNegativeTimestamp=!1;this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new zo(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(let r of this.output.tracks)r.isVideoTrack()&&r.metadata.decoderConfig?this.getVideoTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig}):r.isAudioTrack()&&r.metadata.decoderConfig&&this.getAudioTrackData(r,r.metadata.primingPacket??null,{decoderConfig:r.metadata.decoderConfig})}finally{e()}}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof ir?"webm":"matroska"},{id:17031,data:4},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(r,n)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let r=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),a=new Uint8Array([22,84,174,107]),s=new Uint8Array([25,65,164,105]),o=new Uint8Array([18,84,195,103]),c={id:290298740,data:[{id:19899,data:[{id:21419,data:n},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:a},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:s},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:o},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null,{id:19899,data:[{id:21419,data:r},{id:21420,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]}]};this.seekHead=c}createSegmentInfo(){let e={id:17545,data:new $i(0)};this.segmentDuration=e;let r=this.output._metadataTags.creationTime===void 0?new Date:this.output._metadataTags.creationTime,n=null;if(r){let s=1000000n*BigInt(r.getTime()-No);if(BigInt.asIntN(64,s)!==s)throw new Error("creationTime is out of the range representable by Matroska files.");n={id:17505,size:8,data:BigInt.asUintN(64,s)}}let a={id:357149030,data:[{id:2807729,data:1e6},this.format._options.appendOnly?null:e,n,{id:19840,data:Kr},{id:22337,data:Kr}]};this.segmentInfo=a}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=Be[r.track.source._codec];b(n),r.type==="audio"&&r.track.source._codec==="dts"?r.info.decoderConfig.codec==="dtse"?n="A_DTS/EXPRESS":r.info.decoderConfig.codec==="dtsl"&&(n="A_DTS/LOSSLESS"):r.type==="subtitle"&&this.format instanceof ir&&(n="D_WEBVTT/SUBTITLES");let a=0;if(r.type==="audio"){let s=Mc(r.track.source._codec,r.info.decoderConfig);a=Math.round(1e9*s)}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:iy[r.type]},r.track.metadata.disposition?.default===!1?{id:136,data:0}:null,r.track.metadata.disposition?.forced?{id:21930,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,r.track.metadata.disposition?.original?{id:21934,data:1}:null,r.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},r.type==="video"&&r.info.alphaMode||r.type==="subtitle"&&!(this.format instanceof ir)?{id:21998,data:1}:null,{id:2274716,data:r.track.metadata.languageCode??le},{id:134,data:n},r.codecPrivate?{id:25506,data:Q(r.codecPrivate)}:null,r.type==="audio"&&r.info.codecDelay?{id:22186,data:Math.round(1e9*r.info.codecDelay)}:null,a>0?{id:22203,data:a}:null,r.track.metadata.name!==void 0?{id:21358,data:new Dt(r.track.metadata.name)}:null,r.type==="video"?this.videoSpecificTrackInfo(r):null,r.type==="audio"?this.audioSpecificTrackInfo(r):null,r.type==="subtitle"?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){let{frameRate:r,transformationMatrix:n}=e.track.metadata,a=[r?{id:2352003,data:Math.round(1e9/r)}:null],s,o,c;if(n){s=Di(n);let h=sr(Tn(-s),n);o=Math.sign(h[0]),c=Math.sign(h[4]),c===-1&&(c=1,o=-o,s=ai(s+180))}else s=e.track.metadata.rotation??0,o=e.track.metadata.flip?-1:1,c=1;let l=s?ai(o===-1?s:-s):0,u=Math.round(Math.acos(o)*Es),d=Math.round(Math.acos(c)*Es),m=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,f=e.info.decoderConfig.colorSpace,p={id:224,data:[{id:176,data:e.info.width},{id:186,data:e.info.height},m?{id:21680,data:e.info.aspectRatio.num}:null,m?{id:21690,data:e.info.aspectRatio.den}:null,m?{id:21682,data:3}:null,e.info.alphaMode?{id:21440,data:1}:null,Rs(f)?null:{id:21936,data:[{id:21937,data:f?.matrix!=null?Ft[f.matrix]:2},{id:21946,data:f?.transfer!=null?Rt[f.transfer]:2},{id:21947,data:f?.primaries!=null?_t[f.primaries]:2},{id:21945,data:f?.fullRange!=null?f.fullRange?2:1:0}]},l||u||d?{id:30320,data:[{id:30321,data:0},u?{id:30323,data:new Tr(u)}:null,d?{id:30324,data:new Tr(d)}:null,l?{id:30325,data:new Tr((l+180)%360-180)}:null]}:null]};return a.push(p),a}audioSpecificTrackInfo(e){let r=se.includes(e.track.source._codec)?Me(e.track.source._codec):null,n=e.info.sampleRate;return e.track.source._codec==="aac"&&(b(e.codecPrivate),n=xt(Q(e.codecPrivate)).coreSampleRate??n),[{id:225,data:[{id:181,data:new Tr(n)},n!==e.info.sampleRate?{id:30901,data:new Tr(e.info.sampleRate)}:null,{id:159,data:e.info.numberOfChannels},r?{id:25188,data:8*r.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],r=(s,o)=>{e.push({id:26568,data:[{id:17827,data:new Dt(s)},typeof o=="string"?{id:17543,data:new Dt(o)}:{id:17541,data:o}]})},n=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of qt(n))switch(s){case"title":r("TITLE",o),a.add("TITLE");break;case"description":r("DESCRIPTION",o),a.add("DESCRIPTION");break;case"artist":r("ARTIST",o),a.add("ARTIST");break;case"album":r("ALBUM",o),a.add("ALBUM");break;case"albumArtist":r("ALBUM_ARTIST",o),a.add("ALBUM_ARTIST");break;case"genre":r("GENRE",o),a.add("GENRE");break;case"beatsPerMinute":r("BPM",o.toString()),a.add("BPM");break;case"comment":r("COMMENT",o),a.add("COMMENT");break;case"lyrics":r("LYRICS",o),a.add("LYRICS");break;case"date":r("DATE",o.toISOString().slice(0,10)),a.add("DATE");break;case"trackNumber":{let c=n.tracksTotal!==void 0?`${o}/${n.tracksTotal}`:o.toString();r("PART_NUMBER",c),a.add("PART_NUMBER")}break;case"discNumber":{let c=n.discsTotal!==void 0?`${o}/${n.discsTotal}`:o.toString();r("DISC",c),a.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":case"creationTime":break;default:Z(s)}if(n.raw)for(let s in n.raw){let o=n.raw[s];o==null||a.has(s)||(typeof o=="string"||o instanceof Uint8Array)&&r(s,o)}e.length!==0&&(this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,r=[],n=new Set,a=e.images??[];for(let s of a){let o=s.name;o===void 0&&(o=(s.kind==="coverFront"?"cover":s.kind==="coverBack"?"back":"image")+(zd(s.mimeType)??""));let c;for(;;){c=0n;for(let l=0;l<8;l++)c<<=8n,c|=BigInt(Math.floor(Math.random()*256));if(c!==0n&&!n.has(c))break}n.add(c),r.push({id:24999,data:[s.description!==void 0?{id:18046,data:new Dt(s.description)}:null,{id:18030,data:new Dt(o)},{id:18016,data:s.mimeType},{id:18012,data:s.data},{id:18094,data:c}]})}for(let[s,o]of Object.entries(e.raw??{}))!(o instanceof Lr)||!/^\d+$/.test(s)||a.find(l=>l.mimeType===o.mimeType&&Vs(l.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new Dt(o.description)}:null,{id:18030,data:new Dt(o.name??"")},{id:18016,data:o.mimeType??""},{id:18012,data:o.data},{id:18094,data:BigInt(s)}]});r.length!==0&&(this.attachmentsElement={id:423732329,data:r})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:408125543,size:this.format._options.appendOnly?-1:Wp,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(r,n)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return b(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(r=>r.type==="video"||r.type==="audio"?r.info.decoderConfig.codec:{webvtt:"wvtt"}[r.track.source._codec]);return Ho({isWebM:this.format instanceof ir,hasVideo:this.trackDatas.some(r=>r.type==="video"),hasAudio:this.trackDatas.some(r=>r.type==="audio"),codecStrings:e})}getVideoTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;_r(n,e.source._codec),b(n),b(n.decoderConfig),b(n.decoderConfig.codedWidth!==void 0),b(n.decoderConfig.codedHeight!==void 0);let s=n.decoderConfig.displayAspectWidth,o=n.decoderConfig.displayAspectHeight,c=s===void 0||o===void 0?null:zr({num:s,den:o}),l={track:e,type:"video",info:{width:n.decoderConfig.codedWidth,height:n.decoderConfig.codedHeight,aspectRatio:c,decoderConfig:n.decoderConfig,alphaMode:e.metadata.canBeTransparent||(r?!!r.sideData.alpha:null)},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.decoderConfig.description??null};return e.source._codec==="vp9"?l.codecPrivate=new Uint8Array(gp(l.info.decoderConfig.codec)):e.source._codec==="av1"?l.codecPrivate=new Uint8Array(Nc(l.info.decoderConfig.codec)):e.source._codec==="prores"&&(l.codecPrivate=Y.encode(n.decoderConfig.codec)),this.trackDatas.push(l),this.trackDatas.sort((u,d)=>u.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,r,n){let a=this.trackDatas.find(l=>l.track===e);if(a)return a;Re(n,e.source._codec),b(n),b(n.decoderConfig);let s={...n.decoderConfig},o=!1;if(e.source._codec==="aac"&&!s.description){if(!r)throw new Error("No AAC description provided; you must therefore provide a priming packet.");let l=It(xe.tempFromBytes(r.data));if(!l)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");let u,d=null;if(l.channelConfiguration===0){let m=l.crcCheck===null?rt:Ye,f=mr(r.data.subarray(m));if(!f)throw new Error("ADTS frames with channel configuration 0 must begin with a program config element.");d=f.programConfigElement,u=Wr(d)}else u=dr[l.channelConfiguration];s.description=ui({objectType:l.objectType,outputSampleRate:Xe[l.samplingFrequencyIndex],outputNumberOfChannels:u,programConfigElement:d}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o,codecDelay:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null};return this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Lc(r),b(r),b(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Y.encode(r.config.description)};return this.trackDatas.push(a),this.trackDatas.sort((s,o)=>s.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,r,n);s.info.alphaMode??=!!r.sideData.alpha;let o=r.data;if(e.source._codec==="prores"){if(o.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");o=o.subarray(8)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let l=r.timestamp,u=r.duration;e.metadata.frameRate!==void 0&&(l=Mt(l,e.metadata.frameRate),u=Mt(u,e.metadata.frameRate));let d=s.info.alphaMode?r.sideData.alpha??null:null,m=this.createInternalChunk(o,l,u,r.type,d);s.chunkQueue.push(m),await this.interleaveChunks()}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,r,n),o=r.data;if(s.info.requiresAdtsStripping){let u=It(xe.tempFromBytes(o));if(!u)throw new Error("Expected ADTS frame, didn't get one.");let d=u.crcCheck===null?rt:Ye;if(o=o.subarray(d),u.channelConfiguration===0){let m=mr(o);m&&(o=o.subarray(m.size))}}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c),s.info.codecDelay??=Math.max(-r.timestamp,0);let l=this.createInternalChunk(o,r.timestamp+s.info.codecDelay,r.duration,r.type);s.chunkQueue.push(l),await this.interleaveChunks()}finally{a()}}async addSubtitleCue(e,r,n){let a=await this.mutex.acquire();try{let s=this.getSubtitleTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,!0);let o=r.text,c=Math.round(r.timestamp*1e3);Fn.lastIndex=0,o=o.replace(Fn,u=>{let m=oo(u.slice(1,-1))-c;return`<${co(m/1e3)}>`});let l;if(this.format instanceof ir){let u=Y.encode(`${r.identifier??""}
|
|
16
16
|
${r.settings??""}
|
|
17
17
|
${o}`);l=this.createInternalChunk(u,r.timestamp,r.duration,"key")}else{let u=Y.encode(o),d=`${r.settings??""}
|
|
18
18
|
${r.identifier??""}
|
|
19
|
-
${r.notes??""}`;l=this.createInternalChunk(u,r.timestamp,r.duration,"key",d.trim()?Y.encode(d):null)}s.chunkQueue.push(l),await this.interleaveChunks()}finally{a()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!this.closedTracks.has(s.track))break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<n&&(r=s,n=s.chunkQueue[0].timestamp)}if(!r)break;let a=r.chunkQueue.shift();this.addBlock(r,a)}e||await this.writer.flush()}}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}addBlock(e,r){this.segment||this.createSegment();let n=Math.round(1e3*r.timestamp),a=this.trackDatas.every(c=>{if(e===c)return r.type==="key";let l=c.chunkQueue[0];return l?l.type==="key":this.closedTracks.has(c.track)}),s=!1;if(this.currentClusterStartMsTimestamp===null)s=!0;else{b(this.currentClusterMaxMsTimestamp!==null);let c=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&c>=1e3*(this.format._options.minimumClusterDuration??1)||c>ty}if(s&&this.startNewCluster(n),n-this.currentClusterStartMsTimestamp<ey){if(!this.warnedAboutTooNegativeTimestamp){let c=this.format instanceof ir?"WebM":"Matroska";O._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${c}.`),this.warnedAboutTooNegativeTimestamp=!0}return}this.currentClusterBlocks.push({trackData:e,chunk:r,msTimestamp:n,previousMsTimestamp:e.lastWrittenMsTimestamp}),this.endTimestamp=Math.max(this.endTimestamp,n+Math.round(1e3*r.duration)),e.lastWrittenMsTimestamp=n,this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}startNewCluster(e){this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster();let r=Math.max(0,e);this.currentClusterStartMsTimestamp=r,this.currentClusterMaxMsTimestamp=r}writeCurrentCluster(){b(this.currentClusterStartMsTimestamp!==null);let e=this.currentClusterStartMsTimestamp,r=new Map,n=new Map;for(let d of this.currentClusterBlocks){d.chunk.type==="key"&&!r.has(d.trackData)&&r.set(d.trackData,d);let m=n.get(d.trackData);(!m||d.msTimestamp>=m.msTimestamp)&&n.set(d.trackData,d)}let a=new Map;for(let d of this.currentClusterBlocks)a.set(d,this.createBlockElement(d,e,n.get(d.trackData)===d));let s={id:524531317,size:this.format._options.appendOnly?-1:ry,data:[{id:231,data:e},...a.values()]};if(this.format._options.onCluster&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(s),this.currentClusterBlocks=[],this.format._options.onCluster){let{data:d,start:m}=this.writer.stopTrackingWrites();this.format._options.onCluster(d,m,e/1e3)}let o=this.ebmlWriter.offsets.get(s)-this.segmentDataOffset,c=this.ebmlWriter.dataOffsets.get(s),l=new Map;for(let d of r.values())l.has(d.msTimestamp)||l.set(d.msTimestamp,[]),l.get(d.msTimestamp).push(d);let u=[...l.entries()].sort((d,m)=>d[0]-m[0]);for(let[d,m]of u)b(this.cues),this.cues.data.push({id:187,data:[{id:179,data:Math.max(0,d)},...m.map(f=>{let p=this.ebmlWriter.offsets.get(a.get(f));return{id:183,data:[{id:247,data:f.trackData.track.id},{id:241,data:o},{id:240,data:p-c}]}})]})}createBlockElement(e,r,n){let{trackData:a,chunk:s,msTimestamp:o}=e,c=new Uint8Array(4),l=new DataView(c.buffer);l.setUint8(0,128|a.track.id),l.setInt16(1,o-r,!1);let u=Math.round(1e3*s.duration);return!!s.additions||a.type==="subtitle"||n&&u>0?{id:160,data:[{id:161,data:[c,s.data]},s.type==="delta"?{id:251,data:new Ln(e.previousMsTimestamp-o)}:null,s.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:s.additions}]}]}:null,u>0?{id:155,data:u}:null]}:(l.setUint8(3,+(s.type==="key")<<7),{id:163,data:[c,s.data]})}async onTrackClose(e){let r=await this.mutex.acquire();try{this.closedTracks.add(e),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks()}finally{r()}}async finalize(){let e=await this.mutex.acquire();try{this.allTracksKnown.resolve();for(let r of this.trackDatas)this.closedTracks.add(r.track);if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster(),b(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(r,Wp);let n=Math.max(this.endTimestamp,0);this.segmentDuration.data=new $i(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),b(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}}finally{e()}}};var Xc=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.crc=0}writeAndUpdateCrc(t){for(let e of t){this.crc^=e;for(let r=0;r<8;r++)this.crc=this.crc>>>1^(this.crc&1?40961:0)}this.writer.write(t)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writeAndUpdateCrc(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos();this.crc=0;let r=255,n=224|t.mpegVersionId<<3|t.layer<<1|1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=mi(t.mpegVersionId,t.channel),c=t.encoderDelayInSamples===null?155:o+8+4+4+100+36,l=-1,u=a*16*4+t.layer*16;for(let h=0;h<16;h++){let y=Ns[u+h];if(1e3*y<(t.targetBitrate??0))continue;if(Ls(a,t.layer,1e3*y,t.sampleRate,s)>=c){l=h;break}}if(l===-1)throw new Error("No suitable bitrate found.");let d=l<<4|t.frequencyIndex<<2|s<<1,m=t.channel<<6|t.modeExtension<<4|t.copyright<<3|t.original<<2|t.emphasis;this.helper[0]=r,this.helper[1]=n,this.helper[2]=d,this.helper[3]=m,this.writeAndUpdateCrc(this.helper.subarray(0,4)),this.writeAndUpdateCrc(new Uint8Array(o-4)),this.writeU32(t.isCbr?di:qr);let f=0;if(t.frameCount!==null&&(f|=1),t.fileSize!==null&&(f|=2),t.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(t.frameCount??0),this.writeU32(t.fileSize??0),this.writeAndUpdateCrc(t.toc??new Uint8Array(100)),t.encoderDelayInSamples!==null){let h=new Uint8Array(36);h.set([76,65,77,69]),h[21]=t.encoderDelayInSamples>>4,h[22]=(t.encoderDelayInSamples&15)<<4|2,h[23]=17,this.writeAndUpdateCrc(h.subarray(0,34)),new DataView(h.buffer).setUint16(34,this.crc),this.writer.write(h.subarray(34))}let p=Ns[u+l],g=Ls(a,t.layer,1e3*p,t.sampleRate,s);this.writer.write(new Uint8Array(e+g-this.writer.getPos()))}};var $c=class extends Pe{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.frameBitrate=null;this.hasVariableBitrate=!1;this.framePositions=[];this.xingFramePos=null;this.format=r,this.writeXingHeader=r._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new Xc(this.writer),Hr(this.output._metadataTags)||new Ci(this.writer).writeId3V2Tag(this.output._metadataTags)}finally{e()}}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,r){let n=await this.mutex.acquire();try{if(this.writeXingHeader){let a=N(r.data);if(a.byteLength<4)throw new Error("Invalid MP3 header in sample.");let s=a.getUint32(0,!1),o=fr(s,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");if(!this.xingFrameData&&o.layer!==1)this.writeXingHeader=!1;else if(!this.xingFrameData){let c=mi(o.mpegVersionId,o.channel);if(a.byteLength>=c+4){let u=a.getUint32(c,!1);if(u===qr||u===di)return}let l=r.timestamp<0?Math.round(-r.timestamp*o.sampleRate)-529:null;l!==null&&(l<0||l>4095)&&(l=null),this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,targetBitrate:o.bitrate,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:l},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData)}this.frameBitrate===null?this.frameBitrate=o.bitrate:o.bitrate!==this.frameBitrate&&(this.hasVariableBitrate=!0)}this.validateTimestamp(e,r.timestamp,r.type==="key"),this.writeXingHeader&&this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.frameCount===0){if(!this.writeXingHeader)throw new Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");let n=this.output.tracks[0];b(n?.isAudioTrack());let a=n.metadata.primingPacket;if(a){let s=N(a.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in priming packet.");let o=s.getUint32(0,!1),c=fr(o,null).header;if(!c)throw new Error("Invalid MP3 header in priming packet.");this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,targetBitrate:c.bitrate,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else if(n.metadata.decoderConfig){let{sampleRate:s,numberOfChannels:o}=n.metadata.decoderConfig,c=[3,2,0],l=null,u=-1;for(let d=0;d<c.length;d++)if(u=Dl.indexOf(s<<d),u!==-1){l=c[d];break}if(l===null)throw new Error(`${s} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:l,layer:1,frequencyIndex:u,sampleRate:s,channel:o===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,targetBitrate:null,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else throw new Error("Cannot finalize an empty MP3 file: no packets were added and the track specified neither a decoderConfig nor a primingPacket in its metadata, so there's no telling what the file should look like.");this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData)}if(this.writeXingHeader){b(this.xingFrameData),b(this.xingFramePos!==null);let a=this.writer.getPos()-this.xingFramePos;if(this.writer.seek(this.xingFramePos),this.framePositions.length>0){let s=new Uint8Array(100);for(let o=0;o<100;o++){let c=Math.floor(this.framePositions.length*(o/100)),l=this.framePositions[c]-this.xingFramePos;s[o]=256*(l/a)}this.xingFrameData.toc=s}if(this.xingFrameData.isCbr=this.frameBitrate!==null&&!this.hasVariableBitrate,this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(s,o)}}e()}};var ny=8192,Yc=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.closedTracks=new Set;this.bosPagesWritten=!1;this.allTracksKnown=te();this.warnedAboutTooNegativeTimestamp=!1;this.pageBytes=new Uint8Array(jo);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0);for(let r of this.output.tracks)b(r.isAudioTrack()),r.metadata.decoderConfig&&this.getTrackData(r,{decoderConfig:r.metadata.decoderConfig})}finally{e()}}async getMimeType(){return await this.allTracksKnown.promise,Qo({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let n=this.trackDatas.find(c=>c.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(c=>c.serialNumber===a));b(e.source._codec==="vorbis"||e.source._codec==="opus"),Re(r,e.source._codec),b(r),b(r.decoderConfig);let s;e.source._codec==="vorbis"?s=r.decoderConfig.sampleRate:e.source._codec==="opus"?s=tt:(Z(e.source._codec),b(!1));let o={track:e,serialNumber:a,internalSampleRate:s,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],leadingPackets:[],startOffsetInSamples:0,currentTimestampInSamples:null,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0};return this.queueHeaderPackets(o,r),this.trackDatas.push(o),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}queueHeaderPackets(e,r){if(b(r.decoderConfig),e.codecInfo.codec==="vorbis"){b(r.decoderConfig.description);let n=G(r.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let y=0;for(;;){let k=n[a++];if(k===void 0)throw new TypeError("Vorbis decoder description is too short.");if(y+=k,k<255)return y}},o=s(),c=s();if(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let u=n.subarray(a,a+=o);a+=c;let d=n.subarray(a),m=new Uint8Array(7);m[0]=3,m[1]=118,m[2]=111,m[3]=114,m[4]=98,m[5]=105,m[6]=115;let f=ya(m,this.output._metadataTags,!0),p=new Uint8Array(f.length+1);p.set(f),p[f.length]=1,e.packetQueue.push({data:u,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:p,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1,holdPage:!1,isHeader:!0},{data:d,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0});let h=N(u).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(h&15),1<<(h>>4)],modeBlockflags:Xs(d).modeBlockflags}}else if(e.codecInfo.codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let n=G(r.decoderConfig.description),a=new Uint8Array(8),s=N(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=ya(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:o,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0}),e.codecInfo.opusInfo={preSkip:yr(n).preSkip}}else Z(e.codecInfo.codec)}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let{durationInSamples:o,vorbisBlockSize:c}=Ka(r.data,s.codecInfo,s.vorbisLastBlocksize);if(s.vorbisLastBlocksize=c,s.currentTimestampInSamples===null){let u=Math.round(r.timestamp*s.internalSampleRate);if(s.codecInfo.codec==="vorbis")s.currentTimestampInSamples=u;else if(s.codecInfo.codec==="opus"){let d=s.codecInfo.opusInfo;if(b(d),s.pagesWritten===0){let m=ne(-u,d.preSkip,65535),f=s.packetQueue[0];b(f?.isHeader),f.data=f.data.slice(),N(f.data).setUint16(10,m,!0),d.preSkip=m}s.currentTimestampInSamples=u+d.preSkip}else Z(s.codecInfo.codec),b(!1)}let l={data:r.data,timestampInSamples:s.currentTimestampInSamples,durationInSamples:o,forcePageFlush:!1,holdPage:!1,isHeader:!1};if(s.currentTimestampInSamples+=o,s.audioPacketCount===0){let u=l.timestampInSamples+o;if(s.codecInfo.codec==="opus"){if(l.timestampInSamples<0){this.warnAboutDiscardedPackets();return}s.startOffsetInSamples=l.timestampInSamples}else if(s.codecInfo.codec==="vorbis"){if(u<0){s.leadingPackets.push(l);return}let d=Math.floor(l.data.length/255)+1,m=s.leadingPackets.length;for(;m>0;){let p=s.leadingPackets[m-1],g=Math.floor(p.data.length/255)+1;if(d+g>255)break;d+=g,m--}m>0&&this.warnAboutDiscardedPackets();let f=s.leadingPackets.slice(m);if(s.leadingPackets.length=0,f.length>0){for(let p of f)p.holdPage=!0,s.packetQueue.push(p);l.holdPage=!0,l.forcePageFlush=!0,s.audioPacketCount+=f.length}else s.startOffsetInSamples=u}else Z(s.codecInfo.codec)}s.startOffsetInSamples>0&&s.audioPacketCount===1&&(l.forcePageFlush=!0),s.audioPacketCount++,s.packetQueue.push(l),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let n=r.packetQueue.shift();if(this.writePacket(r,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,n=1/0;for(let o of this.trackDatas){if(!e&&o.packetQueue.length<=1&&!this.closedTracks.has(o.track))break e;if(o.packetQueue.length===0)continue;let c=o.packetQueue[0],l=c.isHeader?-1/0:c.timestampInSamples/o.internalSampleRate;l<n&&(r=o,n=l)}if(!r)break;let a=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,a,s)}e||await this.writer.flush()}writePacket(e,r,n){let a=r.timestampInSamples+r.durationInSamples;if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=r.timestampInSamples),this.format._options.maximumPageDuration!==void 0&&!r.holdPage){let u=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&a-e.currentPageStartTimestampInSamples>u&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let u=Math.min(255,s);e.currentLacingValues.push(u),e.currentPageSize++,c+=u;let d=s<255;if(e.currentLacingValues.length===255){let m=r.data.subarray(o,c);if(o=c,e.currentPageData.push(m),e.currentPageSize+=m.length,d&&(e.currentGranulePosition=a),this.writePage(e,n&&d),d)return}if(d)break;s-=255}let l=r.data.subarray(o);e.currentPageData.push(l),e.currentPageSize+=l.length,e.currentGranulePosition=a,(e.currentPageSize>=ny&&!r.holdPage||r.forcePageFlush||n)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,qa,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),r&&(n|=4),this.pageView.setUint8(5,n);let a=e.currentLacingValues.every(l=>l===255)?-1:e.currentGranulePosition;Fd(this.pageView,6,a,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let l of e.currentPageData)this.pageBytes.set(l,s),s+=l.length;let o=this.pageBytes.subarray(0,s),c=If(o);if(this.pageView.setUint32(22,c,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(o),this.format._options.onPage){let{data:l,start:u}=this.writer.stopTrackingWrites();this.format._options.onPage(l,u,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire();try{this.closedTracks.add(e);let n=this.trackDatas.find(a=>a.track===e);n&&n.leadingPackets.length>0&&(n.leadingPackets.length=0,this.warnAboutDiscardedPackets()),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages()}finally{r()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)this.closedTracks.add(r.track),r.leadingPackets.length>0&&(r.leadingPackets.length=0,this.warnAboutDiscardedPackets());await this.interleavePages(!0),e()}warnAboutDiscardedPackets(){this.warnedAboutTooNegativeTimestamp||(O._warn("Packets had to be discarded because their timestamp is too negative to represent in Ogg."),this.warnedAboutTooNegativeTimestamp=!0)}};var ay=0,Gp=4096,qp=256,sy=224,Kp=192,Zc=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.closedTracks=new Set;this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(ze);this.packetView=N(this.packetBuffer);this.allTracksKnown=te();this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r,this.timestampOffset=r._options.timestampOffset??0}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0)}finally{e()}}async getMimeType(){return await this.allTracksKnown.promise,ic(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(u=>u.track===e);if(n)return n;_r(r,e.source._codec),b(r?.decoderConfig);let a=e.source._codec;b(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=qp+this.output.tracks.indexOf(e),c=sy+this.output.tracks.filter(u=>u.type==="video").indexOf(e),l={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],reorderDelay:0,lastDecodeTimestamp:-1/0,packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(l),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,r){let n=this.trackDatas.find(d=>d.track===e);if(n)return n;Re(r,e.source._codec),b(r?.decoderConfig);let a=e.source._codec;b(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3"||a==="dts");let s=qp+this.output.tracks.indexOf(e),o=this.output.tracks.filter(d=>d.type==="audio").indexOf(e),c,l;switch(a){case"aac":c=15,l=Kp+o;break;case"mp3":c=3,l=Kp+o;break;case"ac3":c=129,l=189;break;case"eac3":c=135,l=189;break;case"dts":c=130,l=189;break}let u={track:e,pid:s,streamType:c,streamId:l,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],reorderDelay:0,lastDecodeTimestamp:-1/0,packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,r,n){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=n?.decoderConfig?.description;if(s){let o=G(s);a==="avc"?e.avcDecoderConfig=gr(o):e.hevcDecoderConfig=In(o)}e.inputIsAnnexB=!s}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let a of pi(e)){let s=e.subarray(a.offset,a.offset+a.length);(r==="avc"?pr(s[0])===9:Qt(s[0])===35)||n.push(s)}return n.unshift(this.createAud(n,r)),ga(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let c of Ws(a,s)){let l=a.subarray(c.offset,c.offset+c.length);(n==="avc"?pr(l[0])===9:Qt(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="avc"){let c=e.avcDecoderConfig;for(let l of c.pictureParameterSets)o.unshift(l);for(let l of c.sequenceParameterSets)o.unshift(l)}else{let c=e.hevcDecoderConfig;for(let l of c.arrays)if(l.nalUnitType===34)for(let u of l.nalUnits)o.unshift(u);for(let l of c.arrays)if(l.nalUnitType===33)for(let u of l.nalUnits)o.unshift(u);for(let l of c.arrays)if(l.nalUnitType===32)for(let u of l.nalUnits)o.unshift(u)}return o.unshift(this.createAud(o,n)),ga(o)}createAud(e,r){if(r==="avc")return new Uint8Array([9,240]);let n=e.find(s=>Qt(s[0])<32),a=n?n[1]&7:1;return new Uint8Array([70,a,80])}prepareAudioPacket(e,r,n){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3"||a==="dts")return r.data;if(e.inputIsAdts===null){let l=n?.decoderConfig?.description;if(l){let u=xt(G(l)),d=Us(u);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}e.inputIsAdts=!l}if(e.inputIsAdts)return r.data;b(e.adtsHeader),b(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;zs(e.adtsHeaderBitstream,o);let c=new Uint8Array(o);return c.set(s,0),c.set(r.data,s.byteLength),c}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async flushTimestampQueue(e,r=!0){if(e.timestampProcessingQueue.length===0)return;let n=e.timestampProcessingQueue.map(a=>a.presentationTimestamp).sort((a,s)=>a-s);for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a];e.reorderDelay=Math.max(e.reorderDelay,n[a]-s.presentationTimestamp)}for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a],o=Math.max(n[a]-e.reorderDelay,e.lastDecodeTimestamp+1/Ue);s.decodeTimestamp=o,s.presentationTimestamp=Math.max(s.presentationTimestamp,o),e.lastDecodeTimestamp=o,e.packetQueue.push(s)}e.timestampProcessingQueue.length=0,r&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.packetQueue.length===0&&!this.closedTracks.has(s.track))break e;s.packetQueue.length>0&&s.packetQueue[0].presentationTimestamp<n&&(r=s,n=s.packetQueue[0].presentationTimestamp)}if(!r)break;let a=r.packetQueue.shift();this.writePesPacket(r,a)}e||await this.writer.flush()}writeTables(){b(!this.tablesWritten),this.writePsiSection(ay,pn),this.writePsiSection(Gp,cy(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,r){let n=0,a=!0;for(;n<r.length;){let o=184-(a?1:0),c=r.length-n,l=Math.min(o,c),u;a?(u=this.payloadBuffer.subarray(0,1+l),u[0]=0,u.set(r.subarray(n,n+l),1)):u=r.subarray(n,n+l),this.writeTsPacket(e,a,null,u),n+=l,a=!1}}writePesPacket(e,r){let n=e.track.type==="video",a=n?10:5,s=new Uint8Array(9+a),o=N(s),c=new K(s.subarray(9));zi(o,0,1,!1),s[3]=e.streamId;let l=e.track.type==="video"||8+r.data.length>65535?0:8+r.data.length;o.setUint16(4,l,!1),o.setUint8(6,132),o.setUint8(7,n?192:128),o.setUint8(8,a);let u=ja(r.presentationTimestamp+this.timestampOffset);if(c.pos=0,c.writeBits(4,n?3:2),c.writeBits(3,Math.floor(u/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(u/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,u%2**15),c.writeBits(1,1),n){b(r.decodeTimestamp!==null);let p=ja(r.decodeTimestamp+this.timestampOffset);c.writeBits(4,1),c.writeBits(3,Math.floor(p/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(p/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,p%2**15),c.writeBits(1,1)}let d=s.length+r.data.length,m=0,f=!0;for(;m<d;){let p=f,g=d-m,h=f&&r.isKeyframe,y=f&&!e.firstPacketWritten,k=Math.max(0,184-g),T;h||y?T=Math.max(2,k):T=k;let S=null;if(T>0){let x=this.adaptationFieldBuffer;T===1?x[0]=0:(x[0]=T-1,x[1]=Number(y)<<7|Number(h)<<6,x.fill(255,2,T)),S=x.subarray(0,T)}let w=Math.min(184-T,g),A=this.payloadBuffer.subarray(0,w),C=0;if(m<s.length){let x=Math.min(s.length-m,w);A.set(s.subarray(m,m+x),0),C=x}let E=Math.max(0,m-s.length),I=E+(w-C);C<w&&A.set(r.data.subarray(E,I),C),this.writeTsPacket(e.pid,p,S,A),m+=w,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,r,n,a){let s=this.continuityCounters.get(e)??0,o=a.length>0,c=n?o?3:2:o?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(r?16384:0)|e&8191,!1),this.packetBuffer[3]=c<<4|s&15,o&&this.continuityCounters.set(e,s+1&15);let l=4;n&&(this.packetBuffer.set(n,l),l+=n.length),this.packetBuffer.set(a,l),l+=a.length,l<ze&&this.packetBuffer.fill(255,l);let u=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),u)}async onTrackClose(e){let r=await this.mutex.acquire();try{this.closedTracks.add(e);let n=this.trackDatas.find(a=>a.track===e);n&&await this.flushTimestampQueue(n,!1),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets()}finally{r()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)this.closedTracks.add(r.track),await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},oy=79764919,Qp=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^oy:t<<1;Qp[i]=t>>>0&4294967295}var jp=i=>{let t=4294967295;for(let e=0;e<i.length;e++){let r=i[e];t=(t<<8^Qp[t>>>24^r])>>>0}return t},pn=new Uint8Array(16);{let i=N(pn);pn[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),pn[5]=193,pn[6]=0,pn[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|Gp&8191,!1),i.setUint32(12,jp(pn.subarray(0,12)),!1)}var cy=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=Ta.length:c.streamType===135&&(t+=wa.length);let e=9+t+4,r=new Uint8Array(3+e-4),n=N(r);r[0]=2,n.setUint16(1,45056|e&4095,!1),n.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,n.setUint16(8,65535,!1),n.setUint16(10,61440,!1);let a=12;for(let c of[...i].sort((l,u)=>l.pid-u.pid))r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|Ta.length,!1),a+=2,r.set(Ta,a),a+=Ta.length):c.streamType===135?(n.setUint16(a,61440|wa.length,!1),a+=2,r.set(wa,a),a+=wa.length):(n.setUint16(a,61440,!1),a+=2);let s=jp(r),o=new Uint8Array(r.length+4);return o.set(r,0),N(o).setUint32(r.length,s,!1),o};var Jc=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(t){this.helperView.setUint16(0,t,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,t,!0),this.helperView.setUint32(4,Math.floor(t/2**32),!0),this.writer.write(this.helper)}writeAscii(t){this.writer.write(Y.encode(t))}};var el=class extends Pe{constructor(e,r){super(e);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.riffSizePos=null;this.dataSizePos=null;this.factSampleCountPos=null;this.ds64RiffSizePos=null;this.ds64DataSizePos=null;this.ds64SampleCountPos=null;this.format=r,this.isRf64=!!r._options.large,this.appendOnly=!!r._options.appendOnly}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(this.appendOnly),this.riffWriter=new Jc(this.writer);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Re({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.writeHeader(r,r.metadata.decoderConfig),this.sampleRate=r.metadata.decoderConfig.sampleRate,this.headerWritten=!0)}finally{e()}}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.headerWritten||(Re(n,e.source._codec),b(n),b(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let n,a=e.source._codec,s=Me(a);s.dataType==="ulaw"?n=7:s.dataType==="alaw"?n=6:s.dataType==="float"?n=3:n=1;let o=r.numberOfChannels,c=r.sampleRate,l=8*s.sampleSize,u=s.sampleSize*o,d=o>2||n===1&&l>16,m=this.appendOnly?4294967295:0,f=()=>{this.appendOnly?(this.riffWriter.writeU32(4294967295),this.riffWriter.writeU32(2147483647)):this.riffWriter.writeU64(0)};if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(m)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),f(),this.ds64DataSizePos=this.writer.getPos(),f(),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(d?40:16),this.riffWriter.writeU16(d?65534:n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(l),d){let p={1:4,2:3,3:7,4:51,5:55,6:63,7:1807,8:1599},g=new Uint8Array([0,0,16,0,128,0,0,170,0,56,155,113]);this.riffWriter.writeU16(22),this.riffWriter.writeU16(l),this.riffWriter.writeU32(p[o]??0),this.riffWriter.writeU32(n),this.writer.write(g)}if(n!==1&&!this.appendOnly&&(this.riffWriter.writeAscii("fact"),this.riffWriter.writeU32(4),this.factSampleCountPos=this.writer.getPos(),this.riffWriter.writeU32(0)),!Hr(this.output._metadataTags)){let p=this.format._options.metadataFormat??"info";p==="info"?this.writeInfoChunk(this.output._metadataTags):p==="id3"?this.writeId3Chunk(this.output._metadataTags):Z(p)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(m)),this.format._options.onHeader){let{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onHeader(p,g)}}writeInfoChunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let n=new Set,a=(c,l)=>{if(!Ht(l)){O._warn(`Didn't write tag '${c}' because '${l}' is not ISO 8859-1-compatible.`);return}let u=l.length+1,d=new Uint8Array(u);for(let m=0;m<l.length;m++)d[m]=l.charCodeAt(m);this.riffWriter.writeAscii(c),this.riffWriter.writeU32(u),this.writer.write(d),u&1&&this.writer.write(new Uint8Array(1)),n.add(c)};for(let{key:c,value:l}of qt(e))switch(c){case"title":a("INAM",l),n.add("INAM");break;case"artist":a("IART",l),n.add("IART");break;case"album":a("IPRD",l),n.add("IPRD");break;case"trackNumber":{let u=e.tracksTotal!==void 0?`${l}/${e.tracksTotal}`:l.toString();a("ITRK",u),n.add("ITRK")}break;case"genre":a("IGNR",l),n.add("IGNR");break;case"date":a("ICRD",l.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":a("ICMT",l),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"beatsPerMinute":case"description":case"lyrics":case"images":case"creationTime":break;case"raw":break;default:Z(c)}if(e.raw)for(let c in e.raw){let l=e.raw[c];l==null||c.length!==4||n.has(c)||typeof l=="string"&&a(c,l)}let s=this.writer.getPos(),o=s-r-8;this.writer.seek(r+4),this.riffWriter.writeU32(o),this.writer.seek(s),o&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let a=new Ci(this.writer).writeId3V2Tag(e),s=this.writer.getPos();this.writer.seek(r+4),this.riffWriter.writeU32(a),this.writer.seek(s),a&1&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire();if(!this.headerWritten)throw new Error("Cannot finalize an empty WAVE file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");this.dataSize&1&&!this.appendOnly&&this.writer.write(new Uint8Array(1));let r=this.writer.getPos();this.factSampleCountPos!==null&&(this.writer.seek(this.factSampleCountPos),this.riffWriter.writeU32(Math.min(this.sampleCount,4294967295))),this.appendOnly||(this.isRf64?(b(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),b(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),b(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(b(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),b(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize))),e()}};var Xp=i=>i==="opus"?"Opus":i==="flac"?"fLaC":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"?"mp4a.40.34":i,rl=class extends Pe{constructor(e,r){if(!(e._target instanceof ft))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];this.closedTracks=new Set;this.firstPacketTimestamp=null;this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.format=r,this.targetSegmentDuration=r._options.targetDuration??2,this.singleFilePerPlaylist=r._options.singleFilePerPlaylist??!1,this.isLive=r._options.live??!1,this.maxLiveSegmentCount=r._options.maxLiveSegmentCount??1/0,this.mediaTimestampBase=r._options.mediaTimestampBase??10,this.globalTargetDuration=0,this.getPlaylistPath=r._options.getPlaylistPath??(({n})=>`playlist-${n}.m3u8`),this.getSegmentPath=r._options.getSegmentPath??(n=>n.isSingleFile?`segments-${n.playlist.n}${n.format.fileExtension}`:`segment-${n.playlist.n}-${n.n}${n.format.fileExtension}`),this.getInitPath=r._options.getInitPath??(n=>`init-${n.n}${n.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire();try{let r=this.output.tracks.some(y=>y.metadata.isRelativeToUnixEpoch),n=this.output.tracks.some(y=>!y.metadata.isRelativeToUnixEpoch);if(r&&n)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=r;let a=new Map,s=[],o=!1,c=!1,l=!1;for(let y of this.output.tracks){y.type==="video"&&(o=!0);let k=new Map;for(let T of this.output.tracks){if(y===T||!y.canBePairedWith(T))continue;if(y.type===T.type){c||(O._warn(`Illegal pairing of two ${y.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),c=!0);continue}if(y.isVideoTrack()&&y.metadata.hasOnlyKeyPackets||T.isVideoTrack()&&T.metadata.hasOnlyKeyPackets){l||(O._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),l=!0);continue}let S=k.get(T.source._codec);S||k.set(T.source._codec,S=[]),S.push(T)}for(let[,T]of k){let S=T.map(C=>C.id).join("-");s.find(C=>C.key===S)||s.push({name:T[0].type+"-"+(s.length+1),key:S,tracks:T,needsEmit:!1,firstNoUri:!1});let A=a.get(y);A||a.set(y,A=[]),A.push(S)}}let u=o?"video":"audio",d=[],m=[],f=[],p=y=>{let k=[],T=0,S=0,w=!1,A=null,C=-1/0;for(let E of y)E.isVideoTrack()?(T++,w||=(E.metadata.rotation??0)!==0||!!E.metadata.flip||!!E.metadata.transformationMatrix):E.isAudioTrack()&&S++,k.push(E.source._codec);for(let E of Bt(this.format._options.segmentFormat)){let I=E.getSupportedCodecs(),x=E.getSupportedTrackCounts();if(k.some(v=>!I.includes(v))||T<x.video.min||T>x.video.max||S<x.audio.min||S>x.audio.max)continue;let P=0;w&&E.supportsVideoTransformationMetadata&&P++,P>C&&(A=E,C=P)}return A};for(let y of this.output.tracks){let k=a.get(y);if(k){if(b(k.length>0),y.type!==u)continue;for(let T of k){let S=s.find(w=>w.key===T);if(b(S),k.length===1&&S.tracks.length===1){let w=a.get(S.tracks[0]);if(b(w!==void 0),w.length===1){let A=s.find(C=>C.key===w[0]);if(A.tracks.length===1&&(b(A.tracks[0]===y),!!p([y,S.tracks[0]]))){d.push({tracks:[y,S.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[y],linkedGroup:S}),S.needsEmit=!0}}else y.type==="video"?m.push(y):y.type==="audio"&&f.push(y)}let g=({metadata:y})=>{let k="";return k+=`${y.languageCode??ce}-`,k+=`${y.name??""}-`,k+=`${y.disposition?.default??!0}-`,k+=`${y.disposition?.primary??!1}-`,k+=`${y.disposition?.forced??!1}-`,k};if(m.length>0){let y=m.filter(S=>S.isVideoTrack()&&S.metadata.hasOnlyKeyPackets),k=m.filter(S=>!y.includes(S));if(new Set(k.map(g)).size>1){let S={key:k.map(w=>w.id).join("-"),name:"video-"+(s.length+1),tracks:k,needsEmit:!0,firstNoUri:!0};s.push(S),d.push({tracks:[k[0]],linkedGroup:S});for(let w of y)d.push({tracks:[w],linkedGroup:null})}else for(let S of m)d.push({tracks:[S],linkedGroup:null})}if(f.length>0)if(new Set(f.map(g)).size>1){let k={key:f.map(T=>T.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[f[0]],linkedGroup:k})}else for(let k of f)d.push({tracks:[k],linkedGroup:null});let h=async y=>{if(y.some(A=>this.playlists.some(C=>C.tracks.includes(A))))throw new Error("Internal error: track is already registered in a playlist.");let k=p(y);b(k);let T=this.playlists.length+1,S=await this.getPlaylistPath({n:T,tracks:y,segmentFormat:k});ly(S);let w={id:this.playlists.length+1,path:S,tracks:y,segmentFormat:k,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new Ee};return this.playlists.push(w),w};for(let y of s)if(y.needsEmit)for(let k=0;k<y.tracks.length;k++){let T=y.tracks[k],S=this.playlists.find(w=>w.tracks[0].id===T.id);S??=await h([T]),this.playlistDeclarations.push({playlist:S,groupId:y.name,noUri:y.firstNoUri&&k===0,references:[]})}for(let y of d){let k=this.playlists.find(T=>T.tracks[0].id===y.tracks[0].id);k??=await h(y.tracks),this.playlistDeclarations.push({playlist:k,groupId:null,noUri:!1,references:y.linkedGroup?this.playlistDeclarations.filter(T=>T.groupId===y.linkedGroup.name):[]})}for(let y of this.output.tracks)y.isVideoTrack()&&y.metadata.decoderConfig?this.getVideoTrackData(y,y.metadata.primingPacket??null,{decoderConfig:y.metadata.decoderConfig}):y.isAudioTrack()&&y.metadata.decoderConfig&&this.getAudioTrackData(y,y.metadata.primingPacket??null,{decoderConfig:y.metadata.decoderConfig})}finally{e()}}async getMimeType(){return Cr}allTracksAreKnown(e){for(let r of e.tracks)if(!this.closedTracks.has(r)&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.playlists.find(a=>a.tracks.includes(e));b(r);let n=await r.mutex.acquire();try{this.closedTracks.add(e),r.done||await this.advancePlaylist(r)}finally{n()}}getVideoTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;_r(n,e.source._codec),b(n),b(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return b(s.length===1),a={track:e,packets:[],playlist:s[0],info:{type:"video",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}getAudioTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;Re(n,e.source._codec),b(n),b(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return b(s.length===1),a={track:e,packets:[],playlist:s[0],info:{type:"audio",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}async addEncodedVideoPacket(e,r,n){let a=this.getVideoTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),this.firstPacketTimestamp??=r.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(e,r,n){let a=this.getAudioTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),this.firstPacketTimestamp??=r.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addSubtitleCue(e,r,n){throw new Error("Unreachable.")}async advancePlaylist(e){if(b(!e.done),!this.allTracksAreKnown(e))return;let r=this.trackDatas.filter(u=>e.tracks.includes(u.track)),n=r.every(u=>this.closedTracks.has(u.track));if(e.currentSegmentStartTimestamp===null){n&&await this.onPlaylistDone(e);return}let a=r.find(u=>u.info.type==="video"),s=r.find(u=>u.info.type==="audio"),o=!!a&&this.closedTracks.has(a.track),c=!!s&&this.closedTracks.has(s.track),l=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;for(;;){let u=e.currentSegmentStartTimestamp+this.targetSegmentDuration,d=0,m=0;if(a&&(!o||a.packets.length>0)){let x=a.packets.every(_=>_.timestamp<u),P=null,v=null;if(x&&!l){if(!o)return}else for(let _=0;_<a.packets.length;_++){let M=a.packets[_];if(P!==null&&M.timestamp>u||_>0&&M.type==="key"&&(P=M,v=_,l))break}if(v!==null){if(d=v,s){let _=s.packets.findIndex(M=>M.timestamp>=P.timestamp);if(_!==-1)m=_;else if(c)m=s.packets.length;else return}}else{if(!o)return;d=a.packets.length;let _=Hd(a.packets,D=>D.timestamp),M=a.packets[_];if(b(M),s)if(M.timestamp<u){let D=s.packets.findIndex(L=>L.timestamp>=u);if(D!==-1)m=D;else if(c)m=s.packets.length;else return}else{let D=s.packets.findIndex(L=>L.timestamp>M.timestamp);if(D!==-1)m=D;else if(c)m=s.packets.length;else return}}}else if(s&&(!c||s.packets.length>0))if(s.packets.every(P=>P.timestamp<u))if(c)m=s.packets.length;else return;else{let P=lr(s.packets,v=>v.timestamp<=u);m=Math.max(P,1)}if(d===0&&m===0){n&&await this.onPlaylistDone(e);return}let f=null,p,g;b(this.output._target instanceof ft);let h=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let x={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:tl(e)};p=await this.getSegmentPath(x),$p(p),g=ve(ve(h.rootPath,e.path),p);let P=await this.output._getTarget({path:g,isRoot:!1,mimeType:e.segmentFormat.mimeType}),v=null;if(e.segmentFormat._isFragmentedIsobmff()){v={output:new Or({format:e.segmentFormat,target:P}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},P.on("write",({end:D})=>{v.currentFileSize=Math.max(v.currentFileSize,D)});let _=v.output._muxer;_.minimumFragmentDuration=1/0;let M=_.formatOptions.onMoof;_.formatOptions.onMoof=(D,L,z)=>{v.firstMoofPosition=L,M?.(D,L,z),_.formatOptions.onMoof=M},a&&(v.videoSource=new ri(a.track.source._codec),v.output.addVideoTrack(v.videoSource,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),s&&(v.audioSource=new ii(s.track.source._codec),v.output.addAudioTrack(v.audioSource,{...s.track.metadata,decoderConfig:s.info.decoderConfig,primingPacket:s.info.primingPacket??void 0})),await v.output.start()}else P._start();e.singleFile={target:P,path:p,nextOffset:0,info:x,fragmentedIsobmffOutput:v}}else p=e.singleFile.path,g=ve(ve(h.rootPath,e.path),p);else f={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:tl(e)},p=await this.getSegmentPath(f),$p(p),g=ve(ve(h.rootPath,e.path),p),e.nextSegmentId++;let y=0,k=null,T=-1/0,S=null,w=null,A=null;try{if(e.singleFile?.fragmentedIsobmffOutput)S=e.singleFile.fragmentedIsobmffOutput.output,w=e.singleFile.fragmentedIsobmffOutput.videoSource,A=e.singleFile.fragmentedIsobmffOutput.audioSource;else{if(S=new Or({format:e.segmentFormat._withoutXingHeader(),target:new ft(g,async x=>{let P={...x,isRoot:!1};if(x.isRoot)if(e.singleFile){let v=e.singleFile.target.slice(e.singleFile.nextOffset);return v.on("write",({end:_})=>y=Math.max(y,_)),v}else{let v=await this.output._getTarget(P);return k=v,v.on("write",({end:_})=>y=Math.max(y,_)),v}return this.output._getTarget(P)}),initTarget:async()=>{if(e.initSegment)return new Oi;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let x=e.singleFile.target.slice(e.singleFile.nextOffset);return x.on("write",({end:P})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,P)}),x.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),x}else{let x=tl(e),P=await this.getInitPath(x);uy(P),e.initSegment={path:P,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let v=ve(ve(h.rootPath,e.path),P),_=await this.output._getTarget({path:v,isRoot:!1,mimeType:e.segmentFormat.mimeType});return _.on("write",({end:M})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,M)}),_.on("finalized",()=>{this.format._options.onInit?.(_,x)}),_}}}),a&&(w=new ri(a.track.source._codec),S.addVideoTrack(w,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0,maximumPacketCount:d})),s&&(A=new ii(s.track.source._codec),S.addAudioTrack(A,{...s.track.metadata,decoderConfig:s.info.decoderConfig,primingPacket:s.info.primingPacket??void 0,maximumPacketCount:m}),!e.segmentFormat.supportsTimestampedMediaData&&m>0)){let x=this.toMediaTimestamp(s.packets[0].timestamp),P=ja(x),v=new Uint8Array(zt.length+1+8);v.set(Y.encode(zt),0);let _=N(v);_.setUint32(zt.length+1,Math.floor(P/2**32)),_.setUint32(zt.length+5,P%2**32),S.setMetadataTags({raw:{PRIV:v}})}await S.start()}if(a){b(w);let x={decoderConfig:a.info.decoderConfig};for(let P=0;P<d;P++){let v=a.packets[P],_=v.clone({timestamp:this.toMediaTimestamp(v.timestamp)});await w.add(_,x),T=Math.max(T,v.timestamp+v.duration)}}if(s){b(A);let x={decoderConfig:s.info.decoderConfig};for(let P=0;P<m;P++){let v=s.packets[P],_=v.clone({timestamp:this.toMediaTimestamp(v.timestamp)});await A.add(_,x),T=Math.max(T,v.timestamp+v.duration)}}e.singleFile?.fragmentedIsobmffOutput?(await e.singleFile.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.singleFile.fragmentedIsobmffOutput.firstMoofPosition!==null&&!e.initSegment&&(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),y=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await S.finalize()}catch(x){throw await S?.cancel(),x}f&&(b(k),this.format._options.onSegment?.(k,f)),d>0&&(b(a),a.packets.splice(0,d)),m>0&&(b(s),s.packets.splice(0,m));let C=1/0;a&&a.packets.length>0&&(C=a.packets[0].timestamp),s&&s.packets.length>0&&(C=Math.min(C,s.packets[0].timestamp));let E=C<1/0?C:T;b(Number.isFinite(E));let I=E-e.currentSegmentStartTimestamp;if(b(I>=0),e.writtenSegments.push({path:p,duration:I,timestamp:e.currentSegmentStartTimestamp,byteSize:y,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:f??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,I),e.currentSegmentStartTimestamp=E,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=y),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let x=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(b(x.info),this.format._options.onSegmentPopped?.(x.path,x.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}toMediaTimestamp(e){return b(this.firstPacketTimestamp!==null),e-this.firstPacketTimestamp+this.mediaTimestampBase}async onPlaylistDone(e){b(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),this.isLive&&(await this.writePlaylist(e),e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist())}updatePlaylistBitrates(e,r){let n=e.writtenSegments,a=0,s=0,o=0;for(let l=0;l<n.length;l++){o+=n[l].duration;let u=0,d=0;for(let m=l;m<n.length&&(u+=n[m].byteSize,d+=n[m].duration,d>=.5*r&&d<=1.5*r&&(a=Math.max(a,8*u/d)),!(d>1.5*r));m++);}if(a===0)for(let l of n){let u=l.duration||1;a=Math.max(a,8*l.byteSize/u)}for(let l of n)s+=8*l.byteSize;let c=s/(o||1);if(n.length===0)for(let l of e.tracks){let u=this.trackDatas.find(m=>m.track===l),d=l.source._nominalBitrate??l.metadata.bitrate??0;if(c+=l.source._nominalBitrate??l.metadata.averageBitrate??0,d===0){let m=new ue("medium");if(l.isVideoTrack()){let f=u?.info.decoderConfig;d=m._toVideoBitrate(l.source._codec,f?.codedWidth??1920,f?.codedHeight??1080)}else if(l.isAudioTrack()){let f=u?.info.decoderConfig;d=m._toAudioBitrate(l.source._codec,f?.numberOfChannels??2)??0}}a+=d}e.peakBitrate=a,e.averageBitrate=c}async writePlaylist(e){b(this.output._target instanceof ft);let r=this.output._target,n=Math.max(Math.ceil(+(this.isLive?this.targetSegmentDuration:this.globalTargetDuration).toFixed(12)),1);this.updatePlaylistBitrates(e,n);let a=!1;for(let m of e.writtenSegments)a||=m.byteOffset!==null;let s=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,o=3;(s||a)&&(o=4),e.initSegment&&(o=5),e.initSegment&&!s&&(o=6);let c=ve(r.rootPath,e.path),l=`#EXTM3U
|
|
19
|
+
${r.notes??""}`;l=this.createInternalChunk(u,r.timestamp,r.duration,"key",d.trim()?Y.encode(d):null)}s.chunkQueue.push(l),await this.interleaveChunks()}finally{a()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.chunkQueue.length===0&&!this.closedTracks.has(s.track))break e;s.chunkQueue.length>0&&s.chunkQueue[0].timestamp<n&&(r=s,n=s.chunkQueue[0].timestamp)}if(!r)break;let a=r.chunkQueue.shift();this.addBlock(r,a)}e||await this.writer.flush()}}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}addBlock(e,r){this.segment||this.createSegment();let n=Math.round(1e3*r.timestamp),a=this.trackDatas.every(c=>{if(e===c)return r.type==="key";let l=c.chunkQueue[0];return l?l.type==="key":this.closedTracks.has(c.track)}),s=!1;if(this.currentClusterStartMsTimestamp===null)s=!0;else{b(this.currentClusterMaxMsTimestamp!==null);let c=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&c>=1e3*(this.format._options.minimumClusterDuration??1)||c>ty}if(s&&this.startNewCluster(n),n-this.currentClusterStartMsTimestamp<ey){if(!this.warnedAboutTooNegativeTimestamp){let c=this.format instanceof ir?"WebM":"Matroska";O._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${c}.`),this.warnedAboutTooNegativeTimestamp=!0}return}this.currentClusterBlocks.push({trackData:e,chunk:r,msTimestamp:n,previousMsTimestamp:e.lastWrittenMsTimestamp}),this.endTimestamp=Math.max(this.endTimestamp,n+Math.round(1e3*r.duration)),e.lastWrittenMsTimestamp=n,this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}startNewCluster(e){this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster();let r=Math.max(0,e);this.currentClusterStartMsTimestamp=r,this.currentClusterMaxMsTimestamp=r}writeCurrentCluster(){b(this.currentClusterStartMsTimestamp!==null);let e=this.currentClusterStartMsTimestamp,r=new Map,n=new Map;for(let d of this.currentClusterBlocks){d.chunk.type==="key"&&!r.has(d.trackData)&&r.set(d.trackData,d);let m=n.get(d.trackData);(!m||d.msTimestamp>=m.msTimestamp)&&n.set(d.trackData,d)}let a=new Map;for(let d of this.currentClusterBlocks)a.set(d,this.createBlockElement(d,e,n.get(d.trackData)===d));let s={id:524531317,size:this.format._options.appendOnly?-1:ry,data:[{id:231,data:e},...a.values()]};if(this.format._options.onCluster&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(s),this.currentClusterBlocks=[],this.format._options.onCluster){let{data:d,start:m}=this.writer.stopTrackingWrites();this.format._options.onCluster(d,m,e/1e3)}let o=this.ebmlWriter.offsets.get(s)-this.segmentDataOffset,c=this.ebmlWriter.dataOffsets.get(s),l=new Map;for(let d of r.values())l.has(d.msTimestamp)||l.set(d.msTimestamp,[]),l.get(d.msTimestamp).push(d);let u=[...l.entries()].sort((d,m)=>d[0]-m[0]);for(let[d,m]of u)b(this.cues),this.cues.data.push({id:187,data:[{id:179,data:Math.max(0,d)},...m.map(f=>{let p=this.ebmlWriter.offsets.get(a.get(f));return{id:183,data:[{id:247,data:f.trackData.track.id},{id:241,data:o},{id:240,data:p-c}]}})]})}createBlockElement(e,r,n){let{trackData:a,chunk:s,msTimestamp:o}=e,c=new Uint8Array(4),l=new DataView(c.buffer);l.setUint8(0,128|a.track.id),l.setInt16(1,o-r,!1);let u=Math.round(1e3*s.duration);return!!s.additions||a.type==="subtitle"||n&&u>0?{id:160,data:[{id:161,data:[c,s.data]},s.type==="delta"?{id:251,data:new Hn(e.previousMsTimestamp-o)}:null,s.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:s.additions}]}]}:null,u>0?{id:155,data:u}:null]}:(l.setUint8(3,+(s.type==="key")<<7),{id:163,data:[c,s.data]})}async onTrackClose(e){let r=await this.mutex.acquire();try{this.closedTracks.add(e),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks()}finally{r()}}async finalize(){let e=await this.mutex.acquire();try{this.allTracksKnown.resolve();for(let r of this.trackDatas)this.closedTracks.add(r.track);if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentClusterStartMsTimestamp!==null&&this.writeCurrentCluster(),b(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let r=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(r,Wp);let n=Math.max(this.endTimestamp,0);this.segmentDuration.data=new $i(n),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),b(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}}finally{e()}}};var $c=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer);this.crc=0}writeAndUpdateCrc(t){for(let e of t){this.crc^=e;for(let r=0;r<8;r++)this.crc=this.crc>>>1^(this.crc&1?40961:0)}this.writer.write(t)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writeAndUpdateCrc(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos();this.crc=0;let r=255,n=224|t.mpegVersionId<<3|t.layer<<1|1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=mi(t.mpegVersionId,t.channel),c=t.encoderDelayInSamples===null?155:o+8+4+4+100+36,l=-1,u=a*16*4+t.layer*16;for(let y=0;y<16;y++){let g=Ls[u+y];if(1e3*g<(t.targetBitrate??0))continue;if(Hs(a,t.layer,1e3*g,t.sampleRate,s)>=c){l=y;break}}if(l===-1)throw new Error("No suitable bitrate found.");let d=l<<4|t.frequencyIndex<<2|s<<1,m=t.channel<<6|t.modeExtension<<4|t.copyright<<3|t.original<<2|t.emphasis;this.helper[0]=r,this.helper[1]=n,this.helper[2]=d,this.helper[3]=m,this.writeAndUpdateCrc(this.helper.subarray(0,4)),this.writeAndUpdateCrc(new Uint8Array(o-4)),this.writeU32(t.isCbr?di:qr);let f=0;if(t.frameCount!==null&&(f|=1),t.fileSize!==null&&(f|=2),t.toc!==null&&(f|=4),this.writeU32(f),this.writeU32(t.frameCount??0),this.writeU32(t.fileSize??0),this.writeAndUpdateCrc(t.toc??new Uint8Array(100)),t.encoderDelayInSamples!==null){let y=new Uint8Array(36);y.set([76,65,77,69]),y[21]=t.encoderDelayInSamples>>4,y[22]=(t.encoderDelayInSamples&15)<<4|2,y[23]=17,this.writeAndUpdateCrc(y.subarray(0,34)),new DataView(y.buffer).setUint16(34,this.crc),this.writer.write(y.subarray(34))}let p=Ls[u+l],h=Hs(a,t.layer,1e3*p,t.sampleRate,s);this.writer.write(new Uint8Array(e+h-this.writer.getPos()))}};var Yc=class extends Pe{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.frameBitrate=null;this.hasVariableBitrate=!1;this.framePositions=[];this.xingFramePos=null;this.format=r,this.writeXingHeader=r._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new $c(this.writer),Hr(this.output._metadataTags)||new Ci(this.writer).writeId3V2Tag(this.output._metadataTags)}finally{e()}}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,r){let n=await this.mutex.acquire();try{if(this.writeXingHeader){let a=z(r.data);if(a.byteLength<4)throw new Error("Invalid MP3 header in sample.");let s=a.getUint32(0,!1),o=fr(s,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");if(!this.xingFrameData&&o.layer!==1)this.writeXingHeader=!1;else if(!this.xingFrameData){let c=mi(o.mpegVersionId,o.channel);if(a.byteLength>=c+4){let u=a.getUint32(c,!1);if(u===qr||u===di)return}let l=r.timestamp<0?Math.round(-r.timestamp*o.sampleRate)-529:null;l!==null&&(l<0||l>4095)&&(l=null),this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,targetBitrate:o.bitrate,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:l},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData)}this.frameBitrate===null?this.frameBitrate=o.bitrate:o.bitrate!==this.frameBitrate&&(this.hasVariableBitrate=!0)}this.validateTimestamp(e,r.timestamp,r.type==="key"),this.writeXingHeader&&this.framePositions.push(this.writer.getPos()),this.writer.write(r.data),this.frameCount++,await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(this.frameCount===0){if(!this.writeXingHeader)throw new Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");let n=this.output.tracks[0];b(n?.isAudioTrack());let a=n.metadata.primingPacket;if(a){let s=z(a.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in priming packet.");let o=s.getUint32(0,!1),c=fr(o,null).header;if(!c)throw new Error("Invalid MP3 header in priming packet.");this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,targetBitrate:c.bitrate,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else if(n.metadata.decoderConfig){let{sampleRate:s,numberOfChannels:o}=n.metadata.decoderConfig,c=[3,2,0],l=null,u=-1;for(let d=0;d<c.length;d++)if(u=Vl.indexOf(s<<d),u!==-1){l=c[d];break}if(l===null)throw new Error(`${s} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:l,layer:1,frequencyIndex:u,sampleRate:s,channel:o===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,targetBitrate:null,isCbr:!1,frameCount:null,fileSize:null,toc:null,encoderDelayInSamples:null}}else throw new Error("Cannot finalize an empty MP3 file: no packets were added and the track specified neither a decoderConfig nor a primingPacket in its metadata, so there's no telling what the file should look like.");this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData)}if(this.writeXingHeader){b(this.xingFrameData),b(this.xingFramePos!==null);let a=this.writer.getPos()-this.xingFramePos;if(this.writer.seek(this.xingFramePos),this.framePositions.length>0){let s=new Uint8Array(100);for(let o=0;o<100;o++){let c=Math.floor(this.framePositions.length*(o/100)),l=this.framePositions[c]-this.xingFramePos;s[o]=256*(l/a)}this.xingFrameData.toc=s}if(this.xingFrameData.isCbr=this.frameBitrate!==null&&!this.hasVariableBitrate,this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=a,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:s,start:o}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(s,o)}}e()}};var ny=8192,Zc=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.closedTracks=new Set;this.bosPagesWritten=!1;this.allTracksKnown=te();this.warnedAboutTooNegativeTimestamp=!1;this.pageBytes=new Uint8Array(Xo);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0);for(let r of this.output.tracks)b(r.isAudioTrack()),r.metadata.decoderConfig&&this.getTrackData(r,{decoderConfig:r.metadata.decoderConfig})}finally{e()}}async getMimeType(){return await this.allTracksKnown.promise,jo({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){let n=this.trackDatas.find(c=>c.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(c=>c.serialNumber===a));b(e.source._codec==="vorbis"||e.source._codec==="opus"),Re(r,e.source._codec),b(r),b(r.decoderConfig);let s;e.source._codec==="vorbis"?s=r.decoderConfig.sampleRate:e.source._codec==="opus"?s=tt:(Z(e.source._codec),b(!1));let o={track:e,serialNumber:a,internalSampleRate:s,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],leadingPackets:[],startOffsetInSamples:0,currentTimestampInSamples:null,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0};return this.queueHeaderPackets(o,r),this.trackDatas.push(o),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}queueHeaderPackets(e,r){if(b(r.decoderConfig),e.codecInfo.codec==="vorbis"){b(r.decoderConfig.description);let n=Q(r.decoderConfig.description);if(n[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1,s=()=>{let g=0;for(;;){let k=n[a++];if(k===void 0)throw new TypeError("Vorbis decoder description is too short.");if(g+=k,k<255)return g}},o=s(),c=s();if(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let u=n.subarray(a,a+=o);a+=c;let d=n.subarray(a),m=new Uint8Array(7);m[0]=3,m[1]=118,m[2]=111,m[3]=114,m[4]=98,m[5]=105,m[6]=115;let f=ka(m,this.output._metadataTags,!0),p=new Uint8Array(f.length+1);p.set(f),p[f.length]=1,e.packetQueue.push({data:u,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:p,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1,holdPage:!1,isHeader:!0},{data:d,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0});let y=z(u).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(y&15),1<<(y>>4)],modeBlockflags:$s(d).modeBlockflags}}else if(e.codecInfo.codec==="opus"){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");let n=Q(r.decoderConfig.description),a=new Uint8Array(8),s=z(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=ka(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0},{data:o,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0,holdPage:!1,isHeader:!0}),e.codecInfo.opusInfo={preSkip:yr(n).preSkip}}else Z(e.codecInfo.codec)}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let{durationInSamples:o,vorbisBlockSize:c}=Ga(r.data,s.codecInfo,s.vorbisLastBlocksize);if(s.vorbisLastBlocksize=c,s.currentTimestampInSamples===null){let u=Math.round(r.timestamp*s.internalSampleRate);if(s.codecInfo.codec==="vorbis")s.currentTimestampInSamples=u;else if(s.codecInfo.codec==="opus"){let d=s.codecInfo.opusInfo;if(b(d),s.pagesWritten===0){let m=ne(-u,d.preSkip,65535),f=s.packetQueue[0];b(f?.isHeader),f.data=f.data.slice(),z(f.data).setUint16(10,m,!0),d.preSkip=m}s.currentTimestampInSamples=u+d.preSkip}else Z(s.codecInfo.codec),b(!1)}let l={data:r.data,timestampInSamples:s.currentTimestampInSamples,durationInSamples:o,forcePageFlush:!1,holdPage:!1,isHeader:!1};if(s.currentTimestampInSamples+=o,s.audioPacketCount===0){let u=l.timestampInSamples+o;if(s.codecInfo.codec==="opus"){if(l.timestampInSamples<0){this.warnAboutDiscardedPackets();return}s.startOffsetInSamples=l.timestampInSamples}else if(s.codecInfo.codec==="vorbis"){if(u<0){s.leadingPackets.push(l);return}let d=Math.floor(l.data.length/255)+1,m=s.leadingPackets.length;for(;m>0;){let p=s.leadingPackets[m-1],h=Math.floor(p.data.length/255)+1;if(d+h>255)break;d+=h,m--}m>0&&this.warnAboutDiscardedPackets();let f=s.leadingPackets.slice(m);if(s.leadingPackets.length=0,f.length>0){for(let p of f)p.holdPage=!0,s.packetQueue.push(p);l.holdPage=!0,l.forcePageFlush=!0,s.audioPacketCount+=f.length}else s.startOffsetInSamples=u}else Z(s.codecInfo.codec)}s.startOffsetInSamples>0&&s.audioPacketCount===1&&(l.forcePageFlush=!0),s.audioPacketCount++,s.packetQueue.push(l),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let r of this.trackDatas)for(;r.packetQueue.length>0;){let n=r.packetQueue.shift();if(this.writePacket(r,n,!1),n.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let r=null,n=1/0;for(let o of this.trackDatas){if(!e&&o.packetQueue.length<=1&&!this.closedTracks.has(o.track))break e;if(o.packetQueue.length===0)continue;let c=o.packetQueue[0],l=c.isHeader?-1/0:c.timestampInSamples/o.internalSampleRate;l<n&&(r=o,n=l)}if(!r)break;let a=r.packetQueue.shift(),s=r.packetQueue.length===0;this.writePacket(r,a,s)}e||await this.writer.flush()}writePacket(e,r,n){let a=r.timestampInSamples+r.durationInSamples;if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=r.timestampInSamples),this.format._options.maximumPageDuration!==void 0&&!r.holdPage){let u=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&a-e.currentPageStartTimestampInSamples>u&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let u=Math.min(255,s);e.currentLacingValues.push(u),e.currentPageSize++,c+=u;let d=s<255;if(e.currentLacingValues.length===255){let m=r.data.subarray(o,c);if(o=c,e.currentPageData.push(m),e.currentPageSize+=m.length,d&&(e.currentGranulePosition=a),this.writePage(e,n&&d),d)return}if(d)break;s-=255}let l=r.data.subarray(o);e.currentPageData.push(l),e.currentPageSize+=l.length,e.currentGranulePosition=a,(e.currentPageSize>=ny&&!r.holdPage||r.forcePageFlush||n)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,Ka,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),r&&(n|=4),this.pageView.setUint8(5,n);let a=e.currentLacingValues.every(l=>l===255)?-1:e.currentGranulePosition;Fd(this.pageView,6,a,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let l of e.currentPageData)this.pageBytes.set(l,s),s+=l.length;let o=this.pageBytes.subarray(0,s),c=If(o);if(this.pageView.setUint32(22,c,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(o),this.format._options.onPage){let{data:l,start:u}=this.writer.stopTrackingWrites();this.format._options.onPage(l,u,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire();try{this.closedTracks.add(e);let n=this.trackDatas.find(a=>a.track===e);n&&n.leadingPackets.length>0&&(n.leadingPackets.length=0,this.warnAboutDiscardedPackets()),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages()}finally{r()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)this.closedTracks.add(r.track),r.leadingPackets.length>0&&(r.leadingPackets.length=0,this.warnAboutDiscardedPackets());await this.interleavePages(!0),e()}warnAboutDiscardedPackets(){this.warnedAboutTooNegativeTimestamp||(O._warn("Packets had to be discarded because their timestamp is too negative to represent in Ogg."),this.warnedAboutTooNegativeTimestamp=!0)}};var ay=0,Gp=4096,qp=256,sy=224,Kp=192,Jc=class extends Pe{constructor(e,r){super(e);this.trackDatas=[];this.closedTracks=new Set;this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(ze);this.packetView=z(this.packetBuffer);this.allTracksKnown=te();this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r,this.timestampOffset=r._options.timestampOffset??0}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(!0)}finally{e()}}async getMimeType(){return await this.allTracksKnown.promise,nc(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(u=>u.track===e);if(n)return n;_r(r,e.source._codec),b(r?.decoderConfig);let a=e.source._codec;b(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=qp+this.output.tracks.indexOf(e),c=sy+this.output.tracks.filter(u=>u.type==="video").indexOf(e),l={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],reorderDelay:0,lastDecodeTimestamp:-1/0,packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(l),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,r){let n=this.trackDatas.find(d=>d.track===e);if(n)return n;Re(r,e.source._codec),b(r?.decoderConfig);let a=e.source._codec;b(a==="aac"||a==="mp3"||a==="ac3"||a==="eac3"||a==="dts");let s=qp+this.output.tracks.indexOf(e),o=this.output.tracks.filter(d=>d.type==="audio").indexOf(e),c,l;switch(a){case"aac":c=15,l=Kp+o;break;case"mp3":c=3,l=Kp+o;break;case"ac3":c=129,l=189;break;case"eac3":c=135,l=189;break;case"dts":c=130,l=189;break}let u={track:e,pid:s,streamType:c,streamId:l,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],reorderDelay:0,lastDecodeTimestamp:-1/0,packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}async addEncodedVideoPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getVideoTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareVideoPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getAudioTrackData(e,n);this.validateTimestamp(s.track,r.timestamp,r.type==="key");let o=this.prepareAudioPacket(s,r,n);r.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:o,presentationTimestamp:r.timestamp,decodeTimestamp:null,isKeyframe:r.type==="key"})}finally{a()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,r,n){let a=e.track.source._codec;if(e.inputIsAnnexB===null){let s=n?.decoderConfig?.description;if(s){let o=Q(s);a==="avc"?e.avcDecoderConfig=gr(o):e.hevcDecoderConfig=vn(o)}e.inputIsAnnexB=!s}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let a of pi(e)){let s=e.subarray(a.offset,a.offset+a.length);(r==="avc"?pr(s[0])===9:Qt(s[0])===35)||n.push(s)}return n.unshift(this.createAud(n,r)),ba(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let c of qs(a,s)){let l=a.subarray(c.offset,c.offset+c.length);(n==="avc"?pr(l[0])===9:Qt(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="avc"){let c=e.avcDecoderConfig;for(let l of c.pictureParameterSets)o.unshift(l);for(let l of c.sequenceParameterSets)o.unshift(l)}else{let c=e.hevcDecoderConfig;for(let l of c.arrays)if(l.nalUnitType===34)for(let u of l.nalUnits)o.unshift(u);for(let l of c.arrays)if(l.nalUnitType===33)for(let u of l.nalUnits)o.unshift(u);for(let l of c.arrays)if(l.nalUnitType===32)for(let u of l.nalUnits)o.unshift(u)}return o.unshift(this.createAud(o,n)),ba(o)}createAud(e,r){if(r==="avc")return new Uint8Array([9,240]);let n=e.find(s=>Qt(s[0])<32),a=n?n[1]&7:1;return new Uint8Array([70,a,80])}prepareAudioPacket(e,r,n){let a=e.track.source._codec;if(a==="mp3"||a==="ac3"||a==="eac3"||a==="dts")return r.data;if(e.inputIsAdts===null){let l=n?.decoderConfig?.description;if(l){let u=xt(Q(l)),d=zs(u);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}e.inputIsAdts=!l}if(e.inputIsAdts)return r.data;b(e.adtsHeader),b(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;Ns(e.adtsHeaderBitstream,o);let c=new Uint8Array(o);return c.set(s,0),c.set(r.data,s.byteLength),c}allTracksAreKnown(){for(let e of this.output.tracks)if(!this.closedTracks.has(e)&&!this.trackDatas.some(r=>r.track===e))return!1;return!0}async flushTimestampQueue(e,r=!0){if(e.timestampProcessingQueue.length===0)return;let n=e.timestampProcessingQueue.map(a=>a.presentationTimestamp).sort((a,s)=>a-s);for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a];e.reorderDelay=Math.max(e.reorderDelay,n[a]-s.presentationTimestamp)}for(let a=0;a<e.timestampProcessingQueue.length;a++){let s=e.timestampProcessingQueue[a],o=Math.max(n[a]-e.reorderDelay,e.lastDecodeTimestamp+1/Ue);s.decodeTimestamp=o,s.presentationTimestamp=Math.max(s.presentationTimestamp,o),e.lastDecodeTimestamp=o,e.packetQueue.push(s)}e.timestampProcessingQueue.length=0,r&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.packetQueue.length===0&&!this.closedTracks.has(s.track))break e;s.packetQueue.length>0&&s.packetQueue[0].presentationTimestamp<n&&(r=s,n=s.packetQueue[0].presentationTimestamp)}if(!r)break;let a=r.packetQueue.shift();this.writePesPacket(r,a)}e||await this.writer.flush()}writeTables(){b(!this.tablesWritten),this.writePsiSection(ay,pn),this.writePsiSection(Gp,cy(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,r){let n=0,a=!0;for(;n<r.length;){let o=184-(a?1:0),c=r.length-n,l=Math.min(o,c),u;a?(u=this.payloadBuffer.subarray(0,1+l),u[0]=0,u.set(r.subarray(n,n+l),1)):u=r.subarray(n,n+l),this.writeTsPacket(e,a,null,u),n+=l,a=!1}}writePesPacket(e,r){let n=e.track.type==="video",a=n?10:5,s=new Uint8Array(9+a),o=z(s),c=new K(s.subarray(9));zi(o,0,1,!1),s[3]=e.streamId;let l=e.track.type==="video"||8+r.data.length>65535?0:8+r.data.length;o.setUint16(4,l,!1),o.setUint8(6,132),o.setUint8(7,n?192:128),o.setUint8(8,a);let u=Xa(r.presentationTimestamp+this.timestampOffset);if(c.pos=0,c.writeBits(4,n?3:2),c.writeBits(3,Math.floor(u/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(u/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,u%2**15),c.writeBits(1,1),n){b(r.decodeTimestamp!==null);let p=Xa(r.decodeTimestamp+this.timestampOffset);c.writeBits(4,1),c.writeBits(3,Math.floor(p/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(p/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,p%2**15),c.writeBits(1,1)}let d=s.length+r.data.length,m=0,f=!0;for(;m<d;){let p=f,h=d-m,y=f&&r.isKeyframe,g=f&&!e.firstPacketWritten,k=Math.max(0,184-h),T;y||g?T=Math.max(2,k):T=k;let S=null;if(T>0){let x=this.adaptationFieldBuffer;T===1?x[0]=0:(x[0]=T-1,x[1]=Number(g)<<7|Number(y)<<6,x.fill(255,2,T)),S=x.subarray(0,T)}let w=Math.min(184-T,h),A=this.payloadBuffer.subarray(0,w),C=0;if(m<s.length){let x=Math.min(s.length-m,w);A.set(s.subarray(m,m+x),0),C=x}let E=Math.max(0,m-s.length),I=E+(w-C);C<w&&A.set(r.data.subarray(E,I),C),this.writeTsPacket(e.pid,p,S,A),m+=w,f=!1}e.firstPacketWritten=!0}writeTsPacket(e,r,n,a){let s=this.continuityCounters.get(e)??0,o=a.length>0,c=n?o?3:2:o?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(r?16384:0)|e&8191,!1),this.packetBuffer[3]=c<<4|s&15,o&&this.continuityCounters.set(e,s+1&15);let l=4;n&&(this.packetBuffer.set(n,l),l+=n.length),this.packetBuffer.set(a,l),l+=a.length,l<ze&&this.packetBuffer.fill(255,l);let u=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),u)}async onTrackClose(e){let r=await this.mutex.acquire();try{this.closedTracks.add(e);let n=this.trackDatas.find(a=>a.track===e);n&&await this.flushTimestampQueue(n,!1),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets()}finally{r()}}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)this.closedTracks.add(r.track),await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},oy=79764919,Qp=new Uint32Array(256);for(let i=0;i<256;i++){let t=i<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^oy:t<<1;Qp[i]=t>>>0&4294967295}var jp=i=>{let t=4294967295;for(let e=0;e<i.length;e++){let r=i[e];t=(t<<8^Qp[t>>>24^r])>>>0}return t},pn=new Uint8Array(16);{let i=z(pn);pn[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),pn[5]=193,pn[6]=0,pn[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|Gp&8191,!1),i.setUint32(12,jp(pn.subarray(0,12)),!1)}var cy=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=wa.length:c.streamType===135&&(t+=Sa.length);let e=9+t+4,r=new Uint8Array(3+e-4),n=z(r);r[0]=2,n.setUint16(1,45056|e&4095,!1),n.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,n.setUint16(8,65535,!1),n.setUint16(10,61440,!1);let a=12;for(let c of[...i].sort((l,u)=>l.pid-u.pid))r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|wa.length,!1),a+=2,r.set(wa,a),a+=wa.length):c.streamType===135?(n.setUint16(a,61440|Sa.length,!1),a+=2,r.set(Sa,a),a+=Sa.length):(n.setUint16(a,61440,!1),a+=2);let s=jp(r),o=new Uint8Array(r.length+4);return o.set(r,0),z(o).setUint32(r.length,s,!1),o};var el=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU16(t){this.helperView.setUint16(0,t,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(t){this.helperView.setUint32(0,t,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(t){this.helperView.setUint32(0,t,!0),this.helperView.setUint32(4,Math.floor(t/2**32),!0),this.writer.write(this.helper)}writeAscii(t){this.writer.write(Y.encode(t))}};var tl=class extends Pe{constructor(e,r){super(e);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.riffSizePos=null;this.dataSizePos=null;this.factSampleCountPos=null;this.ds64RiffSizePos=null;this.ds64DataSizePos=null;this.ds64SampleCountPos=null;this.format=r,this.isRf64=!!r._options.large,this.appendOnly=!!r._options.appendOnly}async start(){let e=await this.mutex.acquire();try{this.writer=await this.output._getRootWriter(this.appendOnly),this.riffWriter=new el(this.writer);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Re({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.writeHeader(r,r.metadata.decoderConfig),this.sampleRate=r.metadata.decoderConfig.sampleRate,this.headerWritten=!0)}finally{e()}}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{if(this.headerWritten||(Re(n,e.source._codec),b(n),b(n.decoderConfig),this.writeHeader(e,n.decoderConfig),this.sampleRate=n.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,r.timestamp,r.type==="key"),!this.isRf64&&this.writer.getPos()+r.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,r){this.format._options.onHeader&&this.writer.startTrackingWrites();let n,a=e.source._codec,s=Me(a);s.dataType==="ulaw"?n=7:s.dataType==="alaw"?n=6:s.dataType==="float"?n=3:n=1;let o=r.numberOfChannels,c=r.sampleRate,l=8*s.sampleSize,u=s.sampleSize*o,d=o>2||n===1&&l>16,m=this.appendOnly?4294967295:0,f=()=>{this.appendOnly?(this.riffWriter.writeU32(4294967295),this.riffWriter.writeU32(2147483647)):this.riffWriter.writeU64(0)};if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(m)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),f(),this.ds64DataSizePos=this.writer.getPos(),f(),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(d?40:16),this.riffWriter.writeU16(d?65534:n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(l),d){let p={1:4,2:3,3:7,4:51,5:55,6:63,7:1807,8:1599},h=new Uint8Array([0,0,16,0,128,0,0,170,0,56,155,113]);this.riffWriter.writeU16(22),this.riffWriter.writeU16(l),this.riffWriter.writeU32(p[o]??0),this.riffWriter.writeU32(n),this.writer.write(h)}if(n!==1&&!this.appendOnly&&(this.riffWriter.writeAscii("fact"),this.riffWriter.writeU32(4),this.factSampleCountPos=this.writer.getPos(),this.riffWriter.writeU32(0)),!Hr(this.output._metadataTags)){let p=this.format._options.metadataFormat??"info";p==="info"?this.writeInfoChunk(this.output._metadataTags):p==="id3"?this.writeId3Chunk(this.output._metadataTags):Z(p)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(m)),this.format._options.onHeader){let{data:p,start:h}=this.writer.stopTrackingWrites();this.format._options.onHeader(p,h)}}writeInfoChunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let n=new Set,a=(c,l)=>{if(!Ht(l)){O._warn(`Didn't write tag '${c}' because '${l}' is not ISO 8859-1-compatible.`);return}let u=l.length+1,d=new Uint8Array(u);for(let m=0;m<l.length;m++)d[m]=l.charCodeAt(m);this.riffWriter.writeAscii(c),this.riffWriter.writeU32(u),this.writer.write(d),u&1&&this.writer.write(new Uint8Array(1)),n.add(c)};for(let{key:c,value:l}of qt(e))switch(c){case"title":a("INAM",l),n.add("INAM");break;case"artist":a("IART",l),n.add("IART");break;case"album":a("IPRD",l),n.add("IPRD");break;case"trackNumber":{let u=e.tracksTotal!==void 0?`${l}/${e.tracksTotal}`:l.toString();a("ITRK",u),n.add("ITRK")}break;case"genre":a("IGNR",l),n.add("IGNR");break;case"date":a("ICRD",l.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":a("ICMT",l),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"beatsPerMinute":case"description":case"lyrics":case"images":case"creationTime":break;case"raw":break;default:Z(c)}if(e.raw)for(let c in e.raw){let l=e.raw[c];l==null||c.length!==4||n.has(c)||typeof l=="string"&&a(c,l)}let s=this.writer.getPos(),o=s-r-8;this.writer.seek(r+4),this.riffWriter.writeU32(o),this.writer.seek(s),o&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let r=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let a=new Ci(this.writer).writeId3V2Tag(e),s=this.writer.getPos();this.writer.seek(r+4),this.riffWriter.writeU32(a),this.writer.seek(s),a&1&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire();if(!this.headerWritten)throw new Error("Cannot finalize an empty WAVE file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");this.dataSize&1&&!this.appendOnly&&this.writer.write(new Uint8Array(1));let r=this.writer.getPos();this.factSampleCountPos!==null&&(this.writer.seek(this.factSampleCountPos),this.riffWriter.writeU32(Math.min(this.sampleCount,4294967295))),this.appendOnly||(this.isRf64?(b(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),b(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),b(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(b(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),b(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize))),e()}};var Xp=i=>i==="opus"?"Opus":i==="flac"?"fLaC":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"?"mp4a.40.34":i,il=class extends Pe{constructor(e,r){if(!(e._target instanceof ft))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];this.closedTracks=new Set;this.firstPacketTimestamp=null;this.isRelativeToUnixEpoch=!1;this.numWrittenMasterPlaylists=0;this.playlists=[];this.playlistDeclarations=[];this.format=r,this.targetSegmentDuration=r._options.targetDuration??2,this.singleFilePerPlaylist=r._options.singleFilePerPlaylist??!1,this.isLive=r._options.live??!1,this.maxLiveSegmentCount=r._options.maxLiveSegmentCount??1/0,this.mediaTimestampBase=r._options.mediaTimestampBase??10,this.globalTargetDuration=0,this.getPlaylistPath=r._options.getPlaylistPath??(({n})=>`playlist-${n}.m3u8`),this.getSegmentPath=r._options.getSegmentPath??(n=>n.isSingleFile?`segments-${n.playlist.n}${n.format.fileExtension}`:`segment-${n.playlist.n}-${n.n}${n.format.fileExtension}`),this.getInitPath=r._options.getInitPath??(n=>`init-${n.n}${n.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire();try{let r=this.output.tracks.some(g=>g.metadata.isRelativeToUnixEpoch),n=this.output.tracks.some(g=>!g.metadata.isRelativeToUnixEpoch);if(r&&n)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=r;let a=new Map,s=[],o=!1,c=!1,l=!1;for(let g of this.output.tracks){g.type==="video"&&(o=!0);let k=new Map;for(let T of this.output.tracks){if(g===T||!g.canBePairedWith(T))continue;if(g.type===T.type){c||(O._warn(`Illegal pairing of two ${g.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),c=!0);continue}if(g.isVideoTrack()&&g.metadata.hasOnlyKeyPackets||T.isVideoTrack()&&T.metadata.hasOnlyKeyPackets){l||(O._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),l=!0);continue}let S=k.get(T.source._codec);S||k.set(T.source._codec,S=[]),S.push(T)}for(let[,T]of k){let S=T.map(C=>C.id).join("-");s.find(C=>C.key===S)||s.push({name:T[0].type+"-"+(s.length+1),key:S,tracks:T,needsEmit:!1,firstNoUri:!1});let A=a.get(g);A||a.set(g,A=[]),A.push(S)}}let u=o?"video":"audio",d=[],m=[],f=[],p=g=>{let k=[],T=0,S=0,w=!1,A=null,C=-1/0;for(let E of g)E.isVideoTrack()?(T++,w||=(E.metadata.rotation??0)!==0||!!E.metadata.flip||!!E.metadata.transformationMatrix):E.isAudioTrack()&&S++,k.push(E.source._codec);for(let E of Bt(this.format._options.segmentFormat)){let I=E.getSupportedCodecs(),x=E.getSupportedTrackCounts();if(k.some(v=>!I.includes(v))||T<x.video.min||T>x.video.max||S<x.audio.min||S>x.audio.max)continue;let P=0;w&&E.supportsVideoTransformationMetadata&&P++,P>C&&(A=E,C=P)}return A};for(let g of this.output.tracks){let k=a.get(g);if(k){if(b(k.length>0),g.type!==u)continue;for(let T of k){let S=s.find(w=>w.key===T);if(b(S),k.length===1&&S.tracks.length===1){let w=a.get(S.tracks[0]);if(b(w!==void 0),w.length===1){let A=s.find(C=>C.key===w[0]);if(A.tracks.length===1&&(b(A.tracks[0]===g),!!p([g,S.tracks[0]]))){d.push({tracks:[g,S.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[g],linkedGroup:S}),S.needsEmit=!0}}else g.type==="video"?m.push(g):g.type==="audio"&&f.push(g)}let h=({metadata:g})=>{let k="";return k+=`${g.languageCode??le}-`,k+=`${g.name??""}-`,k+=`${g.disposition?.default??!0}-`,k+=`${g.disposition?.primary??!1}-`,k+=`${g.disposition?.forced??!1}-`,k};if(m.length>0){let g=m.filter(S=>S.isVideoTrack()&&S.metadata.hasOnlyKeyPackets),k=m.filter(S=>!g.includes(S));if(new Set(k.map(h)).size>1){let S={key:k.map(w=>w.id).join("-"),name:"video-"+(s.length+1),tracks:k,needsEmit:!0,firstNoUri:!0};s.push(S),d.push({tracks:[k[0]],linkedGroup:S});for(let w of g)d.push({tracks:[w],linkedGroup:null})}else for(let S of m)d.push({tracks:[S],linkedGroup:null})}if(f.length>0)if(new Set(f.map(h)).size>1){let k={key:f.map(T=>T.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[f[0]],linkedGroup:k})}else for(let k of f)d.push({tracks:[k],linkedGroup:null});let y=async g=>{if(g.some(A=>this.playlists.some(C=>C.tracks.includes(A))))throw new Error("Internal error: track is already registered in a playlist.");let k=p(g);b(k);let T=this.playlists.length+1,S=await this.getPlaylistPath({n:T,tracks:g,segmentFormat:k});ly(S);let w={id:this.playlists.length+1,path:S,tracks:g,segmentFormat:k,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new Ee};return this.playlists.push(w),w};for(let g of s)if(g.needsEmit)for(let k=0;k<g.tracks.length;k++){let T=g.tracks[k],S=this.playlists.find(w=>w.tracks[0].id===T.id);S??=await y([T]),this.playlistDeclarations.push({playlist:S,groupId:g.name,noUri:g.firstNoUri&&k===0,references:[]})}for(let g of d){let k=this.playlists.find(T=>T.tracks[0].id===g.tracks[0].id);k??=await y(g.tracks),this.playlistDeclarations.push({playlist:k,groupId:null,noUri:!1,references:g.linkedGroup?this.playlistDeclarations.filter(T=>T.groupId===g.linkedGroup.name):[]})}for(let g of this.output.tracks)g.isVideoTrack()&&g.metadata.decoderConfig?this.getVideoTrackData(g,g.metadata.primingPacket??null,{decoderConfig:g.metadata.decoderConfig}):g.isAudioTrack()&&g.metadata.decoderConfig&&this.getAudioTrackData(g,g.metadata.primingPacket??null,{decoderConfig:g.metadata.decoderConfig})}finally{e()}}async getMimeType(){return Cr}allTracksAreKnown(e){for(let r of e.tracks)if(!this.closedTracks.has(r)&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.playlists.find(a=>a.tracks.includes(e));b(r);let n=await r.mutex.acquire();try{this.closedTracks.add(e),r.done||await this.advancePlaylist(r)}finally{n()}}getVideoTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;_r(n,e.source._codec),b(n),b(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return b(s.length===1),a={track:e,packets:[],playlist:s[0],info:{type:"video",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}getAudioTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;Re(n,e.source._codec),b(n),b(n?.decoderConfig);let s=this.playlists.filter(o=>o.tracks.includes(e));return b(s.length===1),a={track:e,packets:[],playlist:s[0],info:{type:"audio",decoderConfig:n.decoderConfig,primingPacket:r}},this.trackDatas.push(a),a}async addEncodedVideoPacket(e,r,n){let a=this.getVideoTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),this.firstPacketTimestamp??=r.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addEncodedAudioPacket(e,r,n){let a=this.getAudioTrackData(e,r,n),s=a.playlist,o=await s.mutex.acquire();try{this.validateTimestamp(e,r.timestamp,r.type==="key"),a.packets.push(r),this.firstPacketTimestamp??=r.timestamp,s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=r.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,r.timestamp)),await this.advancePlaylist(s)}finally{o()}}async addSubtitleCue(e,r,n){throw new Error("Unreachable.")}async advancePlaylist(e){if(b(!e.done),!this.allTracksAreKnown(e))return;let r=this.trackDatas.filter(u=>e.tracks.includes(u.track)),n=r.every(u=>this.closedTracks.has(u.track));if(e.currentSegmentStartTimestamp===null){n&&await this.onPlaylistDone(e);return}let a=r.find(u=>u.info.type==="video"),s=r.find(u=>u.info.type==="audio"),o=!!a&&this.closedTracks.has(a.track),c=!!s&&this.closedTracks.has(s.track),l=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;for(;;){let u=e.currentSegmentStartTimestamp+this.targetSegmentDuration,d=0,m=0;if(a&&(!o||a.packets.length>0)){let x=a.packets.every(_=>_.timestamp<u),P=null,v=null;if(x&&!l){if(!o)return}else for(let _=0;_<a.packets.length;_++){let M=a.packets[_];if(P!==null&&M.timestamp>u||_>0&&M.type==="key"&&(P=M,v=_,l))break}if(v!==null){if(d=v,s){let _=s.packets.findIndex(M=>M.timestamp>=P.timestamp);if(_!==-1)m=_;else if(c)m=s.packets.length;else return}}else{if(!o)return;d=a.packets.length;let _=Hd(a.packets,U=>U.timestamp),M=a.packets[_];if(b(M),s)if(M.timestamp<u){let U=s.packets.findIndex(N=>N.timestamp>=u);if(U!==-1)m=U;else if(c)m=s.packets.length;else return}else{let U=s.packets.findIndex(N=>N.timestamp>M.timestamp);if(U!==-1)m=U;else if(c)m=s.packets.length;else return}}}else if(s&&(!c||s.packets.length>0))if(s.packets.every(P=>P.timestamp<u))if(c)m=s.packets.length;else return;else{let P=lr(s.packets,v=>v.timestamp<=u);m=Math.max(P,1)}if(d===0&&m===0){n&&await this.onPlaylistDone(e);return}let f=null,p,h;b(this.output._target instanceof ft);let y=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let x={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:rl(e)};p=await this.getSegmentPath(x),$p(p),h=ve(ve(y.rootPath,e.path),p);let P=await this.output._getTarget({path:h,isRoot:!1,mimeType:e.segmentFormat.mimeType}),v=null;if(e.segmentFormat._isFragmentedIsobmff()){v={output:new Or({format:e.segmentFormat,target:P}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},P.on("write",({end:U})=>{v.currentFileSize=Math.max(v.currentFileSize,U)});let _=v.output._muxer;_.minimumFragmentDuration=1/0;let M=_.formatOptions.onMoof;_.formatOptions.onMoof=(U,N,L)=>{v.firstMoofPosition=N,M?.(U,N,L),_.formatOptions.onMoof=M},a&&(v.videoSource=new ri(a.track.source._codec),v.output.addVideoTrack(v.videoSource,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),s&&(v.audioSource=new ii(s.track.source._codec),v.output.addAudioTrack(v.audioSource,{...s.track.metadata,decoderConfig:s.info.decoderConfig,primingPacket:s.info.primingPacket??void 0})),await v.output.start()}else P._start();e.singleFile={target:P,path:p,nextOffset:0,info:x,fragmentedIsobmffOutput:v}}else p=e.singleFile.path,h=ve(ve(y.rootPath,e.path),p);else f={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:rl(e)},p=await this.getSegmentPath(f),$p(p),h=ve(ve(y.rootPath,e.path),p),e.nextSegmentId++;let g=0,k=null,T=-1/0,S=null,w=null,A=null;try{if(e.singleFile?.fragmentedIsobmffOutput)S=e.singleFile.fragmentedIsobmffOutput.output,w=e.singleFile.fragmentedIsobmffOutput.videoSource,A=e.singleFile.fragmentedIsobmffOutput.audioSource;else{if(S=new Or({format:e.segmentFormat._withoutXingHeader(),target:new ft(h,async x=>{let P={...x,isRoot:!1};if(x.isRoot)if(e.singleFile){let v=e.singleFile.target.slice(e.singleFile.nextOffset);return v.on("write",({end:_})=>g=Math.max(g,_)),v}else{let v=await this.output._getTarget(P);return k=v,v.on("write",({end:_})=>g=Math.max(g,_)),v}return this.output._getTarget(P)}),initTarget:async()=>{if(e.initSegment)return new Oi;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let x=e.singleFile.target.slice(e.singleFile.nextOffset);return x.on("write",({end:P})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,P)}),x.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),x}else{let x=rl(e),P=await this.getInitPath(x);uy(P),e.initSegment={path:P,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let v=ve(ve(y.rootPath,e.path),P),_=await this.output._getTarget({path:v,isRoot:!1,mimeType:e.segmentFormat.mimeType});return _.on("write",({end:M})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,M)}),_.on("finalized",()=>{this.format._options.onInit?.(_,x)}),_}}}),a&&(w=new ri(a.track.source._codec),S.addVideoTrack(w,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0,maximumPacketCount:d})),s&&(A=new ii(s.track.source._codec),S.addAudioTrack(A,{...s.track.metadata,decoderConfig:s.info.decoderConfig,primingPacket:s.info.primingPacket??void 0,maximumPacketCount:m}),!e.segmentFormat.supportsTimestampedMediaData&&m>0)){let x=this.toMediaTimestamp(s.packets[0].timestamp),P=Xa(x),v=new Uint8Array(zt.length+1+8);v.set(Y.encode(zt),0);let _=z(v);_.setUint32(zt.length+1,Math.floor(P/2**32)),_.setUint32(zt.length+5,P%2**32),S.setMetadataTags({raw:{PRIV:v}})}await S.start()}if(a){b(w);let x={decoderConfig:a.info.decoderConfig};for(let P=0;P<d;P++){let v=a.packets[P],_=v.clone({timestamp:this.toMediaTimestamp(v.timestamp)});await w.add(_,x),T=Math.max(T,v.timestamp+v.duration)}}if(s){b(A);let x={decoderConfig:s.info.decoderConfig};for(let P=0;P<m;P++){let v=s.packets[P],_=v.clone({timestamp:this.toMediaTimestamp(v.timestamp)});await A.add(_,x),T=Math.max(T,v.timestamp+v.duration)}}e.singleFile?.fragmentedIsobmffOutput?(await e.singleFile.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.singleFile.fragmentedIsobmffOutput.firstMoofPosition!==null&&!e.initSegment&&(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),g=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await S.finalize()}catch(x){throw await S?.cancel(),x}f&&(b(k),this.format._options.onSegment?.(k,f)),d>0&&(b(a),a.packets.splice(0,d)),m>0&&(b(s),s.packets.splice(0,m));let C=1/0;a&&a.packets.length>0&&(C=a.packets[0].timestamp),s&&s.packets.length>0&&(C=Math.min(C,s.packets[0].timestamp));let E=C<1/0?C:T;b(Number.isFinite(E));let I=E-e.currentSegmentStartTimestamp;if(b(I>=0),e.writtenSegments.push({path:p,duration:I,timestamp:e.currentSegmentStartTimestamp,byteSize:g,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:f??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,I),e.currentSegmentStartTimestamp=E,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=g),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let x=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(b(x.info),this.format._options.onSegmentPopped?.(x.path,x.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}toMediaTimestamp(e){return b(this.firstPacketTimestamp!==null),e-this.firstPacketTimestamp+this.mediaTimestampBase}async onPlaylistDone(e){b(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),this.isLive&&(await this.writePlaylist(e),e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist())}updatePlaylistBitrates(e,r){let n=e.writtenSegments,a=0,s=0,o=0;for(let l=0;l<n.length;l++){o+=n[l].duration;let u=0,d=0;for(let m=l;m<n.length&&(u+=n[m].byteSize,d+=n[m].duration,d>=.5*r&&d<=1.5*r&&(a=Math.max(a,8*u/d)),!(d>1.5*r));m++);}if(a===0)for(let l of n){let u=l.duration||1;a=Math.max(a,8*l.byteSize/u)}for(let l of n)s+=8*l.byteSize;let c=s/(o||1);if(n.length===0)for(let l of e.tracks){let u=this.trackDatas.find(m=>m.track===l),d=l.source._nominalBitrate??l.metadata.bitrate??0;if(c+=l.source._nominalBitrate??l.metadata.averageBitrate??0,d===0){let m=new de("medium");if(l.isVideoTrack()){let f=u?.info.decoderConfig;d=m._toVideoBitrate(l.source._codec,f?.codedWidth??1920,f?.codedHeight??1080)}else if(l.isAudioTrack()){let f=u?.info.decoderConfig;d=m._toAudioBitrate(l.source._codec,f?.numberOfChannels??2)??0}}a+=d}e.peakBitrate=a,e.averageBitrate=c}async writePlaylist(e){b(this.output._target instanceof ft);let r=this.output._target,n=Math.max(Math.ceil(+(this.isLive?this.targetSegmentDuration:this.globalTargetDuration).toFixed(12)),1);this.updatePlaylistBitrates(e,n);let a=!1;for(let m of e.writtenSegments)a||=m.byteOffset!==null;let s=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,o=3;(s||a)&&(o=4),e.initSegment&&(o=5),e.initSegment&&!s&&(o=6);let c=ve(r.rootPath,e.path),l=`#EXTM3U
|
|
20
20
|
#EXT-X-VERSION:${o}
|
|
21
21
|
`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
|
|
22
22
|
`)+`#EXT-X-TARGETDURATION:${n}
|
|
@@ -31,14 +31,14 @@ ${r.notes??""}`;l=this.createInternalChunk(u,r.timestamp,r.duration,"key",d.trim
|
|
|
31
31
|
`:"")+`${m.path}
|
|
32
32
|
`).join("")+(e.done?(e.writtenSegments.length>0?`
|
|
33
33
|
`:"")+`#EXT-X-ENDLIST
|
|
34
|
-
`:"");this.format._options.onPlaylist?.(l,
|
|
35
|
-
`,n=!1,a=null,s=0,o=!1,c=new Set;for(let u of this.playlistDeclarations)if(u.groupId===null){let d=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,m=[];for(let w of u.playlist.tracks){let C=this.trackDatas.find(E=>E.track===w)?.info.decoderConfig.codec??w.source._codec;m.push(Xp(C))}let f=0,p=0,
|
|
34
|
+
`:"");this.format._options.onPlaylist?.(l,rl(e));let u=await this.output._getTarget({path:c,isRoot:!1,mimeType:Cr}),d=new Br(u,!0);d.start(),d.write(Y.encode(l)),await d.flush(),await d.finalize()}async writeMasterPlaylist(){b(this.output._target instanceof ft);let e=this.output._target,r=`#EXTM3U
|
|
35
|
+
`,n=!1,a=null,s=0,o=!1,c=new Set;for(let u of this.playlistDeclarations)if(u.groupId===null){let d=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,m=[];for(let w of u.playlist.tracks){let C=this.trackDatas.find(E=>E.track===w)?.info.decoderConfig.codec??w.source._codec;m.push(Xp(C))}let f=0,p=0,h=u.references.some(w=>w.playlist===u.playlist);for(let w of u.references){for(let A of w.playlist.tracks){let E=this.trackDatas.find(I=>I.track===A)?.info.decoderConfig.codec??A.source._codec;m.push(Xp(E))}b(w.playlist.peakBitrate!==null),f=Math.max(f,w.playlist.peakBitrate),p=Math.max(p,w.playlist.averageBitrate??0)}b(u.playlist.peakBitrate!==null);let y=h?0:u.playlist.peakBitrate,g=h?0:u.playlist.averageBitrate??0,k=y+f,T=g+p;n||(r+=`
|
|
36
36
|
`,n=!0),d?r+="#EXT-X-I-FRAME-STREAM-INF:":r+="#EXT-X-STREAM-INF:",r+=`BANDWIDTH=${Math.ceil(k)}`,T>0&&(r+=`,AVERAGE-BANDWIDTH=${Math.ceil(T)}`),r+=`,CODECS="${[...new Set(m)].join(",")}"`;let S=u.playlist.tracks.find(w=>w.isVideoTrack());if(S?.isVideoTrack()){let A=this.trackDatas.find(C=>C.track===S)?.info.decoderConfig;if(A){b(A.codedWidth!==void 0),b(A.codedHeight!==void 0);let C=A.codedWidth,E=A.codedHeight;if(A.displayAspectWidth!==void 0&&A.displayAspectHeight!==void 0){let I=A.displayAspectWidth*A.codedHeight,x=A.displayAspectHeight*A.codedWidth;I>x?C=Math.round(C*I/x):E=Math.round(E*x/I)}S.metadata.rotation!==void 0&&S.metadata.rotation%180===90&&([C,E]=[E,C]),r+=`,RESOLUTION=${C}x${E}`}!d&&S.metadata.frameRate!==void 0&&(r+=`,FRAME-RATE=${+S.metadata.frameRate.toFixed(3)}`)}if(!d){let w=new Map;for(let A of u.references){b(A.groupId!==null);let C=A.playlist.tracks[0].type;w.set(C,A.groupId)}for(let[A,C]of w)r+=`,${A.toUpperCase()}="${C}"`}d?(r+=`,URI="${u.playlist.path}"`,r+=`
|
|
37
37
|
`):(r+=`
|
|
38
38
|
`,r+=`${u.playlist.path}
|
|
39
|
-
`)}else{b(u.playlist.tracks.length===1);let d=u.playlist.tracks[0],m=d.type,f=d.metadata.name??null,p=d.metadata.languageCode,
|
|
40
|
-
`,o=!1,c.clear()),a=u.groupId,s++,r+=`#EXT-X-MEDIA:TYPE=${m.toUpperCase()},GROUP-ID="${u.groupId}"`,f!==null&&/[\n\r"]/.test(f)&&(O._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),f=null),f??=`${p??u.groupId}-${s}`;let
|
|
41
|
-
`}this.format._options.onMaster?.(r);let l=await this.mutex.acquire();try{let u;if(this.numWrittenMasterPlaylists===0)u=await this.output._getRootWriter(!0);else{let d=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:Cr});u=new Br(d,!0),u.start()}u.write(Y.encode(r)),await u.flush(),await u.finalize(),this.numWrittenMasterPlaylists++}finally{l()}}async tryWriteMasterPlaylist(){b(this.isLive);for(let e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(r=>r.mutex.acquire()))).forEach(r=>r());for(let r of this.output.tracks)this.closedTracks.add(r);await Promise.all(this.playlists.map(r=>r.done?Promise.resolve():this.advancePlaylist(r))),this.isLive||(await Promise.all(this.playlists.map(r=>this.writePlaylist(r))),await this.writeMasterPlaylist())}},ly=i=>{if(typeof i!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},$p=i=>{if(typeof i!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},uy=i=>{if(typeof i!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},tl=i=>({n:i.id,tracks:i.tracks,segmentFormat:i.segmentFormat});var Ne=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>le.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>pe.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>qe.includes(t))}_codecUnsupportedHint(t){return""}_isFragmentedIsobmff(){return!1}_withoutXingHeader(){return this}},hn=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(t.minimumFragmentDuration!==void 0&&(!Ie(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(t.onFtyp!==void 0&&typeof t.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(t.onMoov!==void 0&&typeof t.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(t.onMdat!==void 0&&typeof t.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(t.onMoof!==void 0&&typeof t.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(t.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=t}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(t){return new Qc(t,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},ys=class extends hn{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...le,...Jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qe]}_codecUnsupportedHint(t){return new fn().getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},mn=class extends hn{constructor(t){super(t)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...le,...Jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qe]}},fn=class extends hn{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...le,...pe]}_codecUnsupportedHint(t){return new ys().getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},la=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.minimumClusterDuration!==void 0&&(!Ie(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(t.onEbmlHeader!==void 0&&typeof t.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(t.onSegmentHeader!==void 0&&typeof t.onSegmentHeader!="function")throw new TypeError("options.onSegmentHeader, when provided, must be a function.");if(t.onCluster!==void 0&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new jc(t,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...le,...Jt,...se.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...qe]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},ir=class extends la{constructor(t){super(t)}getSupportedCodecs(){return[...le.filter(t=>["vp8","vp9","av1"].includes(t)),...pe.filter(t=>["opus","vorbis"].includes(t)),...qe]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(t){return new la().getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},il=class i extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.xingHeader!==void 0&&typeof t.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(t.onXingFrame!==void 0&&typeof t.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new $c(t,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}_withoutXingHeader(){return new i({...this._options,xingHeader:!1})}},nl=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.large!==void 0&&typeof t.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(t.metadataFormat!==void 0&&!["info","id3"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(t.onHeader!==void 0&&typeof t.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new el(t,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...se.filter(t=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},al=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maximumPageDuration!==void 0&&(!Ie(t.maximumPageDuration)||t.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(t.onPage!==void 0&&typeof t.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Yc(t,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...pe.filter(t=>["vorbis","opus"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},sl=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.onFrame!==void 0&&typeof t.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Hc(t,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ol=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.onFrame!==void 0&&typeof t.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new qc(t,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},cl=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.timestampOffset!==void 0&&(!Number.isFinite(t.timestampOffset)||t.timestampOffset<0))throw new TypeError("options.timestampOffset, when provided, must be a non-negative number.");if(t.onPacket!==void 0&&typeof t.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Zc(t,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...le.filter(t=>["avc","hevc"].includes(t)),...pe.filter(t=>["aac","mp3","ac3","eac3","dts"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},ll=class extends Ne{constructor(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.segmentFormat instanceof Ne)&&(!Array.isArray(t.segmentFormat)||t.segmentFormat.length===0||!t.segmentFormat.every(e=>e instanceof Ne)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(t.targetDuration!==void 0&&(!Ie(t.targetDuration)||t.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(t.singleFilePerPlaylist!==void 0&&typeof t.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(t.live!==void 0&&typeof t.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(t.live&&t.targetDuration===1/0)throw new TypeError("options.targetDuration must be finite in live mode.");if(t.maxLiveSegmentCount!==void 0&&(!Ie(t.maxLiveSegmentCount)||t.maxLiveSegmentCount<1||Number.isFinite(t.maxLiveSegmentCount)&&!Number.isInteger(t.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(t.mediaTimestampBase!==void 0&&!Number.isFinite(t.mediaTimestampBase))throw new TypeError("options.mediaTimestampBase, when provided, must be a finite number.");if(t.getPlaylistPath!==void 0&&typeof t.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(t.getSegmentPath!==void 0&&typeof t.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(t.getInitPath!==void 0&&typeof t.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(t.onMaster!==void 0&&typeof t.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(t.onPlaylist!==void 0&&typeof t.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(t.onSegment!==void 0&&typeof t.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(t.onInit!==void 0&&typeof t.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(t.onSegmentPopped!==void 0&&typeof t.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new rl(t,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return Cr}getSupportedCodecs(){let t=new Set(Bt(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()));for(let e of Ji)t.delete(e);for(let e of qe)t.delete(e);return[...t]}getSupportedTrackCounts(){let t=!1,e=!1,r=!1;for(let n of Bt(this._options.segmentFormat)){let a=n.getSupportedTrackCounts();t||=a.video.max>0,e||=a.audio.max>0,r||=a.subtitle.max>0}return{video:{min:0,max:t?1/0:0},audio:{min:0,max:e?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return Bt(this._options.segmentFormat).some(t=>t.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let t=Bt(this._options.segmentFormat);return t.some(e=>e.negativeTimestampSupport==="none")?"none":t.some(e=>e.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":t.some(e=>e.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(t){return Ji.includes(t)?"":" Using different segment formats may grant support for this codec."}},ul=class extends Ne{_createMuxer(t){return new Lc(t)}get _name(){return"Null"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:0,max:1/0}}}get fileExtension(){return""}get mimeType(){return"application/x-black-hole"}getSupportedCodecs(){return[...le,...pe,...qe]}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}};var dl=["video","audio","subtitle"],gn=class i{constructor(t,e,r,n,a){this.id=t,this.output=e,this.type=r,this.source=n,this.metadata=a}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrack.");if(this===t)return!1;let e=Bt(this.metadata.group),r=Bt(t.metadata.group);for(let n of e)if(this.type!==t.type&&r.some(o=>n===o)||r.some(o=>n._pairedGroups.has(o)))return!0;return!1}},ks=class extends gn{constructor(t,e,r,n){super(t,e,"video",r,n)}},Ts=class extends gn{constructor(t,e,r,n){super(t,e,"audio",r,n)}},ws=class extends gn{constructor(t,e,r,n){super(t,e,"subtitle",r,n)}},pt=class i{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrackGroup.");if(this===t)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(t),t._pairedGroups.add(this)}},hd=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!Ur(i.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(i.name!==void 0&&typeof i.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(i.disposition!==void 0&&jd(i.disposition),i.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(i.bitrate!==void 0&&(!Number.isFinite(i.bitrate)||i.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(i.averageBitrate!==void 0&&(!Number.isFinite(i.averageBitrate)||i.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(i.group!==void 0&&!(i.group instanceof pt)&&(!Array.isArray(i.group)||i.group.some(t=>!(t instanceof pt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},Or=class extends st{constructor(e){super();this.state="pending";this.defaultTrackGroup=new pt;this.tracks=[];this._onFinalize=null;this._unfinalizedTargets=new Set;this._targetsClosed=!1;this._rootWriterPromise=null;this._startPromise=null;this._cancelPromise=null;this._canceled=te();this._finalizePromise=null;this._mutex=new Ee;this._metadataTags={};this._rootTarget=null;this._rootTargetPromise=null;this._firstMediaStreamTimestamp=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Ne))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Oe||e.target instanceof ft))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Oe&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Oe)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Oe&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let r=this._getRootTarget();if(R(r))throw r.catch(()=>{}),new TypeError(e);return r}_getTargetValidated(e){b(this._target instanceof ft);let r=this._target.getTarget(e),n=a=>{if(!(a instanceof Oe))throw new TypeError("getTarget must return a Target.");return a};return R(r)?r.then(n):n(r)}async _getTarget(e){b(this._target instanceof ft);let r=await this._getTargetValidated(e);if(this._emit("target",{target:r,request:e,isRoot:e.isRoot}),this._targetsClosed)throw await r._close(),new Error(this.state==="canceled"?"Output has been canceled.":"Output has already been finalized.");return this._rememberTarget(r),r}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(b(this._initTarget!==null),this._initTarget instanceof Oe)return this._initTarget;let e=await this._initTarget();if(!(e instanceof Oe))throw new TypeError("initTarget must return or resolve to a Target.");return this._targetsClosed?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Oe)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},r=this._getTargetValidated(e),n=a=>(this._targetsClosed?a._close().catch(()=>{}):this._rememberTarget(a),this._emit("target",{target:a,request:e,isRoot:!0}),this._rootTarget=a,a);return R(r)?this._rootTargetPromise=r.then(n):n(r)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let r=await this._getRootTarget(),n=new Br(r,typeof e=="boolean"?e:e(r));return n.start(),n})()}addVideoTrack(e,r={}){if(!(e instanceof Ir))throw new TypeError("source must be a VideoSource.");if(hd(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(r.transformationMatrix!==void 0&&(!Array.isArray(r.transformationMatrix)||r.transformationMatrix.length!==9||!r.transformationMatrix.every(a=>Number.isFinite(a))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);if(r.hasOnlyKeyPackets!==void 0&&typeof r.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(r.canBeTransparent!==void 0&&typeof r.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(r.decoderConfig!==void 0&&_r({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof ee))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new ks(this.tracks.length+1,this,e,n))}addAudioTrack(e,r={}){if(!(e instanceof vr))throw new TypeError("source must be an AudioSource.");if(hd(r),r.decoderConfig!==void 0&&Re({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof ee))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new Ts(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,r={}){if(!(e instanceof ln))throw new TypeError("source must be a SubtitleSource.");hd(r);let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new ws(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(ma(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let r=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((o,c)=>o+(c.type===e.type?1:0),0),a=r[e.type].max;if(n===a)throw new Error(a===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${a} ${e.type} track${a===1?"":"s"}.`);let s=r.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} track${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let n of dl){let a=this.tracks.reduce((o,c)=>o+(c.type===n?1:0),0),s=e[n].min;if(a<s)return!1}let r=e.total.min;return!(this.tracks.length<r)}async start(){let e=this.format.getSupportedTrackCounts();for(let n of dl){let a=this.tracks.reduce((o,c)=>o+(c.type===n?1:0),0),s=e[n].min;if(a<s)throw new Error(s===e[n].max?`${this.format._name} requires exactly ${s} ${n} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${n} track${s===1?"":"s"}.`)}let r=e.total.min;if(this.tracks.length<r)throw new Error(r===e.total.max?`${this.format._name} requires exactly ${r} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} track${r===1?"":"s"}.`);if(this._cancelPromise||this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(O._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let n=this._mutex.acquire();try{try{await this._muxer.start();let a=this.tracks.map(s=>s.source._start());await Promise.all(a)}finally{(await n)()}}catch(a){throw await this.cancel(),a}})()}getMimeType(){return Promise.race([this._muxer.getMimeType(),this._canceled.promise.then(()=>{throw new Error("Output has been canceled.")})])}async cancel(){if(this._cancelPromise||this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalized"){O._warn("Output has already been finalized.");return}else if(this._finalizePromise)return this._finalizePromise.catch(()=>{});return this._cancelPromise=(async()=>{let e=await this._mutex.acquire();try{this.state="canceled",this._canceled.resolve();let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0).catch(()=>{}));await Promise.all(r),this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(n=>n._close().catch(()=>{}))),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this._cancelPromise||this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(O._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{let e=await this._mutex.acquire();try{this.state="finalizing";let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(r),await this._muxer.finalize(),this._rootWriterPromise){let n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(r){throw this.state="canceled",this._canceled.resolve(),r}finally{this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};var ml=i=>{if(!i||typeof i!="object")throw new TypeError("options.video, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!le.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${le.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof ue))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof ue)&&(!Number.isInteger(t)||t<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(i?.width!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(i?.height!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(i?.fit!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(i?.width!==void 0&&i.height!==void 0&&i.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(i?.rotate!==void 0&&![0,90,180,270].includes(i.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(i?.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if(i?.allowTransformationMetadata!==void 0&&typeof i.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if(i?.allowRotationMetadata!==void 0&&typeof i.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(i?.crop!==void 0&&ki(i.crop,"options.video."),i?.frameRate!==void 0&&(!Number.isFinite(i.frameRate)||i.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(i?.alpha!==void 0&&!["discard","keep"].includes(i.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(i?.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(i?.processedWidth!==void 0&&(!Number.isInteger(i.processedWidth)||i.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(i?.processedHeight!==void 0&&(!Number.isInteger(i.processedHeight)||i.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(i?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i?.group!==void 0&&!(i.group instanceof pt||Array.isArray(i.group)&&i.group.every(e=>e instanceof pt)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(i?.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("options.video.maximumPacketCount, when provided, must be a non-negative integer.")},fl=i=>{if(!i||typeof i!="object")throw new TypeError("options.audio, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!pe.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${pe.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof ue))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof ue)&&(!Number.isInteger(t)||t<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(i?.numberOfChannels!==void 0&&(!Number.isInteger(i.numberOfChannels)||i.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(i?.sampleRate!==void 0&&(!Number.isInteger(i.sampleRate)||i.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(i?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(i?.processedNumberOfChannels!==void 0&&(!Number.isInteger(i.processedNumberOfChannels)||i.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(i?.processedSampleRate!==void 0&&(!Number.isInteger(i.processedSampleRate)||i.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(i?.group!==void 0&&!(i.group instanceof pt||Array.isArray(i.group)&&i.group.every(e=>e instanceof pt)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(i?.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("options.audio.maximumPacketCount, when provided, must be a non-negative integer.")},gd=2,bd=48e3,dy=256,pl=class i{constructor(t){this._state="idle";this._timestampOffset=0;this._timestampOffsetAdjusted=!1;this._copyTimestampPossible=new Map;this._copyStartPackets=new Map;this._trackDurations=new Map;this._nextOutputTrackId=0;this._outputTrackIds=[];this._outputOwnTrackGroups=[];this._trackPumps=[];this._composable=!1;this._executed=!1;this._executionUntil=1/0;this._pauseRequested=!1;this._synchronizer=new yd(this);this._totalDuration=null;this._maxTimestamps=new Map;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this._lastProcessedTime=0;this.isValid=!1;this.utilizedTracks=[];this.discardedTracks=[];if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.input instanceof vi))throw new TypeError("options.input must be an Input.");if(!(t.output instanceof Or))throw new TypeError("options.output must be an Output.");if(t.tracks!==void 0&&t.tracks!=="all"&&t.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(t.composable!==void 0&&typeof t.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(t.copy!==void 0&&t.copy!==!1){if(!t.copy||typeof t.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(t.copy.mode!==void 0&&!["forced","preferred"].includes(t.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(t.copy.shiftTolerance!==void 0&&(!Ie(t.copy.shiftTolerance)||t.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(t.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(t.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(t.copy.boundaryTolerance!==void 0&&(!Ie(t.copy.boundaryTolerance)||t.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}let e=t.composable??!1;if(e){if(t.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(t.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(t.output.tracks.length>0||Object.keys(t.output._metadataTags).length>0||t.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(t.video!==void 0&&typeof t.video!="function")if(Array.isArray(t.video))for(let r of t.video)ml(r);else ml(t.video);if(t.audio!==void 0&&typeof t.audio!="function")if(Array.isArray(t.audio))for(let r of t.audio)fl(r);else fl(t.audio);if(t.trim!==void 0&&(!t.trim||typeof t.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(t.trim?.start!==void 0&&!Number.isFinite(t.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(t.trim?.end!==void 0&&!Ie(t.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(t.trim?.start!==void 0&&t.trim.end!==void 0&&t.trim.start>=t.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(t.tags!==void 0&&(typeof t.tags!="object"||!t.tags)&&typeof t.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof t.tags=="object"&&ma(t.tags),t.showWarnings!==void 0&&typeof t.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=t,this._copyMode=t.copy===!1?!1:t.copy?.mode??"preferred",this._copyTimestampShiftTolerance=t.copy===!1?0:t.copy?.shiftTolerance??0,this._copyBoundaryPolicy=t.copy===!1?"expand":t.copy?.boundaryPolicy??"expand",this._copyBoundaryTolerance=t.copy===!1?1/0:t.copy?.boundaryTolerance??1/0,this._composable=e,this.input=t.input,this.output=t.output}get state(){return this._state}static async init(t){let e=new i(t);return await e._init(),e}async _init(){let t=await this.input.getFormat(),e,r=this._options.tracks;if(r===void 0&&(r=t.name.includes("(HLS)")?"primary":"all"),r==="all")e=await this.input.getTracks();else if(r==="primary"){let o=await this.input.getPrimaryVideoTrack(),c=await this.input.getPrimaryAudioTrack();e=[o,c].filter(l=>l!==null)}else Z(r),b(!1);let n=this.output.format.getSupportedTrackCounts(),a=[],s=[];for(let o of e){let c;if(o.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){let d=await this._options.video(o,o.number)??{};if(Array.isArray(d))for(let m of d)ml(m);else ml(d);c=Array.isArray(d)?d:[d]}else c=Array.isArray(this._options.video)?this._options.video:[this._options.video];else c=[{}];else if(o.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){let d=await this._options.audio(o,o.number)??{};if(Array.isArray(d))for(let m of d)fl(m);else fl(d);c=Array.isArray(d)?d:[d]}else c=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else c=[{}];else b(!1);let l=c.filter(d=>d.discard);for(let d of l)this.discardedTracks.push({track:o,reason:"discarded_by_user",trackOptions:d});if(c.length===l.length){c.length===0&&this.discardedTracks.push({track:o,reason:"discarded_by_user",trackOptions:{}});continue}let u=c.filter(d=>!d.discard);a.push(o),s.push(u)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(a),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let o=0;o<a.length;o++){let c=a[o],l=s[o];for(let u of l){if(this.output.tracks.length===n.total.max){this.discardedTracks.push({track:c,reason:"max_track_count_reached",trackOptions:u});continue}if(this.output.tracks.reduce((f,p)=>f+(p.type===c.type?1:0),0)===n[c.type].max){this.discardedTracks.push({track:c,reason:"max_track_count_of_type_reached",trackOptions:u});continue}let m=this._nextOutputTrackId++;c.isVideoTrack()?await this._processVideoTrack(c,u,m):c.isAudioTrack()?await this._processAudioTrack(c,u,m):b(!1)}}for(let o=0;o<this.utilizedTracks.length-1;o++)for(let c=o+1;c<this.utilizedTracks.length;c++){let l=this.utilizedTracks[o],u=this.utilizedTracks[c],d=this._outputOwnTrackGroups[o],m=this._outputOwnTrackGroups[c];b(d!==void 0),b(m!==void 0),d&&m&&l.canBePairedWith(u)&&d.pairWith(m)}if(!this._composable){let o={...await this.input.getMetadataTags()};delete o.creationTime;let c;if(this._options.tags){let d=typeof this._options.tags=="function"?await this._options.tags(o):this._options.tags;ma(d),c=d}else c=o;let l=t.mimeType===this.output.format.mimeType;o.raw===c.raw&&!l&&delete c.raw,this.output.setMetadataTags(c)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let o=[],c=this.discardedTracks.filter(l=>l.reason!=="discarded_by_user");c.length>0&&o.push("Some tracks had to be discarded from the conversion:",c),this.isValid||(o.length>0&&o.push(`
|
|
39
|
+
`)}else{b(u.playlist.tracks.length===1);let d=u.playlist.tracks[0],m=d.type,f=d.metadata.name??null,p=d.metadata.languageCode,h=d.metadata.disposition;(a===null||u.groupId!==a)&&(s=0,r+=`
|
|
40
|
+
`,o=!1,c.clear()),a=u.groupId,s++,r+=`#EXT-X-MEDIA:TYPE=${m.toUpperCase()},GROUP-ID="${u.groupId}"`,f!==null&&/[\n\r"]/.test(f)&&(O._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),f=null),f??=`${p??u.groupId}-${s}`;let y=f;for(let S=2;c.has(y);S++)y=`${f} (${S})`;c.add(y),r+=`,NAME="${y}"`,p!==void 0&&(r+=`,LANGUAGE="${p}"`);let g=h?.primary??!1,k=h?.default??!0,T=h?.forced??!1;if(g&&!o&&(r+=",DEFAULT=YES",o=!0),(g||k)&&(r+=",AUTOSELECT=YES"),T&&m==="subtitle"&&(r+=",FORCED=YES"),m==="audio"){let w=this.trackDatas.find(A=>A.track===d)?.info.decoderConfig;w&&(r+=`,CHANNELS="${w.numberOfChannels}"`)}u.noUri||(r+=`,URI="${u.playlist.path}"`),r+=`
|
|
41
|
+
`}this.format._options.onMaster?.(r);let l=await this.mutex.acquire();try{let u;if(this.numWrittenMasterPlaylists===0)u=await this.output._getRootWriter(!0);else{let d=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:Cr});u=new Br(d,!0),u.start()}u.write(Y.encode(r)),await u.flush(),await u.finalize(),this.numWrittenMasterPlaylists++}finally{l()}}async tryWriteMasterPlaylist(){b(this.isLive);for(let e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(r=>r.mutex.acquire()))).forEach(r=>r());for(let r of this.output.tracks)this.closedTracks.add(r);await Promise.all(this.playlists.map(r=>r.done?Promise.resolve():this.advancePlaylist(r))),this.isLive||(await Promise.all(this.playlists.map(r=>this.writePlaylist(r))),await this.writeMasterPlaylist())}},ly=i=>{if(typeof i!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},$p=i=>{if(typeof i!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},uy=i=>{if(typeof i!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},rl=i=>({n:i.id,tracks:i.tracks,segmentFormat:i.segmentFormat});var Ne=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}get requiresMaximumPacketCount(){return!1}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>ue.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>pe.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>qe.includes(t))}_codecUnsupportedHint(t){return""}_isFragmentedIsobmff(){return!1}_withoutXingHeader(){return this}},hn=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(t.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(t.minimumFragmentDuration!==void 0&&(!Ie(t.minimumFragmentDuration)||t.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(t.onFtyp!==void 0&&typeof t.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(t.onMoov!==void 0&&typeof t.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(t.onMdat!==void 0&&typeof t.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(t.onMoof!==void 0&&typeof t.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(t.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=t}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}get requiresMaximumPacketCount(){return this._options.fastStart==="reserve"}_createMuxer(t){return new jc(t,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},ks=class extends hn{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ue,...Jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qe]}_codecUnsupportedHint(t){return new fn().getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},mn=class extends hn{constructor(t){super(t)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ue,...Jt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...qe]}},fn=class extends hn{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ue,...pe]}_codecUnsupportedHint(t){return new ks().getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},ua=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.minimumClusterDuration!==void 0&&(!Ie(t.minimumClusterDuration)||t.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(t.onEbmlHeader!==void 0&&typeof t.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(t.onSegmentHeader!==void 0&&typeof t.onSegmentHeader!="function")throw new TypeError("options.onSegmentHeader, when provided, must be a function.");if(t.onCluster!==void 0&&typeof t.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Xc(t,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...ue,...Jt,...se.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...qe]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},ir=class extends ua{constructor(t){super(t)}getSupportedCodecs(){return[...ue.filter(t=>["vp8","vp9","av1"].includes(t)),...pe.filter(t=>["opus","vorbis"].includes(t)),...qe]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(t){return new ua().getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},nl=class i extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.xingHeader!==void 0&&typeof t.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(t.onXingFrame!==void 0&&typeof t.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Yc(t,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}_withoutXingHeader(){return new i({...this._options,xingHeader:!1})}},al=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.large!==void 0&&typeof t.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(t.metadataFormat!==void 0&&!["info","id3"].includes(t.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(t.onHeader!==void 0&&typeof t.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new tl(t,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...se.filter(t=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},sl=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maximumPageDuration!==void 0&&(!Ie(t.maximumPageDuration)||t.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(t.onPage!==void 0&&typeof t.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Zc(t,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...pe.filter(t=>["vorbis","opus"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},ol=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.onFrame!==void 0&&typeof t.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Wc(t,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},cl=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.appendOnly!==void 0&&typeof t.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(t.onFrame!==void 0&&typeof t.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Kc(t,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}},ll=class extends Ne{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.timestampOffset!==void 0&&(!Number.isFinite(t.timestampOffset)||t.timestampOffset<0))throw new TypeError("options.timestampOffset, when provided, must be a non-negative number.");if(t.onPacket!==void 0&&typeof t.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new Jc(t,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...ue.filter(t=>["avc","hevc"].includes(t)),...pe.filter(t=>["aac","mp3","ac3","eac3","dts"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},ul=class extends Ne{constructor(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.segmentFormat instanceof Ne)&&(!Array.isArray(t.segmentFormat)||t.segmentFormat.length===0||!t.segmentFormat.every(e=>e instanceof Ne)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(t.targetDuration!==void 0&&(!Ie(t.targetDuration)||t.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(t.singleFilePerPlaylist!==void 0&&typeof t.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(t.live!==void 0&&typeof t.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(t.live&&t.targetDuration===1/0)throw new TypeError("options.targetDuration must be finite in live mode.");if(t.maxLiveSegmentCount!==void 0&&(!Ie(t.maxLiveSegmentCount)||t.maxLiveSegmentCount<1||Number.isFinite(t.maxLiveSegmentCount)&&!Number.isInteger(t.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(t.mediaTimestampBase!==void 0&&!Number.isFinite(t.mediaTimestampBase))throw new TypeError("options.mediaTimestampBase, when provided, must be a finite number.");if(t.getPlaylistPath!==void 0&&typeof t.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(t.getSegmentPath!==void 0&&typeof t.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(t.getInitPath!==void 0&&typeof t.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(t.onMaster!==void 0&&typeof t.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(t.onPlaylist!==void 0&&typeof t.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(t.onSegment!==void 0&&typeof t.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(t.onInit!==void 0&&typeof t.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(t.onSegmentPopped!==void 0&&typeof t.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=t}_createMuxer(t){return new il(t,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return Cr}getSupportedCodecs(){let t=new Set(Bt(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()));for(let e of Ji)t.delete(e);for(let e of qe)t.delete(e);return[...t]}getSupportedTrackCounts(){let t=!1,e=!1,r=!1;for(let n of Bt(this._options.segmentFormat)){let a=n.getSupportedTrackCounts();t||=a.video.max>0,e||=a.audio.max>0,r||=a.subtitle.max>0}return{video:{min:0,max:t?1/0:0},audio:{min:0,max:e?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return Bt(this._options.segmentFormat).some(t=>t.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let t=Bt(this._options.segmentFormat);return t.some(e=>e.negativeTimestampSupport==="none")?"none":t.some(e=>e.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":t.some(e=>e.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(t){return Ji.includes(t)?"":" Using different segment formats may grant support for this codec."}},dl=class extends Ne{_createMuxer(t){return new Hc(t)}get _name(){return"Null"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:0,max:1/0}}}get fileExtension(){return""}get mimeType(){return"application/x-black-hole"}getSupportedCodecs(){return[...ue,...pe,...qe]}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}};var ml=["video","audio","subtitle"],gn=class i{constructor(t,e,r,n,a){this.id=t,this.output=e,this.type=r,this.source=n,this.metadata=a}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrack.");if(this===t)return!1;let e=Bt(this.metadata.group),r=Bt(t.metadata.group);for(let n of e)if(this.type!==t.type&&r.some(o=>n===o)||r.some(o=>n._pairedGroups.has(o)))return!0;return!1}},Ts=class extends gn{constructor(t,e,r,n){super(t,e,"video",r,n)}},ws=class extends gn{constructor(t,e,r,n){super(t,e,"audio",r,n)}},Ss=class extends gn{constructor(t,e,r,n){super(t,e,"subtitle",r,n)}},pt=class i{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof i))throw new TypeError("other must be an OutputTrackGroup.");if(this===t)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(t),t._pairedGroups.add(this)}},pd=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!Ur(i.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(i.name!==void 0&&typeof i.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(i.disposition!==void 0&&jd(i.disposition),i.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(i.bitrate!==void 0&&(!Number.isFinite(i.bitrate)||i.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(i.averageBitrate!==void 0&&(!Number.isFinite(i.averageBitrate)||i.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(i.group!==void 0&&!(i.group instanceof pt)&&(!Array.isArray(i.group)||i.group.some(t=>!(t instanceof pt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},Or=class extends st{constructor(e){super();this.state="pending";this.defaultTrackGroup=new pt;this.tracks=[];this._onFinalize=null;this._unfinalizedTargets=new Set;this._targetsClosed=!1;this._rootWriterPromise=null;this._startPromise=null;this._cancelPromise=null;this._canceled=te();this._finalizePromise=null;this._mutex=new Ee;this._metadataTags={};this._rootTarget=null;this._rootTargetPromise=null;this._firstMediaStreamTimestamp=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Ne))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Oe||e.target instanceof ft))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Oe&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Oe)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Oe&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);let r=this._getRootTarget();if(R(r))throw r.catch(()=>{}),new TypeError(e);return r}_getTargetValidated(e){b(this._target instanceof ft);let r=this._target.getTarget(e),n=a=>{if(!(a instanceof Oe))throw new TypeError("getTarget must return a Target.");return a};return R(r)?r.then(n):n(r)}async _getTarget(e){b(this._target instanceof ft);let r=await this._getTargetValidated(e);if(this._emit("target",{target:r,request:e,isRoot:e.isRoot}),this._targetsClosed)throw await r._close(),new Error(this.state==="canceled"?"Output has been canceled.":"Output has already been finalized.");return this._rememberTarget(r),r}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(b(this._initTarget!==null),this._initTarget instanceof Oe)return this._initTarget;let e=await this._initTarget();if(!(e instanceof Oe))throw new TypeError("initTarget must return or resolve to a Target.");return this._targetsClosed?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Oe)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},r=this._getTargetValidated(e),n=a=>(this._targetsClosed?a._close().catch(()=>{}):this._rememberTarget(a),this._emit("target",{target:a,request:e,isRoot:!0}),this._rootTarget=a,a);return R(r)?this._rootTargetPromise=r.then(n):n(r)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let r=await this._getRootTarget(),n=new Br(r,typeof e=="boolean"?e:e(r));return n.start(),n})()}addVideoTrack(e,r={}){if(!(e instanceof Ir))throw new TypeError("source must be a VideoSource.");if(pd(r),r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw new TypeError(`Invalid video rotation: ${r.rotation}. Has to be 0, 90, 180 or 270.`);if(r.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(r.transformationMatrix!==void 0&&(!Array.isArray(r.transformationMatrix)||r.transformationMatrix.length!==9||!r.transformationMatrix.every(a=>Number.isFinite(a))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");if(r.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${r.frameRate}. Must be a positive number.`);if(r.hasOnlyKeyPackets!==void 0&&typeof r.hasOnlyKeyPackets!="boolean")throw new TypeError("metadata.hasOnlyKeyPackets, when provided, must be a boolean.");if(r.canBeTransparent!==void 0&&typeof r.canBeTransparent!="boolean")throw new TypeError("metadata.canBeTransparent, when provided, must be a boolean.");if(r.decoderConfig!==void 0&&_r({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof ee))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new Ts(this.tracks.length+1,this,e,n))}addAudioTrack(e,r={}){if(!(e instanceof vr))throw new TypeError("source must be an AudioSource.");if(pd(r),r.decoderConfig!==void 0&&Re({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof ee))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(r.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new ws(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,r={}){if(!(e instanceof ln))throw new TypeError("source must be a SubtitleSource.");pd(r);let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new Ss(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(fa(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");let r=this.format.getSupportedTrackCounts(),n=this.tracks.reduce((o,c)=>o+(c.type===e.type?1:0),0),a=r[e.type].max;if(n===a)throw new Error(a===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${a} ${e.type} track${a===1?"":"s"}.`);let s=r.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} track${s===1?"":"s"} in total.`);if(e.isVideoTrack()){let o=this.format.getSupportedVideoCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let o=this.format.getSupportedAudioCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let o=this.format.getSupportedSubtitleCodecs();if(o.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!o.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${o.map(c=>`'${c}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let n of ml){let a=this.tracks.reduce((o,c)=>o+(c.type===n?1:0),0),s=e[n].min;if(a<s)return!1}let r=e.total.min;return!(this.tracks.length<r)}async start(){let e=this.format.getSupportedTrackCounts();for(let n of ml){let a=this.tracks.reduce((o,c)=>o+(c.type===n?1:0),0),s=e[n].min;if(a<s)throw new Error(s===e[n].max?`${this.format._name} requires exactly ${s} ${n} track${s===1?"":"s"}.`:`${this.format._name} requires at least ${s} ${n} track${s===1?"":"s"}.`)}let r=e.total.min;if(this.tracks.length<r)throw new Error(r===e.total.max?`${this.format._name} requires exactly ${r} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} track${r===1?"":"s"}.`);if(this._cancelPromise||this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(O._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let n=this._mutex.acquire();try{try{await this._muxer.start();let a=this.tracks.map(s=>s.source._start());await Promise.all(a)}finally{(await n)()}}catch(a){throw await this.cancel(),a}})()}getMimeType(){return Promise.race([this._muxer.getMimeType(),this._canceled.promise.then(()=>{throw new Error("Output has been canceled.")})])}async cancel(){if(this._cancelPromise||this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalized"){O._warn("Output has already been finalized.");return}else if(this._finalizePromise)return this._finalizePromise.catch(()=>{});return this._cancelPromise=(async()=>{let e=await this._mutex.acquire();try{this.state="canceled",this._canceled.resolve();let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0).catch(()=>{}));await Promise.all(r),this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(n=>n._close().catch(()=>{}))),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this._cancelPromise||this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(O._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{let e=await this._mutex.acquire();try{this.state="finalizing";let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(r),await this._muxer.finalize(),this._rootWriterPromise){let n=await this._rootWriterPromise;n.finalized||(await n.flush(),await n.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}catch(r){throw this.state="canceled",this._canceled.resolve(),r}finally{this._targetsClosed=!0,await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};var fl=i=>{if(!i||typeof i!="object")throw new TypeError("options.video, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!ue.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${ue.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof de))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof de)&&(!Number.isInteger(t)||t<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(i?.width!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(i?.height!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(i?.fit!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(i?.width!==void 0&&i.height!==void 0&&i.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(i?.rotate!==void 0&&![0,90,180,270].includes(i.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(i?.flip!==void 0&&typeof i.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if(i?.allowTransformationMetadata!==void 0&&typeof i.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if(i?.allowRotationMetadata!==void 0&&typeof i.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(i?.crop!==void 0&&ki(i.crop,"options.video."),i?.frameRate!==void 0&&(!Number.isFinite(i.frameRate)||i.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(i?.alpha!==void 0&&!["discard","keep"].includes(i.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(i?.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(i?.processedWidth!==void 0&&(!Number.isInteger(i.processedWidth)||i.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(i?.processedHeight!==void 0&&(!Number.isInteger(i.processedHeight)||i.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(i?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(i?.group!==void 0&&!(i.group instanceof pt||Array.isArray(i.group)&&i.group.every(e=>e instanceof pt)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(i?.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("options.video.maximumPacketCount, when provided, must be a non-negative integer.")},pl=i=>{if(!i||typeof i!="object")throw new TypeError("options.audio, when provided, must be an object.");if(i?.discard!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(i?.forceTranscode!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(i?.codec!==void 0&&!pe.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${pe.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof de))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(i?.quality!==void 0&&t!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(t!==void 0&&!(t instanceof de)&&(!Number.isInteger(t)||t<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(i?.numberOfChannels!==void 0&&(!Number.isInteger(i.numberOfChannels)||i.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(i?.sampleRate!==void 0&&(!Number.isInteger(i.sampleRate)||i.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(i?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i?.process!==void 0&&typeof i.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(i?.processedNumberOfChannels!==void 0&&(!Number.isInteger(i.processedNumberOfChannels)||i.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(i?.processedSampleRate!==void 0&&(!Number.isInteger(i.processedSampleRate)||i.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(i?.group!==void 0&&!(i.group instanceof pt||Array.isArray(i.group)&&i.group.every(e=>e instanceof pt)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.");if(i?.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("options.audio.maximumPacketCount, when provided, must be a non-negative integer.")},hd=2,gd=48e3,dy=256,hl=class i{constructor(t){this._state="idle";this._timestampOffset=0;this._timestampOffsetAdjusted=!1;this._copyTimestampPossible=new Map;this._copyStartPackets=new Map;this._trackDurations=new Map;this._nextOutputTrackId=0;this._outputTrackIds=[];this._outputOwnTrackGroups=[];this._trackPumps=[];this._composable=!1;this._executed=!1;this._executionUntil=1/0;this._pauseRequested=!1;this._synchronizer=new bd(this);this._totalDuration=null;this._maxTimestamps=new Map;this.onProgress=void 0;this._computeProgress=!1;this._lastProgress=0;this._lastProcessedTime=0;this.isValid=!1;this.utilizedTracks=[];this.discardedTracks=[];if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.input instanceof vi))throw new TypeError("options.input must be an Input.");if(!(t.output instanceof Or))throw new TypeError("options.output must be an Output.");if(t.tracks!==void 0&&t.tracks!=="all"&&t.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(t.composable!==void 0&&typeof t.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(t.copy!==void 0&&t.copy!==!1){if(!t.copy||typeof t.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(t.copy.mode!==void 0&&!["forced","preferred"].includes(t.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(t.copy.shiftTolerance!==void 0&&(!Ie(t.copy.shiftTolerance)||t.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(t.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(t.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(t.copy.boundaryTolerance!==void 0&&(!Ie(t.copy.boundaryTolerance)||t.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}let e=t.composable??!1;if(e){if(t.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(t.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(t.output.tracks.length>0||Object.keys(t.output._metadataTags).length>0||t.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(t.video!==void 0&&typeof t.video!="function")if(Array.isArray(t.video))for(let r of t.video)fl(r);else fl(t.video);if(t.audio!==void 0&&typeof t.audio!="function")if(Array.isArray(t.audio))for(let r of t.audio)pl(r);else pl(t.audio);if(t.trim!==void 0&&(!t.trim||typeof t.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(t.trim?.start!==void 0&&!Number.isFinite(t.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(t.trim?.end!==void 0&&!Ie(t.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(t.trim?.start!==void 0&&t.trim.end!==void 0&&t.trim.start>=t.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(t.tags!==void 0&&(typeof t.tags!="object"||!t.tags)&&typeof t.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof t.tags=="object"&&fa(t.tags),t.showWarnings!==void 0&&typeof t.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=t,this._copyMode=t.copy===!1?!1:t.copy?.mode??"preferred",this._copyTimestampShiftTolerance=t.copy===!1?0:t.copy?.shiftTolerance??0,this._copyBoundaryPolicy=t.copy===!1?"expand":t.copy?.boundaryPolicy??"expand",this._copyBoundaryTolerance=t.copy===!1?1/0:t.copy?.boundaryTolerance??1/0,this._composable=e,this.input=t.input,this.output=t.output}get state(){return this._state}static async init(t){let e=new i(t);return await e._init(),e}async _init(){let t=await this.input.getFormat(),e,r=this._options.tracks;if(r===void 0&&(r=t.name.includes("(HLS)")?"primary":"all"),r==="all")e=await this.input.getTracks();else if(r==="primary"){let o=await this.input.getPrimaryVideoTrack(),c=await this.input.getPrimaryAudioTrack();e=[o,c].filter(l=>l!==null)}else Z(r),b(!1);let n=this.output.format.getSupportedTrackCounts(),a=[],s=[];for(let o of e){let c;if(o.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){let d=await this._options.video(o,o.number)??{};if(Array.isArray(d))for(let m of d)fl(m);else fl(d);c=Array.isArray(d)?d:[d]}else c=Array.isArray(this._options.video)?this._options.video:[this._options.video];else c=[{}];else if(o.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){let d=await this._options.audio(o,o.number)??{};if(Array.isArray(d))for(let m of d)pl(m);else pl(d);c=Array.isArray(d)?d:[d]}else c=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else c=[{}];else b(!1);let l=c.filter(d=>d.discard);for(let d of l)this.discardedTracks.push({track:o,reason:"discarded_by_user",trackOptions:d});if(c.length===l.length){c.length===0&&this.discardedTracks.push({track:o,reason:"discarded_by_user",trackOptions:{}});continue}let u=c.filter(d=>!d.discard);a.push(o),s.push(u)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(a),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let o=0;o<a.length;o++){let c=a[o],l=s[o];for(let u of l){if(this.output.tracks.length===n.total.max){this.discardedTracks.push({track:c,reason:"max_track_count_reached",trackOptions:u});continue}if(this.output.tracks.reduce((f,p)=>f+(p.type===c.type?1:0),0)===n[c.type].max){this.discardedTracks.push({track:c,reason:"max_track_count_of_type_reached",trackOptions:u});continue}let m=this._nextOutputTrackId++;c.isVideoTrack()?await this._processVideoTrack(c,u,m):c.isAudioTrack()?await this._processAudioTrack(c,u,m):b(!1)}}for(let o=0;o<this.utilizedTracks.length-1;o++)for(let c=o+1;c<this.utilizedTracks.length;c++){let l=this.utilizedTracks[o],u=this.utilizedTracks[c],d=this._outputOwnTrackGroups[o],m=this._outputOwnTrackGroups[c];b(d!==void 0),b(m!==void 0),d&&m&&l.canBePairedWith(u)&&d.pairWith(m)}if(!this._composable){let o={...await this.input.getMetadataTags()};delete o.creationTime;let c;if(this._options.tags){let d=typeof this._options.tags=="function"?await this._options.tags(o):this._options.tags;fa(d),c=d}else c=o;let l=t.mimeType===this.output.format.mimeType;o.raw===c.raw&&!l&&delete c.raw,this.output.setMetadataTags(c)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let o=[],c=this.discardedTracks.filter(l=>l.reason!=="discarded_by_user");c.length>0&&o.push("Some tracks had to be discarded from the conversion:",c),this.isValid||(o.length>0&&o.push(`
|
|
42
42
|
|
|
43
43
|
`),o.push(this._getInvalidityExplanation().join(""))),o.length>0&&O._warn(...o)}}_getInvalidityExplanation(){let t=[];if(this.discardedTracks.length===0)t.push("Due to missing tracks, this conversion cannot be executed.");else{let e=this.discardedTracks.every(r=>r.reason==="discarded_by_user"||r.reason==="no_encodable_target_codec")&&this.discardedTracks.some(r=>r.reason==="no_encodable_target_codec");if(t.push("Due to discarded tracks, this conversion cannot be executed."),e){let r=[],n=[];for(let o of this.discardedTracks){if(o.reason==="discarded_by_user")continue;let c;o.track.type==="video"?c=this.output.format.getSupportedVideoCodecs():o.track.type==="audio"?c=this.output.format.getSupportedAudioCodecs():c=this.output.format.getSupportedSubtitleCodecs();let l=o.trackOptions.codec;l&&!c.includes(l)?n.push(l):r.push(...c.filter(u=>!l||u===l))}let a=[...new Set(r)],s=[...new Set(n)];s.length>0&&t.push(`
|
|
44
44
|
Tracks were discarded because the output format cannot contain the requested codecs ${s.map(o=>`'${o}'`).join(", ")}.`),a.length===1?t.push(`
|
|
@@ -52,6 +52,6 @@ The @mediabunny/dts extension package provides support for encoding and decoding
|
|
|
52
52
|
The @mediabunny/truehd extension package provides support for encoding and decoding TrueHD.`),a.length>0&&typeof VideoEncoder>"u"&&t.push(`
|
|
53
53
|
In server-side environments, the @mediabunny/server extension package provides support for encoding and decoding all common codecs.`)}else t.push(`
|
|
54
54
|
Check the discardedTracks field for more info.`)}return t}async execute(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.until!==void 0&&(typeof t.until!="number"||Number.isNaN(t.until)))throw new TypeError("options.until, when provided, must be a number.");if(t.pauseSignal!==void 0&&!(t.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
|
|
55
|
-
`+this._getInvalidityExplanation().join(""));if(this._state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this._state==="canceled")throw new bn;if(this._state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this._state="executing",this._executionUntil=t.until??1/0,this._pauseRequested=t.pauseSignal?.aborted??!1;let e=()=>{this._state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};t.pauseSignal?.addEventListener("abort",e);for(let n of this._trackPumps)n.done||(n.resolvers=te());try{if(this._executed)for(let n of this._trackPumps)n.wake?.();else{this._executed=!0;for(let n of this._outputTrackIds)this._synchronizer.declareTrack(n);if(this.onProgress){let a=[...new Set(this.utilizedTracks)].map(o=>this._getTrackDuration(o)),s=Math.max(0,...await Promise.all(a));this._computeProgress=!0,this._totalDuration=Math.min(s-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let o of this._outputTrackIds)this._maxTimestamps.set(o,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let n of this._trackPumps)n.start()}await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){if(this._state!=="canceled")throw this.cancel().catch(()=>{}),n}finally{t.pauseSignal?.removeEventListener("abort",e)}if(this._state==="canceled")throw new bn;if(!this._trackPumps.every(n=>n.done)){this._state="idle";return}if(!this._composable){try{await this.output.finalize()}catch(n){throw this._state="canceled",n}if(this._state==="canceled")throw new bn}this._state="done",this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime)}async cancel(){if(this._state!=="done"){if(this._state==="canceled"){O._warn("Conversion already canceled.");return}this._state="canceled";for(let t of this._trackPumps)t.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(t,e,r){let n=await t.getCodec();if(!n){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}if(this.output.format.requiresMaximumPacketCount&&e.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await t.isLive()){this.discardedTracks.push({track:t,reason:"unknown_maximum_packet_count",trackOptions:e});return}let a,s=await t.getRotation(),o=await t.getFlip(),{rotation:c,flip:l}=vs(s,o,e.rotate??0,e.flip??!1),u=c,d=l,m=e.rotate||e.flip?null:await t.getTransformationMatrix(),f=this.output.format.supportsVideoTransformationMetadata&&(e.allowTransformationMetadata??e.allowRotationMetadata??!0),p=await t.getSquarePixelWidth(),g=await t.getSquarePixelHeight(),[h,y]=c%180===0?[p,g]:[g,p],k=e.crop;k&&(k=Fn(k,h,y));let[T,S]=k?[k.width,k.height]:[h,y],w=T,A=S,C=w/A;e.width!==void 0&&e.height===void 0?(w=qi(e.width),A=qi(Math.round(w/C))):e.width===void 0&&e.height!==void 0?(A=qi(e.height),w=qi(Math.round(A*C))):e.width!==void 0&&e.height!==void 0&&(w=qi(e.width),A=qi(e.height));let E=this.output.format.getSupportedVideoCodecs(),I=e.alpha??"discard",x=!this._copyMode||!!e.forceTranscode||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.quality!==void 0||e.bitrate!==void 0||!E.includes(n)||e.codec&&e.codec!==n||w!==T||A!==S||c!==0&&!f||l&&!f||!!k,P=null;if(!x){let Le=new ut(t),He=await Le.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await Le.getFirstKeyPacket({verifyKeyPackets:!0});if(He&&He.timestamp<this._startTimestamp&&He.timestamp+He.duration<=this._startTimestamp&&this._copyBoundaryPolicy==="shrink"&&(He=await Le.getNextKeyPacket(He,{verifyKeyPackets:!0})),P=He,He){let je=this._copyBoundaryPolicy==="shrink"?Math.max(He.timestamp,this._startTimestamp):He.timestamp;if((this._copyBoundaryPolicy==="shrink"?je-this._startTimestamp:Math.max(this._startTimestamp-je,0))>this._copyBoundaryTolerance)x=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&je<this._startTimestamp){let We=Math.min(this._startTimestamp-je,this._copyTimestampShiftTolerance);je+We>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+We):x=!0}}else if(this._timestampOffsetAdjusted)je+this._timestampOffset===0||(x=!0);else{let We=ne(this._startTimestamp-je,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);je+We===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+We,this._timestampOffsetAdjusted=!0):x=!0}}}if(x&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(x){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(E=E.filter(he=>he===e.codec));let He=Ti(e.quality,e.bitrate)??new ue("high"),je=await To(E,{width:e.process&&e.processedWidth?e.processedWidth:w,height:e.process&&e.processedHeight?e.processedHeight:A,quality:He});if(!je){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let ie={codec:je,quality:He,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:I,hardwareAcceleration:e.hardwareAcceleration,transform:{}};b(ie.transform);let We=w!==T||A!==S||c!==0&&(!f||e.process!==void 0)||l&&(!f||e.process!==void 0)||!!k||p!==await t.getCodedWidth()||g!==await t.getCodedHeight();if(!We){var ye=[];try{let he=new Or({format:new ul,target:new Oi});let Se=new cn(ie);he.addVideoTrack(Se);await he.start();let gt=new _i(t,{hardwareAcceleration:e.hardwareAcceleration});let De=yt(ye,await gt.getSample(await t.getFirstTimestamp()));if(De)try{await Se.add(De),De.close(),await he.finalize()}catch(nr){O._warn("An error occurred when probing encoder support. Falling back to rerender path.",nr),he.cancel(),We=!0,ie.transform.force=!0}else await he.cancel()}catch(we){var Ze=we,at=!0}finally{kt(ye,Ze,at)}}e.frameRate&&(ie.transform.frameRate=e.frameRate),e.process&&(ie.transform.process=e.process),We&&(u=0,d=!1,m=null,ie.transform.width=w,ie.transform.height=A,ie.transform.fit=e.fit??"fill",ie.transform.rotate=e.rotate,ie.transform.flip=e.flip,ie.transform.crop=k,ie.transform.alpha=I);let Je=null;ie.onEncodedSample=he=>{Je=he.timestamp};let ht=new cn(ie);a=ht,this._registerTrackPump(async he=>{let Se=new _i(t,{hardwareAcceleration:e.hardwareAcceleration});for await(var gt of Se.samples(this._startTimestamp,this._endTimestamp)){var De=[];try{let bt=yt(De,gt);if(this._state==="canceled")break;let yn=Math.max(this._startTimestamp,bt.timestamp),kn=Math.min(this._endTimestamp,bt.timestamp+bt.duration);yn>kn||yn===kn&&bt.duration>0||(bt.setTimestamp(yn+this._timestampOffset),bt.setDuration(kn-yn),this._updateProgress(r,bt.timestamp+bt.duration),await ht.add(bt),bt.close(),Je!==null&&(this._synchronizer.shouldWait(r,Je)&&await this._synchronizer.wait(Je),await this._checkpoint(he,Je)))}catch(nr){var ar=nr,Ss=!0}finally{kt(De,ar,Ss)}}ht.close(),this._closeTrack(r)})}else{let Le=new ri(n);a=Le,this._registerTrackPump(async He=>{let je=new ut(t),We={decoderConfig:await t.getDecoderConfig()??void 0},Je=new sa,ht=!1,he=!1;if(P)for await(let Se of je.packets(P,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(Se.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let Ss=Se,bt=!1,yn=6;for(let kn=0;kn<yn;kn++){let hl=await je.getNextPacket(Ss,{metadataOnly:!0});if(!hl)break;if(hl.timestamp<this._endTimestamp){bt=!0;break}Ss=hl}if(!bt)break}}if(Se.timestamp<P.timestamp)continue;let gt=Se.timestamp,De=Se.timestamp+Se.duration;if(this._copyBoundaryPolicy==="shrink"&&(gt=Math.max(gt,this._startTimestamp),De=Math.min(De,this._endTimestamp),De=Math.max(De,gt)),gt+=this._timestampOffset,De+=this._timestampOffset,Se.type==="key"&&(ht=!1),ht)continue;let nr=Se.type;if(nr==="key"&&!Je.check(gt,"key")&&(nr="delta"),!Je.digest(gt,nr)){ht=Se.type==="key",he||(O._warn("Some video packets had to be dropped in order to produce correct output timestamps."),he=!0);continue}let ar=Se.clone({timestamp:gt,duration:De-gt,sideData:I==="discard"?{}:Se.sideData,type:nr});this._updateProgress(r,ar.timestamp+ar.duration),await Le.add(ar,We),this._synchronizer.shouldWait(r,ar.timestamp)&&await this._synchronizer.wait(ar.timestamp),await this._checkpoint(He,ar.timestamp)}Le.close(),this._closeTrack(r)})}let v=null;!e.group&&!this._composable&&(v=new pt);let _=await t.getLanguageCode(),M=await t.getName(),D=await t.getDisposition(),L=x?null:await t.getBitrate(),z=x?null:await t.getAverageBitrate(),$=I==="keep"&&await t.canBeTransparent(),fe=e.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&fe===void 0){let Le=x?this._startTimestamp:P?.timestamp??this._startTimestamp;fe=await this._estimateMaximumPacketCount(t,Le,e.frameRate??null)}this.output.addVideoTrack(a,{frameRate:e.frameRate,languageCode:Ur(_)?_:void 0,name:M??void 0,disposition:D,rotation:u,flip:d,transformationMatrix:m??void 0,canBeTransparent:$,group:v??e.group,bitrate:L??void 0,averageBitrate:z??void 0,maximumPacketCount:fe}),this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(v)}async _processAudioTrack(t,e,r){let n=await t.getCodec();if(!n){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}if(this.output.format.requiresMaximumPacketCount&&e.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await t.isLive()){this.discardedTracks.push({track:t,reason:"unknown_maximum_packet_count",trackOptions:e});return}let a,s=await t.getNumberOfChannels(),o=await t.getSampleRate(),c=e.numberOfChannels??s,l=e.sampleRate??o,u=null,d=this.output.format.getSupportedAudioCodecs(),m=!this._copyMode||!!e.forceTranscode||!!e.quality||!!e.bitrate||c!==s||l!==o||!d.includes(n)||!!e.codec&&e.codec!==n||e.process!==void 0||e.sampleFormat!==void 0,f=null;if(!m){let w=new ut(t),A=await w.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await w.getFirstKeyPacket({verifyKeyPackets:!0});A&&(this._copyBoundaryPolicy==="shrink"&&A.timestamp<this._startTimestamp||this._copyBoundaryPolicy==="expand"&&A.timestamp+A.duration<=this._startTimestamp&&await t.hasOnlyKeyPackets())&&(A=await w.getNextKeyPacket(A,{verifyKeyPackets:!0}));let C=await t.getPreRollDuration();if(b(C!==null),A&&this._copyBoundaryPolicy==="expand"&&C>0&&(A=await w.getKeyPacket(A.timestamp-C,{verifyKeyPackets:!0})??await w.getFirstKeyPacket({verifyKeyPackets:!0})),f=A,A)if((this._copyBoundaryPolicy==="shrink"?Math.max(A.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-A.timestamp,0))>this._copyBoundaryTolerance)m=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&A.timestamp<this._startTimestamp){let I=Math.min(this._startTimestamp-A.timestamp,this._copyTimestampShiftTolerance);A.timestamp+I>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+I):m=!0}}else if(this._timestampOffsetAdjusted)A.timestamp+this._timestampOffset===0||(m=!0);else{let I=ne(this._startTimestamp-A.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);A.timestamp+I===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+I,this._timestampOffsetAdjusted=!0):m=!0}}if(m&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(m){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(d=d.filter(P=>P===e.codec));let A=Ti(e.quality,e.bitrate)??new ue("high"),C=await Mn(d,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:c,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:l,quality:A});if(!C.some(P=>Jt.includes(P))&&d.some(P=>Jt.includes(P))&&(c!==gd||l!==bd)){let v=(await Mn(d,{numberOfChannels:gd,sampleRate:bd,quality:A})).find(_=>Jt.includes(_));v?(u=v,c=gd,l=bd):u=C[0]??null}else u=C[0]??null;if(u===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let E={codec:u,quality:A,transform:{sampleFormat:e.sampleFormat,process:e.process}};b(E.transform),c!==s&&(E.transform.numberOfChannels=c),l!==o&&(E.transform.sampleRate=l);let I=null;E.onEncodedSample=P=>{I=P.timestamp};let x=new aa(E);a=x,this._registerTrackPump(async P=>{let v=null,_=new sn(t);for await(var Ze of _.samples(this._startTimestamp,this._endTimestamp)){var at=[];try{let ie=yt(at,Ze);var $=[];try{if(this._state==="canceled")break;let We=0;let Je=ie.numberOfFrames;ie.timestamp<this._startTimestamp&&(We=Math.round((this._startTimestamp-ie.timestamp)*ie.sampleRate));ie.timestamp+ie.duration>this._endTimestamp&&(Je=Math.round((this._endTimestamp-ie.timestamp)*ie.sampleRate));if(We>=Je){ie.close();continue}let ht;if(We>0||Je<ie.numberOfFrames){let Se=ie.trim(We,Je);if(ie.close(),ht=Se,Se.numberOfFrames===0){Se.close();continue}}else ht=ie;let he=yt($,ht);he.setTimestamp(he.timestamp+this._timestampOffset);v===null&&(v=this.output.format.supportsTimestampedMediaData?0:Math.round(he.timestamp*he.sampleRate));if(v>0){let Se=Ct(ie.format)*he.numberOfChannels,gt=new Uint8Array(Se*Math.min(v,he.sampleRate));(ie.format==="u8"||ie.format==="u8-planar")&>.fill(2**7);for(let De=0;De<v;De+=he.sampleRate){var M=[];try{let nr=Math.min(v-De,he.sampleRate);let ar=yt(M,new Ce({data:gt.subarray(0,Se*nr),_doNotCopy:!0,format:ie.format,numberOfChannels:he.numberOfChannels,sampleRate:he.sampleRate,timestamp:De/he.sampleRate}));await this._registerAudioSample(P,ar,x,r,()=>I)}catch(D){var L=D,z=!0}finally{kt(M,L,z)}}v=0}await this._registerAudioSample(P,he,x,r,()=>I)}catch(fe){var ye=fe,we=!0}finally{kt($,ye,we)}}catch(Le){var He=Le,je=!0}finally{kt(at,He,je)}}x.close(),this._closeTrack(r)})}else{let w=new ii(n);a=w,this._registerTrackPump(async A=>{let C=new ut(t),I={decoderConfig:await t.getDecoderConfig()??void 0},x=new sa,P=!1,v=!1;if(f)for await(let _ of C.packets(f)){if(this._state==="canceled"||_.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&_.timestamp+_.duration>this._endTimestamp)break;if(_.timestamp<f.timestamp)continue;let M=_.timestamp+this._timestampOffset;if(_.type==="key"&&(P=!1),P)continue;if(!x.digest(M,_.type)){P=_.type==="key",v||(O._warn("Some audio packets had to be dropped in order to produce correct output timestamps."),v=!0);continue}let D=_.clone({timestamp:M,duration:_.duration});this._updateProgress(r,D.timestamp+D.duration),await w.add(D,I),this._synchronizer.shouldWait(r,D.timestamp)&&await this._synchronizer.wait(D.timestamp),await this._checkpoint(A,D.timestamp)}w.close(),this._closeTrack(r)})}let p=null;!e.group&&!this._composable&&(p=new pt);let g=await t.getLanguageCode(),h=await t.getName(),y=await t.getDisposition(),k=m?null:await t.getBitrate(),T=m?null:await t.getAverageBitrate(),S=e.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&S===void 0){let w=null;m&&(b(u),w=l/bp(u,l));let A=m?this._startTimestamp:f?.timestamp??this._startTimestamp;S=await this._estimateMaximumPacketCount(t,A,w)}this.output.addAudioTrack(a,{languageCode:Ur(g)?g:void 0,name:h??void 0,disposition:y,group:p??e.group,bitrate:k??void 0,averageBitrate:T??void 0,maximumPacketCount:S}),this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(p)}async _estimateMaximumPacketCount(t,e,r){if(r===null){let s=await t.computePacketStats(dy);if(s.averagePacketRate===1/0)return s.packetCount;r=s.averagePacketRate}let n=Math.min(await this._getTrackDuration(t),this._endTimestamp),a=Math.max(n-e,0);return Math.ceil(1.5*r*a)+64}_getTrackDuration(t){let e=this._trackDurations.get(t);return e||(e=(async()=>await t.isLive()?1/0:await t.getDurationFromMetadata()??await t.computeDuration())(),this._trackDurations.set(t,e)),e}async _registerAudioSample(t,e,r,n,a){this._updateProgress(n,e.timestamp+e.duration),await r.add(e),e.close();let s=a();s!==null&&(this._synchronizer.shouldWait(n,s)&&await this._synchronizer.wait(s),await this._checkpoint(t,s))}_registerTrackPump(t){let e={done:!1,resolvers:te(),wake:null,start:()=>{t(e).then(()=>{e.done=!0,e.resolvers.resolve()},r=>{e.resolvers.reject(r)})}};this._trackPumps.push(e)}async _checkpoint(t,e){for(;this._state!=="canceled"&&(e>=this._executionUntil||this._pauseRequested);){t.resolvers.resolve();let{promise:r,resolve:n}=te();t.wake=n,await r}}_closeTrack(t){this._synchronizer.closeTrack(t),this._maxTimestamps.delete(t),this._reportProgress()}_updateProgress(t,e){this._computeProgress&&(this._maxTimestamps.set(t,Math.max(e,this._maxTimestamps.get(t))),this._reportProgress())}_reportProgress(){if(!this._computeProgress||this._maxTimestamps.size===0)return;b(this._totalDuration!==null);let t=Math.min(...this._maxTimestamps.values()),e=this._totalDuration>0?ne(t/this._totalDuration,0,1):0;this._lastProcessedTime=t,e!==this._lastProgress&&(this._lastProgress=e,this.onProgress?.(e,t))}},bn=class extends Error{constructor(t="Conversion has been canceled."){super(t),this.name="ConversionCanceledError"}},Yp=1,yd=class{constructor(t){this.maxTimestamps=new Map;this.resolvers=[];this.conversion=t}declareTrack(t){this.maxTimestamps.set(t,-1/0)}shouldWait(t,e){let r=this.maxTimestamps.get(t);b(r!==void 0),this.maxTimestamps.set(t,Math.max(e,r));let n=this.computeMinAndMaybeResolve();return this.conversion._state==="canceled"||this.conversion._pauseRequested||e>=this.conversion._executionUntil?!1:e-n>Yp}wait(t){let{promise:e,resolve:r}=te();return this.resolvers.push({timestamp:t,resolve:r}),e}closeTrack(t){this.maxTimestamps.delete(t),this.computeMinAndMaybeResolve()}resolveAll(){for(let t of this.resolvers)t.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let t=1/0;for(let[,e]of this.maxTimestamps)t=Math.min(t,e);for(let e=0;e<this.resolvers.length;e++){let r=this.resolvers[e];r.timestamp-t<Yp&&(r.resolve(),this.resolvers.splice(e,1),e--)}return t}};var Zp=Symbol.for("mediabunny loaded");globalThis[Zp]&&O._error(`[WARNING]
|
|
55
|
+
`+this._getInvalidityExplanation().join(""));if(this._state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this._state==="canceled")throw new bn;if(this._state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this._state="executing",this._executionUntil=t.until??1/0,this._pauseRequested=t.pauseSignal?.aborted??!1;let e=()=>{this._state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};t.pauseSignal?.addEventListener("abort",e);for(let n of this._trackPumps)n.done||(n.resolvers=te());try{if(this._executed)for(let n of this._trackPumps)n.wake?.();else{this._executed=!0;for(let n of this._outputTrackIds)this._synchronizer.declareTrack(n);if(this.onProgress){let a=[...new Set(this.utilizedTracks)].map(o=>this._getTrackDuration(o)),s=Math.max(0,...await Promise.all(a));this._computeProgress=!0,this._totalDuration=Math.min(s-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let o of this._outputTrackIds)this._maxTimestamps.set(o,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(let n of this._trackPumps)n.start()}await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){if(this._state!=="canceled")throw this.cancel().catch(()=>{}),n}finally{t.pauseSignal?.removeEventListener("abort",e)}if(this._state==="canceled")throw new bn;if(!this._trackPumps.every(n=>n.done)){this._state="idle";return}if(!this._composable){try{await this.output.finalize()}catch(n){throw this._state="canceled",n}if(this._state==="canceled")throw new bn}this._state="done",this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime)}async cancel(){if(this._state!=="done"){if(this._state==="canceled"){O._warn("Conversion already canceled.");return}this._state="canceled";for(let t of this._trackPumps)t.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(t,e,r){let n=await t.getCodec();if(!n){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}if(this.output.format.requiresMaximumPacketCount&&e.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await t.isLive()){this.discardedTracks.push({track:t,reason:"unknown_maximum_packet_count",trackOptions:e});return}let a,s=await t.getRotation(),o=await t.getFlip(),{rotation:c,flip:l}=_s(s,o,e.rotate??0,e.flip??!1),u=c,d=l,m=e.rotate||e.flip?null:await t.getTransformationMatrix(),f=this.output.format.supportsVideoTransformationMetadata&&(e.allowTransformationMetadata??e.allowRotationMetadata??!0),p=await t.getSquarePixelWidth(),h=await t.getSquarePixelHeight(),[y,g]=c%180===0?[p,h]:[h,p],k=e.crop;k&&(k=Mn(k,y,g));let[T,S]=k?[k.width,k.height]:[y,g],w=T,A=S,C=w/A;e.width!==void 0&&e.height===void 0?(w=qi(e.width),A=qi(Math.round(w/C))):e.width===void 0&&e.height!==void 0?(A=qi(e.height),w=qi(Math.round(A*C))):e.width!==void 0&&e.height!==void 0&&(w=qi(e.width),A=qi(e.height));let E=this.output.format.getSupportedVideoCodecs(),I=e.alpha??"discard",x=!this._copyMode||!!e.forceTranscode||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.quality!==void 0||e.bitrate!==void 0||!E.includes(n)||e.codec&&e.codec!==n||w!==T||A!==S||c!==0&&!f||l&&!f||!!k,P=null;if(!x){let Le=new ut(t),He=await Le.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await Le.getFirstKeyPacket({verifyKeyPackets:!0});if(He&&He.timestamp<this._startTimestamp&&He.timestamp+He.duration<=this._startTimestamp&&this._copyBoundaryPolicy==="shrink"&&(He=await Le.getNextKeyPacket(He,{verifyKeyPackets:!0})),P=He,He){let je=this._copyBoundaryPolicy==="shrink"?Math.max(He.timestamp,this._startTimestamp):He.timestamp;if((this._copyBoundaryPolicy==="shrink"?je-this._startTimestamp:Math.max(this._startTimestamp-je,0))>this._copyBoundaryTolerance)x=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&je<this._startTimestamp){let We=Math.min(this._startTimestamp-je,this._copyTimestampShiftTolerance);je+We>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+We):x=!0}}else if(this._timestampOffsetAdjusted)je+this._timestampOffset===0||(x=!0);else{let We=ne(this._startTimestamp-je,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);je+We===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+We,this._timestampOffsetAdjusted=!0):x=!0}}}if(x&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(x){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(E=E.filter(he=>he===e.codec));let He=Ti(e.quality,e.bitrate)??new de("high"),je=await wo(E,{width:e.process&&e.processedWidth?e.processedWidth:w,height:e.process&&e.processedHeight?e.processedHeight:A,quality:He});if(!je){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let ie={codec:je,quality:He,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:I,hardwareAcceleration:e.hardwareAcceleration,transform:{}};b(ie.transform);let We=w!==T||A!==S||c!==0&&(!f||e.process!==void 0)||l&&(!f||e.process!==void 0)||!!k||p!==await t.getCodedWidth()||h!==await t.getCodedHeight();if(!We){var ye=[];try{let he=new Or({format:new dl,target:new Oi});let Se=new cn(ie);he.addVideoTrack(Se);await he.start();let gt=new _i(t,{hardwareAcceleration:e.hardwareAcceleration});let De=yt(ye,await gt.getSample(await t.getFirstTimestamp()));if(De)try{await Se.add(De),De.close(),await he.finalize()}catch(nr){O._warn("An error occurred when probing encoder support. Falling back to rerender path.",nr),he.cancel(),We=!0,ie.transform.force=!0}else await he.cancel()}catch(ke){var Ze=ke,at=!0}finally{kt(ye,Ze,at)}}e.frameRate&&(ie.transform.frameRate=e.frameRate),e.process&&(ie.transform.process=e.process),We&&(u=0,d=!1,m=null,ie.transform.width=w,ie.transform.height=A,ie.transform.fit=e.fit??"fill",ie.transform.rotate=e.rotate,ie.transform.flip=e.flip,ie.transform.crop=k,ie.transform.alpha=I);let Je=null;ie.onEncodedSample=he=>{Je=he.timestamp};let ht=new cn(ie);a=ht,this._registerTrackPump(async he=>{let Se=new _i(t,{hardwareAcceleration:e.hardwareAcceleration});for await(var gt of Se.samples(this._startTimestamp,this._endTimestamp)){var De=[];try{let bt=yt(De,gt);if(this._state==="canceled")break;let yn=Math.max(this._startTimestamp,bt.timestamp),kn=Math.min(this._endTimestamp,bt.timestamp+bt.duration);yn>kn||yn===kn&&bt.duration>0||(bt.setTimestamp(yn+this._timestampOffset),bt.setDuration(kn-yn),this._updateProgress(r,bt.timestamp+bt.duration),await ht.add(bt),bt.close(),Je!==null&&(this._synchronizer.shouldWait(r,Je)&&await this._synchronizer.wait(Je),await this._checkpoint(he,Je)))}catch(nr){var ar=nr,As=!0}finally{kt(De,ar,As)}}ht.close(),this._closeTrack(r)})}else{let Le=new ri(n);a=Le,this._registerTrackPump(async He=>{let je=new ut(t),We={decoderConfig:await t.getDecoderConfig()??void 0},Je=new oa,ht=!1,he=!1;if(P)for await(let Se of je.packets(P,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(Se.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let As=Se,bt=!1,yn=6;for(let kn=0;kn<yn;kn++){let gl=await je.getNextPacket(As,{metadataOnly:!0});if(!gl)break;if(gl.timestamp<this._endTimestamp){bt=!0;break}As=gl}if(!bt)break}}if(Se.timestamp<P.timestamp)continue;let gt=Se.timestamp,De=Se.timestamp+Se.duration;if(this._copyBoundaryPolicy==="shrink"&&(gt=Math.max(gt,this._startTimestamp),De=Math.min(De,this._endTimestamp),De=Math.max(De,gt)),gt+=this._timestampOffset,De+=this._timestampOffset,Se.type==="key"&&(ht=!1),ht)continue;let nr=Se.type;if(nr==="key"&&!Je.check(gt,"key")&&(nr="delta"),!Je.digest(gt,nr)){ht=Se.type==="key",he||(O._warn("Some video packets had to be dropped in order to produce correct output timestamps."),he=!0);continue}let ar=Se.clone({timestamp:gt,duration:De-gt,sideData:I==="discard"?{}:Se.sideData,type:nr});this._updateProgress(r,ar.timestamp+ar.duration),await Le.add(ar,We),this._synchronizer.shouldWait(r,ar.timestamp)&&await this._synchronizer.wait(ar.timestamp),await this._checkpoint(He,ar.timestamp)}Le.close(),this._closeTrack(r)})}let v=null;!e.group&&!this._composable&&(v=new pt);let _=await t.getLanguageCode(),M=await t.getName(),U=await t.getDisposition(),N=x?null:await t.getBitrate(),L=x?null:await t.getAverageBitrate(),G=I==="keep"&&await t.canBeTransparent(),me=e.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&me===void 0){let Le=x?this._startTimestamp:P?.timestamp??this._startTimestamp;me=await this._estimateMaximumPacketCount(t,Le,e.frameRate??null)}this.output.addVideoTrack(a,{frameRate:e.frameRate,languageCode:Ur(_)?_:void 0,name:M??void 0,disposition:U,rotation:u,flip:d,transformationMatrix:m??void 0,canBeTransparent:G,group:v??e.group,bitrate:N??void 0,averageBitrate:L??void 0,maximumPacketCount:me}),this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(v)}async _processAudioTrack(t,e,r){let n=await t.getCodec();if(!n){this.discardedTracks.push({track:t,reason:"unknown_source_codec",trackOptions:e});return}if(this.output.format.requiresMaximumPacketCount&&e.maximumPacketCount===void 0&&this._endTimestamp===1/0&&await t.isLive()){this.discardedTracks.push({track:t,reason:"unknown_maximum_packet_count",trackOptions:e});return}let a,s=await t.getNumberOfChannels(),o=await t.getSampleRate(),c=e.numberOfChannels??s,l=e.sampleRate??o,u=null,d=this.output.format.getSupportedAudioCodecs(),m=!this._copyMode||!!e.forceTranscode||!!e.quality||!!e.bitrate||c!==s||l!==o||!d.includes(n)||!!e.codec&&e.codec!==n||e.process!==void 0||e.sampleFormat!==void 0,f=null;if(!m){let w=new ut(t),A=await w.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await w.getFirstKeyPacket({verifyKeyPackets:!0});A&&(this._copyBoundaryPolicy==="shrink"&&A.timestamp<this._startTimestamp||this._copyBoundaryPolicy==="expand"&&A.timestamp+A.duration<=this._startTimestamp&&await t.hasOnlyKeyPackets())&&(A=await w.getNextKeyPacket(A,{verifyKeyPackets:!0}));let C=await t.getPreRollDuration();if(b(C!==null),A&&this._copyBoundaryPolicy==="expand"&&C>0&&(A=await w.getKeyPacket(A.timestamp-C,{verifyKeyPackets:!0})??await w.getFirstKeyPacket({verifyKeyPackets:!0})),f=A,A)if((this._copyBoundaryPolicy==="shrink"?Math.max(A.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-A.timestamp,0))>this._copyBoundaryTolerance)m=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&A.timestamp<this._startTimestamp){let I=Math.min(this._startTimestamp-A.timestamp,this._copyTimestampShiftTolerance);A.timestamp+I>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+I):m=!0}}else if(this._timestampOffsetAdjusted)A.timestamp+this._timestampOffset===0||(m=!0);else{let I=ne(this._startTimestamp-A.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);A.timestamp+I===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+I,this._timestampOffsetAdjusted=!0):m=!0}}if(m&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(m){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(d=d.filter(P=>P===e.codec));let A=Ti(e.quality,e.bitrate)??new de("high"),C=await Bn(d,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:c,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:l,quality:A});if(!C.some(P=>Jt.includes(P))&&d.some(P=>Jt.includes(P))&&(c!==hd||l!==gd)){let v=(await Bn(d,{numberOfChannels:hd,sampleRate:gd,quality:A})).find(_=>Jt.includes(_));v?(u=v,c=hd,l=gd):u=C[0]??null}else u=C[0]??null;if(u===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let E={codec:u,quality:A,transform:{sampleFormat:e.sampleFormat,process:e.process}};b(E.transform),c!==s&&(E.transform.numberOfChannels=c),l!==o&&(E.transform.sampleRate=l);let I=null;E.onEncodedSample=P=>{I=P.timestamp};let x=new sa(E);a=x,this._registerTrackPump(async P=>{let v=null,_=new sn(t);for await(var Ze of _.samples(this._startTimestamp,this._endTimestamp)){var at=[];try{let ie=yt(at,Ze);var G=[];try{if(this._state==="canceled")break;let We=0;let Je=ie.numberOfFrames;ie.timestamp<this._startTimestamp&&(We=Math.round((this._startTimestamp-ie.timestamp)*ie.sampleRate));ie.timestamp+ie.duration>this._endTimestamp&&(Je=Math.round((this._endTimestamp-ie.timestamp)*ie.sampleRate));if(We>=Je){ie.close();continue}let ht;if(We>0||Je<ie.numberOfFrames){let Se=ie.trim(We,Je);if(ie.close(),ht=Se,Se.numberOfFrames===0){Se.close();continue}}else ht=ie;let he=yt(G,ht);he.setTimestamp(he.timestamp+this._timestampOffset);v===null&&(v=this.output.format.supportsTimestampedMediaData?0:Math.round(he.timestamp*he.sampleRate));if(v>0){let Se=Ct(ie.format)*he.numberOfChannels,gt=new Uint8Array(Se*Math.min(v,he.sampleRate));(ie.format==="u8"||ie.format==="u8-planar")&>.fill(2**7);for(let De=0;De<v;De+=he.sampleRate){var M=[];try{let nr=Math.min(v-De,he.sampleRate);let ar=yt(M,new Ce({data:gt.subarray(0,Se*nr),_doNotCopy:!0,format:ie.format,numberOfChannels:he.numberOfChannels,sampleRate:he.sampleRate,timestamp:De/he.sampleRate}));await this._registerAudioSample(P,ar,x,r,()=>I)}catch(U){var N=U,L=!0}finally{kt(M,N,L)}}v=0}await this._registerAudioSample(P,he,x,r,()=>I)}catch(me){var ye=me,ke=!0}finally{kt(G,ye,ke)}}catch(Le){var He=Le,je=!0}finally{kt(at,He,je)}}x.close(),this._closeTrack(r)})}else{let w=new ii(n);a=w,this._registerTrackPump(async A=>{let C=new ut(t),I={decoderConfig:await t.getDecoderConfig()??void 0},x=new oa,P=!1,v=!1;if(f)for await(let _ of C.packets(f)){if(this._state==="canceled"||_.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&_.timestamp+_.duration>this._endTimestamp)break;if(_.timestamp<f.timestamp)continue;let M=_.timestamp+this._timestampOffset;if(_.type==="key"&&(P=!1),P)continue;if(!x.digest(M,_.type)){P=_.type==="key",v||(O._warn("Some audio packets had to be dropped in order to produce correct output timestamps."),v=!0);continue}let U=_.clone({timestamp:M,duration:_.duration});this._updateProgress(r,U.timestamp+U.duration),await w.add(U,I),this._synchronizer.shouldWait(r,U.timestamp)&&await this._synchronizer.wait(U.timestamp),await this._checkpoint(A,U.timestamp)}w.close(),this._closeTrack(r)})}let p=null;!e.group&&!this._composable&&(p=new pt);let h=await t.getLanguageCode(),y=await t.getName(),g=await t.getDisposition(),k=m?null:await t.getBitrate(),T=m?null:await t.getAverageBitrate(),S=e.maximumPacketCount;if(this.output.format.requiresMaximumPacketCount&&S===void 0){let w=null;m&&(b(u),w=l/bp(u,l));let A=m?this._startTimestamp:f?.timestamp??this._startTimestamp;S=await this._estimateMaximumPacketCount(t,A,w)}this.output.addAudioTrack(a,{languageCode:Ur(h)?h:void 0,name:y??void 0,disposition:g,group:p??e.group,bitrate:k??void 0,averageBitrate:T??void 0,maximumPacketCount:S}),this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(p)}async _estimateMaximumPacketCount(t,e,r){if(r===null){let s=await t.computePacketStats(dy);if(s.averagePacketRate===1/0)return s.packetCount;r=s.averagePacketRate}let n=Math.min(await this._getTrackDuration(t),this._endTimestamp),a=Math.max(n-e,0);return Math.ceil(1.5*r*a)+64}_getTrackDuration(t){let e=this._trackDurations.get(t);return e||(e=(async()=>await t.isLive()?1/0:await t.getDurationFromMetadata()??await t.computeDuration())(),this._trackDurations.set(t,e)),e}async _registerAudioSample(t,e,r,n,a){this._updateProgress(n,e.timestamp+e.duration),await r.add(e),e.close();let s=a();s!==null&&(this._synchronizer.shouldWait(n,s)&&await this._synchronizer.wait(s),await this._checkpoint(t,s))}_registerTrackPump(t){let e={done:!1,resolvers:te(),wake:null,start:()=>{t(e).then(()=>{e.done=!0,e.resolvers.resolve()},r=>{e.resolvers.reject(r)})}};this._trackPumps.push(e)}async _checkpoint(t,e){for(;this._state!=="canceled"&&(e>=this._executionUntil||this._pauseRequested);){t.resolvers.resolve();let{promise:r,resolve:n}=te();t.wake=n,await r}}_closeTrack(t){this._synchronizer.closeTrack(t),this._maxTimestamps.delete(t),this._reportProgress()}_updateProgress(t,e){this._computeProgress&&(this._maxTimestamps.set(t,Math.max(e,this._maxTimestamps.get(t))),this._reportProgress())}_reportProgress(){if(!this._computeProgress||this._maxTimestamps.size===0)return;b(this._totalDuration!==null);let t=Math.min(...this._maxTimestamps.values()),e=this._totalDuration>0?ne(t/this._totalDuration,0,1):0;this._lastProcessedTime=t,e!==this._lastProgress&&(this._lastProgress=e,this.onProgress?.(e,t))}},bn=class extends Error{constructor(t="Conversion has been canceled."){super(t),this.name="ConversionCanceledError"}},Yp=1,bd=class{constructor(t){this.maxTimestamps=new Map;this.resolvers=[];this.conversion=t}declareTrack(t){this.maxTimestamps.set(t,-1/0)}shouldWait(t,e){let r=this.maxTimestamps.get(t);b(r!==void 0),this.maxTimestamps.set(t,Math.max(e,r));let n=this.computeMinAndMaybeResolve();return this.conversion._state==="canceled"||this.conversion._pauseRequested||e>=this.conversion._executionUntil?!1:e-n>Yp}wait(t){let{promise:e,resolve:r}=te();return this.resolvers.push({timestamp:t,resolve:r}),e}closeTrack(t){this.maxTimestamps.delete(t),this.computeMinAndMaybeResolve()}resolveAll(){for(let t of this.resolvers)t.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let t=1/0;for(let[,e]of this.maxTimestamps)t=Math.min(t,e);for(let e=0;e<this.resolvers.length;e++){let r=this.resolvers[e];r.timestamp-t<Yp&&(r.resolve(),this.resolvers.splice(e,1),e--)}return t}};var Zp=Symbol.for("mediabunny loaded");globalThis[Zp]&&O._error(`[WARNING]
|
|
56
56
|
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[Zp]=!0;return sh(my);})();
|
|
57
57
|
if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, Mediabunny)
|