agentroam-runtime-darwin-arm64 0.2.0-preview.63 → 0.2.0-preview.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (813) hide show
  1. package/manifest.json +2 -2
  2. package/package.json +1 -1
  3. package/runtime/.next/BUILD_ID +1 -1
  4. package/runtime/.next/app-build-manifest.json +10 -10
  5. package/runtime/.next/app-path-routes-manifest.json +1 -1
  6. package/runtime/.next/build-manifest.json +3 -3
  7. package/runtime/.next/prerender-manifest.json +1 -1
  8. package/runtime/.next/required-server-files.json +1 -1
  9. package/runtime/.next/server/app/_not-found/page.js +1 -1
  10. package/runtime/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  11. package/runtime/.next/server/app/_not-found.html +1 -1
  12. package/runtime/.next/server/app/_not-found.rsc +1 -1
  13. package/runtime/.next/server/app/api/agent/abort/route.js +1 -1
  14. package/runtime/.next/server/app/api/agent/answer/route.js +1 -1
  15. package/runtime/.next/server/app/api/agent/codex-sharing/route.js +1 -1
  16. package/runtime/.next/server/app/api/agent/harness/status/route.js +1 -1
  17. package/runtime/.next/server/app/api/agent/model/route.js +1 -1
  18. package/runtime/.next/server/app/api/agent/models/route.js +1 -1
  19. package/runtime/.next/server/app/api/agent/run/route.js +2 -2
  20. package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
  21. package/runtime/.next/server/app/api/agent/steer/route.js +1 -1
  22. package/runtime/.next/server/app/api/agent/stream/route.js +3 -3
  23. package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js +1 -1
  24. package/runtime/.next/server/app/api/agent-workspaces/route.js +1 -1
  25. package/runtime/.next/server/app/api/auth/verify/route.js +1 -1
  26. package/runtime/.next/server/app/api/business/route.js +1 -1
  27. package/runtime/.next/server/app/api/client-logs/route.js +1 -1
  28. package/runtime/.next/server/app/api/collaboration/route.js +1 -1
  29. package/runtime/.next/server/app/api/flow/v1/catalog/route.js +1 -1
  30. package/runtime/.next/server/app/api/flow/v1/runs/[runId]/cancel/route.js +1 -1
  31. package/runtime/.next/server/app/api/flow/v1/runs/[runId]/events/route.js +3 -3
  32. package/runtime/.next/server/app/api/flow/v1/runs/route.js +1 -1
  33. package/runtime/.next/server/app/api/flow-studio/config/route.js +1 -1
  34. package/runtime/.next/server/app/api/mcp/connect/route.js +1 -1
  35. package/runtime/.next/server/app/api/mcp/disconnect/route.js +1 -1
  36. package/runtime/.next/server/app/api/mcp/servers/route.js +1 -1
  37. package/runtime/.next/server/app/api/memory/[key]/route.js +1 -1
  38. package/runtime/.next/server/app/api/memory/route.js +1 -1
  39. package/runtime/.next/server/app/api/plugins/load/route.js +1 -1
  40. package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
  41. package/runtime/.next/server/app/api/projects/check/route.js +1 -1
  42. package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
  43. package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
  44. package/runtime/.next/server/app/api/projects/route.js +1 -1
  45. package/runtime/.next/server/app/api/push/subscribe/route.js +2 -2
  46. package/runtime/.next/server/app/api/push/unsubscribe/route.js +2 -2
  47. package/runtime/.next/server/app/api/push/vapid/route.js +2 -2
  48. package/runtime/.next/server/app/api/push/vapid.body +1 -1
  49. package/runtime/.next/server/app/api/remote-tools/register/route.js +1 -1
  50. package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +2 -2
  51. package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
  52. package/runtime/.next/server/app/api/sessions/[id]/fork-at/route.js +1 -1
  53. package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +1 -1
  54. package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
  55. package/runtime/.next/server/app/api/sessions/[id]/native-goal/route.js +1 -1
  56. package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js +1 -1
  57. package/runtime/.next/server/app/api/sessions/[id]/release/route.js +1 -1
  58. package/runtime/.next/server/app/api/sessions/[id]/route.js +1 -1
  59. package/runtime/.next/server/app/api/sessions/[id]/thread-goal/route.js +1 -1
  60. package/runtime/.next/server/app/api/sessions/[id]/tool-result/route.js +1 -1
  61. package/runtime/.next/server/app/api/sessions/route.js +1 -1
  62. package/runtime/.next/server/app/api/settings/route.js +1 -1
  63. package/runtime/.next/server/app/api/skills/route.js +1 -1
  64. package/runtime/.next/server/app/api/tool-policies/[policyId]/route.js +1 -1
  65. package/runtime/.next/server/app/api/tool-policies/route.js +1 -1
  66. package/runtime/.next/server/app/api/tools/route.js +1 -1
  67. package/runtime/.next/server/app/api/update/check/route.js +1 -1
  68. package/runtime/.next/server/app/api/update/install/route.js +1 -1
  69. package/runtime/.next/server/app/api/update/status/route.js +1 -1
  70. package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
  71. package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
  72. package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
  73. package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
  74. package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
  75. package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
  76. package/runtime/.next/server/app/api/web-console/computer-settings/route.js +1 -1
  77. package/runtime/.next/server/app/api/web-console/computers/route.js +1 -1
  78. package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
  79. package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
  80. package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
  81. package/runtime/.next/server/app/web/page.js +4 -4
  82. package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
  83. package/runtime/.next/server/app-paths-manifest.json +35 -35
  84. package/runtime/.next/server/chunks/5303.js +1 -1
  85. package/runtime/.next/server/middleware-build-manifest.js +1 -1
  86. package/runtime/.next/server/pages/404.html +1 -1
  87. package/runtime/.next/server/pages/500.html +1 -1
  88. package/runtime/.next/server/pages-manifest.json +1 -1
  89. package/runtime/.next/server/server-reference-manifest.json +1 -1
  90. package/runtime/.next/static/chunks/216-befe93998f760830.js +1 -0
  91. package/runtime/.next/static/chunks/app/web/{error-7ac82267d3330344.js → error-17e28c153738a003.js} +1 -1
  92. package/runtime/.next/static/chunks/app/web/layout-60e82f81fa232177.js +1 -0
  93. package/runtime/.next/static/chunks/app/web/page-9d2cdb1ef9ad40b2.js +1 -0
  94. package/runtime/.next/static/chunks/{main-app-51ee029f2d3c9d9e.js → main-app-a953e6764afe1e60.js} +1 -1
  95. package/runtime/.next/static/css/1c4153a5b834f93f.css +1 -0
  96. package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/MacOS/agentroam-remote-desktop +0 -0
  97. package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/Resources/agentroam-component.json +1 -1
  98. package/runtime/native/Support.noindex/AgentRoam Remote Desktop.app/Contents/_CodeSignature/CodeResources +2 -2
  99. package/runtime/node_modules/.package-lock.json +133 -128
  100. package/runtime/node_modules/@agent/native-runtime/dist/index.js +572 -93
  101. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs +75 -75
  102. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js +37 -37
  103. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-mh5qmqqf.mjs → core-1qw7dszx.mjs} +1 -1
  104. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-cz9sh4ze.mjs +40 -0
  105. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-nmrdrt5c.mjs +52 -0
  106. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/{core-p79weg14.mjs → core-nxm5bcfb.mjs} +4 -4
  107. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core.mjs +10 -10
  108. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/extractFromBunfs.js +169 -40
  109. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.json +21 -23
  110. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json +25 -27
  111. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/package.json +14 -14
  112. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs +74 -74
  113. package/runtime/node_modules/caniuse-lite/data/agents.js +1 -1
  114. package/runtime/node_modules/caniuse-lite/data/browserVersions.js +1 -1
  115. package/runtime/node_modules/caniuse-lite/data/features/aac.js +1 -1
  116. package/runtime/node_modules/caniuse-lite/data/features/abortcontroller.js +1 -1
  117. package/runtime/node_modules/caniuse-lite/data/features/ac3-ec3.js +1 -1
  118. package/runtime/node_modules/caniuse-lite/data/features/accelerometer.js +1 -1
  119. package/runtime/node_modules/caniuse-lite/data/features/addeventlistener.js +1 -1
  120. package/runtime/node_modules/caniuse-lite/data/features/alternate-stylesheet.js +1 -1
  121. package/runtime/node_modules/caniuse-lite/data/features/ambient-light.js +1 -1
  122. package/runtime/node_modules/caniuse-lite/data/features/apng.js +1 -1
  123. package/runtime/node_modules/caniuse-lite/data/features/array-find-index.js +1 -1
  124. package/runtime/node_modules/caniuse-lite/data/features/array-find.js +1 -1
  125. package/runtime/node_modules/caniuse-lite/data/features/array-flat.js +1 -1
  126. package/runtime/node_modules/caniuse-lite/data/features/array-includes.js +1 -1
  127. package/runtime/node_modules/caniuse-lite/data/features/arrow-functions.js +1 -1
  128. package/runtime/node_modules/caniuse-lite/data/features/asmjs.js +1 -1
  129. package/runtime/node_modules/caniuse-lite/data/features/async-clipboard.js +1 -1
  130. package/runtime/node_modules/caniuse-lite/data/features/async-functions.js +1 -1
  131. package/runtime/node_modules/caniuse-lite/data/features/atob-btoa.js +1 -1
  132. package/runtime/node_modules/caniuse-lite/data/features/audio-api.js +1 -1
  133. package/runtime/node_modules/caniuse-lite/data/features/audio.js +1 -1
  134. package/runtime/node_modules/caniuse-lite/data/features/audiotracks.js +1 -1
  135. package/runtime/node_modules/caniuse-lite/data/features/autofocus.js +1 -1
  136. package/runtime/node_modules/caniuse-lite/data/features/auxclick.js +1 -1
  137. package/runtime/node_modules/caniuse-lite/data/features/av1.js +1 -1
  138. package/runtime/node_modules/caniuse-lite/data/features/avif.js +1 -1
  139. package/runtime/node_modules/caniuse-lite/data/features/background-attachment.js +1 -1
  140. package/runtime/node_modules/caniuse-lite/data/features/background-clip-text.js +1 -1
  141. package/runtime/node_modules/caniuse-lite/data/features/background-img-opts.js +1 -1
  142. package/runtime/node_modules/caniuse-lite/data/features/background-position-x-y.js +1 -1
  143. package/runtime/node_modules/caniuse-lite/data/features/background-repeat-round-space.js +1 -1
  144. package/runtime/node_modules/caniuse-lite/data/features/background-sync.js +1 -1
  145. package/runtime/node_modules/caniuse-lite/data/features/battery-status.js +1 -1
  146. package/runtime/node_modules/caniuse-lite/data/features/beacon.js +1 -1
  147. package/runtime/node_modules/caniuse-lite/data/features/beforeafterprint.js +1 -1
  148. package/runtime/node_modules/caniuse-lite/data/features/bigint.js +1 -1
  149. package/runtime/node_modules/caniuse-lite/data/features/blobbuilder.js +1 -1
  150. package/runtime/node_modules/caniuse-lite/data/features/bloburls.js +1 -1
  151. package/runtime/node_modules/caniuse-lite/data/features/border-image.js +1 -1
  152. package/runtime/node_modules/caniuse-lite/data/features/border-radius.js +1 -1
  153. package/runtime/node_modules/caniuse-lite/data/features/broadcastchannel.js +1 -1
  154. package/runtime/node_modules/caniuse-lite/data/features/brotli.js +1 -1
  155. package/runtime/node_modules/caniuse-lite/data/features/calc.js +1 -1
  156. package/runtime/node_modules/caniuse-lite/data/features/canvas-blending.js +1 -1
  157. package/runtime/node_modules/caniuse-lite/data/features/canvas-text.js +1 -1
  158. package/runtime/node_modules/caniuse-lite/data/features/canvas.js +1 -1
  159. package/runtime/node_modules/caniuse-lite/data/features/ch-unit.js +1 -1
  160. package/runtime/node_modules/caniuse-lite/data/features/chacha20-poly1305.js +1 -1
  161. package/runtime/node_modules/caniuse-lite/data/features/channel-messaging.js +1 -1
  162. package/runtime/node_modules/caniuse-lite/data/features/childnode-remove.js +1 -1
  163. package/runtime/node_modules/caniuse-lite/data/features/classlist.js +1 -1
  164. package/runtime/node_modules/caniuse-lite/data/features/client-hints-dpr-width-viewport.js +1 -1
  165. package/runtime/node_modules/caniuse-lite/data/features/clipboard.js +1 -1
  166. package/runtime/node_modules/caniuse-lite/data/features/colr-v1.js +1 -1
  167. package/runtime/node_modules/caniuse-lite/data/features/colr.js +1 -1
  168. package/runtime/node_modules/caniuse-lite/data/features/comparedocumentposition.js +1 -1
  169. package/runtime/node_modules/caniuse-lite/data/features/console-basic.js +1 -1
  170. package/runtime/node_modules/caniuse-lite/data/features/console-time.js +1 -1
  171. package/runtime/node_modules/caniuse-lite/data/features/const.js +1 -1
  172. package/runtime/node_modules/caniuse-lite/data/features/constraint-validation.js +1 -1
  173. package/runtime/node_modules/caniuse-lite/data/features/contenteditable.js +1 -1
  174. package/runtime/node_modules/caniuse-lite/data/features/contentsecuritypolicy.js +1 -1
  175. package/runtime/node_modules/caniuse-lite/data/features/contentsecuritypolicy2.js +1 -1
  176. package/runtime/node_modules/caniuse-lite/data/features/cookie-store-api.js +1 -1
  177. package/runtime/node_modules/caniuse-lite/data/features/cors.js +1 -1
  178. package/runtime/node_modules/caniuse-lite/data/features/createimagebitmap.js +1 -1
  179. package/runtime/node_modules/caniuse-lite/data/features/credential-management.js +1 -1
  180. package/runtime/node_modules/caniuse-lite/data/features/cross-document-view-transitions.js +1 -1
  181. package/runtime/node_modules/caniuse-lite/data/features/cryptography.js +1 -1
  182. package/runtime/node_modules/caniuse-lite/data/features/css-all.js +1 -1
  183. package/runtime/node_modules/caniuse-lite/data/features/css-anchor-positioning.js +1 -1
  184. package/runtime/node_modules/caniuse-lite/data/features/css-animation.js +1 -1
  185. package/runtime/node_modules/caniuse-lite/data/features/css-any-link.js +1 -1
  186. package/runtime/node_modules/caniuse-lite/data/features/css-appearance.js +1 -1
  187. package/runtime/node_modules/caniuse-lite/data/features/css-at-counter-style.js +1 -1
  188. package/runtime/node_modules/caniuse-lite/data/features/css-autofill.js +1 -1
  189. package/runtime/node_modules/caniuse-lite/data/features/css-backdrop-filter.js +1 -1
  190. package/runtime/node_modules/caniuse-lite/data/features/css-background-offsets.js +1 -1
  191. package/runtime/node_modules/caniuse-lite/data/features/css-backgroundblendmode.js +1 -1
  192. package/runtime/node_modules/caniuse-lite/data/features/css-boxdecorationbreak.js +1 -1
  193. package/runtime/node_modules/caniuse-lite/data/features/css-boxshadow.js +1 -1
  194. package/runtime/node_modules/caniuse-lite/data/features/css-canvas.js +1 -1
  195. package/runtime/node_modules/caniuse-lite/data/features/css-caret-color.js +1 -1
  196. package/runtime/node_modules/caniuse-lite/data/features/css-cascade-layers.js +1 -1
  197. package/runtime/node_modules/caniuse-lite/data/features/css-cascade-scope.js +1 -1
  198. package/runtime/node_modules/caniuse-lite/data/features/css-case-insensitive.js +1 -1
  199. package/runtime/node_modules/caniuse-lite/data/features/css-clip-path.js +1 -1
  200. package/runtime/node_modules/caniuse-lite/data/features/css-color-adjust.js +1 -1
  201. package/runtime/node_modules/caniuse-lite/data/features/css-color-function.js +1 -1
  202. package/runtime/node_modules/caniuse-lite/data/features/css-conic-gradients.js +1 -1
  203. package/runtime/node_modules/caniuse-lite/data/features/css-container-queries-style.js +1 -1
  204. package/runtime/node_modules/caniuse-lite/data/features/css-container-queries.js +1 -1
  205. package/runtime/node_modules/caniuse-lite/data/features/css-container-query-units.js +1 -1
  206. package/runtime/node_modules/caniuse-lite/data/features/css-containment.js +1 -1
  207. package/runtime/node_modules/caniuse-lite/data/features/css-content-visibility.js +1 -1
  208. package/runtime/node_modules/caniuse-lite/data/features/css-counters.js +1 -1
  209. package/runtime/node_modules/caniuse-lite/data/features/css-crisp-edges.js +1 -1
  210. package/runtime/node_modules/caniuse-lite/data/features/css-cross-fade.js +1 -1
  211. package/runtime/node_modules/caniuse-lite/data/features/css-default-pseudo.js +1 -1
  212. package/runtime/node_modules/caniuse-lite/data/features/css-descendant-gtgt.js +1 -1
  213. package/runtime/node_modules/caniuse-lite/data/features/css-deviceadaptation.js +1 -1
  214. package/runtime/node_modules/caniuse-lite/data/features/css-dir-pseudo.js +1 -1
  215. package/runtime/node_modules/caniuse-lite/data/features/css-display-contents.js +1 -1
  216. package/runtime/node_modules/caniuse-lite/data/features/css-element-function.js +1 -1
  217. package/runtime/node_modules/caniuse-lite/data/features/css-env-function.js +1 -1
  218. package/runtime/node_modules/caniuse-lite/data/features/css-exclusions.js +1 -1
  219. package/runtime/node_modules/caniuse-lite/data/features/css-featurequeries.js +1 -1
  220. package/runtime/node_modules/caniuse-lite/data/features/css-file-selector-button.js +1 -1
  221. package/runtime/node_modules/caniuse-lite/data/features/css-filter-function.js +1 -1
  222. package/runtime/node_modules/caniuse-lite/data/features/css-filters.js +1 -1
  223. package/runtime/node_modules/caniuse-lite/data/features/css-first-letter.js +1 -1
  224. package/runtime/node_modules/caniuse-lite/data/features/css-first-line.js +1 -1
  225. package/runtime/node_modules/caniuse-lite/data/features/css-fixed.js +1 -1
  226. package/runtime/node_modules/caniuse-lite/data/features/css-focus-visible.js +1 -1
  227. package/runtime/node_modules/caniuse-lite/data/features/css-focus-within.js +1 -1
  228. package/runtime/node_modules/caniuse-lite/data/features/css-font-palette.js +1 -1
  229. package/runtime/node_modules/caniuse-lite/data/features/css-font-rendering-controls.js +1 -1
  230. package/runtime/node_modules/caniuse-lite/data/features/css-font-stretch.js +1 -1
  231. package/runtime/node_modules/caniuse-lite/data/features/css-gencontent.js +1 -1
  232. package/runtime/node_modules/caniuse-lite/data/features/css-gradients.js +1 -1
  233. package/runtime/node_modules/caniuse-lite/data/features/css-grid-animation.js +1 -1
  234. package/runtime/node_modules/caniuse-lite/data/features/css-grid-lanes.js +1 -1
  235. package/runtime/node_modules/caniuse-lite/data/features/css-grid.js +1 -1
  236. package/runtime/node_modules/caniuse-lite/data/features/css-hanging-punctuation.js +1 -1
  237. package/runtime/node_modules/caniuse-lite/data/features/css-has.js +1 -1
  238. package/runtime/node_modules/caniuse-lite/data/features/css-hyphens.js +1 -1
  239. package/runtime/node_modules/caniuse-lite/data/features/css-if.js +1 -1
  240. package/runtime/node_modules/caniuse-lite/data/features/css-image-orientation.js +1 -1
  241. package/runtime/node_modules/caniuse-lite/data/features/css-image-set.js +1 -1
  242. package/runtime/node_modules/caniuse-lite/data/features/css-in-out-of-range.js +1 -1
  243. package/runtime/node_modules/caniuse-lite/data/features/css-indeterminate-pseudo.js +1 -1
  244. package/runtime/node_modules/caniuse-lite/data/features/css-initial-letter.js +1 -1
  245. package/runtime/node_modules/caniuse-lite/data/features/css-initial-value.js +1 -1
  246. package/runtime/node_modules/caniuse-lite/data/features/css-lch-lab.js +1 -1
  247. package/runtime/node_modules/caniuse-lite/data/features/css-letter-spacing.js +1 -1
  248. package/runtime/node_modules/caniuse-lite/data/features/css-line-clamp.js +1 -1
  249. package/runtime/node_modules/caniuse-lite/data/features/css-logical-props.js +1 -1
  250. package/runtime/node_modules/caniuse-lite/data/features/css-marker-pseudo.js +1 -1
  251. package/runtime/node_modules/caniuse-lite/data/features/css-masks.js +1 -1
  252. package/runtime/node_modules/caniuse-lite/data/features/css-matches-pseudo.js +1 -1
  253. package/runtime/node_modules/caniuse-lite/data/features/css-math-functions.js +1 -1
  254. package/runtime/node_modules/caniuse-lite/data/features/css-media-interaction.js +1 -1
  255. package/runtime/node_modules/caniuse-lite/data/features/css-media-range-syntax.js +1 -1
  256. package/runtime/node_modules/caniuse-lite/data/features/css-media-resolution.js +1 -1
  257. package/runtime/node_modules/caniuse-lite/data/features/css-media-scripting.js +1 -1
  258. package/runtime/node_modules/caniuse-lite/data/features/css-mediaqueries.js +1 -1
  259. package/runtime/node_modules/caniuse-lite/data/features/css-mixblendmode.js +1 -1
  260. package/runtime/node_modules/caniuse-lite/data/features/css-module-scripts.js +1 -1
  261. package/runtime/node_modules/caniuse-lite/data/features/css-motion-paths.js +1 -1
  262. package/runtime/node_modules/caniuse-lite/data/features/css-namespaces.js +1 -1
  263. package/runtime/node_modules/caniuse-lite/data/features/css-nesting.js +1 -1
  264. package/runtime/node_modules/caniuse-lite/data/features/css-not-sel-list.js +1 -1
  265. package/runtime/node_modules/caniuse-lite/data/features/css-nth-child-of.js +1 -1
  266. package/runtime/node_modules/caniuse-lite/data/features/css-opacity.js +1 -1
  267. package/runtime/node_modules/caniuse-lite/data/features/css-optional-pseudo.js +1 -1
  268. package/runtime/node_modules/caniuse-lite/data/features/css-overflow-anchor.js +1 -1
  269. package/runtime/node_modules/caniuse-lite/data/features/css-overflow-overlay.js +1 -1
  270. package/runtime/node_modules/caniuse-lite/data/features/css-overflow.js +1 -1
  271. package/runtime/node_modules/caniuse-lite/data/features/css-overscroll-behavior.js +1 -1
  272. package/runtime/node_modules/caniuse-lite/data/features/css-page-break.js +1 -1
  273. package/runtime/node_modules/caniuse-lite/data/features/css-paged-media.js +1 -1
  274. package/runtime/node_modules/caniuse-lite/data/features/css-paint-api.js +1 -1
  275. package/runtime/node_modules/caniuse-lite/data/features/css-placeholder-shown.js +1 -1
  276. package/runtime/node_modules/caniuse-lite/data/features/css-placeholder.js +1 -1
  277. package/runtime/node_modules/caniuse-lite/data/features/css-print-color-adjust.js +1 -1
  278. package/runtime/node_modules/caniuse-lite/data/features/css-read-only-write.js +1 -1
  279. package/runtime/node_modules/caniuse-lite/data/features/css-rebeccapurple.js +1 -1
  280. package/runtime/node_modules/caniuse-lite/data/features/css-reflections.js +1 -1
  281. package/runtime/node_modules/caniuse-lite/data/features/css-regions.js +1 -1
  282. package/runtime/node_modules/caniuse-lite/data/features/css-relative-colors.js +1 -1
  283. package/runtime/node_modules/caniuse-lite/data/features/css-repeating-gradients.js +1 -1
  284. package/runtime/node_modules/caniuse-lite/data/features/css-resize.js +1 -1
  285. package/runtime/node_modules/caniuse-lite/data/features/css-revert-value.js +1 -1
  286. package/runtime/node_modules/caniuse-lite/data/features/css-rrggbbaa.js +1 -1
  287. package/runtime/node_modules/caniuse-lite/data/features/css-scroll-behavior.js +1 -1
  288. package/runtime/node_modules/caniuse-lite/data/features/css-scrollbar.js +1 -1
  289. package/runtime/node_modules/caniuse-lite/data/features/css-sel2.js +1 -1
  290. package/runtime/node_modules/caniuse-lite/data/features/css-sel3.js +1 -1
  291. package/runtime/node_modules/caniuse-lite/data/features/css-selection.js +1 -1
  292. package/runtime/node_modules/caniuse-lite/data/features/css-shapes.js +1 -1
  293. package/runtime/node_modules/caniuse-lite/data/features/css-snappoints.js +1 -1
  294. package/runtime/node_modules/caniuse-lite/data/features/css-sticky.js +1 -1
  295. package/runtime/node_modules/caniuse-lite/data/features/css-subgrid.js +1 -1
  296. package/runtime/node_modules/caniuse-lite/data/features/css-supports-api.js +1 -1
  297. package/runtime/node_modules/caniuse-lite/data/features/css-table.js +1 -1
  298. package/runtime/node_modules/caniuse-lite/data/features/css-text-align-last.js +1 -1
  299. package/runtime/node_modules/caniuse-lite/data/features/css-text-box-trim.js +1 -1
  300. package/runtime/node_modules/caniuse-lite/data/features/css-text-indent.js +1 -1
  301. package/runtime/node_modules/caniuse-lite/data/features/css-text-justify.js +1 -1
  302. package/runtime/node_modules/caniuse-lite/data/features/css-text-orientation.js +1 -1
  303. package/runtime/node_modules/caniuse-lite/data/features/css-text-spacing.js +1 -1
  304. package/runtime/node_modules/caniuse-lite/data/features/css-text-wrap-balance.js +1 -1
  305. package/runtime/node_modules/caniuse-lite/data/features/css-textshadow.js +1 -1
  306. package/runtime/node_modules/caniuse-lite/data/features/css-touch-action.js +1 -1
  307. package/runtime/node_modules/caniuse-lite/data/features/css-transitions.js +1 -1
  308. package/runtime/node_modules/caniuse-lite/data/features/css-unicode-bidi.js +1 -1
  309. package/runtime/node_modules/caniuse-lite/data/features/css-unset-value.js +1 -1
  310. package/runtime/node_modules/caniuse-lite/data/features/css-variables.js +1 -1
  311. package/runtime/node_modules/caniuse-lite/data/features/css-when-else.js +1 -1
  312. package/runtime/node_modules/caniuse-lite/data/features/css-widows-orphans.js +1 -1
  313. package/runtime/node_modules/caniuse-lite/data/features/css-width-stretch.js +1 -1
  314. package/runtime/node_modules/caniuse-lite/data/features/css-writing-mode.js +1 -1
  315. package/runtime/node_modules/caniuse-lite/data/features/css-zoom.js +1 -1
  316. package/runtime/node_modules/caniuse-lite/data/features/css3-attr.js +1 -1
  317. package/runtime/node_modules/caniuse-lite/data/features/css3-boxsizing.js +1 -1
  318. package/runtime/node_modules/caniuse-lite/data/features/css3-colors.js +1 -1
  319. package/runtime/node_modules/caniuse-lite/data/features/css3-cursors-grab.js +1 -1
  320. package/runtime/node_modules/caniuse-lite/data/features/css3-cursors-newer.js +1 -1
  321. package/runtime/node_modules/caniuse-lite/data/features/css3-cursors.js +1 -1
  322. package/runtime/node_modules/caniuse-lite/data/features/css3-tabsize.js +1 -1
  323. package/runtime/node_modules/caniuse-lite/data/features/currentcolor.js +1 -1
  324. package/runtime/node_modules/caniuse-lite/data/features/custom-elements.js +1 -1
  325. package/runtime/node_modules/caniuse-lite/data/features/custom-elementsv1.js +1 -1
  326. package/runtime/node_modules/caniuse-lite/data/features/customevent.js +1 -1
  327. package/runtime/node_modules/caniuse-lite/data/features/customizable-select.js +1 -1
  328. package/runtime/node_modules/caniuse-lite/data/features/datalist.js +1 -1
  329. package/runtime/node_modules/caniuse-lite/data/features/dataset.js +1 -1
  330. package/runtime/node_modules/caniuse-lite/data/features/datauri.js +1 -1
  331. package/runtime/node_modules/caniuse-lite/data/features/date-tolocaledatestring.js +1 -1
  332. package/runtime/node_modules/caniuse-lite/data/features/declarative-shadow-dom.js +1 -1
  333. package/runtime/node_modules/caniuse-lite/data/features/decorators.js +1 -1
  334. package/runtime/node_modules/caniuse-lite/data/features/details.js +1 -1
  335. package/runtime/node_modules/caniuse-lite/data/features/deviceorientation.js +1 -1
  336. package/runtime/node_modules/caniuse-lite/data/features/devicepixelratio.js +1 -1
  337. package/runtime/node_modules/caniuse-lite/data/features/dialog.js +1 -1
  338. package/runtime/node_modules/caniuse-lite/data/features/dispatchevent.js +1 -1
  339. package/runtime/node_modules/caniuse-lite/data/features/dnssec.js +1 -1
  340. package/runtime/node_modules/caniuse-lite/data/features/do-not-track.js +1 -1
  341. package/runtime/node_modules/caniuse-lite/data/features/document-currentscript.js +1 -1
  342. package/runtime/node_modules/caniuse-lite/data/features/document-evaluate-xpath.js +1 -1
  343. package/runtime/node_modules/caniuse-lite/data/features/document-execcommand.js +1 -1
  344. package/runtime/node_modules/caniuse-lite/data/features/document-policy.js +1 -1
  345. package/runtime/node_modules/caniuse-lite/data/features/document-scrollingelement.js +1 -1
  346. package/runtime/node_modules/caniuse-lite/data/features/documenthead.js +1 -1
  347. package/runtime/node_modules/caniuse-lite/data/features/dom-manip-convenience.js +1 -1
  348. package/runtime/node_modules/caniuse-lite/data/features/dom-range.js +1 -1
  349. package/runtime/node_modules/caniuse-lite/data/features/domcontentloaded.js +1 -1
  350. package/runtime/node_modules/caniuse-lite/data/features/dommatrix.js +1 -1
  351. package/runtime/node_modules/caniuse-lite/data/features/download.js +1 -1
  352. package/runtime/node_modules/caniuse-lite/data/features/dragndrop.js +1 -1
  353. package/runtime/node_modules/caniuse-lite/data/features/element-closest.js +1 -1
  354. package/runtime/node_modules/caniuse-lite/data/features/element-from-point.js +1 -1
  355. package/runtime/node_modules/caniuse-lite/data/features/element-scroll-methods.js +1 -1
  356. package/runtime/node_modules/caniuse-lite/data/features/eme.js +1 -1
  357. package/runtime/node_modules/caniuse-lite/data/features/eot.js +1 -1
  358. package/runtime/node_modules/caniuse-lite/data/features/es5.js +1 -1
  359. package/runtime/node_modules/caniuse-lite/data/features/es6-class.js +1 -1
  360. package/runtime/node_modules/caniuse-lite/data/features/es6-generators.js +1 -1
  361. package/runtime/node_modules/caniuse-lite/data/features/es6-module-dynamic-import.js +1 -1
  362. package/runtime/node_modules/caniuse-lite/data/features/es6-module.js +1 -1
  363. package/runtime/node_modules/caniuse-lite/data/features/es6-number.js +1 -1
  364. package/runtime/node_modules/caniuse-lite/data/features/es6-string-includes.js +1 -1
  365. package/runtime/node_modules/caniuse-lite/data/features/es6.js +1 -1
  366. package/runtime/node_modules/caniuse-lite/data/features/eventsource.js +1 -1
  367. package/runtime/node_modules/caniuse-lite/data/features/extended-system-fonts.js +1 -1
  368. package/runtime/node_modules/caniuse-lite/data/features/feature-policy.js +1 -1
  369. package/runtime/node_modules/caniuse-lite/data/features/fetch.js +1 -1
  370. package/runtime/node_modules/caniuse-lite/data/features/fieldset-disabled.js +1 -1
  371. package/runtime/node_modules/caniuse-lite/data/features/fileapi.js +1 -1
  372. package/runtime/node_modules/caniuse-lite/data/features/filereader.js +1 -1
  373. package/runtime/node_modules/caniuse-lite/data/features/filereadersync.js +1 -1
  374. package/runtime/node_modules/caniuse-lite/data/features/filesystem.js +1 -1
  375. package/runtime/node_modules/caniuse-lite/data/features/flac.js +1 -1
  376. package/runtime/node_modules/caniuse-lite/data/features/flexbox-gap.js +1 -1
  377. package/runtime/node_modules/caniuse-lite/data/features/flexbox.js +1 -1
  378. package/runtime/node_modules/caniuse-lite/data/features/flow-root.js +1 -1
  379. package/runtime/node_modules/caniuse-lite/data/features/focusin-focusout-events.js +1 -1
  380. package/runtime/node_modules/caniuse-lite/data/features/font-family-system-ui.js +1 -1
  381. package/runtime/node_modules/caniuse-lite/data/features/font-feature.js +1 -1
  382. package/runtime/node_modules/caniuse-lite/data/features/font-kerning.js +1 -1
  383. package/runtime/node_modules/caniuse-lite/data/features/font-loading.js +1 -1
  384. package/runtime/node_modules/caniuse-lite/data/features/font-size-adjust.js +1 -1
  385. package/runtime/node_modules/caniuse-lite/data/features/font-smooth.js +1 -1
  386. package/runtime/node_modules/caniuse-lite/data/features/font-unicode-range.js +1 -1
  387. package/runtime/node_modules/caniuse-lite/data/features/font-variant-alternates.js +1 -1
  388. package/runtime/node_modules/caniuse-lite/data/features/font-variant-numeric.js +1 -1
  389. package/runtime/node_modules/caniuse-lite/data/features/fontface.js +1 -1
  390. package/runtime/node_modules/caniuse-lite/data/features/form-attribute.js +1 -1
  391. package/runtime/node_modules/caniuse-lite/data/features/form-submit-attributes.js +1 -1
  392. package/runtime/node_modules/caniuse-lite/data/features/form-validation.js +1 -1
  393. package/runtime/node_modules/caniuse-lite/data/features/forms.js +1 -1
  394. package/runtime/node_modules/caniuse-lite/data/features/fullscreen.js +1 -1
  395. package/runtime/node_modules/caniuse-lite/data/features/gamepad.js +1 -1
  396. package/runtime/node_modules/caniuse-lite/data/features/geolocation.js +1 -1
  397. package/runtime/node_modules/caniuse-lite/data/features/getboundingclientrect.js +1 -1
  398. package/runtime/node_modules/caniuse-lite/data/features/getcomputedstyle.js +1 -1
  399. package/runtime/node_modules/caniuse-lite/data/features/getelementsbyclassname.js +1 -1
  400. package/runtime/node_modules/caniuse-lite/data/features/getrandomvalues.js +1 -1
  401. package/runtime/node_modules/caniuse-lite/data/features/gyroscope.js +1 -1
  402. package/runtime/node_modules/caniuse-lite/data/features/hardwareconcurrency.js +1 -1
  403. package/runtime/node_modules/caniuse-lite/data/features/hashchange.js +1 -1
  404. package/runtime/node_modules/caniuse-lite/data/features/heif.js +1 -1
  405. package/runtime/node_modules/caniuse-lite/data/features/hevc.js +1 -1
  406. package/runtime/node_modules/caniuse-lite/data/features/hidden.js +1 -1
  407. package/runtime/node_modules/caniuse-lite/data/features/high-resolution-time.js +1 -1
  408. package/runtime/node_modules/caniuse-lite/data/features/history.js +1 -1
  409. package/runtime/node_modules/caniuse-lite/data/features/html-media-capture.js +1 -1
  410. package/runtime/node_modules/caniuse-lite/data/features/html5semantic.js +1 -1
  411. package/runtime/node_modules/caniuse-lite/data/features/http-live-streaming.js +1 -1
  412. package/runtime/node_modules/caniuse-lite/data/features/http2.js +1 -1
  413. package/runtime/node_modules/caniuse-lite/data/features/http3.js +1 -1
  414. package/runtime/node_modules/caniuse-lite/data/features/iframe-sandbox.js +1 -1
  415. package/runtime/node_modules/caniuse-lite/data/features/iframe-seamless.js +1 -1
  416. package/runtime/node_modules/caniuse-lite/data/features/iframe-srcdoc.js +1 -1
  417. package/runtime/node_modules/caniuse-lite/data/features/imagecapture.js +1 -1
  418. package/runtime/node_modules/caniuse-lite/data/features/ime.js +1 -1
  419. package/runtime/node_modules/caniuse-lite/data/features/img-naturalwidth-naturalheight.js +1 -1
  420. package/runtime/node_modules/caniuse-lite/data/features/import-maps.js +1 -1
  421. package/runtime/node_modules/caniuse-lite/data/features/imports.js +1 -1
  422. package/runtime/node_modules/caniuse-lite/data/features/indeterminate-checkbox.js +1 -1
  423. package/runtime/node_modules/caniuse-lite/data/features/indexeddb.js +1 -1
  424. package/runtime/node_modules/caniuse-lite/data/features/indexeddb2.js +1 -1
  425. package/runtime/node_modules/caniuse-lite/data/features/inline-block.js +1 -1
  426. package/runtime/node_modules/caniuse-lite/data/features/innertext.js +1 -1
  427. package/runtime/node_modules/caniuse-lite/data/features/input-autocomplete-onoff.js +1 -1
  428. package/runtime/node_modules/caniuse-lite/data/features/input-color.js +1 -1
  429. package/runtime/node_modules/caniuse-lite/data/features/input-datetime.js +1 -1
  430. package/runtime/node_modules/caniuse-lite/data/features/input-email-tel-url.js +1 -1
  431. package/runtime/node_modules/caniuse-lite/data/features/input-event.js +1 -1
  432. package/runtime/node_modules/caniuse-lite/data/features/input-file-accept.js +1 -1
  433. package/runtime/node_modules/caniuse-lite/data/features/input-file-directory.js +1 -1
  434. package/runtime/node_modules/caniuse-lite/data/features/input-file-multiple.js +1 -1
  435. package/runtime/node_modules/caniuse-lite/data/features/input-inputmode.js +1 -1
  436. package/runtime/node_modules/caniuse-lite/data/features/input-minlength.js +1 -1
  437. package/runtime/node_modules/caniuse-lite/data/features/input-number.js +1 -1
  438. package/runtime/node_modules/caniuse-lite/data/features/input-pattern.js +1 -1
  439. package/runtime/node_modules/caniuse-lite/data/features/input-placeholder.js +1 -1
  440. package/runtime/node_modules/caniuse-lite/data/features/input-range.js +1 -1
  441. package/runtime/node_modules/caniuse-lite/data/features/input-search.js +1 -1
  442. package/runtime/node_modules/caniuse-lite/data/features/input-selection.js +1 -1
  443. package/runtime/node_modules/caniuse-lite/data/features/insert-adjacent.js +1 -1
  444. package/runtime/node_modules/caniuse-lite/data/features/insertadjacenthtml.js +1 -1
  445. package/runtime/node_modules/caniuse-lite/data/features/internationalization.js +1 -1
  446. package/runtime/node_modules/caniuse-lite/data/features/intersectionobserver-v2.js +1 -1
  447. package/runtime/node_modules/caniuse-lite/data/features/intersectionobserver.js +1 -1
  448. package/runtime/node_modules/caniuse-lite/data/features/intl-pluralrules.js +1 -1
  449. package/runtime/node_modules/caniuse-lite/data/features/intrinsic-width.js +1 -1
  450. package/runtime/node_modules/caniuse-lite/data/features/jpeg2000.js +1 -1
  451. package/runtime/node_modules/caniuse-lite/data/features/jpegxl.js +1 -1
  452. package/runtime/node_modules/caniuse-lite/data/features/jpegxr.js +1 -1
  453. package/runtime/node_modules/caniuse-lite/data/features/js-regexp-lookbehind.js +1 -1
  454. package/runtime/node_modules/caniuse-lite/data/features/json.js +1 -1
  455. package/runtime/node_modules/caniuse-lite/data/features/justify-content-space-evenly.js +1 -1
  456. package/runtime/node_modules/caniuse-lite/data/features/kerning-pairs-ligatures.js +1 -1
  457. package/runtime/node_modules/caniuse-lite/data/features/keyboardevent-charcode.js +1 -1
  458. package/runtime/node_modules/caniuse-lite/data/features/keyboardevent-code.js +1 -1
  459. package/runtime/node_modules/caniuse-lite/data/features/keyboardevent-getmodifierstate.js +1 -1
  460. package/runtime/node_modules/caniuse-lite/data/features/keyboardevent-key.js +1 -1
  461. package/runtime/node_modules/caniuse-lite/data/features/keyboardevent-location.js +1 -1
  462. package/runtime/node_modules/caniuse-lite/data/features/keyboardevent-which.js +1 -1
  463. package/runtime/node_modules/caniuse-lite/data/features/lazyload.js +1 -1
  464. package/runtime/node_modules/caniuse-lite/data/features/let.js +1 -1
  465. package/runtime/node_modules/caniuse-lite/data/features/link-icon-png.js +1 -1
  466. package/runtime/node_modules/caniuse-lite/data/features/link-icon-svg.js +1 -1
  467. package/runtime/node_modules/caniuse-lite/data/features/link-rel-dns-prefetch.js +1 -1
  468. package/runtime/node_modules/caniuse-lite/data/features/link-rel-modulepreload.js +1 -1
  469. package/runtime/node_modules/caniuse-lite/data/features/link-rel-preconnect.js +1 -1
  470. package/runtime/node_modules/caniuse-lite/data/features/link-rel-prefetch.js +1 -1
  471. package/runtime/node_modules/caniuse-lite/data/features/link-rel-preload.js +1 -1
  472. package/runtime/node_modules/caniuse-lite/data/features/link-rel-prerender.js +1 -1
  473. package/runtime/node_modules/caniuse-lite/data/features/loading-lazy-attr.js +1 -1
  474. package/runtime/node_modules/caniuse-lite/data/features/loading-lazy-media.js +1 -1
  475. package/runtime/node_modules/caniuse-lite/data/features/localecompare.js +1 -1
  476. package/runtime/node_modules/caniuse-lite/data/features/magnetometer.js +1 -1
  477. package/runtime/node_modules/caniuse-lite/data/features/matchesselector.js +1 -1
  478. package/runtime/node_modules/caniuse-lite/data/features/matchmedia.js +1 -1
  479. package/runtime/node_modules/caniuse-lite/data/features/mathml.js +1 -1
  480. package/runtime/node_modules/caniuse-lite/data/features/maxlength.js +1 -1
  481. package/runtime/node_modules/caniuse-lite/data/features/mdn-css-backdrop-pseudo-element.js +1 -1
  482. package/runtime/node_modules/caniuse-lite/data/features/mdn-css-unicode-bidi-isolate-override.js +1 -1
  483. package/runtime/node_modules/caniuse-lite/data/features/mdn-css-unicode-bidi-isolate.js +1 -1
  484. package/runtime/node_modules/caniuse-lite/data/features/mdn-css-unicode-bidi-plaintext.js +1 -1
  485. package/runtime/node_modules/caniuse-lite/data/features/mdn-text-decoration-color.js +1 -1
  486. package/runtime/node_modules/caniuse-lite/data/features/mdn-text-decoration-line.js +1 -1
  487. package/runtime/node_modules/caniuse-lite/data/features/mdn-text-decoration-shorthand.js +1 -1
  488. package/runtime/node_modules/caniuse-lite/data/features/mdn-text-decoration-style.js +1 -1
  489. package/runtime/node_modules/caniuse-lite/data/features/media-fragments.js +1 -1
  490. package/runtime/node_modules/caniuse-lite/data/features/mediacapture-fromelement.js +1 -1
  491. package/runtime/node_modules/caniuse-lite/data/features/mediarecorder.js +1 -1
  492. package/runtime/node_modules/caniuse-lite/data/features/mediasource.js +1 -1
  493. package/runtime/node_modules/caniuse-lite/data/features/menu.js +1 -1
  494. package/runtime/node_modules/caniuse-lite/data/features/meta-theme-color.js +1 -1
  495. package/runtime/node_modules/caniuse-lite/data/features/meter.js +1 -1
  496. package/runtime/node_modules/caniuse-lite/data/features/midi.js +1 -1
  497. package/runtime/node_modules/caniuse-lite/data/features/minmaxwh.js +1 -1
  498. package/runtime/node_modules/caniuse-lite/data/features/mp3.js +1 -1
  499. package/runtime/node_modules/caniuse-lite/data/features/mpeg-dash.js +1 -1
  500. package/runtime/node_modules/caniuse-lite/data/features/mpeg4.js +1 -1
  501. package/runtime/node_modules/caniuse-lite/data/features/multibackgrounds.js +1 -1
  502. package/runtime/node_modules/caniuse-lite/data/features/multicolumn.js +1 -1
  503. package/runtime/node_modules/caniuse-lite/data/features/mutation-events.js +1 -1
  504. package/runtime/node_modules/caniuse-lite/data/features/mutationobserver.js +1 -1
  505. package/runtime/node_modules/caniuse-lite/data/features/namevalue-storage.js +1 -1
  506. package/runtime/node_modules/caniuse-lite/data/features/native-filesystem-api.js +1 -1
  507. package/runtime/node_modules/caniuse-lite/data/features/nav-timing.js +1 -1
  508. package/runtime/node_modules/caniuse-lite/data/features/netinfo.js +1 -1
  509. package/runtime/node_modules/caniuse-lite/data/features/notifications.js +1 -1
  510. package/runtime/node_modules/caniuse-lite/data/features/object-entries.js +1 -1
  511. package/runtime/node_modules/caniuse-lite/data/features/object-fit.js +1 -1
  512. package/runtime/node_modules/caniuse-lite/data/features/object-observe.js +1 -1
  513. package/runtime/node_modules/caniuse-lite/data/features/object-values.js +1 -1
  514. package/runtime/node_modules/caniuse-lite/data/features/objectrtc.js +1 -1
  515. package/runtime/node_modules/caniuse-lite/data/features/offline-apps.js +1 -1
  516. package/runtime/node_modules/caniuse-lite/data/features/offscreencanvas.js +1 -1
  517. package/runtime/node_modules/caniuse-lite/data/features/ogg-vorbis.js +1 -1
  518. package/runtime/node_modules/caniuse-lite/data/features/ogv.js +1 -1
  519. package/runtime/node_modules/caniuse-lite/data/features/ol-reversed.js +1 -1
  520. package/runtime/node_modules/caniuse-lite/data/features/once-event-listener.js +1 -1
  521. package/runtime/node_modules/caniuse-lite/data/features/online-status.js +1 -1
  522. package/runtime/node_modules/caniuse-lite/data/features/opus.js +1 -1
  523. package/runtime/node_modules/caniuse-lite/data/features/orientation-sensor.js +1 -1
  524. package/runtime/node_modules/caniuse-lite/data/features/outline.js +1 -1
  525. package/runtime/node_modules/caniuse-lite/data/features/pad-start-end.js +1 -1
  526. package/runtime/node_modules/caniuse-lite/data/features/page-transition-events.js +1 -1
  527. package/runtime/node_modules/caniuse-lite/data/features/pagevisibility.js +1 -1
  528. package/runtime/node_modules/caniuse-lite/data/features/passive-event-listener.js +1 -1
  529. package/runtime/node_modules/caniuse-lite/data/features/passkeys.js +1 -1
  530. package/runtime/node_modules/caniuse-lite/data/features/passwordrules.js +1 -1
  531. package/runtime/node_modules/caniuse-lite/data/features/path2d.js +1 -1
  532. package/runtime/node_modules/caniuse-lite/data/features/payment-request.js +1 -1
  533. package/runtime/node_modules/caniuse-lite/data/features/pdf-viewer.js +1 -1
  534. package/runtime/node_modules/caniuse-lite/data/features/permissions-api.js +1 -1
  535. package/runtime/node_modules/caniuse-lite/data/features/permissions-policy.js +1 -1
  536. package/runtime/node_modules/caniuse-lite/data/features/picture-in-picture.js +1 -1
  537. package/runtime/node_modules/caniuse-lite/data/features/picture.js +1 -1
  538. package/runtime/node_modules/caniuse-lite/data/features/ping.js +1 -1
  539. package/runtime/node_modules/caniuse-lite/data/features/png-alpha.js +1 -1
  540. package/runtime/node_modules/caniuse-lite/data/features/pointer-events.js +1 -1
  541. package/runtime/node_modules/caniuse-lite/data/features/pointer.js +1 -1
  542. package/runtime/node_modules/caniuse-lite/data/features/pointerlock.js +1 -1
  543. package/runtime/node_modules/caniuse-lite/data/features/portals.js +1 -1
  544. package/runtime/node_modules/caniuse-lite/data/features/prefers-color-scheme.js +1 -1
  545. package/runtime/node_modules/caniuse-lite/data/features/prefers-reduced-motion.js +1 -1
  546. package/runtime/node_modules/caniuse-lite/data/features/progress.js +1 -1
  547. package/runtime/node_modules/caniuse-lite/data/features/promise-finally.js +1 -1
  548. package/runtime/node_modules/caniuse-lite/data/features/promises.js +1 -1
  549. package/runtime/node_modules/caniuse-lite/data/features/proximity.js +1 -1
  550. package/runtime/node_modules/caniuse-lite/data/features/proxy.js +1 -1
  551. package/runtime/node_modules/caniuse-lite/data/features/publickeypinning.js +1 -1
  552. package/runtime/node_modules/caniuse-lite/data/features/push-api.js +1 -1
  553. package/runtime/node_modules/caniuse-lite/data/features/queryselector.js +1 -1
  554. package/runtime/node_modules/caniuse-lite/data/features/readonly-attr.js +1 -1
  555. package/runtime/node_modules/caniuse-lite/data/features/referrer-policy.js +1 -1
  556. package/runtime/node_modules/caniuse-lite/data/features/registerprotocolhandler.js +1 -1
  557. package/runtime/node_modules/caniuse-lite/data/features/rel-noopener.js +1 -1
  558. package/runtime/node_modules/caniuse-lite/data/features/rel-noreferrer.js +1 -1
  559. package/runtime/node_modules/caniuse-lite/data/features/rellist.js +1 -1
  560. package/runtime/node_modules/caniuse-lite/data/features/rem.js +1 -1
  561. package/runtime/node_modules/caniuse-lite/data/features/requestanimationframe.js +1 -1
  562. package/runtime/node_modules/caniuse-lite/data/features/requestidlecallback.js +1 -1
  563. package/runtime/node_modules/caniuse-lite/data/features/resizeobserver.js +1 -1
  564. package/runtime/node_modules/caniuse-lite/data/features/resource-timing.js +1 -1
  565. package/runtime/node_modules/caniuse-lite/data/features/rest-parameters.js +1 -1
  566. package/runtime/node_modules/caniuse-lite/data/features/rtcpeerconnection.js +1 -1
  567. package/runtime/node_modules/caniuse-lite/data/features/ruby.js +1 -1
  568. package/runtime/node_modules/caniuse-lite/data/features/run-in.js +1 -1
  569. package/runtime/node_modules/caniuse-lite/data/features/same-site-cookie-attribute.js +1 -1
  570. package/runtime/node_modules/caniuse-lite/data/features/screen-orientation.js +1 -1
  571. package/runtime/node_modules/caniuse-lite/data/features/script-async.js +1 -1
  572. package/runtime/node_modules/caniuse-lite/data/features/script-defer.js +1 -1
  573. package/runtime/node_modules/caniuse-lite/data/features/scrollintoview.js +1 -1
  574. package/runtime/node_modules/caniuse-lite/data/features/scrollintoviewifneeded.js +1 -1
  575. package/runtime/node_modules/caniuse-lite/data/features/sdch.js +1 -1
  576. package/runtime/node_modules/caniuse-lite/data/features/selection-api.js +1 -1
  577. package/runtime/node_modules/caniuse-lite/data/features/server-timing.js +1 -1
  578. package/runtime/node_modules/caniuse-lite/data/features/serviceworkers.js +1 -1
  579. package/runtime/node_modules/caniuse-lite/data/features/setimmediate.js +1 -1
  580. package/runtime/node_modules/caniuse-lite/data/features/shadowdom.js +1 -1
  581. package/runtime/node_modules/caniuse-lite/data/features/shadowdomv1.js +1 -1
  582. package/runtime/node_modules/caniuse-lite/data/features/sharedarraybuffer.js +1 -1
  583. package/runtime/node_modules/caniuse-lite/data/features/sharedworkers.js +1 -1
  584. package/runtime/node_modules/caniuse-lite/data/features/sni.js +1 -1
  585. package/runtime/node_modules/caniuse-lite/data/features/spdy.js +1 -1
  586. package/runtime/node_modules/caniuse-lite/data/features/speech-recognition.js +1 -1
  587. package/runtime/node_modules/caniuse-lite/data/features/speech-synthesis.js +1 -1
  588. package/runtime/node_modules/caniuse-lite/data/features/spellcheck-attribute.js +1 -1
  589. package/runtime/node_modules/caniuse-lite/data/features/sql-storage.js +1 -1
  590. package/runtime/node_modules/caniuse-lite/data/features/srcset.js +1 -1
  591. package/runtime/node_modules/caniuse-lite/data/features/stream.js +1 -1
  592. package/runtime/node_modules/caniuse-lite/data/features/streams.js +1 -1
  593. package/runtime/node_modules/caniuse-lite/data/features/stricttransportsecurity.js +1 -1
  594. package/runtime/node_modules/caniuse-lite/data/features/style-scoped.js +1 -1
  595. package/runtime/node_modules/caniuse-lite/data/features/subresource-bundling.js +1 -1
  596. package/runtime/node_modules/caniuse-lite/data/features/subresource-integrity.js +1 -1
  597. package/runtime/node_modules/caniuse-lite/data/features/svg-css.js +1 -1
  598. package/runtime/node_modules/caniuse-lite/data/features/svg-filters.js +1 -1
  599. package/runtime/node_modules/caniuse-lite/data/features/svg-fonts.js +1 -1
  600. package/runtime/node_modules/caniuse-lite/data/features/svg-fragment.js +1 -1
  601. package/runtime/node_modules/caniuse-lite/data/features/svg-html.js +1 -1
  602. package/runtime/node_modules/caniuse-lite/data/features/svg-html5.js +1 -1
  603. package/runtime/node_modules/caniuse-lite/data/features/svg-img.js +1 -1
  604. package/runtime/node_modules/caniuse-lite/data/features/svg-smil.js +1 -1
  605. package/runtime/node_modules/caniuse-lite/data/features/svg.js +1 -1
  606. package/runtime/node_modules/caniuse-lite/data/features/sxg.js +1 -1
  607. package/runtime/node_modules/caniuse-lite/data/features/tabindex-attr.js +1 -1
  608. package/runtime/node_modules/caniuse-lite/data/features/template-literals.js +1 -1
  609. package/runtime/node_modules/caniuse-lite/data/features/template.js +1 -1
  610. package/runtime/node_modules/caniuse-lite/data/features/temporal.js +1 -1
  611. package/runtime/node_modules/caniuse-lite/data/features/testfeat.js +1 -1
  612. package/runtime/node_modules/caniuse-lite/data/features/text-decoration.js +1 -1
  613. package/runtime/node_modules/caniuse-lite/data/features/text-emphasis.js +1 -1
  614. package/runtime/node_modules/caniuse-lite/data/features/text-overflow.js +1 -1
  615. package/runtime/node_modules/caniuse-lite/data/features/text-size-adjust.js +1 -1
  616. package/runtime/node_modules/caniuse-lite/data/features/text-stroke.js +1 -1
  617. package/runtime/node_modules/caniuse-lite/data/features/textcontent.js +1 -1
  618. package/runtime/node_modules/caniuse-lite/data/features/textencoder.js +1 -1
  619. package/runtime/node_modules/caniuse-lite/data/features/tls1-1.js +1 -1
  620. package/runtime/node_modules/caniuse-lite/data/features/tls1-2.js +1 -1
  621. package/runtime/node_modules/caniuse-lite/data/features/tls1-3.js +1 -1
  622. package/runtime/node_modules/caniuse-lite/data/features/touch.js +1 -1
  623. package/runtime/node_modules/caniuse-lite/data/features/transforms2d.js +1 -1
  624. package/runtime/node_modules/caniuse-lite/data/features/transforms3d.js +1 -1
  625. package/runtime/node_modules/caniuse-lite/data/features/trusted-types.js +1 -1
  626. package/runtime/node_modules/caniuse-lite/data/features/ttf.js +1 -1
  627. package/runtime/node_modules/caniuse-lite/data/features/typedarrays.js +1 -1
  628. package/runtime/node_modules/caniuse-lite/data/features/u2f.js +1 -1
  629. package/runtime/node_modules/caniuse-lite/data/features/unhandledrejection.js +1 -1
  630. package/runtime/node_modules/caniuse-lite/data/features/upgradeinsecurerequests.js +1 -1
  631. package/runtime/node_modules/caniuse-lite/data/features/url-scroll-to-text-fragment.js +1 -1
  632. package/runtime/node_modules/caniuse-lite/data/features/url.js +1 -1
  633. package/runtime/node_modules/caniuse-lite/data/features/urlsearchparams.js +1 -1
  634. package/runtime/node_modules/caniuse-lite/data/features/use-strict.js +1 -1
  635. package/runtime/node_modules/caniuse-lite/data/features/user-select-none.js +1 -1
  636. package/runtime/node_modules/caniuse-lite/data/features/user-timing.js +1 -1
  637. package/runtime/node_modules/caniuse-lite/data/features/variable-fonts.js +1 -1
  638. package/runtime/node_modules/caniuse-lite/data/features/vector-effect.js +1 -1
  639. package/runtime/node_modules/caniuse-lite/data/features/vibration.js +1 -1
  640. package/runtime/node_modules/caniuse-lite/data/features/video.js +1 -1
  641. package/runtime/node_modules/caniuse-lite/data/features/videotracks.js +1 -1
  642. package/runtime/node_modules/caniuse-lite/data/features/view-transitions.js +1 -1
  643. package/runtime/node_modules/caniuse-lite/data/features/viewport-unit-variants.js +1 -1
  644. package/runtime/node_modules/caniuse-lite/data/features/viewport-units.js +1 -1
  645. package/runtime/node_modules/caniuse-lite/data/features/wai-aria.js +1 -1
  646. package/runtime/node_modules/caniuse-lite/data/features/wake-lock.js +1 -1
  647. package/runtime/node_modules/caniuse-lite/data/features/wasm-bigint.js +1 -1
  648. package/runtime/node_modules/caniuse-lite/data/features/wasm-bulk-memory.js +1 -1
  649. package/runtime/node_modules/caniuse-lite/data/features/wasm-extended-const.js +1 -1
  650. package/runtime/node_modules/caniuse-lite/data/features/wasm-gc.js +1 -1
  651. package/runtime/node_modules/caniuse-lite/data/features/wasm-multi-memory.js +1 -1
  652. package/runtime/node_modules/caniuse-lite/data/features/wasm-multi-value.js +1 -1
  653. package/runtime/node_modules/caniuse-lite/data/features/wasm-mutable-globals.js +1 -1
  654. package/runtime/node_modules/caniuse-lite/data/features/wasm-nontrapping-fptoint.js +1 -1
  655. package/runtime/node_modules/caniuse-lite/data/features/wasm-reference-types.js +1 -1
  656. package/runtime/node_modules/caniuse-lite/data/features/wasm-relaxed-simd.js +1 -1
  657. package/runtime/node_modules/caniuse-lite/data/features/wasm-signext.js +1 -1
  658. package/runtime/node_modules/caniuse-lite/data/features/wasm-simd.js +1 -1
  659. package/runtime/node_modules/caniuse-lite/data/features/wasm-tail-calls.js +1 -1
  660. package/runtime/node_modules/caniuse-lite/data/features/wasm-threads.js +1 -1
  661. package/runtime/node_modules/caniuse-lite/data/features/wasm.js +1 -1
  662. package/runtime/node_modules/caniuse-lite/data/features/wav.js +1 -1
  663. package/runtime/node_modules/caniuse-lite/data/features/wbr-element.js +1 -1
  664. package/runtime/node_modules/caniuse-lite/data/features/web-animation.js +1 -1
  665. package/runtime/node_modules/caniuse-lite/data/features/web-app-manifest.js +1 -1
  666. package/runtime/node_modules/caniuse-lite/data/features/web-bluetooth.js +1 -1
  667. package/runtime/node_modules/caniuse-lite/data/features/web-serial.js +1 -1
  668. package/runtime/node_modules/caniuse-lite/data/features/web-share.js +1 -1
  669. package/runtime/node_modules/caniuse-lite/data/features/webauthn.js +1 -1
  670. package/runtime/node_modules/caniuse-lite/data/features/webcodecs.js +1 -1
  671. package/runtime/node_modules/caniuse-lite/data/features/webgl.js +1 -1
  672. package/runtime/node_modules/caniuse-lite/data/features/webgl2.js +1 -1
  673. package/runtime/node_modules/caniuse-lite/data/features/webgpu.js +1 -1
  674. package/runtime/node_modules/caniuse-lite/data/features/webhid.js +1 -1
  675. package/runtime/node_modules/caniuse-lite/data/features/webkit-user-drag.js +1 -1
  676. package/runtime/node_modules/caniuse-lite/data/features/webm.js +1 -1
  677. package/runtime/node_modules/caniuse-lite/data/features/webnfc.js +1 -1
  678. package/runtime/node_modules/caniuse-lite/data/features/webp.js +1 -1
  679. package/runtime/node_modules/caniuse-lite/data/features/websockets.js +1 -1
  680. package/runtime/node_modules/caniuse-lite/data/features/webtransport.js +1 -1
  681. package/runtime/node_modules/caniuse-lite/data/features/webusb.js +1 -1
  682. package/runtime/node_modules/caniuse-lite/data/features/webvr.js +1 -1
  683. package/runtime/node_modules/caniuse-lite/data/features/webvtt.js +1 -1
  684. package/runtime/node_modules/caniuse-lite/data/features/webworkers.js +1 -1
  685. package/runtime/node_modules/caniuse-lite/data/features/webxr.js +1 -1
  686. package/runtime/node_modules/caniuse-lite/data/features/will-change.js +1 -1
  687. package/runtime/node_modules/caniuse-lite/data/features/woff.js +1 -1
  688. package/runtime/node_modules/caniuse-lite/data/features/woff2.js +1 -1
  689. package/runtime/node_modules/caniuse-lite/data/features/word-break.js +1 -1
  690. package/runtime/node_modules/caniuse-lite/data/features/wordwrap.js +1 -1
  691. package/runtime/node_modules/caniuse-lite/data/features/x-doc-messaging.js +1 -1
  692. package/runtime/node_modules/caniuse-lite/data/features/x-frame-options.js +1 -1
  693. package/runtime/node_modules/caniuse-lite/data/features/xhr2.js +1 -1
  694. package/runtime/node_modules/caniuse-lite/data/features/xhtml.js +1 -1
  695. package/runtime/node_modules/caniuse-lite/data/features/xhtmlsmil.js +1 -1
  696. package/runtime/node_modules/caniuse-lite/data/features/xml-serializer.js +1 -1
  697. package/runtime/node_modules/caniuse-lite/data/features/zstd.js +1 -1
  698. package/runtime/node_modules/caniuse-lite/data/versionGroups.js +1 -1
  699. package/runtime/node_modules/caniuse-lite/package.json +1 -1
  700. package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.cjs +25 -13
  701. package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.min.cjs +8 -8
  702. package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.min.mjs +8 -8
  703. package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.mjs +25 -13
  704. package/runtime/node_modules/mediabunny/dist/bundles/mediabunny.node.cjs +25 -13
  705. package/runtime/node_modules/mediabunny/dist/modules/src/isobmff/isobmff-demuxer.js +22 -11
  706. package/runtime/node_modules/mediabunny/dist/modules/src/matroska/matroska-demuxer.js +27 -11
  707. package/runtime/node_modules/mediabunny/dist/modules/src/tsconfig.tsbuildinfo +1 -1
  708. package/runtime/node_modules/mediabunny/dist/modules/src/version.js +1 -1
  709. package/runtime/node_modules/mediabunny/package.json +1 -1
  710. package/runtime/node_modules/mediabunny/src/isobmff/isobmff-demuxer.ts +23 -11
  711. package/runtime/node_modules/mediabunny/src/matroska/matroska-demuxer.ts +30 -11
  712. package/runtime/node_modules/mediabunny/src/version.ts +1 -1
  713. package/runtime/package-lock.json +166 -161
  714. package/runtime/server.js +1 -1
  715. package/runtime/webapp/dist/assets/{AiHubPane-D3O__UGN.js → AiHubPane-Cd-7gwJs.js} +1 -1
  716. package/runtime/webapp/dist/assets/{App-DJXr24vO.js → App-DQqv62sH.js} +57 -57
  717. package/runtime/webapp/dist/assets/{BrowserLivePanel-DEl_6FZj.js → BrowserLivePanel-DDrnghqj.js} +2 -2
  718. package/runtime/webapp/dist/assets/{CollaborationDashboard-DhLKl7mR.js → CollaborationDashboard-qQQqXrQI.js} +1 -1
  719. package/runtime/webapp/dist/assets/CollaborationPage-BS3Z5dAy.js +16 -0
  720. package/runtime/webapp/dist/assets/{FilePreview-BQBYZYpb.js → FilePreview-C4gxZRtw.js} +3 -3
  721. package/runtime/webapp/dist/assets/{FileTree-CXiXQO4N.js → FileTree-DrpruRST.js} +1 -1
  722. package/runtime/webapp/dist/assets/{FlowStudioPane-DUjBX_7t.js → FlowStudioPane-BjOuLwks.js} +1 -1
  723. package/runtime/webapp/dist/assets/{RemoteDesktopPage-BDK0Mq5I.js → RemoteDesktopPage-B1AGyJrT.js} +1 -1
  724. package/runtime/webapp/dist/assets/{TerminalPane-L6DN1Y0T.js → TerminalPane-BxEtw8rn.js} +1 -1
  725. package/runtime/webapp/dist/assets/{abnfDiagram-VCTEODGH-Dloq4lbc.js → abnfDiagram-VCTEODGH-BHgKdAyZ.js} +1 -1
  726. package/runtime/webapp/dist/assets/{arc-DdmNhDp9.js → arc-B8zNXyCl.js} +1 -1
  727. package/runtime/webapp/dist/assets/{architectureDiagram-5GKGNRK7-BTqm_9oY.js → architectureDiagram-5GKGNRK7-D596eLfj.js} +1 -1
  728. package/runtime/webapp/dist/assets/{artifact-links-BI9xeGhs.js → artifact-links-DwSH3xn_.js} +1 -1
  729. package/runtime/webapp/dist/assets/{blockDiagram-I7D4REHJ-jT-ztA_A.js → blockDiagram-I7D4REHJ-C4eZ-RzC.js} +1 -1
  730. package/runtime/webapp/dist/assets/{c4Diagram-7LVT6UL2-DxX89YpZ.js → c4Diagram-7LVT6UL2-Cxe44X-3.js} +1 -1
  731. package/runtime/webapp/dist/assets/channel-8FdPmR58.js +1 -0
  732. package/runtime/webapp/dist/assets/{chunk-2Q5K7J3B-BgXNuFPn.js → chunk-2Q5K7J3B-D_syaagC.js} +1 -1
  733. package/runtime/webapp/dist/assets/{chunk-5VM5RSS4-Bv7-4JNt.js → chunk-5VM5RSS4-q_wDWTVC.js} +1 -1
  734. package/runtime/webapp/dist/assets/{chunk-F27PBJKO-BNSskrgg.js → chunk-F27PBJKO-C5U_ckFK.js} +1 -1
  735. package/runtime/webapp/dist/assets/{chunk-IMKFNOWR-C166MQKM.js → chunk-IMKFNOWR-5a_rZZVM.js} +1 -1
  736. package/runtime/webapp/dist/assets/{chunk-JWPE2WC7-Bl1a_rZ8.js → chunk-JWPE2WC7-DR8znCWR.js} +1 -1
  737. package/runtime/webapp/dist/assets/{chunk-POPQ4Y6H-Ck6xvnVw.js → chunk-POPQ4Y6H-3vOXloa3.js} +1 -1
  738. package/runtime/webapp/dist/assets/{chunk-SVP7TREG-h6j1DDv5.js → chunk-SVP7TREG-y9Uxi4pg.js} +1 -1
  739. package/runtime/webapp/dist/assets/{chunk-TICWLB2K-BFafTq0K.js → chunk-TICWLB2K-Bi7VvqOR.js} +1 -1
  740. package/runtime/webapp/dist/assets/{chunk-XXDRQBXY-BQPWRmrg.js → chunk-XXDRQBXY-CRpw-5Cj.js} +1 -1
  741. package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-CCHBpIvI.js +1 -0
  742. package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-CCHBpIvI.js +1 -0
  743. package/runtime/webapp/dist/assets/{clipboard-B2fwlVD5.js → clipboard-BKglnESD.js} +1 -1
  744. package/runtime/webapp/dist/assets/{codeSyntax-VUYFxRDg.js → codeSyntax-Dmbrlor0.js} +1 -1
  745. package/runtime/webapp/dist/assets/{collaboration-CalhGKdD.js → collaboration-BZSnjFZ-.js} +1 -1
  746. package/runtime/webapp/dist/assets/{cose-bilkent-JH36ORCC-IgwThNmP.js → cose-bilkent-JH36ORCC-4JQKrvR5.js} +1 -1
  747. package/runtime/webapp/dist/assets/{cynefin-OW5HDTMX-kfamOzdb.js → cynefin-OW5HDTMX-BO4eLWHY.js} +1 -1
  748. package/runtime/webapp/dist/assets/{cynefinDiagram-5FMLGOSQ-TVskTO_2.js → cynefinDiagram-5FMLGOSQ-Dg-Bt9fs.js} +1 -1
  749. package/runtime/webapp/dist/assets/{dagre-GXQ25YYZ-DA85rDs9.js → dagre-GXQ25YYZ-utMMpYq0.js} +1 -1
  750. package/runtime/webapp/dist/assets/{diagram-S7CK7UJ4-CK0LkDfU.js → diagram-S7CK7UJ4-BUzOnotG.js} +1 -1
  751. package/runtime/webapp/dist/assets/{diagram-UQ7AKVKN-Bkskt6g2.js → diagram-UQ7AKVKN-Bkesml6e.js} +1 -1
  752. package/runtime/webapp/dist/assets/{diagram-VSXAHHWV-DN2UO2Hh.js → diagram-VSXAHHWV-P-Qqxnpn.js} +1 -1
  753. package/runtime/webapp/dist/assets/{diagram-VX7I27RA-BLSOCEKl.js → diagram-VX7I27RA-xpyBMRkH.js} +1 -1
  754. package/runtime/webapp/dist/assets/{diagram-Z3DM3KII-DNr6MVnd.js → diagram-Z3DM3KII-FMNqO2NJ.js} +1 -1
  755. package/runtime/webapp/dist/assets/{ebnfDiagram-PWID7BFC-CRASUUeC.js → ebnfDiagram-PWID7BFC-D8-cmvEK.js} +1 -1
  756. package/runtime/webapp/dist/assets/{erDiagram-RLTQ6QDP-1VwQNW79.js → erDiagram-RLTQ6QDP-mEgSpGUN.js} +1 -1
  757. package/runtime/webapp/dist/assets/{file-types-MDD5RUla.js → file-types-DgQXHGm7.js} +1 -1
  758. package/runtime/webapp/dist/assets/{flowDiagram-HODETNUW-DzhiH-fC.js → flowDiagram-HODETNUW-DJWXgpoo.js} +1 -1
  759. package/runtime/webapp/dist/assets/{ganttDiagram-EL5Y4UJY-DH8HcfJq.js → ganttDiagram-EL5Y4UJY-B5HA7Xox.js} +1 -1
  760. package/runtime/webapp/dist/assets/{gitGraphDiagram-WWUBYQGX-DYOG2d-R.js → gitGraphDiagram-WWUBYQGX-CP4Zmize.js} +1 -1
  761. package/runtime/webapp/dist/assets/index-BReRPZnZ.js +485 -0
  762. package/runtime/webapp/dist/assets/index-DfpiL3X7.css +1 -0
  763. package/runtime/webapp/dist/assets/{infoDiagram-27XIBGKW-DOjkALCi.js → infoDiagram-27XIBGKW-DApDSX70.js} +1 -1
  764. package/runtime/webapp/dist/assets/{ishikawaDiagram-5VMMS53U-DBXZxz82.js → ishikawaDiagram-5VMMS53U-BCYtD2Fm.js} +1 -1
  765. package/runtime/webapp/dist/assets/{journeyDiagram-3NMN7TZE-DEpi9Fbd.js → journeyDiagram-3NMN7TZE-D3WEyKHq.js} +1 -1
  766. package/runtime/webapp/dist/assets/{kanban-definition-UXKFOSKX-Chbcb2nn.js → kanban-definition-UXKFOSKX-Q6vb0ZbD.js} +1 -1
  767. package/runtime/webapp/dist/assets/{layout-0ld5oekM.js → layout-Bp7cvpx1.js} +1 -1
  768. package/runtime/webapp/dist/assets/{linear-BCRtBckJ.js → linear-4ik7NzLN.js} +1 -1
  769. package/runtime/webapp/dist/assets/{loader-circle-DGJsEr0r.js → loader-circle-BCsj2yyN.js} +1 -1
  770. package/runtime/webapp/dist/assets/{mermaid.core-ByBSaE2T.js → mermaid.core-CmhaKXiP.js} +5 -5
  771. package/runtime/webapp/dist/assets/{mindmap-definition-YA3MSWOX-BW9I4Kuv.js → mindmap-definition-YA3MSWOX-DabuuB2q.js} +1 -1
  772. package/runtime/webapp/dist/assets/{page-DVdz2jp6.js → page-Cgp9NEw1.js} +6 -6
  773. package/runtime/webapp/dist/assets/{pegDiagram-XKGWAZYB-D9oxCTQA.js → pegDiagram-XKGWAZYB-eIBdAhCQ.js} +1 -1
  774. package/runtime/webapp/dist/assets/{pieDiagram-E7YTZNPT-Ca4vPJj3.js → pieDiagram-E7YTZNPT-DUd7f60Q.js} +1 -1
  775. package/runtime/webapp/dist/assets/{quadrantDiagram-AXDQQJYC-DM9Go2ES.js → quadrantDiagram-AXDQQJYC-BPSqBWPV.js} +1 -1
  776. package/runtime/webapp/dist/assets/{railroadDiagram-O6MQD6OU-BinalW7_.js → railroadDiagram-O6MQD6OU-CHqMz56-.js} +1 -1
  777. package/runtime/webapp/dist/assets/{requirementDiagram-BXWQKSXE-C4KXL_m1.js → requirementDiagram-BXWQKSXE-BfOzGN7B.js} +1 -1
  778. package/runtime/webapp/dist/assets/{rotate-ccw-DrBaBbCR.js → rotate-ccw-p76OF6j6.js} +1 -1
  779. package/runtime/webapp/dist/assets/{rotate-cw-Ccsl7hB3.js → rotate-cw-D5iQzT0K.js} +1 -1
  780. package/runtime/webapp/dist/assets/{sankeyDiagram-P5KCCOFB-Ba3vi6ln.js → sankeyDiagram-P5KCCOFB-BFOPAhWl.js} +1 -1
  781. package/runtime/webapp/dist/assets/{send-OgOSXSRs.js → send-DdY_K1RT.js} +1 -1
  782. package/runtime/webapp/dist/assets/{sequenceDiagram-WJ2MYXX4-DJzCQdxN.js → sequenceDiagram-WJ2MYXX4-CdQhFjho.js} +1 -1
  783. package/runtime/webapp/dist/assets/{sizeCapture-INFHLROL-DYsPME1d.js → sizeCapture-INFHLROL-BP_2bwHb.js} +1 -1
  784. package/runtime/webapp/dist/assets/{smartphone-BaeWE4n-.js → smartphone-C2--txxG.js} +1 -1
  785. package/runtime/webapp/dist/assets/{stateDiagram-D77RDMKH-D2prIqK-.js → stateDiagram-D77RDMKH-D2_O1o9C.js} +1 -1
  786. package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-b3DtWIlg.js +1 -0
  787. package/runtime/webapp/dist/assets/{swimlanes-42K2YHIH-NODzX6Rz.js → swimlanes-42K2YHIH-BwEWz-Bu.js} +1 -1
  788. package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-CxL0Wh2Z.js +8 -0
  789. package/runtime/webapp/dist/assets/{timeline-definition-24CTP7MA-CTh1zdtP.js → timeline-definition-24CTP7MA-DqDB5dmr.js} +1 -1
  790. package/runtime/webapp/dist/assets/{trash-2-DoqYR_LW.js → trash-2-CZx0p0L3.js} +1 -1
  791. package/runtime/webapp/dist/assets/{vennDiagram-4TSXK5OY-DyjbbvAr.js → vennDiagram-4TSXK5OY-Cf4VnZ2O.js} +1 -1
  792. package/runtime/webapp/dist/assets/{wardleyDiagram-VM6X3IG4-BFWVhSKh.js → wardleyDiagram-VM6X3IG4-D9FBNJOU.js} +1 -1
  793. package/runtime/webapp/dist/assets/{web-BeDKAt7R.js → web-BVybOQy8.js} +1 -1
  794. package/runtime/webapp/dist/assets/{web-W_qr76-r.js → web-CT9Joona.js} +1 -1
  795. package/runtime/webapp/dist/assets/{x-Dp1u7spG.js → x-COYLzqlQ.js} +1 -1
  796. package/runtime/webapp/dist/assets/{xychartDiagram-S5SC5T6Z-CkRP6Drf.js → xychartDiagram-S5SC5T6Z-BRVtPtRz.js} +1 -1
  797. package/runtime/webapp/dist/index.html +2 -2
  798. package/runtime/.next/static/chunks/344-04fd45d8838bfada.js +0 -1
  799. package/runtime/.next/static/chunks/app/web/layout-4e2120c7c4a57f7c.js +0 -1
  800. package/runtime/.next/static/chunks/app/web/page-aa406cbaa5109651.js +0 -1
  801. package/runtime/.next/static/css/71e679260520d186.css +0 -1
  802. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-50f20fv8.mjs +0 -40
  803. package/runtime/node_modules/@anthropic-ai/claude-agent-sdk/core-x5tcx9zy.mjs +0 -52
  804. package/runtime/webapp/dist/assets/CollaborationPage-BCzxWWHA.js +0 -16
  805. package/runtime/webapp/dist/assets/channel-9wfiqrt1.js +0 -1
  806. package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-CTD9Lt2V.js +0 -1
  807. package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-CTD9Lt2V.js +0 -1
  808. package/runtime/webapp/dist/assets/index-Bqpz5--c.js +0 -480
  809. package/runtime/webapp/dist/assets/index-WGJ3Mevp.css +0 -1
  810. package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-tpTQhbGu.js +0 -1
  811. package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-CUH3ZqiP.js +0 -8
  812. /package/runtime/.next/static/{wybbbDbeFWOi1186WVCZe → nDZmrx61FQSBYCG7rH1JD}/_buildManifest.js +0 -0
  813. /package/runtime/.next/static/{wybbbDbeFWOi1186WVCZe → nDZmrx61FQSBYCG7rH1JD}/_ssgManifest.js +0 -0
@@ -5,16 +5,16 @@
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 ip=Object.create;var is=Object.defineProperty;var np=Object.getOwnPropertyDescriptor;var ap=Object.getOwnPropertyNames;var sp=Object.getPrototypeOf,op=Object.prototype.hasOwnProperty;var Fl=(i,t)=>(t=Symbol[i])?t:Symbol.for("Symbol."+i),Ml=i=>{throw TypeError(i)};var cp=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),up=(i,t)=>{for(var e in t)is(i,e,{get:t[e],enumerable:!0})},Bl=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ap(t))!op.call(i,n)&&n!==e&&is(i,n,{get:()=>t[n],enumerable:!(r=np(t,n))||r.enumerable});return i};var Ol=(i,t,e)=>(e=i!=null?ip(sp(i)):{},Bl(t||!i||!i.__esModule?is(e,"default",{value:i,enumerable:!0}):e,i)),lp=i=>Bl(is({},"__esModule",{value:!0}),i);var dt=(i,t,e)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&Ml("Object expected");var r,n;e&&(r=t[Fl("asyncDispose")]),r===void 0&&(r=t[Fl("dispose")],e&&(n=r)),typeof r!="function"&&Ml("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},mt=(i,t,e)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(s,o,c,u){return u=Error(c),u.name="SuppressedError",u.error=s,u.suppressed=o,u},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 Vu=cp(()=>{});var mb={};up(mb,{ADTS:()=>zo,ALL_FORMATS:()=>Vm,ALL_TRACK_TYPES:()=>Fc,AUDIO_CODECS:()=>me,AdtsInputFormat:()=>Fa,AdtsOutputFormat:()=>Ec,AppendOnlyStreamTarget:()=>oc,AttachedFile:()=>xr,AudioBufferSink:()=>ec,AudioBufferSource:()=>Tc,AudioSample:()=>Ae,AudioSampleResource:()=>Dr,AudioSampleSink:()=>Wi,AudioSampleSource:()=>Gn,AudioSource:()=>gr,BaseMediaSampleSink:()=>Un,BlobSource:()=>Io,BufferSource:()=>Po,BufferTarget:()=>yi,CanvasSink:()=>Jo,CanvasSource:()=>yc,CmafOutputFormat:()=>Ki,ConcurrentRunner:()=>as,Conversion:()=>Oc,ConversionCanceledError:()=>jn,CustomAudioDecoder:()=>Ha,CustomAudioEncoder:()=>Ka,CustomPathedSource:()=>_n,CustomSource:()=>Rn,CustomVideoDecoder:()=>Wa,CustomVideoEncoder:()=>qa,EncodedAudioPacketSource:()=>zr,EncodedPacket:()=>j,EncodedPacketSink:()=>st,EncodedVideoPacketSource:()=>Ur,EventEmitter:()=>Je,FLAC:()=>Qu,FilePathSource:()=>vo,FilePathTarget:()=>cc,FlacInputFormat:()=>Ra,FlacOutputFormat:()=>vc,HLS:()=>Lo,HLS_FORMATS:()=>Um,HlsInputFormat:()=>Ui,HlsOutputFormat:()=>Rc,Input:()=>oi,InputAudioTrack:()=>lr,InputDisposedError:()=>ge,InputFormat:()=>Ze,InputTrack:()=>fi,InputVideoTrack:()=>ur,IsobmffInputFormat:()=>Fn,IsobmffOutputFormat:()=>Yi,LogLevel:()=>Yc,Logging:()=>V,MATROSKA:()=>Hu,MP3:()=>Uo,MP4:()=>Do,MPEG_TS:()=>No,MatroskaInputFormat:()=>Mn,MediaSource:()=>ji,MediaStreamAudioTrackSource:()=>wc,MediaStreamVideoTrackSource:()=>kc,MkvOutputFormat:()=>Qn,MovOutputFormat:()=>Gi,Mp3InputFormat:()=>Ea,Mp3OutputFormat:()=>Cc,Mp4InputFormat:()=>Ca,Mp4OutputFormat:()=>Zi,MpegTsInputFormat:()=>Ma,MpegTsOutputFormat:()=>_c,NON_PCM_AUDIO_CODECS:()=>At,NullTarget:()=>ki,OGG:()=>Gu,OggInputFormat:()=>_a,OggOutputFormat:()=>Ic,Output:()=>br,OutputAudioTrack:()=>es,OutputFormat:()=>Le,OutputSubtitleTrack:()=>ts,OutputTrack:()=>Ji,OutputTrackGroup:()=>lt,OutputVideoTrack:()=>Ja,PCM_AUDIO_CODECS:()=>ne,PathedSource:()=>Ye,PathedTarget:()=>ut,QTFF:()=>Vo,QUALITY_HIGH:()=>of,QUALITY_LOW:()=>af,QUALITY_MEDIUM:()=>sf,QUALITY_VERY_HIGH:()=>cf,QUALITY_VERY_LOW:()=>nf,Quality:()=>oe,QuickTimeInputFormat:()=>Pa,RangedSource:()=>Aa,RangedTarget:()=>$a,ReadableStreamSource:()=>Vi,RichImageData:()=>gt,SUBTITLE_CODECS:()=>Xe,Source:()=>Ne,SourceRef:()=>ai,StreamSource:()=>Fm,StreamTarget:()=>Kn,SubtitleSource:()=>$i,Target:()=>Me,TextSubtitleSource:()=>Sc,UnsupportedInputFormatError:()=>Nn,UrlSource:()=>Eo,VIDEO_CODECS:()=>ce,VIDEO_SAMPLE_PIXEL_FORMATS:()=>Ua,VideoSample:()=>Ge,VideoSampleColorSpace:()=>Ni,VideoSampleResource:()=>zt,VideoSampleSink:()=>mi,VideoSampleSource:()=>Xi,VideoSource:()=>hr,WAVE:()=>Ku,WEBM:()=>qu,WavOutputFormat:()=>Pc,WaveInputFormat:()=>va,WebMInputFormat:()=>Ia,WebMOutputFormat:()=>Ti,asc:()=>Af,canDecode:()=>Nm,canDecodeAudio:()=>Ko,canDecodeVideo:()=>qo,canEncode:()=>uf,canEncodeAudio:()=>Na,canEncodeSubtitles:()=>La,canEncodeVideo:()=>za,desc:()=>Qa,getDecodableAudioCodecs:()=>Xu,getDecodableCodecs:()=>Lm,getDecodableVideoCodecs:()=>ju,getEncodableAudioCodecs:()=>On,getEncodableCodecs:()=>lf,getEncodableSubtitleCodecs:()=>rl,getEncodableVideoCodecs:()=>tl,getFirstEncodableAudioCodec:()=>df,getFirstEncodableSubtitleCodec:()=>mf,getFirstEncodableVideoCodec:()=>Zo,prefer:()=>hi,registerDecoder:()=>ff,registerEncoder:()=>pf,registerVideoSampleTransformer:()=>jm});function b(i){if(!i)throw new Error("Assertion failed.")}var ss=Math.PI/180,os=180/Math.PI,yr=i=>{let t=(i%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw new Error(`Invalid rotation ${i}.`)},Wr=[1,0,0,0,1,0,0,0,1],cs=(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 Ht(Ht(Dl(-t/2,-e/2),i),Dl(o/2,c/2))},Si=i=>{let[t,e]=i,r=Math.atan2(e,Lc(i)?-t:t);return yr(fs(r*os,90))},Lc=i=>{let[t,e,,r,n]=i;return t*n-e*r<0},tn=i=>{let t=i*ss,e=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[e,r,0,-r,e,0,0,0,1]},Dl=(i,t)=>[1,0,0,0,1,0,i,t,1],us=(i,t)=>[i,0,0,0,t,0,0,0,1],Ht=(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},ls=(i,t,e,r)=>({rotation:yr(i+(t?-e:e)),flip:t!==r}),Y=i=>i&&i[i.length-1],qt=i=>i>=0&&i<2**32,Ul=i=>i>=-(2**31)&&i<2**31,B=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)},Ai=(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)},Kt=i=>{let t=B(i);return t%2===0?-(t/2):(t+1)/2},zl=(i,t,e,r)=>{for(let n=t;n<e;n++){let a=Math.floor(n/8),s=i[a],o=7-(n&7);s&=~(1<<o),s|=(r&1<<e-n-1)>>e-n-1<<o,i[a]=s}},Q=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),dp=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)}},xi=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 u=s===224?160:s===240?144:128,l=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<u||m>l)break;c=c<<6|m&63,u=128,l=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 u=a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1];if(c+=2,u>=55296&&u<=56319){let l=c+1<e.length?a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1]:-1;l>=56320&&l<=57343?(r.push(u,l),c+=2):r.push(65533)}else u>=56320&&u<=57343?r.push(65533):r.push(u)}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}},he=new xi,Z=new dp,vt=i=>{for(let t=0;t<i.length;t++)if(i.charCodeAt(t)>255)return!1;return!0},Wc=i=>Object.fromEntries(Object.entries(i).map(([t,e])=>[e,t])),Tt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ft=Wc(Tt),wt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},pt=Wc(wt),St={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ht=Wc(St),rn=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,ds=i=>!i||i.primaries==null&&i.transfer==null&&i.matrix==null&&i.fullRange==null,ms={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},kr=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),He=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}},Nl=/^[0-9a-fA-F]+$/,Hr=i=>[...i].map(t=>t.toString(16).padStart(2,"0")).join(""),Ll=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},Hc=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),Tr=(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},G=(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},qc=(i,t,e)=>{let r=G(i,e(t),e);i.splice(r+1,0,t)},ee=()=>{let i,t;return{promise:new Promise((r,n)=>{i=r,t=n}),resolve:i,reject:t}},nn=(i,t)=>{let e=i.indexOf(t);e!==-1&&i.splice(e,1)},Kc=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return i[e]},qr=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1},Wl=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},Hl=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},ae=i=>{throw new Error(`Unexpected value: ${i}`)},Ci=(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},ql=(i,t,e)=>Ci(i,t,e)<<8>>8,Pi=(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))},Kl=(i,t,e,r)=>{e=J(e,-8388608,8388607),e<0&&(e=e+16777216&16777215),Pi(i,t,e,r)},Gl=(i,t,e,r)=>{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),!0),i.setUint32(t+4,e,!0))},$n=(i,t)=>({async next(){let e=await i.next();return e.done?{value:void 0,done:!0}:{value:t(e.value),done:!1}},return(){return i.return()},throw(e){return i.throw(e)},[Symbol.asyncIterator](){return this}}),J=(i,t,e)=>Math.max(t,Math.min(e,i)),Ql=(i,t,e)=>i+(t-i)*e,Gc=(i,t)=>i-Math.floor(i/t)*t,se="und",wr=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,Gt=(i,t)=>Math.round(i*t)/t,ps=(i,t)=>Math.floor(i/t)*t,Qc=(i,t)=>Math.floor(i*t)/t,jl=i=>{let t=0;for(;i;)t++,i>>=1;return t},hs=i=>{let t=0;for(;i!==0;)i&=i-1,t++;return t},mp=/^[a-z]{3}$/,Sr=i=>mp.test(i),Qt=1e6*(1+Number.EPSILON),jc=(i,t)=>{let e={...i,...t};if(i.headers||t.headers){let r=i.headers?ns(i.headers):{},n=t.headers?ns(t.headers):{},a={...r};Object.entries(n).forEach(([s,o])=>{let c=Object.keys(a).find(u=>u.toLowerCase()===s.toLowerCase());c&&delete a[c],a[s]=o}),e.headers=a}return e},ns=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},Xc=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(V._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 Kr(1e3*o),n())throw s}},Xl=(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),u=c*a+r,l=c*s+n;if(l>t)return{num:e*a,den:s};if(r=a,n=s,a=u,s=l,o=1/(o-c),!isFinite(o))break}return{num:e*a,den:s}},Lr=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},Vc=null,jt=()=>Vc!==null?Vc:Vc=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Uc=null,Xt=()=>Uc!==null?Uc:Uc=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),zc=null,Yn=()=>zc!==null?zc:zc=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Nc=null,$l=()=>{if(Nc!==null)return Nc;if(typeof navigator>"u")return null;let i=/\bChrome\/(\d+)/.exec(navigator.userAgent);return i?Nc=Number(i[1]):null},an=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.`,Yl=i=>i instanceof DOMException&&i.name==="QuotaExceededError"&&/reclaimed/i.test(i.message),fp=(async()=>{})().constructor,_=i=>i instanceof fp||i instanceof Promise?!0:typeof i?.then=="function",Ii=(i,t)=>i!==-1?i:t,gs=(i,t,e,r)=>i<=r&&e<=t,_t=function*(i){for(let t in i){let e=i[t];e!==void 0&&(yield{key:t,value:e})}},Zl=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}},Ei=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},Jl=i=>{let t="";for(let e=0;e<i.length;e++)t+=String.fromCharCode(i[e]);return btoa(t)},bs=(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},sn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},ve=i=>typeof i=="number"&&!Number.isNaN(i),xe=(i,t)=>{if(t.includes("://"))return t;if(i.includes("://")){let o=i.indexOf("?");o!==-1&&(i=i.slice(0,o))}let e;if(t.startsWith("/")){let o=i.indexOf("://");if(o===-1)e=t;else{let c=i.indexOf("/",o+3);c===-1?e=i+t:e=i.slice(0,c)+t}}else{let o=i.lastIndexOf("/");o===-1?e=t:e=i.slice(0,o+1)+t}let r="",n=e.indexOf("://");if(n!==-1){let o=e.indexOf("/",n+3);o!==-1&&(r=e.slice(0,o),e=e.slice(o))}let a=e.split("/"),s=[];for(let o of a)o===".."?s.pop():o!=="."&&s.push(o);return r+s.join("/")},ed=(i,t)=>{let e=i.indexOf("?");if(e===-1)return null;let r=i.indexOf("#",e),n=i.slice(e+1,r===-1?void 0:r);for(let a of n.split("&")){let s=a.indexOf("="),o=s===-1?a:a.slice(0,s),c=s===-1?"":a.slice(s+1);try{if(decodeURIComponent(o)===t)return decodeURIComponent(c)}catch{}}return null},vi=(i,t)=>{let e=0;for(let r=0;r<i.length;r++)t(i[r])&&e++;return e},on=(i,t)=>{let e=-1,r=1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);a<r&&(r=a,e=n)}return e},td=(i,t)=>{let e=-1,r=-1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);a>r&&(r=a,e=n)}return e},Ar=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}},ys=(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.`)},Xn,pp=1,Vl=new Map,$c=new Map,rd=()=>typeof window>"u",hp=()=>{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}}},id=()=>{if(Xn)return Xn;let i=`(${hp.toString()})();`,t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));return Xn=new Worker(t),URL.revokeObjectURL(t),Xn.onmessage=e=>{let r=e.data,n=Vl.get(r.timerId);if(n){Vl.delete(r.timerId),n();return}let a=$c.get(r.timerId);a&&a()},Xn};var nd=(i,t)=>{if(rd())return{id:setInterval(i,t)};let e=pp++;return $c.set(e,()=>{i()}),id().postMessage({type:"set-interval",timerId:e,delay:t}),{id:e}},ad=i=>{if(rd()){clearInterval(i.id);return}b(typeof i.id=="number"),$c.delete(i.id),id().postMessage({type:"clear-interval",timerId:i.id})},Kr=i=>new Promise(t=>setTimeout(t,i));var $t=i=>Array.isArray(i)?i:[i],Je=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){try{a.fn(r)}catch(s){console.error(s)}a.once&&n.delete(a)}}},_i=i=>Math.ceil(i/2)*2,as=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(()=>nn(this._queue,e)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}},ks=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(t=>typeof t=="string");var Yc=(n=>(n[n.Silent=0]="Silent",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.Info=3]="Info",n))(Yc||{}),et=class et{constructor(){}static get level(){return et._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.");et._level=t}static get _emitter(){return et._emitterInstance??=new Je}static on(t,e,r){return et._emitter.on(t,e,r)}static _error(...t){et._emitter._emit("error",t),et._level>=1&&console.error(...t)}static _warn(...t){et._emitter._emit("warn",t),et._level>=2&&console.warn(...t)}static _info(...t){et._emitter._emit("info",t),et._level>=3&&console.info(...t)}};et._level=3,et._emitterInstance=null;var V=et;var gt=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.")}},xr=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.")}},Zn=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.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(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)&&!(t instanceof gt)&&!(t instanceof xr)&&!ks(t))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Cr=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),_e={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},sd=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 H=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<<=1,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);s&=~(1<<o),s|=(e&1<<r-n-1)>>r-n-1<<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 tt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Yt=[-1,1,2,3,4,5,6,8],Zt=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let t=new H(i),e=Zc(t),{frequencyIndex:r,sampleRate:n}=Jc(t),a=t.readBits(4),s=null;a>=1&&a<=7&&(s=Yt[a]);let o=e,c=!1,u=n;if(e===5||e===29)c=e===29,u=Jc(t).sampleRate,o=Zc(t),o===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let l=t.pos;if(t.readBits(11)!==695){t.pos=l+1;continue}Zc(t)===5&&t.readBits(1)&&(u=Jc(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,outputSampleRate:u,outputNumberOfChannels:c&&s===1?2:s}},Zc=i=>{let t=i.readBits(5);return t===31?32+i.readBits(6):t},Jc=i=>{let t=i.readBits(4);return t===15?{frequencyIndex:t,sampleRate:i.readBits(24)}:{frequencyIndex:t,sampleRate:t<tt.length?tt[t]:null}},cn=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=Yt.indexOf(n);if(a===-1)throw new TypeError(`Unsupported number of channels: ${i.outputNumberOfChannels}`);let s=16;i.objectType>=32&&(s+=6),eu(r)===15&&(s+=24),t&&(s+=9,eu(i.outputSampleRate)===15&&(s+=24));let o=Math.ceil(s/8),c=new Uint8Array(o),u=new H(c);return od(u,i.objectType),cd(u,r),u.writeBits(4,a),t&&(cd(u,i.outputSampleRate),od(u,2)),u.writeBits(3,0),c},od=(i,t)=>{t<32?i.writeBits(5,t):(i.writeBits(5,31),i.writeBits(6,t-32))},cd=(i,t)=>{let e=eu(t);i.writeBits(4,e),e===15&&i.writeBits(24,t)},eu=i=>{let t=tt.indexOf(i);return t===-1?15:t},Ts=i=>{let t=new Uint8Array(7),e=new H(t),{coreObjectType:r,frequencyIndex:n,channelConfiguration:a}=i,s=r-1;return e.writeBits(12,4095),e.writeBits(1,0),e.writeBits(2,0),e.writeBits(1,1),e.writeBits(2,s),e.writeBits(4,n),e.writeBits(1,0),e.writeBits(3,a),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.skipBits(13),e.writeBits(11,2047),e.writeBits(2,0),{header:t,bitstream:e}},ws=(i,t)=>{i.pos=30,i.writeBits(13,t)};var Ri=[48e3,44100,32e3],tu=[24e3,22050,16e3];var gp="1.62.0",Pr=`Mediabunny v${gp}`;var Gr=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})},As=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=Ci(r,e,!1):(b(t===4),n=r.getUint32(e,!1)),e+=t,yield{offset:e,length:n},e+=n}},iu=(i,t)=>{if(t.description){let n=(Q(t.description)[4]&3)+1;return As(i,n)}else return Gr(i)},Jt=i=>i&31,xs=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)},bp=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)},ru=new Uint8Array([0,0,0,1]),ta=i=>{let t=i.reduce((n,a)=>n+ru.byteLength+a.byteLength,0),e=new Uint8Array(t),r=0;for(let n of i)e.set(ru,r),r+=ru.byteLength,e.set(n,r),r+=n.byteLength;return e},Cs=(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:Pi(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},md=(i,t)=>{if(t.description){let n=(Q(t.description)[4]&3)+1;return Cs(i,n)}else return ta(i)},er=i=>{try{let t=[],e=[],r=[];for(let o of Gr(i)){let c=i.subarray(o.offset,o.offset+o.length),u=Jt(c[0]);u===7&&t.length<31?t.push(c):u===8&&e.length<255?e.push(c):u===13&&r.length<255&&r.push(c)}if(t.length===0||e.length===0)return null;let n=t[0],a=rr(n);if(!a)return null;let s=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;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 V._error("Error building AVC Decoder Configuration Record:",t),null}},un=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((i.avcProfileIndication===100||i.avcProfileIndication===110||i.avcProfileIndication===122||i.avcProfileIndication===144)&&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)},tr=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,u=[];for(let f=0;f<c;f++){let p=t.getUint16(e,!1);e+=2,u.push(i.subarray(e,e+p)),e+=p}let l=t.getUint8(e++),d=[];for(let f=0;f<l;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:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&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 V._error("Error deserializing AVC Decoder Configuration Record:",t),null}},fd={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}},rr=i=>{try{let t=xs(i),e=new H(t);if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),a=e.readAlignedByte(),s=e.readAlignedByte();B(e);let o=1,c=0,u=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(o=B(e),o===3&&(l=e.readBits(1)),c=B(e),u=B(e),e.skipBits(1),e.readBits(1))){for(let D=0;D<(o!==3?8:12);D++)if(e.readBits(1)){let ie=D<6?16:64,be=8,Te=8;for(let Wt=0;Wt<ie;Wt++){if(Te!==0){let yt=Kt(e);Te=(be+yt+256)%256}be=Te===0?be:Te}}}B(e);let d=B(e);if(d===0)B(e);else if(d===1){e.skipBits(1),Kt(e),Kt(e);let z=B(e);for(let D=0;D<z;D++)Kt(e)}B(e),e.skipBits(1);let m=B(e),f=B(e),p=16*(m+1),g=16*(f+1),h=p,y=g,k=e.readBits(1);if(k||e.skipBits(1),e.skipBits(1),e.readBits(1)){let z=B(e),D=B(e),q=B(e),ie=B(e),be,Te;if((l===0?o:0)===0)be=1,Te=2-k;else{let yt=o===3?1:2,Qe=o===1?2:1;be=yt,Te=Qe*(2-k)}h-=be*(z+D),y-=Te*(q+ie)}if(h<=0||y<=0)return null;let w=2,S=2,x=2,C=0,I={num:1,den:1},A=null,P=null,E=null,v=null,M=e.pos;if(e.readBits(1)){if(e.readBits(1)){let yt=e.readBits(8);if(yt===255)I={num:e.readBits(16),den:e.readBits(16)};else{let Qe=fd[yt];Qe&&(I=Qe)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),C=e.readBits(1),e.readBits(1)&&(w=e.readBits(8),S=e.readBits(8),x=e.readBits(8))),e.readBits(1)&&(B(e),B(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let Te=e.readBits(1);Te&&ud(e);let Wt=e.readBits(1);Wt&&ud(e),(Te||Wt)&&e.skipBits(1),e.skipBits(1),E=e.pos,v=e.readBits(1),v&&(e.skipBits(1),B(e),B(e),B(e),B(e),A=Math.min(B(e),16),P=Math.min(B(e),16))}if(A===null){b(P===null);let z=a&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&z)A=0,P=0;else{let D=m+1,q=f+1,ie=(2-k)*q,be=ea.find(Wt=>Wt.level>=s)??Y(ea),Te=Math.min(Math.floor(be.maxDpbMbs/(D*ie)),16);A=Te,P=Te}}return b(P!==null),{emulationUnpreventedBytes:t,profileIdc:n,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:u,codedWidth:p,codedHeight:g,displayWidth:h,displayHeight:y,pixelAspectRatio:I,colourPrimaries:w,matrixCoefficients:x,transferCharacteristics:S,fullRangeFlag:C,numReorderFrames:A,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:M,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:v}}catch(t){return V._error("Error parsing AVC SPS:",t),null}},ud=i=>{let t=B(i);i.skipBits(4),i.skipBits(4);for(let e=0;e<=t;e++)B(i),B(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},nu=i=>{b(i.bitstreamRestrictionFlag!==1);let t=new Uint8Array(i.emulationUnpreventedBytes.byteLength+64),e=new H(i.emulationUnpreventedBytes),r=new H(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),Ai(r,2),Ai(r,1),Ai(r,16),Ai(r,16),Ai(r,i.numReorderFrames),Ai(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)),bp(t.subarray(0,n))},yp=(i,t)=>{if(t.description){let n=(Q(t.description)[21]&3)+1;return Cs(i,n)}else return ta(i)},Jn=(i,t)=>{if(t.description){let n=(Q(t.description)[21]&3)+1;return As(i,n)}else return Gr(i)},Rt=i=>i>>1&63,Fi=i=>{try{let t=new H(xs(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:u}=kp(t,e);B(t);let l=B(t),d=0;l===3&&(d=t.readBits(1));let m=B(t),f=B(t),p=m,g=f;if(t.readBits(1)){let v=B(t),M=B(t),O=B(t),z=B(t),D=1,q=1,ie=d===0?l:0;ie===1?(D=2,q=2):ie===2&&(D=2,q=1),p-=(v+M)*D,g-=(O+z)*q}if(p<=0||g<=0)return null;let h=B(t),y=B(t);B(t);let T=t.readBits(1)?0:e,w=0;for(let v=T;v<=e;v++)B(t),w=B(t),B(t);B(t),B(t),B(t),B(t),B(t),B(t),t.readBits(1)&&t.readBits(1)&&Tp(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),B(t),B(t),t.skipBits(1));let S=B(t);if(wp(t,S),t.readBits(1)){let v=B(t);for(let M=0;M<v;M++)B(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let x=2,C=2,I=2,A=0,P=0,E={num:1,den:1};if(t.readBits(1)){let v=Ap(t,e);E=v.pixelAspectRatio,x=v.colourPrimaries,C=v.transferCharacteristics,I=v.matrixCoefficients,A=v.fullRangeFlag,P=v.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:E,colourPrimaries:x,transferCharacteristics:C,matrixCoefficients:I,fullRangeFlag:A,maxDecFrameBuffering:Math.min(w+1,16),spsMaxSubLayersMinus1:e,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:s,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:l,bitDepthLumaMinus8:h,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:P}}catch(t){return V._error("Error parsing HEVC SPS:",t),null}},ir=i=>{try{let t=[],e=[],r=[],n=[];for(let l of Gr(i)){let d=i.subarray(l.offset,l.offset+l.length),m=Rt(d[0]);m===32&&t.length<65535?t.push(d):m===33&&e.length<65535?e.push(d):m===34&&r.length<65535?r.push(d):(m===39||m===40)&&n.length<65535&&n.push(d)}if(e.length===0||r.length===0)return null;let s=Fi(e[0]);if(!s)return null;let o=0;if(r.length>0){let l=r[0],d=new H(xs(l));d.skipBits(16),B(d),B(d),d.skipBits(1),d.skipBits(1),d.skipBits(3),d.skipBits(1),d.skipBits(1),B(d),B(d),Kt(d),d.skipBits(1),d.skipBits(1),d.readBits(1)&&B(d),Kt(d),Kt(d),d.skipBits(1),d.skipBits(1),d.skipBits(1),d.skipBits(1);let m=d.readBits(1),f=d.readBits(1);!m&&!f?o=0:m&&!f?o=2:!m&&f?o=3:o=0}let c=[...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:1,nalUnitType:Rt(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(t){return V._error("Error building HEVC Decoder Configuration Record:",t),null}},kp=(i,t)=>{let e=i.readBits(2),r=i.readBits(1),n=i.readBits(5),a=0;for(let l=0;l<32;l++)a=a<<1|i.readBits(1);let s=new Uint8Array(6);for(let l=0;l<6;l++)s[l]=i.readBits(8);let o=i.readBits(8),c=[],u=[];for(let l=0;l<t;l++)c.push(i.readBits(1)),u.push(i.readBits(1));if(t>0)for(let l=t;l<8;l++)i.skipBits(2);for(let l=0;l<t;l++)c[l]&&i.skipBits(88),u[l]&&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}},Tp=i=>{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(!i.readBits(1))B(i);else{let n=Math.min(64,1<<4+(t<<1));t>1&&Kt(i);for(let a=0;a<n;a++)Kt(i)}},wp=(i,t)=>{let e=[];for(let r=0;r<t;r++)e[r]=Sp(i,r,t,e)},Sp=(i,t,e,r)=>{let n=0,a=0,s=0;if(t!==0&&(a=i.readBits(1)),a){if(t===e){let c=B(i);s=t-(c+1)}else s=t-1;i.readBits(1),B(i);let o=r[s]??0;for(let c=0;c<=o;c++)i.readBits(1)||i.readBits(1);n=r[s]}else{let o=B(i),c=B(i);for(let u=0;u<o;u++)B(i),i.readBits(1);for(let u=0;u<c;u++)B(i),i.readBits(1);n=o+c}return n},Ap=(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 u=fd[c];u&&(o=u)}}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)&&(B(i),B(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(B(i),B(i),B(i),B(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&B(i),i.readBits(1)&&xp(i,!0,t)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),s=B(i),B(i),B(i),B(i),B(i)),{pixelAspectRatio:o,colourPrimaries:e,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:a,minSpatialSegmentationIdc:s}},xp=(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 u=!1;c?B(i):u=i.readBits(1)===1;let l=1;u||(l=B(i)+1),r&&ld(i,l,a),n&&ld(i,l,a)}},ld=(i,t,e)=>{for(let r=0;r<t;r++)B(i),B(i),e&&(B(i),B(i)),i.readBits(1)},pd=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)},ln=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 u=i.subarray(e,e+6);e+=6;let l=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,w=y>>2&1,S=y&3,x=t.getUint8(e++),C=[];for(let I=0;I<x;I++){let A=t.getUint8(e++),P=A>>7&1,E=A&63,v=t.getUint16(e,!1);e+=2;let M=[];for(let O=0;O<v;O++){let z=t.getUint16(e,!1);e+=2,M.push(i.subarray(e,e+z)),e+=z}C.push({arrayCompleteness:P,nalUnitType:E,nalUnits:M})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:l,minSpatialSegmentationIdc:d,parallelismType:m,chromaFormatIdc:f,bitDepthLumaMinus8:p,bitDepthChromaMinus8:g,avgFrameRate:h,constantFrameRate:k,numTemporalLayers:T,temporalIdNested:w,lengthSizeMinusOne:S,arrays:C}}catch(t){return V._error("Error deserializing HEVC Decoder Configuration Record:",t),null}};var hd=(i,t)=>{let e=new Set,r=0;for(let a of Jn(i,t)){if(r===4){e.add(a.offset);continue}let s=Rt(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 Jn(i,t))e.has(a.offset)||n.push(i.subarray(a.offset,a.offset+a.length));return yp(n,t)},Cp={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}},dn=i=>{let t=new H(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 u=8;a>=2&&(u=t.readBits(1)?12:10);let l=t.readBits(3),d=0,m=0;if(l!==7)if(m=t.readBits(1),a===1||a===3){let I=t.readBits(1),A=t.readBits(1);d=!I&&!A?3:I&&!A?2:1,t.skipBits(1)}else d=1;else d=3,m=1;let f=t.readBits(16),p=t.readBits(16),g=f+1,h=p+1,y=g*h,k=Y(Ir).level;for(let C of Ir)if(y<=C.maxPictureSize){k=C.level;break}let T=Cp[l],w=T?.colourPrimaries??2,S=T?.transferCharacteristics??2,x=T?.matrixCoefficients??2;return{profile:a,level:k,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:w,transferCharacteristics:S,matrixCoefficients:x}},gd=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,bd=function*(i){let t=new H(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)}},Mi=i=>{for(let{type:t,data:e}of bd(i)){if(t!==1)continue;let r=new H(e),n=r.readBits(3),a=r.readBits(1),s=r.readBits(1),o=0,c=0,u=0;if(s)o=r.readBits(5);else{let P=r.readBits(1),E=0;if(P){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let z=0;for(;z<32&&!r.readBits(1);)z++;z<32&&r.skipBits(z)}E=r.readBits(1),E&&(u=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}let v=r.readBits(1),M=r.readBits(5);for(let O=0;O<=M;O++){r.skipBits(12);let z=r.readBits(5);if(O===0&&(o=z),z>7){let D=r.readBits(1);O===0&&(c=D)}if(E&&r.readBits(1)){let q=u+1;r.skipBits(q),r.skipBits(q),r.skipBits(1)}v&&r.readBits(1)&&r.skipBits(4)}}let l=r.readBits(4),d=r.readBits(4),m=l+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 P=r.readBits(1);P&&(r.skipBits(1),r.skipBits(1));let E=r.readBits(1),v=0;E?v=2:v=r.readBits(1),v>0&&(r.readBits(1)||r.skipBits(1)),P&&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,w=2;r.readBits(1)&&(k=r.readBits(8),T=r.readBits(8),w=r.readBits(8));let x=0,C=1,I=1,A=0;return y?x=r.readBits(1):k===1&&T===13&&w===0?(x=1,C=0,I=0):(x=r.readBits(1),n===0?(C=1,I=1):n===1?(C=0,I=0):h===12?(C=r.readBits(1),I=C?r.readBits(1):0):(C=1,I=0),C&&I&&(A=r.readBits(2))),{profile:n,level:o,tier:c,bitDepth:h,monochrome:y,chromaSubsamplingX:C,chromaSubsamplingY:I,chromaSamplePosition:A,videoFullRangeFlag:x,colourPrimaries:k,transferCharacteristics:T,matrixCoefficients:w}}return null},Ps=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,Is=i=>{if(i.length<36)return null;let e=N(i);return e.getUint32(4)!==1768124518||e.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:e.getUint8(22),transferCharacteristics:e.getUint8(23),matrixCoefficients:e.getUint8(24)}},Qr=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,21+e)),{outputChannelCount:e,preSkip:r,inputSampleRate:n,outputGain:a,channelMappingFamily:s,channelMappingTable:o}},Pp=[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],yd=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:Pp[t]*r}},Es=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 H(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 u=c;n.pos=0,n.skipBits(a);let l=Array(u).fill(0);for(let d=u-1;d>=0;d--)n.skipBits(40),l[d]=n.readBits(1);return{modeBlockflags:l}},jr=(i,t,e)=>{switch(i){case"avc":{for(let r of iu(e,t)){let n=e[r.offset],a=Jt(n);if(a>=1&&a<=4)return"delta";if(a===5)return"key";if(a===6&&!Yn()){let s=e.subarray(r.offset,r.offset+r.length),o=xs(s),c=1;do{let u=0;for(;;){let m=o[c++];if(m===void 0||(u+=m,m<255))break}let l=0;for(;;){let m=o[c++];if(m===void 0||(l+=m,m<255))break}if(u===6){let m=new H(o);m.pos=8*c;let f=-1;try{f=B(m)}catch{}let p=m.readBits(1);if(f===0&&p===1)return"key"}c+=l}while(c<o.length-1)}}return"delta"}case"hevc":{for(let r of Jn(e,t)){let n=Rt(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 H(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 bd(e))if(n===1){let s=new H(a);s.skipBits(4),r=!!s.readBits(1)}else if(n===3||n===6||n===7){if(r)return"key";let s=new H(a);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:ae(i),b(!1)}};var ra=(i,t)=>{let e=N(i),r=0;if(i.length<4)return;let n=e.getUint32(r,!0);r+=4;let a=he.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 u=he.decode(i.subarray(r,r+c));r+=c;let l=u.indexOf("=");if(l===-1)continue;let d=u.slice(0,l).toUpperCase(),m=u.slice(l+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=new Date(m);Number.isNaN(f.getTime())||(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=Ei(m),p=N(f),g=p.getUint32(0,!1),h=p.getUint32(4,!1),y=he.decode(f.subarray(8,8+h)),k=p.getUint32(8+h,!1),T=he.decode(f.subarray(12+h,12+h+k)),w=p.getUint32(h+k+28),S=f.subarray(h+k+32,h+k+32+w);t.images??=[],t.images.push({data:S,mimeType:y,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:T||void 0})}catch{}break}}},ia=(i,t,e)=>{let r=[i],n=Z.encode(Pr),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=Z.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 _t(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 x=0;x<g.mimeType.length;x++)y[x]=g.mimeType.charCodeAt(x);let k=Z.encode(g.description??""),T=new Uint8Array(8+y.length+4+k.length+16+4+g.data.length),w=N(T);w.setUint32(0,h,!1),w.setUint32(4,y.length,!1),T.set(y,8),w.setUint32(8+y.length,k.length,!1),T.set(k,12+y.length),w.setUint32(28+y.length+k.length,g.data.length,!1),T.set(g.data,32+y.length+k.length);let S=Jl(T);c("METADATA_BLOCK_PICTURE",S)}}break;case"raw":break;default:ae(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))){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 u=new Uint8Array(4);N(u).setUint32(0,o.length,!0),r.splice(2,0,u);let l=r.reduce((f,p)=>f+p.length,0),d=new Uint8Array(l),m=0;for(let f of r)d.set(f,m),m+=f.length;return d},na=[2,1,2,3,3,4,4,5],vs=i=>{if(i.length<7||i[0]!==11||i[1]!==119)return null;let t=new H(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}},kd=[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],Td=1536,aa=new Uint8Array([5,4,65,67,45,51]),sa=new Uint8Array([5,4,69,65,67,51]),au=[1,2,3,6],_s=i=>{if(i.length<6||i[0]!==11||i[1]!==119)return null;let t=new H(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),u=t.readBits(5);if(u<11||u>16)return null;let l=au[s],d;return n<3?d=Ri[n]/1e3:d=tu[a]/1e3,{dataRate:Math.round((r+1)*d/(l*16)),substreams:[{fscod:n,fscod2:a,bsid:u,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},wd=i=>{if(i.length<2)return null;let t=new H(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),u=t.readBits(3),l=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:u,lfeon:l,numDepSub:d,chanLoc:m})}return n.length===0?null:{dataRate:e,substreams:n}},Rs=i=>{let t=i.substreams[0];return b(t),t.fscod<3?Ri[t.fscod]:t.fscod2!==null&&t.fscod2<3?tu[t.fscod2]:null},Fs=i=>{let t=i.substreams[0];b(t);let e=na[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<<8-n&&(e+=r[n])}return e};var Ip=1683496997,oa=18,Ms=10,Sd=4096,dd=32,Bs=20,Ep=8,vp=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],_p=[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],Rp=[16,16,20,20,0,24,24,0],Ss=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Fp=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Mp=8,Bp=44646,Op=[32e3,44100,48e3,0],Dp=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ad=[512,1024,2048,4096],ca=i=>{let t=su(i),e=N(i),r=t?Math.ceil(t.frameSize/4)*4:0,n=null;for(;r+4<=i.length&&e.getUint32(r)===Ip;){let s=ua(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}},Os=i=>{let t=ca(i);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},su=i=>{if(i.length<oa||i[0]!==127||i[1]!==254||i[2]!==128||i[3]!==1)return null;let t=new H(i);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==dd-1)return null;let e=t.readBits(1),r=t.readBits(7)+1;if(r%Ep!==0)return null;let n=t.readBits(14)+1;if(n<96)return null;let a=t.readBits(6);if(a>=Ss.length)return null;let s=vp[t.readBits(4)];if(s===0)return null;let o=_p[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),e&&t.skipBits(16),t.skipBits(7);let u=Rp[t.readBits(3)];if(u===0)return null;let l=c!==0;return{frameSize:n,sampleRate:s,numberOfChannels:Ss[a]+(l?1:0),sampleCount:r*dd,channelLayout:Fp[a]|(l?Mp:0),amode:a,lfePresent:l,bitRate:o,pcmResolution:u}},ua=i=>{if(i.length<Ms||i[0]!==100||i[1]!==88||i[2]!==32||i[3]!==37)return null;let t=new H(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=Op[t.readBits(2)],u=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let l=t.readBits(3)+1,d=t.readBits(3)+1,m=[];for(let y=0;y<l;y++)m.push(t.readBits(e+1));for(let y of m)t.skipBits(8*hs(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=Dp[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(u*p/c),channelLayout:h,pcmResolution:f}}},xd=i=>{if(i.length<Bs)return null;let t=N(i),e=t.getUint32(0);if(e===0)return null;let r=new H(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=Vp(o):s<Ss.length&&(c=Ss[s]+a),{sampleRate:e,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:i[12],sampleCount:Ad[n],channelLayout:o,numberOfChannels:c}},Cd=i=>{let t=new Uint8Array(Bs),e=N(t);e.setUint32(0,i.sampleRate),e.setUint32(4,i.bitRate),e.setUint32(8,i.bitRate),t[12]=i.pcmResolution;let r=i.core&&!i.hasExtensions?1:0,n=new H(t);return n.seekToByte(13),n.writeBits(2,Math.max(Ad.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},Vp=i=>hs(i)+hs(i&Bp);var ce=["avc","hevc","vp9","av1","vp8","prores"],ne=["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"],At=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],me=[...At,...ne],Xe=["webvtt"],ea=[{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}],Pd=[{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}],Ir=[{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}],Id=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Ed=".01.01.01.01.00",vd=".0.110.01.01.01.0",Er=["ap4x","ap4h","apch","apcn","apcs","apco"],la=["dtsc","dtsh","dtsl","dtse"],Up=[{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}],Vs=(i,t,e,r,n)=>{if(i==="avc"){let s=Math.ceil(t/16)*Math.ceil(e/16),o=ea.find(m=>s<=m.maxMacroblocks&&r<=m.maxBitrate)??Y(ea),c=o?o.level:0,u="64".padStart(2,"0"),l="00",d=c.toString(16).padStart(2,"0");return`avc1.${u}${l}${d}`}else if(i==="hevc"){let a="",o="6",c=t*e,u=Pd.find(d=>c<=d.maxPictureSize&&r<=d.maxBitrate)??Y(Pd);return`hev1.${a}1.${o}.${u.tier}${u.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",s=t*e,o=Ir.find(u=>s<=u.maxPictureSize&&r<=u.maxBitrate)??Y(Ir);return`vp09.${a}.${o.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let s=t*e,o=Id.find(l=>s<=l.maxPictureSize&&r<=l.maxBitrate)??Y(Id);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=Up.filter(l=>l.alpha===n),c=o[0].fourCc,u=1/0;for(let{fourCc:l,bitrate:d}of o){let m=Math.abs(d*s-r);m<u&&(u=m,c=l)}return c}else ae(i)}throw new TypeError(`Unhandled codec '${String(i)}'.`)},_d=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]},Us=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,u=s.slice(-1)==="H"?1:0,l=Number(t[3]),d=l===8?0:1,m=l===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=(u<<7)+(d<<6)+(m<<5)+(f<<4)+(p<<3)+(g<<2)+h;return[n,c,y,0]},Xr=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 u=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${i.avcType}.${Hr(u)}`}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}.${Hr(e.subarray(1,4))}`}else if(t==="hevc"){let u,l,d,m,f,p;if(a)u=a.generalProfileSpace,l=a.generalProfileIdc,d=Hc(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);u=y>>6&3,l=y&31,d=Hc(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="hev1.";for(g+=["","A","B","C"][u]+l,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"){if(!s){let k=i.width*i.height,T=Y(Ir).level;for(let w of Ir)if(k<=w.maxPictureSize){T=w.level;break}return`vp09.00.${T.toString().padStart(2,"0")}.08`}let u=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),d=s.bitDepth.toString().padStart(2,"0"),m=s.chromaSubsampling.toString().padStart(2,"0"),f=s.colourPrimaries.toString().padStart(2,"0"),p=s.transferCharacteristics.toString().padStart(2,"0"),g=s.matrixCoefficients.toString().padStart(2,"0"),h=s.videoFullRangeFlag.toString().padStart(2,"0"),y=`vp09.${u}.${l}.${d}.${m}`;return y+=`.${f}.${p}.${g}.${h}`,y.endsWith(Ed)&&(y=y.slice(0,-Ed.length)),y}else if(t==="av1"){if(!o){let w=i.width*i.height,S=Y(Ir).level;for(let x of Ir)if(w<=x.maxPictureSize){S=x.level;break}return`av01.0.${S.toString().padStart(2,"0")}M.08`}let u=o.profile,l=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;Ps(o)?(g=o.colourPrimaries,h=o.transferCharacteristics,y=o.matrixCoefficients,k=o.videoFullRangeFlag):(g=r?.primaries?Tt[r.primaries]:1,h=r?.transfer?wt[r.transfer]:1,y=r?.matrix?St[r.matrix]:1,k=r?.fullRange?1:0);let T=`av01.${u}.${l}${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(vd)&&(T=T.slice(0,-vd.length)),T}else{if(t==="prores")return c??"apch";t!==null&&ae(t)}}throw new TypeError(`Unhandled codec '${t}'.`)},zs=i=>{switch(i.codec){case"avc":{let t=i.avcCodecInfo?.sequenceParameterSets[0];if(!t&&i.codecDescription&&(t=tr(i.codecDescription)?.sequenceParameterSets[0]),t){let e=rr(t);if(e)return{primaries:ft[e.colourPrimaries],transfer:pt[e.transferCharacteristics],matrix:ht[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=ln(i.codecDescription)?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0]),t){let e=Fi(t);if(e)return{primaries:ft[e.colourPrimaries],transfer:pt[e.transferCharacteristics],matrix:ht[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(i.vp9CodecInfo)return{primaries:ft[i.vp9CodecInfo.colourPrimaries],transfer:pt[i.vp9CodecInfo.transferCharacteristics],matrix:ht[i.vp9CodecInfo.matrixCoefficients],fullRange:!!i.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(i.av1CodecInfo)return{primaries:ft[i.av1CodecInfo.colourPrimaries],transfer:pt[i.av1CodecInfo.transferCharacteristics],matrix:ht[i.av1CodecInfo.matrixCoefficients],fullRange:!!i.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(i.proresCodecInfo)return{primaries:ft[i.proresCodecInfo.colourPrimaries],transfer:pt[i.proresCodecInfo.transferCharacteristics],matrix:ht[i.proresCodecInfo.matrixCoefficients],fullRange:i.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Ns=(i,t,e)=>{if(i==="aac")return t>=2&&e<=24e3?"mp4a.40.29":e<=24e3?"mp4a.40.5":"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(ne.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},mn=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=Zt(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&&ne.includes(t))return t}throw new TypeError(`Unhandled codec '${t}'.`)},Rd=i=>{},Fd=i=>{switch(i.codec){case"flac":{let t=Ei("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=Ei("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}},Ft=48e3,Md=/^pcm-([usf])(\d+)(be)?$/,Re=i=>{if(b(ne.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=Md.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}},rt=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":Er.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"?"flac":i==="ac-3"||i==="ac3"?"ac3":i==="ec-3"||i==="eac3"?"eac3":la.includes(i)?"dts":i==="ulaw"?"ulaw":i==="alaw"?"alaw":Md.test(i)?i:i==="webvtt"?"webvtt":null,Bd=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},Od=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},zp=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Er],Np=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Lp=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Wp=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Hp=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,nr=(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(!zp.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&&!kr(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(Tt);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(wt);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(St);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(!Np.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(!Lp.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(!Wp.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(!Hp.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(Er.some(e=>i.decoderConfig.codec.startsWith(e))&&!Er.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: ${Er.join(", ")}.`);if(t!==null&&rt(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}'.`)},qp=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],Ce=(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(!qp.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&&!kr(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.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("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!ne.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ne.join(", ")}).`);if(t!==null&&rt(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}'.`)},Ls=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 ou=[44100,48e3,32e3],Ws=[-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],$r=1483304551,fn=1231971951,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,Dd=(i,t,e,r)=>t===0?0:t===1?144*e/(r<<i):t===2?144*e/r:12*e/r*4,Yr=(i,t)=>i===3?t===3?21:36:t===3?13:21,Zr=(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,u=r>>1&3,l=n>>4&15,d=(n>>2&3)%3,m=n>>1&1,f=a>>6&3,p=a>>4&3,g=a>>3&1,h=a>>2&1,y=a&3,k=Ws[s*16*4+u*16+l];if(k===-1)return{header:null,bytesAdvanced:1};let T=k*1e3,w=ou[d]>>s+o,S=Hs(s,u,T,w,m);if(t!==null&&t<S)return{header:null,bytesAdvanced:1};let x;return c===3?x=u===3?384:1152:u===3?x=384:u===2?x=1152:x=576,{header:{totalSize:S,mpegVersionId:c,lowSamplingFrequency:s,layer:u,bitrate:T,frequencyIndex:d,sampleRate:w,channel:f,modeExtension:p,copyright:g,original:h,emphasis:y,audioSamplesInFrame:x},bytesAdvanced:1}},Vd=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},qs=i=>{let t=2130706432,e=0;for(;t!==0;)e>>=1,e|=i&t,t>>=8;return e};var Jr=i=>i===3?1:2;var Pe=class{constructor(t){this.input=t}dispose(){}};var Se=new Uint8Array(0),j=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===Se&&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===Se}get microsecondTimestamp(){return Math.trunc(Qt*this.timestamp)}get microsecondDuration(){return Math.trunc(Qt*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,this.byteLength,t?.sideData??this.sideData)}};var Ks=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},Gs=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=Hr(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(Hr(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)}},Qs=(i,t)=>i.systemId===t.systemId&&bs(i.data,t.data);var Mt=8,vr=16,_r=i=>{let t=F(i),e=ue(i,4),r=8;t===1&&(t=qe(i),r=16);let a=t-r;return a<0?null:{name:e,totalSize:t,headerSize:r,contentSize:a}},ei=i=>Rr(i)/65536,js=i=>Rr(i)/1073741824,cu=i=>{let t=0;for(let e=0;e<4;e++){t<<=7;let r=L(i);if(t|=r&127,(r&128)===0)break}return t},Xs=i=>{if(L(i)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");cu(i),i.skip(2);let e=L(i),r=(e&128)!==0,n=(e&64)!==0,a=(e&32)!==0;if(r&&i.skip(2),n){let d=L(i);i.skip(d)}if(a&&i.skip(2),L(i)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");let o=cu(i),c=i.filePos,u=L(i);i.skip(12);let l=null;if(o>i.filePos-c){if(L(i)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");let m=cu(i);l=U(i,m)}return{objectTypeIndication:u,decoderSpecificInfo:l}},Bt=i=>{let t=fe(i);return i.skip(2),t=Math.min(t,i.remainingLength),he.decode(U(i,t))},Ud=i=>{let t=_r(i);if(!t||t.name!=="data"||t.contentSize<8||i.remainingLength<8)return null;let e=F(i);i.skip(4);let r=U(i,t.contentSize-8);switch(e){case 1:return he.decode(r);case 2:return new xi("utf-16be").decode(r);case 13:return new gt(r,"image/jpeg");case 14:return new gt(r,"image/png");case 27:return new gt(r,"image/bmp");default:return r}};var Ot=16,Fr=new Uint32Array(256),pn=new Uint32Array(256),hn=new Uint32Array(256),gn=new Uint32Array(256),bn=new Uint32Array(256),Ue=new Uint32Array(256),zd=new Uint32Array(10),Nd=!1,Kp=()=>{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);Fr[a]=s<<24|s<<16|s<<8|s,Ue[a]=o<<24|o<<16|o<<8|o;let c=r(o,14),u=r(o,9),l=r(o,13),d=r(o,11),m=c<<24|u<<16|l<<8|d;pn[a]=m,hn[a]=m>>>8|m<<24,gn[a]=m>>>16|m<<16,bn[a]=m>>>24|m<<8}let n=1;for(let a=0;a<10;a++)zd[a]=n<<24,n=n<<1^(n&128?283:0);Nd=!0},da=class{constructor(){this.roundkey=new Uint32Array(44);this.iv=new Uint32Array(Ot/Uint32Array.BYTES_PER_ELEMENT);this.in=new Uint8Array(Ot);this.out=new Uint8Array(Ot);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),Nd||Kp();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]^Fr[s>>>16&255]&4278190080^Fr[s>>>8&255]&16711680^Fr[s>>>0&255]&65280^Fr[s>>>24&255]&255^zd[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]=pn[Fr[o>>>24&255]&255]^hn[Fr[o>>>16&255]&255]^gn[Fr[o>>>8&255]&255]^bn[Fr[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),u,l,d,m;for(let y=1;y<10;y++){let k=y*4;u=pn[t>>>24]^hn[n>>>16&255]^gn[r>>>8&255]^bn[e&255]^this.roundkey[k],l=pn[e>>>24]^hn[t>>>16&255]^gn[n>>>8&255]^bn[r&255]^this.roundkey[k+1],d=pn[r>>>24]^hn[e>>>16&255]^gn[t>>>8&255]^bn[n&255]^this.roundkey[k+2],m=pn[n>>>24]^hn[r>>>16&255]^gn[e>>>8&255]^bn[t&255]^this.roundkey[k+3],t=u,e=l,r=d,n=m}let f=Ue[t>>>24&255]&4278190080^Ue[n>>>16&255]&16711680^Ue[r>>>8&255]&65280^Ue[e>>>0&255]&255^this.roundkey[40],p=Ue[e>>>24&255]&4278190080^Ue[t>>>16&255]&16711680^Ue[n>>>8&255]&65280^Ue[r>>>0&255]&255^this.roundkey[41],g=Ue[r>>>24&255]&4278190080^Ue[e>>>16&255]&16711680^Ue[t>>>8&255]&65280^Ue[n>>>0&255]&255^this.roundkey[42],h=Ue[n>>>24&255]&4278190080^Ue[r>>>16&255]&16711680^Ue[e>>>8&255]&65280^Ue[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}},Ld=(i,t,e)=>{let r=!1,n=0,a=2**16,s=16,o=new da;return new ReadableStream({pull:async c=>{r||(o.init(await t()),r=!0);let u=a+s,l=i.requestSliceRange(n,0,u);if(_(l)&&(l=await l),!l||l.length===0)throw new Error("Invalid ciphertext.");let d=l.length;if(d%16!==0)throw new Error("Invalid ciphertext.");let m=d===u?d-s:d,f=U(l,m),p=new Uint8Array(m);for(let g=0;g<m;g+=16)o.in.set(f.subarray(g,g+16)),o.decrypt(),p.set(o.out,g);if(m<d)c.enqueue(p),n+=m;else{let g=p[m-1];if(g===0||g>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let h=p.subarray(0,m-g);c.enqueue(h),c.close(),e()}},cancel:()=>{e()}})};var Gp=64,$s=class i extends Pe{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=Wr;this.isQuickTime=!1;this.metadataTags={};this.currentMetadataKeys=null;this.isFragmented=!1;this.fragmentTrackDefaults=new Map;this.psshBoxes=[];this.currentFragment=null;this.isReadingTraf=!1;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 Ks({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,Mt,vr);if(_(a)&&(a=await a),!a)break;let s=e,o=_r(a);if(!o)break;if((o.name==="ftyp"||o.name==="styp")&&a.remainingLength>=4){let c=ue(a,4);this.isQuickTime=c==="qt "}else if(o.name==="moov"){let c=this.reader.requestSlice(a.filePos,o.contentSize);if(_(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 u of this.tracks){let l=u.editListPreviousSegmentDurations/this.movieTimescale;u.editListOffset-=Math.round(l*u.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);_(a)&&(a=await a),b(a);let s=F(a),o=this.reader.fileSize-s;if(o>=0&&o<=this.reader.fileSize-vr){let c=this.reader.requestSliceRange(o,Mt,vr);if(_(c)&&(c=await c),c){let u=_r(c);if(u&&u.name==="mfra"){let l=this.reader.requestSlice(c.filePos,u.contentSize);_(l)&&(l=await l),l&&this.readContiguousBoxes(l)}}}}for(let a of this.tracks){let s=a.fragmentLookupTable;s.sort((c,u)=>c.timestamp-u.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:[],currentFragmentState:null,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 Zs(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 Js(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(u){throw e.sampleTable=null,u}finally{this.currentTrack=null}let a=Y(r.sampleTimingEntries),s=G(r.sampleToChunk,r.chunkOffsets.length-1,u=>u.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),Kd(r.sampleTimingEntries,r.sampleCount),Kd(r.sampleCompositionTimeOffsets,r.sampleCount),e.info?.type==="audio"&&e.info.codec&&ne.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0&&r.sampleTimingEntries.length>0){b(e.info?.type==="audio");let u=Re(e.info.codec),l=[],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,w=G(r.sampleTimingEntries,k,M=>M.startIndex),S=r.sampleTimingEntries[w],x=G(r.sampleTimingEntries,T,M=>M.startIndex),C=r.sampleTimingEntries[x],I=S.startDecodeTimestamp+(k-S.startIndex)*S.delta,P=C.startDecodeTimestamp+(T-C.startIndex)*C.delta-I,E=Y(l);E&&E.delta===P?E.count++:l.push({startIndex:d.length,startDecodeTimestamp:I,count:1,delta:P});let v=f.samplesPerChunk*u.sampleSize*e.info.numberOfChannels;d.push(v)}f.startSampleIndex=h,f.samplesPerChunk=1}r.sampleTimingEntries=l,r.sampleSizes=d,r.sampleCount=d.length}if(r.sampleCompositionTimeOffsets.length>0){let u=r.sampleCompositionTimeOffsets,l=Y(u),d=l.startIndex+l.count;d<r.sampleCount&&u.push({startIndex:d,count:r.sampleCount-d,offset:0,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1});let m=u.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 u=0;u<r.sampleSizes.length;u++)r.cumulativeSampleSizes.push(r.cumulativeSampleSizes[u]+r.sampleSizes[u])}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,Mt,vr);_(r)&&(r=await r),b(r);let n=_r(r);b(n?.name==="moof");let a=this.reader.requestSlice(e,n.totalSize);if(_(a)&&(a=await a),!a)return null;this.traverseBox(a);let s=this.lastReadFragment;b(s&&s.moofOffset===e),this.fragmentSummaries.set(e,{moofSize:s.moofSize,trackIds:new Set(s.trackData.keys())});for(let[,o]of s.trackData){let c=o.track,{fragmentPositionCache:u}=c;if(!o.startTimestampIsFinal){let f=Tr(c.fragmentLookupTable,s.moofOffset,h=>h.moofOffset),p=c.fragmentLookupTable[f];if(p&&o.trunSampleCounts.length>=p.trunNumber&&o.trunSampleCounts[p.trunNumber-1]>=p.sampleNumber){let h=0;for(let T=1;T<p.trunNumber;T++)h+=o.trunSampleCounts[T-1];h+=p.sampleNumber-1;let y=o.samples[h];b(y);let k=p.timestamp-y.presentationTimestamp;uu(o,k)}else{let h=G(u,s.moofOffset-1,y=>y.moofOffset);if(h!==-1){let y=u[h];uu(o,y.endTimestamp)}}o.startTimestampIsFinal=!0}let l=G(u,o.startTimestamp,f=>f.startTimestamp),d=u[l],m=u[l+1];if((!d||d.moofOffset<s.moofOffset)&&(!m||m.moofOffset>s.moofOffset)&&u.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp}),o.encryptionAuxInfo&&c.encryptionInfo){let f=await Zd(this.reader,c.encryptionInfo,o.encryptionAuxInfo);for(let p=0;p<Math.min(o.samples.length,f.length);p++){let g=f[p];o.samples[p].encryption=g}}}return s}readContiguousBoxes(e){if(this.boxNestingDepth===Gp)throw new Error("Invalid file: boxes are nested too deeply.");let r=e.filePos;this.boxNestingDepth++;try{for(;e.filePos-r<=e.length-Mt&&this.traverseBox(e););}finally{this.boxNestingDepth--}}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Mt;){let n=e.filePos,a=_r(e);if(!a)break;yield{boxInfo:a,slice:e},e.filePos=n+a.totalSize}}traverseBox(e){let r=e.filePos,n=_r(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=L(e);if(e.skip(3),o===1?(e.skip(16),this.movieTimescale=F(e),this.movieDurationInTimescale=qe(e)):(e.skip(8),this.movieTimescale=F(e),this.movieDurationInTimescale=F(e)),this.movieTimescale===0)throw new Error("Invalid mvhd box: timescale must not be 0.");e.skip(8+2*4),this.movieMatrix=Wd(e)}break;case"trak":{if(this.currentFragment||this.currentTrack)break;let o={id:-1,demuxer:this,trackBacking:null,disposition:{..._e,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:Wr,internalCodecId:null,name:null,languageCode:se,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,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 Zs(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 Js(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=L(e),l=!!(Dt(e)&1);if(o.disposition.default=l,c===0)e.skip(8),o.id=F(e),e.skip(4),o.durationInMovieTimescale=F(e);else if(c===1)e.skip(16),o.id=F(e),e.skip(4),o.durationInMovieTimescale=qe(e);else throw new Error(`Incorrect track header version ${c}.`);e.skip(2*4+2+2+2+2);let d=Wd(e);o.matrix=Ht(d,this.movieMatrix)}break;case"elst":{let o=this.currentTrack;if(!o)break;let c=L(e);e.skip(3);let u=!1,l=0,d=F(e);for(let m=0;m<d;m++){let f=c===1?qe(e):F(e),p=c===1?em(e):Rr(e),g=ei(e);if(u){V._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(p===-1){l+=f;continue}if(g!==1){V._warn("Unsupported edit list entry: media rate must be 1.");break}o.editListPreviousSegmentDurations=l,o.editListOffset=p,u=!0}}break;case"mdhd":{let o=this.currentTrack;if(!o)break;let c=L(e);if(e.skip(3),c===0?(e.skip(8),o.timescale=F(e),o.durationInMediaTimescale=F(e)):c===1&&(e.skip(16),o.timescale=F(e),o.durationInMediaTimescale=qe(e)),o.timescale===0)throw new Error("Invalid mdhd box: timescale must not be 0.");let u=fe(e);if(u>0){o.languageCode="";for(let l=0;l<3;l++)o.languageCode=String.fromCharCode(96+(u&31))+o.languageCode,u>>=5;Sr(o.languageCode)||(o.languageCode=se)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let c=ue(e,4);c==="vide"?o.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...ms},avcType:null,avcCodecInfo: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=L(e);e.skip(3);let u=F(e);for(let l=0;l<u;l++){let d=e.filePos,m=_r(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":p==="vp08"?o.info.codec="vp8":p==="vp09"?o.info.codec="vp9":p==="av01"?o.info.codec="av1":Er.includes(f)?(o.info.codec="prores",o.info.proresFormat=f):p===null?V._warn("Unknown encrypted video codec due to missing frma box."):V._warn(`Unsupported video codec (sample entry type '${m.name}').`)}else{e.skip(6*1+2);let p=fe(e);e.skip(3*2);let g=fe(e),h=fe(e);e.skip(2*2);let y=F(e)/65536,k=null;c===0&&p>0&&(p===1?(e.skip(4),h=8*F(e),e.skip(2*4)):p===2&&(e.skip(4),y=eo(e),g=F(e),e.skip(4),h=F(e),k=F(e),e.skip(2*4))),o.info.numberOfChannels=g,o.info.sampleRate=y,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==="opus")o.info.codec="opus",o.info.sampleRate=Ft;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==="twos")h===8?o.info.codec="pcm-s8":h===16?o.info.codec=o.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(V._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":(V._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 w=o.info.pcmSampleSize;o.info.pcmLittleEndian?w===16?o.info.codec="pcm-s16":w===24?o.info.codec="pcm-s24":w===32?o.info.codec="pcm-s32":(V._warn(`Invalid ipcm sample size ${w}.`),o.info.codec=null):w===16?o.info.codec="pcm-s16be":w===24?o.info.codec="pcm-s24be":w===32?o.info.codec="pcm-s32be":(V._warn(`Invalid ipcm sample size ${w}.`),o.info.codec=null)}else if(T==="fpcm"){let w=o.info.pcmSampleSize;o.info.pcmLittleEndian?w===32?o.info.codec="pcm-f32":w===64?o.info.codec="pcm-f64":(V._warn(`Invalid fpcm sample size ${w}.`),o.info.codec=null):w===32?o.info.codec="pcm-f32be":w===64?o.info.codec="pcm-f64be":(V._warn(`Invalid fpcm sample size ${w}.`),o.info.codec=null)}else if(T==="lpcm"&&k!==null){let w=h+7>>3,S=!!(k&1),x=!!(k&2),C=k&4?-1:0;h>0&&h<=64&&(S?h===32&&(o.info.codec=x?"pcm-f32be":"pcm-f32"):C&1<<w-1?w===1?o.info.codec="pcm-s8":w===2?o.info.codec=x?"pcm-s16be":"pcm-s16":w===3?o.info.codec=x?"pcm-s24be":"pcm-s24":w===4&&(o.info.codec=x?"pcm-s32be":"pcm-s32"):w===1&&(o.info.codec="pcm-u8")),o.info.codec===null&&V._warn("Unsupported PCM format.")}else T===null?V._warn("Unknown encrypted audio codec due to missing frma box."):V._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 u=ue(e,4).toLowerCase();o.frmaCodecString=u}break;case"schm":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=ue(e,4);c==="cenc"||c==="cens"||c==="cbcs"?o.encryptionInfo={scheme:c,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:V._warn(`Unsupported encryption scheme '${c}'.`)}break;case"tenc":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=L(e);e.skip(3),e.skip(1);let u=L(e);if(c>0?(o.encryptionInfo.defaultCryptByteBlock=u>>4,o.encryptionInfo.defaultSkipByteBlock=u&15):(o.encryptionInfo.defaultCryptByteBlock=0,o.encryptionInfo.defaultSkipByteBlock=0),o.encryptionInfo.defaultIsProtected=L(e)!==0,o.encryptionInfo.defaultPerSampleIvSize=L(e),o.encryptionInfo.defaultKid=Hr(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 l=L(e);if(l>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");let d=new Uint8Array(16);d.set(U(e,l),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=tr(o.info.codecDescription)?.sequenceParameterSets[0],u=c&&rr(c);u&&Hd(o,u.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=ln(o.info.codecDescription)?.arrays.find(l=>l.nalUnitType===33)?.nalUnits[0],u=c&&Fi(c);u&&Hd(o,u.pixelAspectRatio)}break;case"vpcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;e.skip(4);let c=L(e),u=L(e),l=L(e),d=l>>4,m=l>>1&7,f=l&1,p=L(e),g=L(e),h=L(e);o.info.vp9CodecInfo={profile:c,level:u,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=L(e),u=c>>5,l=c&31,d=L(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=u===2&&f?p?12:10:f?10:8;e.skip(1);let w=U(e,n.contentSize-4),S=Mi(w);o.info.av1CodecInfo={profile:u,level:l,tier:m,bitDepth:T,monochrome:g,chromaSubsamplingX:h,chromaSubsamplingY:y,chromaSamplePosition:k,videoFullRangeFlag:S?.videoFullRangeFlag??0,colourPrimaries:S?.colourPrimaries??2,transferCharacteristics:S?.transferCharacteristics??2,matrixCoefficients:S?.matrixCoefficients??2}}break;case"colr":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=ue(e,4);if(c!=="nclx"&&c!=="nclc")break;let u=fe(e),l=fe(e),d=fe(e),m;c==="nclx"&&(m=!!(L(e)&128)),o.info.colorSpace={primaries:ft[u],transfer:pt[l],matrix:ht[d],fullRange:m}}break;case"pasp":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=F(e),u=F(e);c>0&&u>0&&(o.info.squarePixelWidth=o.info.width,o.info.squarePixelHeight=o.info.height,c>u?o.info.squarePixelWidth=Math.round(o.info.width*c/u):o.info.squarePixelHeight=Math.round(o.info.height*u/c))}break;case"btrt":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=F(e),u=F(e);o.maxBitrate=c>0?c:null,o.avgBitrate=u>0?u: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:u}=Xs(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":V._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),u&&(o.info.codecDescription=u,o.info.codec==="aac")){let l=Zt(o.info.codecDescription);l.outputNumberOfChannels!==null&&(o.info.numberOfChannels=l.outputNumberOfChannels),l.outputSampleRate!==null&&(o.info.sampleRate=l.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=L(e);o.info.pcmLittleEndian=!!(c&1),o.info.pcmSampleSize=L(e)}break;case"dOps":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(1);let c=L(e),u=fe(e),l=F(e),d=ma(e),m=L(e),f;m!==0?f=U(e,2+c):f=new Uint8Array(0);let 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,u,!0),g.setUint32(12,l,!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,u=128,l=e.filePos;for(;e.filePos<s;){let g=L(e),h=Dt(e);if((g&c)===0){e.skip(10);let k=F(e),T=k>>>12,w=(k>>9&7)+1;o.info.sampleRate=T,o.info.numberOfChannels=w,e.skip(20)}else e.skip(h);if(g&u)break}let d=e.filePos;e.filePos=l;let m=U(e,d-l),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),u=new H(c),l=u.readBits(2);u.skipBits(8);let d=u.readBits(3),m=u.readBits(1);l<3&&(o.info.sampleRate=Ri[l]),o.info.numberOfChannels=na[d]+m}break;case"dec3":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=U(e,n.contentSize),u=wd(c);if(!u){V._warn("Invalid dec3 box contents, ignoring.");break}let l=Rs(u);l!==null&&(o.info.sampleRate=l),o.info.numberOfChannels=Fs(u)}break;case"ddts":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=U(e,Math.min(n.contentSize,Bs)),u=xd(c);if(!u){V._warn("Invalid ddts box contents, ignoring.");break}o.info.sampleRate=u.sampleRate,u.numberOfChannels!==null&&(o.info.numberOfChannels=u.numberOfChannels)}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=F(e),u=0,l=0;for(let d=0;d<c;d++){let m=F(e),f=F(e);o.sampleTable.sampleTimingEntries.push({startIndex:u,startDecodeTimestamp:l,count:m,delta:f}),u+=m,l+=m*f}}break;case"ctts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=F(e),u=0;for(let l=0;l<c;l++){let d=F(e),m=Rr(e);o.sampleTable.sampleCompositionTimeOffsets.push({startIndex:u,count:d,offset:m,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1}),u+=d}}break;case"stsz":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=F(e),u=F(e);if(c===0)for(let l=0;l<u;l++){let d=F(e);o.sampleTable.sampleSizes.push(d)}else o.sampleTable.sampleSizes.push(c);o.sampleTable.sampleCount=u}break;case"stz2":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),e.skip(3);let c=L(e),u=F(e);if(c!==4&&c!==8&&c!==16)throw new Error(`Invalid stz2 box: unsupported field size ${c}.`);let l=U(e,Math.ceil(u*c/8)),d=new H(l);for(let m=0;m<u;m++){let f=d.readBits(c);o.sampleTable.sampleSizes.push(f)}o.sampleTable.sampleCount=u}break;case"stss":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),o.sampleTable.keySampleIndices=[];let c=F(e);for(let u=0;u<c;u++){let l=F(e)-1;o.sampleTable.keySampleIndices.push(l)}o.sampleTable.keySampleIndices.sort((u,l)=>u-l),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=F(e),u=0;for(let d=0;d<c;d++){let m=F(e)-1,f=F(e),p=F(e),g=Y(o.sampleTable.sampleToChunk);if(g&&m<=g.startChunkIndex){u++;continue}o.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:m,samplesPerChunk:f,sampleDescriptionIndex:p})}u>0&&V._warn(`Skipped ${u} invalid stsc entries whose chunk indices weren't strictly increasing.`);let l=0;for(let d=0;d<o.sampleTable.sampleToChunk.length;d++)if(o.sampleTable.sampleToChunk[d].startSampleIndex=l,d<o.sampleTable.sampleToChunk.length-1){let f=o.sampleTable.sampleToChunk[d+1].startChunkIndex-o.sampleTable.sampleToChunk[d].startChunkIndex;l+=f*o.sampleTable.sampleToChunk[d].samplesPerChunk}}break;case"stco":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=F(e);for(let u=0;u<c;u++){let l=F(e);o.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=F(e);for(let u=0;u<c;u++){let l=qe(e);o.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mehd":{let o=L(e);e.skip(3);let c=o===1?qe(e):F(e);this.movieDurationInTimescale=c}break;case"trex":{e.skip(4);let o=F(e),c=F(e),u=F(e),l=F(e),d=F(e);this.fragmentTrackDefaults.set(o,{trackId:o,defaultSampleDescriptionIndex:c,defaultSampleDuration:u,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{let o=L(e);e.skip(3);let c=F(e),u=this.idToTrack.get(c);if(!u)break;let l=F(e),d=(l&48)>>4,m=(l&12)>>2,f=l&3,p=[L,fe,Dt,F],g=p[d],h=p[m],y=p[f],k=F(e);for(let T=0;T<k;T++){let w=o===1?qe(e):F(e),S=o===1?qe(e):F(e);g(e);let x=h(e),C=y(e);x>=1&&C>=1&&u.fragmentLookupTable.push({timestamp:w,moofOffset:S,trunNumber:x,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)),this.lastReadFragment=this.currentFragment}finally{this.currentFragment=null,this.currentTrack=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}if(this.currentTrack){let o=this.currentFragment.trackData.get(this.currentTrack.id);e:if(o){if(o.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}o.presentationTimestamps=o.samples.map((d,m)=>({presentationTimestamp:d.presentationTimestamp,sampleIndex:m})).sort((d,m)=>d.presentationTimestamp-m.presentationTimestamp);for(let d=0;d<o.presentationTimestamps.length;d++){let m=o.presentationTimestamps[d],f=o.samples[m.sampleIndex];if(o.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(o.firstKeyFrameTimestamp=f.presentationTimestamp),d<o.presentationTimestamps.length-1){let g=o.presentationTimestamps[d+1].presentationTimestamp-m.presentationTimestamp;f.duration=g}}let c=o.samples[o.presentationTimestamps[0].sampleIndex],u=o.samples[Y(o.presentationTimestamps).sampleIndex];o.startTimestamp=c.presentationTimestamp,o.endTimestamp=u.presentationTimestamp+u.duration;let{currentFragmentState:l}=this.currentTrack;b(l),l.startTimestamp!==null&&(uu(o,l.startTimestamp),o.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!o.samples[0].encryption&&(o.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let o=Gs(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.currentTrack)break;e.skip(1);let o=Dt(e),c=!!(o&1),u=!!(o&2),l=!!(o&8),d=!!(o&16),m=!!(o&32),f=!!(o&65536),p=!!(o&131072),g=F(e),h=this.idToTrack.get(g);if(!h)break;if(this.currentFragment.trackData.has(g)){V._warn(`Multiple traf boxes for track ${g} in the same moof box; skipping.`);break}let y=this.fragmentTrackDefaults.get(g);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:y?.defaultSampleDescriptionIndex??null,defaultSampleDuration:y?.defaultSampleDuration??null,defaultSampleSize:y?.defaultSampleSize??null,defaultSampleFlags:y?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},c?h.currentFragmentState.baseDataOffset=qe(e):p&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),u&&(h.currentFragmentState.sampleDescriptionIndex=F(e)),l&&(h.currentFragmentState.defaultSampleDuration=F(e)),d&&(h.currentFragmentState.defaultSampleSize=F(e)),m&&(h.currentFragmentState.defaultSampleFlags=F(e)),f&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let o=this.currentTrack;if(!o?.currentFragmentState)break;let c=L(e);e.skip(3);let u=c===0?F(e):qe(e);o.currentFragmentState.startTimestamp=u}break;case"trun":{let o=this.currentTrack;if(!o?.currentFragmentState||!this.currentFragment)break;e.skip(1);let c=Dt(e),u=!!(c&1),l=!!(c&4),d=!!(c&256),m=!!(c&512),f=!!(c&1024),p=!!(c&2048),g=F(e),{defaultSampleDuration:h,defaultSampleSize:y,defaultSampleFlags:k}=o.currentFragmentState;if(g>0&&(!d&&h===null||!m&&y===null||!f&&k===null))throw new Error("Invalid trun box: sample values are missing and there are no defaults.");if(this.currentFragment.sampleCount+=g,this.currentFragment.sampleCount>2**20)throw new Error("Too many (> 2^20) samples in fragment.");let T=null;u&&(T=Rr(e));let w=null;l&&(w=F(e));let S;this.currentFragment.trackData.has(o.id)?(S=this.currentFragment.trackData.get(o.id),T!==null&&(S.currentOffset=o.currentFragmentState.baseDataOffset+T)):(S={track:o,currentTimestamp:0,currentOffset:o.currentFragmentState.baseDataOffset+(T??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,trunSampleCounts:[],encryptionAuxInfo:null},this.currentFragment.trackData.set(o.id,S)),S.trunSampleCounts.push(g);for(let x=0;x<g;x++){let C;d?C=F(e):C=h;let I;m?I=F(e):I=y;let A;f?A=F(e):A=k,x===0&&w!==null&&(A=w);let P=0;p&&(P=Rr(e));let E=!(A&65536);S.samples.push({presentationTimestamp:S.currentTimestamp+P,duration:C,byteOffset:S.currentOffset,byteSize:I,isKeyFrame:E,encryption:null}),S.currentOffset+=I,S.currentTimestamp+=C}this.currentFragment.implicitBaseDataOffset=S.currentOffset}break;case"saiz":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;if(e.skip(1),Dt(e)&1){let f=ue(e,4),p=F(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let u=L(e),l=F(e),d=null;u===0&&l>0&&(d=U(e,l));let m=Gd(o);m.defaultSampleInfoSize=u,m.sampleSizes=d,m.sampleCount=l}break;case"saio":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=L(e);if(Dt(e)&1){let f=ue(e,4),p=F(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let l=F(e);if(l===0)break;l>1&&V._warn("Multiple saio entries are not supported; using the first offset only.");let d=c===0?F(e):Number(qe(e));this.currentFragment&&(d+=this.currentFragment.moofOffset);let m=Gd(o);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 l=!!(Dt(e)&2),d=F(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(l){let y=fe(e);g=[];for(let k=0;k<y;k++){let T=fe(e),w=F(e);g.push({clearLen:T,protectedLen:w})}}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:u}of o){if(c.name!=="meta"&&!this.currentTrack){let l=u.filePos;this.metadataTags.raw??={},c.name[0]==="\xA9"?this.metadataTags.raw[c.name]??=Bt(u):this.metadataTags.raw[c.name]??=U(u,c.contentSize),u.filePos=l}switch(c.name){case"meta":u.skip(-c.headerSize),this.traverseBox(u);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=he.decode(U(u,c.contentSize)):this.metadataTags.title??=Bt(u);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Bt(u));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Bt(u));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Bt(u));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Bt(u));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Bt(u));break;case"\xA9day":if(!this.currentTrack){let l=new Date(Bt(u));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Bt(u));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Bt(u));break}}}break;case"meta":{if(this.currentTrack)break;let c=F(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=F(e);for(let c=0;c<o;c++){let u=F(e);if(u<8)throw new Error("Invalid keys box: key size must be at least 8.");e.skip(4);let l=he.decode(U(e,u-8));this.currentMetadataKeys.set(c+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let o=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(let{boxInfo:c,slice:u}of o){let l=c.name,d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));let m=Ud(u);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=m,l){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=new Date(m);Number.isNaN(f.getTime())||(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 gt?(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}},Ys=class{constructor(t){this.internalTrack=t;this.packetToSampleIndex=new WeakMap;this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}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?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.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,t)}mapTimestampIntoTimescale(t){return wr(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,e){let r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=lu(n,r),s=await this.fetchPacketForSampleIndex(a,e);return!qd(n)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=G(c.presentationTimestamps,r,m=>m.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,e)}async getNextPacket(t,e){let r=this.packetToSampleIndex.get(t);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,e);let n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,a=>{if(a===n.fragment){let s=a.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<s.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(a.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=Qp(n,r),s=await this.fetchPacketForSampleIndex(a,e);return!qd(n)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=qr(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=r),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,e)}async getNextKeyPacket(t,e){let r=this.packetToSampleIndex.get(t);if(r!==void 0){let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=$p(a,r);return this.fetchPacketForSampleIndex(s,e)}let n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,a=>{if(a===n.fragment){let s=a.trackData.get(this.internalTrack.id);for(let o=n.sampleIndex+1;o<s.samples.length;o++)if(s.samples[o].isKeyFrame)return{sampleIndex:o,correctSampleFound:!0}}else{let s=a.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let o=s.samples.findIndex(c=>c.isKeyFrame);return b(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}async fetchPacketForSampleIndex(t,e){if(t===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=jp(r,t);if(!n)return null;let a;if(e.metadataOnly)a=Se;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(_(u)&&(u=await u),!u)return null;if(a=U(u,n.sampleSize),this.internalTrack.encryptionInfo){let l=null;if(this.internalTrack.encryptionAuxInfo){let d=await Zd(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);t<d.length&&(l=d[t])}l??=Qd(this.internalTrack.encryptionInfo),l&&(a=await jd(this.internalTrack,l,a,null))}}let s=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,c=new j(a,n.isKeyFrame?"key":"delta",s,o,t,n.sampleSize);return this.packetToSampleIndex.set(c,t),c}async fetchPacketInFragment(t,e,r){if(e===-1)return null;let a=t.trackData.get(this.internalTrack.id).samples[e];b(a);let s;if(r.metadataOnly)s=Se;else{let l=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);if(_(l)&&(l=await l),!l)return null;if(s=U(l,a.byteSize),this.internalTrack.encryptionInfo){let d=a.encryption??Qd(this.internalTrack.encryptionInfo);d&&(s=await jd(this.internalTrack,d,s,t))}}let o=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=a.duration/this.internalTrack.timescale,u=new j(s,a.isKeyFrame?"key":"delta",o,c,t.moofOffset+e,a.byteSize);return this.packetToFragmentLocation.set(u,{fragment:t,sampleIndex:e}),u}async performFragmentedLookup(t,e,r,n,a,s=!1){let o=this.internalTrack.demuxer,c=null,u=null,l=-1;if(t){let{sampleIndex:y,correctSampleFound:k}=e(t);if(k)return this.fetchPacketInFragment(t,y,a);y!==-1&&(u=t,l=y)}let d=G(this.internalTrack.fragmentLookupTable,r,y=>y.timestamp),m=d!==-1?this.internalTrack.fragmentLookupTable[d]:null,f=G(this.internalTrack.fragmentPositionCache,r,y=>y.startTimestamp),p=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,g=Math.max(m?.moofOffset??0,p?.moofOffset??0)||null,h;for(t?g===null||t.moofOffset>=g?(h=t.moofOffset+t.moofSize,c=t):h=g:h=g??0;;){if(c){let S=c.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>n)break}let y=o.fragmentSummaries.get(h);if(y&&!y.trackIds.has(this.internalTrack.id)){h+=y.moofSize;continue}let k=o.reader.requestSliceRange(h,Mt,vr);if(_(k)&&(k=await k),!k)break;let T=h,w=_r(k);if(!w)break;if(w.name==="moof"){if(c=await o.readFragment(T),!c)break;let{sampleIndex:S,correctSampleFound:x}=e(c);if(x)return this.fetchPacketInFragment(c,S,a);S!==-1&&(u=c,l=S)}h=T+w.totalSize}if(m&&(!u||u.moofOffset<m.moofOffset)){let y=this.internalTrack.fragmentLookupTable[d-1],k=!s&&y?y.timestamp:-1/0;return this.performFragmentedLookup(null,e,k,n,a,!0)}return u?this.fetchPacketInFragment(u,l,a):null}},Zs=class extends Ys{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&&er(r.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=r&&ir(r.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!gd(this.internalTrack.info.vp9CodecInfo))){let r=await this.getFirstPacket({}),n=r&&dn(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||!Ps(this.internalTrack.info.av1CodecInfo))){let r=await this.getFirstPacket({}),n=r&&Mi(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&&Is(r.data)}if(!rn(this.internalTrack.info.colorSpace)){let r=zs(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:Xr(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}},Js=class extends Ys{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&&Os(e.data)}return{codec:mn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},lu=(i,t)=>{if(i.sortedCompositionTimeOffsets)return $d(i,t,!1);{let e=G(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)}},Qp=(i,t)=>{if(!i.keySampleIndices)return lu(i,t);if(i.sortedCompositionTimeOffsets)return $d(i,t,!0);{let e=lu(i,t),r=G(i.keySampleIndices,e,n=>n);return i.keySampleIndices[r]??-1}},jp=(i,t)=>{if(t>=i.sampleCount)return null;let e=G(i.sampleTimingEntries,t,h=>h.startIndex),r=i.sampleTimingEntries[e],a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,s=G(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)],u=G(i.sampleToChunk,t,h=>h.startSampleIndex),l=i.sampleToChunk[u],d=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),m=i.chunkOffsets[d],f=l.startSampleIndex+(d-l.startChunkIndex)*l.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=Xp(i,t,a);h!==null&&(g=h-a)}return{presentationTimestamp:a,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:m,isKeyFrame:i.keySampleIndices?Tr(i.keySampleIndices,t,h=>h)!==-1:!0}},$d=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=-1,a=-1/0,s=G(r,t,o=>o.startTimestamp);for(let o=s;o>=0;o--){let c=r[o];if(c.maxLastTimestamp<a)break;let u=c.lastTimestamp<=t?c.startIndex+c.count-1:Yd(i,c,(d,m)=>m>t)-1;if(e){let d=G(i.keySampleIndices,u,m=>m);u=i.keySampleIndices[d]??-1}if(u<c.startIndex)continue;let l=du(i,u)+c.offset;(l>a||l===a&&u>n)&&(n=u,a=l)}return n},Xp=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=G(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=Yd(i,o,(l,d)=>d>e||d===e&&l>t);if(c===o.startIndex+o.count)continue;let u=du(i,c)+o.offset;(a===null||u<a)&&(a=u)}return a},Yd=(i,t,e)=>{let r=t.startIndex,n=t.startIndex+t.count;for(;r<n;){let a=Math.floor((r+n)/2);e(a,du(i,a)+t.offset)?n=a:r=a+1}return r},du=(i,t)=>{let e=G(i.sampleTimingEntries,t,n=>n.startIndex),r=i.sampleTimingEntries[e];return r.startDecodeTimestamp+(t-r.startIndex)*r.delta},$p=(i,t)=>{if(!i.keySampleIndices)return t+1;let e=G(i.keySampleIndices,t,r=>r);return i.keySampleIndices[e+1]??-1},uu=(i,t)=>{i.startTimestamp+=t,i.endTimestamp+=t;for(let e of i.samples)e.presentationTimestamp+=t;for(let e of i.presentationTimestamps)e.presentationTimestamp+=t},Wd=i=>[ei(i),ei(i),js(i),ei(i),ei(i),js(i),ei(i),ei(i),js(i)],Hd=(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)))},qd=i=>i.sampleSizes.length===0,Kd=(i,t)=>{for(;i.length>0&&Y(i).startIndex>=t;)i.pop();let e=Y(i);e&&(e.count=Math.min(e.count,t-e.startIndex))},Gd=i=>i.currentFragmentState?i.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:i.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Zd=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(_(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],u=new Uint8Array(16);if(a>0)u.set(U(n,a),0);else if(t.defaultConstantIv)u.set(t.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let l=null;if(c>a){let d=fe(n);l=[];for(let m=0;m<d;m++){let f=fe(n),p=F(n);l.push({clearLen:f,protectedLen:p})}}s.push({iv:u,subsamples:l})}return e.resolved=s,s},Qd=i=>i.defaultConstantIv?{iv:i.defaultConstantIv,subsamples:null}:null,jd=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 u=i.demuxer.psshBoxes;if(r){u=[...u,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(a));for(let d=0;d<u.length-1;d++)for(let m=d+1;m<u.length;m++)Qs(u[d],u[m])&&(u.splice(m,1),m--)}let l=await i.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:u});if(!(typeof l=="string"&&l.length===32&&Nl.test(l)||l instanceof Uint8Array&&l.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return l instanceof Uint8Array?l:Ll(l)})();i.demuxer.decryptionKeyCache.set(a,c),s=await c}return n.scheme==="cenc"||n.scheme==="cens"?Yp(s,n,t,e):Zp(s,n,t,e)},Yp=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=Jd(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 u=new Uint8Array(c),l=0;for(let p of o)for(let g of p.perSubsample)u.set(r.subarray(g.offset,g.offset+g.length),l),l+=g.length;let d=await s(u),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},Zp=(i,t,e,r)=>{let n=new da;n.init({key:i,iv:e.iv});let a=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(b(a!==null&&s!==null),!e.subsamples){let l=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(),l.set(n.out,f)}return l}if(a===0&&s===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(r),c=Jd(e.subsamples,a,s,r.length),u=new DataView(e.iv.buffer,e.iv.byteOffset,16);for(let l of c){n.iv[0]=u.getUint32(0,!1),n.iv[1]=u.getUint32(4,!1),n.iv[2]=u.getUint32(8,!1),n.iv[3]=u.getUint32(12,!1);for(let d of l.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},Jd=(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 u=o.protectedLen,l=s;for(;u>0&&!(u<16*t);){let d=16*t;c.push({offset:l,length:d}),l+=d,u-=d;let m=Math.min(16*e,u);l+=m,u-=m}s+=o.protectedLen}n.push({perSubsample:c})}return n};var ti=class{constructor(t){this.value=t}},yn=class{constructor(t){this.value=t}},fa=class{constructor(t){this.value=t}},Vt=class{constructor(t){this.value=t}};var Jp=[440786851,408125543],kn=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],pa=[...Jp,...kn],tm=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,rm=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,im=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,eh=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)},to=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=tm(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=rm(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=im(t)){t<0&&(t+=2**(e*8)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=eh(t)){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)){let e=this.writer.getPos(),r=t.size===-1?1:t.size??4;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??tm(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if(typeof t.data=="bigint"){let e=t.size??rm(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 ti)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof yn)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof fa){let e=t.size??im(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Vt){let e=Z.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else ae(t.data)}},nm=8,$e=2,xt=2*nm,mu=i=>{if(i.remainingLength<1)return null;let t=L(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},Tn=i=>{if(i.remainingLength<1)return null;let t=L(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+=L(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+=L(i);return e},am=(i,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let e=0n;for(let r=0;r<t;r++)e<<=8n,e+=BigInt(L(i));return e};var ro=i=>{let t=mu(i);return t===null||i.remainingLength<t?null:X(i,t)},fu=i=>{if(i.remainingLength<1)return null;if(L(i)===255)return;i.skip(-1);let e=Tn(i);if(e===null)return null;if(e!==72057594037927940)return e},Ct=i=>{b(i.remainingLength>=$e);let t=ro(i);if(t===null)return null;let e=fu(i);return e===null?null:{id:t,size:e}},ri=(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},wn=(i,t)=>{let e=U(i,t),r=0;for(;r<t&&e[r]!==0;)r+=1;return he.decode(e.subarray(0,r))},Sn=(i,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw new Error("Bad float size "+t);return t===4?sm(i):eo(i)},io=async(i,t,e,r)=>{let n=new Set(e),a=t;for(;r===null||a<r;){let s=i.requestSliceRange(a,$e,xt);if(_(s)&&(s=await s),!s)break;let o=Ct(s);if(!o)break;if(n.has(o.id))return{pos:a,found:!0};ar(o.size),a=s.filePos+o.size}return{pos:r!==null&&r>a?r:a,found:!1}},pu=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(_(o)&&(o=await o),!o||o.length===0)break;let c=Math.max(o.length-nm,1);for(let u=0;u<c;u++){o.filePos=s;let l=ro(o);if(l!==null&&a.has(l))return s;s++}}return null},ze={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function ar(i){if(i===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var no=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 hu=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],cm=10*2**20,th=64,ao=class extends Pe{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.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 no({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,$e,xt);if(_(r)&&(r=await r),!r)break;let n=Ct(r);if(!n)break;let a=n.id,s=n.size,o=r.filePos;if(a===440786851){ar(s);let c=this.reader.requestSlice(o,s);if(_(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 io(this.reader,o,pa,this.reader.fileSize)).pos-o);let c=Y(this.segments);c&&(c.elementEndPos=o+s)}ar(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,$e,xt);if(_(c)&&(c=await c),!c)break;let u=n,l=Ct(c);if(!l||!kn.includes(l.id)&&l.id!==236){let g=await pu(this.reader,u+1,kn,Math.min(this.currentSegment.elementEndPos??1/0,u+cm));if(g){n=g;continue}else break}let{id:d,size:m}=l,f=c.filePos,p=hu.findIndex(g=>g.id===d);if(p!==-1){let g=hu[p].flag;this.currentSegment[g]=!0,d===290298740&&a.add(u-e),ar(m);let h=this.reader.requestSlice(f,m);_(h)&&(h=await h),h&&this.readContiguousElements(h)}else if(d===307544935||d===423732329){d===307544935?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ar(m);let g=this.reader.requestSlice(f,m);_(g)&&(g=await g),g&&this.readContiguousElements(g)}else if(d===524531317){this.currentSegment.clusterSeekStartPos=u;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 u=this.currentSegment.seekEntries[c];if(u.id!==290298740||a.has(u.segmentPosition)||(a.add(u.segmentPosition),!this.claimSeekTarget(e+u.segmentPosition)))continue;let l=this.reader.requestSliceRange(e+u.segmentPosition,$e,xt);if(_(l)&&(l=await l),!l)continue;let d=Ct(l);if(!d||d.id!==290298740)continue;let{size:m}=d;ar(m);let f=this.reader.requestSlice(l.filePos,m);_(f)&&(f=await f),f&&this.readContiguousElements(f)}if(this.currentSegment.seekEntries.sort((c,u)=>c.segmentPosition-u.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let u=hu.find(g=>g.id===c.id);if(!u||this.currentSegment[u.flag]||!this.claimSeekTarget(e+c.segmentPosition))continue;let l=this.reader.requestSliceRange(e+c.segmentPosition,$e,xt);if(_(l)&&(l=await l),!l)continue;let d=Ct(l);if(!d)continue;let{id:m,size:f}=d;if(m!==u.id)continue;ar(f),this.currentSegment[u.flag]=!0;let p=this.reader.requestSlice(l.filePos,f);_(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);for(let c of this.currentSegment.cuePoints){let u=this.currentSegment.idToTrack.get(c.trackId);u&&u.cuePoints.push(c)}for(let c of this.currentSegment.tracks){let u=c.cuePoints;u.sort((d,m)=>d.time-m.time);let l=0;for(let d of u)(l===0||d.time!==u[l-1].time)&&(u[l++]=d);u.length=l}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,$e,xt);_(n)&&(n=await n),b(n);let a=e,s=Ct(n);b(s);let o=s.id;b(o===524531317);let c=s.size,u=n.filePos;c===void 0&&(c=(await io(this.reader,u,pa,r.elementEndPos)).pos-u);let l=this.reader.requestSlice(u,c);_(l)&&(l=await l);let d={segment:r,elementStartPos:a,elementEndPos:u+c,dataStartPos:u,timestamp:-1,trackData:new Map};if(l){this.currentCluster=d;try{let m=this.readContiguousElements(l,pa);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 S=m.blocks[w];S.timestamp+=d.timestamp,p||=S.lacing!==0}m.presentationTimestamps=m.blocks.map((w,S)=>({timestamp:w.timestamp,blockIndex:S})).sort((w,S)=>w.timestamp-S.timestamp);for(let w=0;w<m.presentationTimestamps.length;w++){let S=m.presentationTimestamps[w],x=m.blocks[S.blockIndex];if(m.firstKeyFrameTimestamp===null&&x.isKeyFrame&&(m.firstKeyFrameTimestamp=x.timestamp),w<m.presentationTimestamps.length-1){let C=m.presentationTimestamps[w+1];x.duration=C.timestamp-x.timestamp}else x.duration===0&&f.defaultDuration!=null&&x.lacing===0&&(x.duration=f.defaultDuration)}p&&(m.blocks=this.expandLacedBlocks(m.blocks,f),m.presentationTimestamps=m.blocks.map((w,S)=>({timestamp:w.timestamp,blockIndex:S})).sort((w,S)=>w.timestamp-S.timestamp));let g=m.blocks[m.presentationTimestamps[0].blockIndex],h=m.blocks[Y(m.presentationTimestamps).blockIndex];m.startTimestamp=g.timestamp,m.endTimestamp=h.timestamp+h.duration;let y=G(f.clusterPositionCache,m.startTimestamp,w=>w.startTimestamp),k=f.clusterPositionCache[y],T=f.clusterPositionCache[y+1];(!k||k.elementStartPos<a)&&(!T||T.elementStartPos>a)&&f.clusterPositionCache.splice(y+1,0,{elementStartPos:d.elementStartPos,startTimestamp:m.startTimestamp})}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=we.tempFromBytes(a.data);if(s.length===0)throw new Error("Invalid laced block: no data.");let o=[],c=L(s)+1;switch(a.lacing){case 1:{let l=0;for(let d=0;d<c-1;d++){let m=0;for(;s.bufferPos<s.length;){let f=L(s);if(m+=f,f<255){o.push(m),l+=m;break}}}o.push(s.length-(s.bufferPos+l))}break;case 2:{let l=s.length-1,d=Math.floor(l/c);for(let m=0;m<c;m++)o.push(d)}break;case 3:{let l=Tn(s);if(l===null)throw new Error("Invalid EBML lacing: bad frame size.");let d=l;o.push(d);let m=d;for(let f=1;f<c-1;f++){let p=s.bufferPos,g=Tn(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(l=>l<=0))throw new Error("Invalid block lacing: frame sizes don't match the block.");let u=a.duration||c*(r.defaultDuration??0);for(let l=0;l<c;l++){let d=o[l],m=U(s,d),f=a.timestamp+u*l/c,p=u/c;n.push({timestamp:f,duration:p,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,$e,xt);if(_(n)&&(n=await n),!n)continue;let a=Ct(n);if(!a||a.id!==r.id)continue;let{size:s}=a;ar(s);let o=this.reader.requestSlice(n.filePos,s);if(_(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===th)throw new Error("Invalid file: elements are nested too deeply.");this.elementNestingDepth++;try{for(;e.remainingLength>=$e;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}finally{this.elementNestingDepth--}}traverseElement(e,r){let n=Ct(e);if(!n||r&&r.includes(n.id))return!1;let{id:a,size:s}=n,o=e.filePos;if(ar(s),o+s>e.end)return!1;switch(a){case 17026:this.isWebM=ri(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=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=Sn(e,s)}break;case 174:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{..._e,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,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)&&(V._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentSegment.idToTrack.has(this.currentTrack.id)&&(V._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("/"),u=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){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let d=this.currentTrack.info.displayWidth*this.currentTrack.info.height,m=this.currentTrack.info.displayHeight*this.currentTrack.info.width;d>0&&m>0&&(d>m?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*d/m):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*m/d))}if(this.currentTrack.codecId===ze.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===ze.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(u===ze.vp8)this.currentTrack.info.codec="vp8";else if(u===ze.vp9)this.currentTrack.info.codec="vp9";else if(u===ze.av1)this.currentTrack.info.codec="av1";else if(u===ze.prores){let d=this.currentTrack.codecPrivate?he.decode(this.currentTrack.codecPrivate):"";Er.includes(d)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=d)}let l=this.currentTrack;this.currentTrack.trackBacking=new gu(l),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}else if(this.currentTrack.info.type==="audio"){u===ze.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ze.mp3?this.currentTrack.info.codec="mp3":u===ze.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Ft):u===ze.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.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")):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 l=this.currentTrack;this.currentTrack.trackBacking=new bu(l),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:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...ms},alphaMode:!1,proresFormat:null}:c===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case 185:{if(!this.currentTrack)break;X(e,s)||(this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!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=ri(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 21358:{if(!this.currentTrack)break;this.currentTrack.name=wn(e,s)}break;case 2274716:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ri(e,s),Sr(this.currentTrack.languageCode)||(this.currentTrack.languageCode=se)}break;case 2274717:{if(!this.currentTrack)break;let u=ri(e,s).split("-")[0];u?this.currentTrack.languageCode=u:this.currentTrack.languageCode=se,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 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=X(e,s),u=ht[c];this.currentTrack.info.colorSpace.matrix=u}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=X(e,s),u=pt[c];this.currentTrack.info.colorSpace.transfer=u}break;case 21947:{if(this.currentTrack?.info?.type!=="video")break;let c=X(e,s),u=ft[c];this.currentTrack.info.colorSpace.primaries=u}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 30323:{if(this.currentTrack?.info?.type!=="video")break;let c=Sn(e,s);try{let u=yr(c);this.currentTrack.info.horizontalScale=Math.round(Math.cos(u*ss))}catch{}}break;case 30324:{if(this.currentTrack?.info?.type!=="video")break;let c=Sn(e,s);try{let u=yr(c);this.currentTrack.info.verticalScale=Math.round(Math.cos(u*ss))}catch{}}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let u=-Sn(e,s);try{this.currentTrack.info.rotation=yr(u)}catch{}}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=Sn(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 159:{if(this.currentTrack?.info?.type!=="audio")break;let c=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),u=Tn(c);if(u===null||c.remainingLength<3)break;let l=this.getTrackDataInCluster(this.currentCluster,u);if(!l)break;let d=ma(c),m=L(c),f=m>>1&3,p=!!(m&128);l.track.info?.type==="audio"&&l.track.info.codec&&(p=!0);let g=U(c,c.remainingLength),h=l.track.decodingInstructions.length>0;l.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),u=Tn(c);if(u===null||c.remainingLength<3)break;let l=this.getTrackDataInCluster(this.currentCluster,u);if(!l)break;let d=ma(c),f=L(c)>>1&3,p=U(c,c.remainingLength),g=l.track.decodingInstructions.length>0;this.currentBlock={timestamp:d,duration:0,isKeyFrame:!0,data:p,lacing:f,decoded:!g,postProcessed:!1,mainAdditional:null},l.blocks.push(this.currentBlock)}break;case 30113:this.readContiguousElements(e.slice(o,s));break;case 166:{let c=this.currentBlock;if(!c)break;let u={addId:1,data:null};this.currentBlockAdditional=u,this.readContiguousElements(e.slice(o,s)),u.data&&u.addId===1&&(c.mainAdditional=u.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=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: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=wn(e,s);break;case 17543:{if(!this.currentSimpleTagName)break;let c=wn(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 xr(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 u=this.currentAttachedFile.fileName,l="unknown";if(u){let d=u.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}c.images??=[],c.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,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=am(e,s)}break;case 18030:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=wn(e,s)}break;case 18016:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ri(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=wn(e,s)}break;case 28032:{let c=this.currentTrack;if(!c)break;this.readContiguousElements(e.slice(o,s)),c.decodingInstructions.sort((u,l)=>l.order-u.order)}break;case 25152:{let c=this.currentTrack;if(!c)break;let u={order:0,scope:1,data:null};this.currentDecodingInstruction=u,this.readContiguousElements(e.slice(o,s)),u.data&&c.decodingInstructions.push(u),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=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=new Date(r);Number.isNaN(a.getTime())||(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){return e.duration<=0?null:e.duration/e.timestampFactor}},so=class{constructor(t){this.internalTrack=t;this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}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)break;return r}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 wr(t*this.internalTrack.segment.timestampFactor)}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=G(a.presentationTimestamps,r,u=>u.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=qr(a.presentationTimestamps,u=>a.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=r),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<a.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,e)}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 m=new Uint8Array(a.data.length+8);N(m).setUint32(0,m.length,!1),m[4]=105,m[5]=99,m[6]=112,m[7]=102,m.set(a.data,8),a.data=m}a.postProcessed=!0}let s=r.metadataOnly?Se:a.data,o=a.timestamp/this.internalTrack.segment.timestampFactor,c=a.duration/this.internalTrack.segment.timestampFactor,u={};a.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=r.metadataOnly?Se:a.mainAdditional,u.alphaByteLength=a.mainAdditional.byteLength);let l=new j(s,a.isKeyFrame?"key":"delta",o,c,t.dataStartPos+e,a.data.byteLength,u);return this.packetToClusterLocation.set(l,{cluster:t,blockIndex:e}),l}async performClusterLookup(t,e,r,n,a,s=!1){let{demuxer:o,segment:c}=this.internalTrack,u=null,l=null,d=-1;if(t){let{blockIndex:k,correctBlockFound:T}=e(t);if(T)return this.fetchPacketInCluster(t,k,a);k!==-1&&(l=t,d=k)}let m=G(this.internalTrack.cuePoints,r,k=>k.time),f=m!==-1?this.internalTrack.cuePoints[m]:null,p=G(this.internalTrack.clusterPositionCache,r,k=>k.startTimestamp),g=p!==-1?this.internalTrack.clusterPositionCache[p]:null,h=Math.max(f?.clusterPosition??0,g?.elementStartPos??0)||null,y;for(t?h===null||t.elementStartPos>=h?(y=t.elementEndPos,u=t):y=h:y=h??c.clusterSeekStartPos;c.elementEndPos===null||y<=c.elementEndPos-$e;){if(u){let P=u.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>n)break}let k=c.clusterSummaries.get(y);if(k&&!k.trackIds.has(this.internalTrack.id)){y=k.elementEndPos;continue}let T=o.reader.requestSliceRange(y,$e,xt);if(_(T)&&(T=await T),!T)break;let w=y,S=Ct(T);if(!S||!kn.includes(S.id)&&S.id!==236){let P=await pu(o.reader,w+1,kn,Math.min(c.elementEndPos??1/0,w+cm));if(P){y=P;continue}else break}let x=S.id,C=S.size,I=T.filePos;if(x===524531317){u=await o.readCluster(w,c),C=u.elementEndPos-I;let{blockIndex:P,correctBlockFound:E}=e(u);if(E)return this.fetchPacketInCluster(u,P,a);P!==-1&&(l=u,d=P)}C===void 0&&(b(x!==524531317),C=(await io(o.reader,I,pa,c.elementEndPos)).pos-I);let A=I+C;if(c.elementEndPos===null){let P=o.reader.requestSliceRange(A,$e,xt);if(_(P)&&(P=await P),!P)break;if(ro(P)===408125543){c.elementEndPos=A;break}}y=A}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let k=this.internalTrack.cuePoints[m-1],T=!s&&k?k.time:-1/0;return this.performClusterLookup(null,e,T,n,a,!0)}return l?this.fetchPacketInCluster(l,d,a):null}},gu=class extends so{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=Ht(us(e.horizontalScale,e.verticalScale),tn(e.rotation));return cs(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=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let n={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"&&e?er(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?ir(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?dn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Mi(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Is(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!rn(this.internalTrack.info.colorSpace)){let s=zs(n);this.internalTrack.info.colorSpace.primaries??=s.primaries,this.internalTrack.info.colorSpace.transfer??=s.transfer,this.internalTrack.info.colorSpace.matrix??=s.matrix,this.internalTrack.info.colorSpace.fullRange??=s.fullRange}let a={codec:Xr(n),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)&&(a.displayAspectWidth=this.internalTrack.info.squarePixelWidth,a.displayAspectHeight=this.internalTrack.info.squarePixelHeight),a})():null}},bu=class extends so{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&&Os(e.data)}return{codec:mn({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 ha=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(_(o)&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,u=F(o),l=i.fileSize!==null?i.fileSize-a:null,d=Zr(u,l);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&Jr(d.header.channel)===Jr(r.channel)))return{header:d.header,startPos:a};o.filePos=c+d.bytesAdvanced,a=o.filePos}}return null};var oo=class extends Pe{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 He;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();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 yu(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let c=this.reader.requestSlice(this.lastLoadedPos,Fe);if(_(c)&&(c=await c),!c){this.lastSampleLoaded=!0;return}let u=it(c);if(!u)break;this.lastLoadedPos=c.filePos+u.size}let e=await ha(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=Yr(r.mpegVersionId,r.channel),a=this.reader.requestSlice(e.startPos+n,4);if(_(a)&&(a=await a),a){let c=F(a);if(c===$r||c===fn){if(this.xingFrameHeader||(this.xingFrameHeader=r,this.xingFrameHeaderPos=e.startPos),!this.xingData){let l=this.reader.requestSlice(e.startPos+n+4,12);if(_(l)&&(l=await l),l){let d=U(l,12),m=N(d),f=m.getUint32(0,!1);this.xingData={frameCount:f&1?m.getUint32(4,!1):null,fileSize:f&2?m.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=r,this.firstFrameHeaderPos=e.startPos);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(o),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,Fe);if(_(a)&&(a=await a),!a)break;let s=it(a);if(!s)break;n=!0;let o=this.reader.requestSlice(a.filePos,s.size);if(_(o)&&(o=await o),!o)break;ii(o,s,this.metadataTags),r=a.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=ga){let a=this.reader.requestSlice(this.reader.fileSize-ga,ga);_(a)&&(a=await a),b(a),ue(a,3)==="TAG"&&um(a,this.metadataTags)}return this.metadataTags}finally{e()}}},yu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let t=this.demuxer;if(b(t.firstFrameHeader!==null),b(t.firstFrameHeaderPos!==null),t.xingData){if(t.xingData.frameCount!==null)return t.xingData.frameCount*t.firstFrameHeader.audioSamplesInFrame/t.firstFrameHeader.sampleRate}else if(t.reader.fileSize!==null){let e=Dd(t.firstFrameHeader.lowSamplingFrequency,t.firstFrameHeader.layer,t.firstFrameHeader.bitrate,t.firstFrameHeader.sampleRate),r=(t.reader.fileSize-t.firstFrameHeaderPos)/e;return Math.round(r)*t.firstFrameHeader.audioSamplesInFrame/t.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return se}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.firstFrameHeader),Jr(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{..._e}}async getDecoderConfig(){return b(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Jr(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=Se;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(_(a)&&(a=await a),!a)return null;n=U(a,r.dataSize)}return new j(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=Tr(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{for(;;){let n=G(this.demuxer.loadedSamples,t,a=>a.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,e);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var ba=1399285583,ih=79764919,lm=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^ih:t<<1;lm[i]=t>>>0&4294967295}var dm=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^lm[r>>>24^a])>>>0}return t.setUint32(22,e,!0),r},ya=(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<<jl(a-1))-1<<1,c=(i[0]&o)>>1;if(c>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=e,l=t.vorbisInfo.modeBlockflags[c];if(n=t.vorbisInfo.blocksizes[l],l===1){let d=(o|1)+1,m=i[0]&d?1:0;u=t.vorbisInfo.blocksizes[m]}r=u!==null?u+n>>2:0}else t.codec==="opus"&&(r=yd(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:n}},co=i=>{let t="audio/ogg";if(i.codecStrings){let e=[...new Set(i.codecStrings)];t+=`; codecs="${e.join(", ")}"`}return t};var Br=27,Bi=282,uo=Bi+255*255,An=i=>{let t=i.filePos;if(ni(i)!==ba)return null;i.skip(1);let r=L(i),n=fm(i),a=ni(i),s=ni(i),o=ni(i),c=L(i);if(c===0||i.remainingLength<c)return null;let u=new Uint8Array(c);for(let f=0;f<c;f++)u[f]=L(i);let l=27+c,d=u.reduce((f,p)=>f+p,0),m=l+d;return{headerStartPos:t,totalSize:m,dataStartPos:t+l,dataSize:d,headerType:r,granulePosition:n,serialNumber:a,sequenceNumber:s,checksum:o,lacingValues:u}},mm=(i,t,e)=>{for(;i.filePos<t-3;){let r=ni(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===ba){if(e===void 0||i.filePos+18>i.end)return!0;i.skip(14);let u=ni(i);if(i.skip(-18),u===e)return!0}i.skip(1)}}return!1};var pm=64,nh=30,ah=19,lo=class extends Pe{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,Br,Bi);if(_(r)&&(r=await r),!r)break;let n=An(r);if(!n||!!!(n.headerType&2))break;if(this.bitstreams.length===pm)throw new Error(`Too many (> ${pm}) 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>=nh&&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>=ah&&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 ku(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),u=o.getUint32(12,!0);if(c===0||u===0)throw new Error("Invalid Vorbis identification header: channel count and sample rate must not be 0.");let l=[],d=p=>{for(;l.push(Math.min(255,p)),!(p<255);)p-=255};d(e.data.length),d(a.data.length);let m=new Uint8Array(1+l.length+e.data.length+a.data.length+s.data.length);m[0]=2,m.set(l,1),m.set(e.data,1+l.length),m.set(a.data,1+l.length+e.data.length),m.set(s.data,1+l.length+e.data.length+a.data.length),r.codecInfo.codec="vorbis",r.description=m,r.lastMetadataPacket=s,r.numberOfChannels=c,r.sampleRate=u;let f=o.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Es(s.data).modeBlockflags},ra(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=Qr(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=Ft,r.codecInfo.opusInfo={preSkip:s.preSkip},ra(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(_(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,Br,Bi);if(_(g)&&(g=await g),!g)return null;let h=An(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 u=c.reduce((m,f)=>m+f.length,0);if(u===0)return null;let l=new Uint8Array(u),d=0;for(let m=0;m<c.length;m++){let f=c[m];l.set(f,d),d+=f.length}return{data:l,endPage:a,endSegmentIndex:o}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let a=this.reader.requestSliceRange(n,Br,Bi);if(_(a)&&(a=await a),!a)return null;let s=An(a);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return co({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},ku=class{constructor(t,e){this.bitstream=t;this.demuxer=e;this.encodedPacketToMetadata=new WeakMap;this.sequentialScanCache=[];this.sequentialScanMutex=new He;this.firstTimestampInSamplesPromise=null;this.internalSampleRate=t.codecInfo.codec==="opus"?Ft:t.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}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 se}getDisposition(){return{..._e,primary:!1}}granulePositionToTimestampInSamples(t){return this.bitstream.codecInfo.codec==="opus"?(b(this.bitstream.codecInfo.opusInfo),t-this.bitstream.codecInfo.opusInfo.preSkip):t}createEncodedPacketFromOggPacket(t,e,r){if(!t)return null;let n=ya(t.data,this.bitstream.codecInfo,e.vorbisLastBlocksize),{vorbisBlockSize:a}=n,{durationInSamples:s}=n;if(!!(t.endPage.headerType&4)&&t.endSegmentIndex===t.endPage.lacingValues.length-1){let d=this.granulePositionToTimestampInSamples(t.endPage.granulePosition);s=J(d-e.timestampInSamples,0,s)}let c=Math.max(e.timestampInSamples,0),u=Math.max(e.timestampInSamples+s,0),l=new j(r.metadataOnly?Se:t.data,"key",c/this.internalSampleRate,(u-c)/this.internalSampleRate,t.endPage.headerStartPos+t.endSegmentIndex,t.data.byteLength);return this.encodedPacketToMetadata.set(l,{packet:t,timestampInSamples:e.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:e.vorbisLastBlocksize,vorbisBlockSize:a}),l}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;for(;e;){let s=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);if(!s||(r??=s.endPage,s.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:o,vorbisBlockSize:c}=ya(s.data,this.bitstream.codecInfo,a);n+=o,a=c,e=await this.demuxer.findNextPacketStart(s)}return r?t+Math.max(r.granulePosition-n,0):t})()}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=wr(t*this.internalSampleRate),n=await this.getFirstTimestampInSamples();if(r===Math.max(n,0))return this.getFirstPacket(e);if(r<Math.max(n,0))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,w=Math.floor((T+o)/2),S=w;for(;;){let x=Math.min(S+uo,o-Br),C=this.demuxer.reader.requestSlice(S,Math.max(x-S,0));if(_(C)&&(C=await C),!C||!mm(C,x,this.bitstream.serialNumber)){if(o<=w+Br)break e;o=w+Br;continue e}let I=C.filePos,A=this.demuxer.reader.requestSliceRange(I,Br,Bi);_(A)&&(A=await A);let P=A&&An(A);if(!P||P.serialNumber!==this.bitstream.serialNumber){S=I+4;continue}if(P.granulePosition===-1){S=P.headerStartPos+P.totalSize;continue}this.granulePositionToTimestampInSamples(P.granulePosition)>r?o=P.headerStartPos:(s=P,c.push(P));continue e}}let u=a.startPage;for(let T of c){if(T.granulePosition===s.granulePosition)break;(!u||T.headerStartPos>u.headerStartPos)&&(u=T)}let l=u,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let T=l.headerStartPos+l.totalSize,w=this.demuxer.reader.requestSliceRange(T,Br,Bi);_(w)&&(w=await w);let S=w&&An(w);if(!S){l=s,d.push(s);break}l=S,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}let m=null,f,p,g=l,h=0;if(l.headerStartPos===a.startPage.headerStartPos)f=n,p=!0,m=0;else{b(l.granulePosition!==-1),f=0,p=!1;for(let S=l.lacingValues.length-1;S>=0;S--)if(l.lacingValues[S]<255){m=S+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:Se,endPage:g,endSegmentIndex:h},w=await this.demuxer.findNextPacketStart(T);if(w){let S=gm(d,l,m);b(S);let x=hm(d,S.page,S.segmentIndex);x?(l=x.page,m=x.segmentIndex):(l=w.startPage,m=w.startSegmentIndex)}else for(;;){let S=gm(d,l,m);if(!S)break;let x=hm(d,S.page,S.segmentIndex);if(!x)break;if(l=x.page,m=x.segmentIndex,S.page.headerStartPos!==g.headerStartPos){g=S.page,h=S.segmentIndex;break}}}let y=null,k=null;for(;l!==null;){b(m!==null);let T=await this.demuxer.readPacket(l,m);if(!T)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let x=this.createEncodedPacketFromOggPacket(T,{timestampInSamples:f,vorbisLastBlocksize:k?.vorbisBlockSize??null},e);b(x);let C=this.encodedPacketToMetadata.get(x);if(b(C),!p&&T.endPage.headerStartPos===g.headerStartPos&&T.endSegmentIndex===h?(f=this.granulePositionToTimestampInSamples(l.granulePosition),p=!0,x=this.createEncodedPacketFromOggPacket(T,{timestampInSamples:f-C.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},e),b(x),C=this.encodedPacketToMetadata.get(x),b(C)):f+=C.durationInSamples,y=x,k=C,p&&(Math.max(f,0)>r||Math.max(C.timestampInSamples,0)===r))break}let S=await this.demuxer.findNextPacketStart(T);if(!S)break;l=S.startPage,m=S.startSegmentIndex}return y}async getPacketSequential(t,e){let r=await this.sequentialScanMutex.acquire();try{let n=wr(t*this.internalSampleRate);t=n/this.internalSampleRate;let a=G(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 u=this.encodedPacketToMetadata.get(s);b(u),this.sequentialScanCache.length>0&&b(Y(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return s}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}},hm=(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=Kc(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}},gm=(i,t,e)=>{if(e>0)return{page:t,segmentIndex:e-1};let r=Kc(i,n=>n.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var mo=class extends Pe{constructor(e){super(e);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.audioInfo=null;this.trackBackings=[];this.lastKnownPacketIndex=0;this.metadataTags={};this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);_(e)&&(e=await e),b(e);let r=ue(e,4),n=r!=="RIFX",a=r==="RF64",s=Or(e,n),o=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(ue(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let u=0,l=null,d=e.filePos;for(;o===null||d<o;){let f=this.reader.requestSlice(d,8);if(_(f)&&(f=await f),!f)break;let p=ue(f,4),g=Or(f,n),h=f.filePos;if(a&&u===0&&p!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(p==="fmt ")await this.parseFmtChunk(h,g,n);else if(p==="data"){if(l??=g,this.dataStart=f.filePos,this.dataSize=Math.max(Math.min(l,(o??1/0)-this.dataStart),0),this.reader.fileSize===null)break}else if(p==="ds64"){let y=this.reader.requestSlice(h,g);if(_(y)&&(y=await y),!y)break;if(g<16)throw new Error('Invalid RF64 file: "ds64" chunk is too small.');let k=wu(y,n);l=wu(y,n),o=Math.min(k+8,this.reader.fileSize??1/0)}else p==="LIST"?await this.parseListChunk(h,g,n):(p==="ID3 "||p==="id3 ")&&await this.parseId3Chunk(h,g);d=h+g+(g&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 m=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/m)*m,this.trackBackings.push(new Tu(this))})()}async parseFmtChunk(e,r,n){let a=this.reader.requestSlice(e,r);if(_(a)&&(a=await a),!a)return;if(r<14)throw new Error('Invalid WAVE file - "fmt " chunk is too small');let s=Cn(a,n),o=Cn(a,n),c=Or(a,n);a.skip(4);let u=Cn(a,n);if(o===0||c===0||u===0)throw new Error("Invalid WAVE file - channel count, sample rate and block align must be positive");let l;if(r<16?l=8:l=Cn(a,n),r>=18&&s!==357){let d=Cn(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.`);this.audioInfo={format:s,numberOfChannels:o,sampleRate:c,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:u}}async parseListChunk(e,r,n){if(r<4)return;let a=this.reader.requestSlice(e,r);if(_(a)&&(a=await a),!a)return;let s=ue(a,4);if(s!=="INFO"&&s!=="INF0")return;let o=a.filePos;for(;o<=e+r-8;){a.filePos=o;let c=ue(a,4),u=Or(a,n);if(u>a.remainingLength)break;let l=U(a,u),d="";for(let m=0;m<l.length&&l[m]!==0;m++)d+=String.fromCharCode(l[m]);switch(this.metadataTags.raw??={},this.metadataTags.raw[c]=d,c){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let m=d.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(d);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(d,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}o+=8+u+(u&1)}}async parseId3Chunk(e,r){if(r<Fe)return;let n=this.reader.requestSlice(e,r);if(_(n)&&(n=await n),!n)return;let a=it(n);if(a){let s=r-Fe;if(a.size=Math.min(a.size,s),a.size>0){let o=n.slice(e+Fe,a.size);ii(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)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},xn=2048,Tu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}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.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return se}getDisposition(){return{..._e}}async getPacketAtIndex(t,e){b(t>=0),b(this.demuxer.audioInfo);let r=t*xn*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let n=Math.min(xn*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,n);if(_(c)&&(c=await c),!c)return null}let a;if(e.metadataOnly)a=Se;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,n);_(c)&&(c=await c),b(c),a=U(c,n)}let s=t*xn/this.demuxer.audioInfo.sampleRate,o=n/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(t,this.demuxer.lastKnownPacketIndex),new j(a,"key",s,o,t,n)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getPacket(t,e){b(this.demuxer.audioInfo);let r=Math.floor(Math.min(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);if(n)return n;if(r===0)return null;b(this.demuxer.reader.fileSize===null);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,e);for(;a;){let s=await this.getNextPacket(a,e);if(!s)break;a=s}return a}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 Ut=7,bt=9,nt=i=>{let t=i.filePos;if(i.remainingLength<Ut)return null;let e=U(i,Ut),r=new H(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>=tt.length)return null;r.skipBits(1);let u=r.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let l=r.readBits(13);r.skipBits(11);let d=r.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;if(s===0){if(i.remainingLength<2)return null;m=fe(i)}return l<i.filePos-t?null:{objectType:o,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:d,crcCheck:m,startPos:t}};var ka=1024,fo=class extends Pe{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.loadedSamples=[];this.metadataTags=null;this.trackBackings=[];this.readingMutex=new He;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();b(this.firstFrameHeader),this.trackBackings=[new Su(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Fe);if(_(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=it(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Ut,bt);if(_(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=nt(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let n=tt[r.samplingFrequencyIndex];b(n!==void 0);let a=ka/n,s={timestamp:this.nextTimestampInSamples/n,duration:a,dataStart:r.startPos,dataSize:r.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ka,this.lastLoadedPos=r.startPos+r.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,Fe);if(_(n)&&(n=await n),!n)break;let a=it(n);if(!a)break;let s=this.reader.requestSlice(n.filePos,a.size);if(_(s)&&(s=await s),!s)break;ii(s,a,this.metadataTags),r=n.filePos+a.size}return this.metadataTags}finally{e()}}},Su=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ka}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 se}getCodec(){return"aac"}getInternalCodecId(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){b(this.demuxer.firstFrameHeader);let t=Yt[this.demuxer.firstFrameHeader.channelConfiguration];return b(t!==void 0),t}getSampleRate(){b(this.demuxer.firstFrameHeader);let t=tt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return b(t!==void 0),t}getDisposition(){return{..._e}}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=Se;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(_(a)&&(a=await a),!a)return null;n=U(a,r.dataSize)}return new j(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=Tr(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{for(;;){let n=G(this.demuxer.loadedSamples,t,a=>a.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,e);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var po=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,bm=(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}},ho=i=>{let t=0,e=new H(U(i,1));for(;e.readBits(1)===1;)t++;if(t===0)return e.readBits(7);let r=[],n=t-1,a=new H(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 u=0;u<8;u++){let l=a.readBits(1);u<2||r.unshift(l)}return r.reduce((c,u,l)=>c|u<<l,0)},go=(i,t)=>{if(t==="uncommon-u16")return fe(i)+1;if(t==="uncommon-u8")return L(i)+1;if(typeof t=="number")return t;ae(t),b(!1)},ym=(i,t)=>t==="uncommon-u16"?fe(i):t==="uncommon-u16-10"?fe(i)*10:t==="uncommon-u8"?L(i):typeof t=="number"?t:null,km=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 bo=class extends Pe{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 He;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,Fe);if(_(r)&&(r=await r),!r)break;let n=it(r);if(!n)break;let a=this.reader.requestSlice(r.filePos,n.size);_(a)&&(a=await a),b(a),ii(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=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);b(r);let n=L(r),a=Dt(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(_(c)&&(c=await c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let u=U(c,34),l=new H(u),d=l.readBits(16),m=l.readBits(16),f=l.readBits(24),p=l.readBits(24),g=l.readBits(20);if(g===0)throw new Error("Invalid StreamInfo block: sample rate is 0. Corrupted file.");let h=l.readBits(3)+1;l.readBits(5);let y=l.readBits(36);l.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(u,8),this.audioInfo={numberOfChannels:h,sampleRate:g,totalSamples:y,minimumBlockSize:d,maximumBlockSize:m,minimumFrameSize:f,maximumFrameSize:p,description:k},this.trackBacking=new Au(this);break}case 4:{let c=this.reader.requestSlice(e,a);if(_(c)&&(c=await c),!c)throw new Error(`Vorbis comment block at position ${e} exceeds the file. Corrupted file.`);ra(U(c,a),this.metadataTags);break}case 6:{let c=this.reader.requestSlice(e,a);if(_(c)&&(c=await c),!c)throw new Error(`Picture block at position ${e} exceeds the file. Corrupted file.`);try{let u=F(c),l=F(c),d=he.decode(U(c,l)),m=F(c),f=he.decode(U(c,m));c.skip(16);let p=F(c),g=U(c,p);this.metadataTags.images??=[],this.metadataTags.images.push({data:g,mimeType:d,kind:u===3?"coverFront":u===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,u=(this.audioInfo.maximumFrameSize||s)+n,l=await this.reader.requestSliceRange(e,n,u);if(!l)return null;let d=this.readFlacFrameHeader(l);if(!d)return null;for(l.filePos=e+o;;){if(l.filePos>l.end-r)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:l.end-e,isLastFrame:!0};if(L(l)===255){let f=l.filePos,p=L(l),g=this.blockingBit===1?249:248;if(p!==g){l.filePos=f;continue}l.skip(-2);let h=l.filePos-e,y=this.readFlacFrameHeader(l);if(!y){l.filePos=f;continue}if(this.blockingBit===0){if(y.num-d.num!==1){l.filePos=f;continue}}else if(y.num-d.num!==d.blockSize){l.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 H(n);if(a.readBits(15)!==32764)return null;let o=a.readBits(1);if(this.blockingBit!==null&&o!==this.blockingBit)return null;let c=po(a.readBits(4));if(!c)return null;b(this.audioInfo);let u=bm(a.readBits(4),this.audioInfo.sampleRate);if(!u||(a.readBits(4),a.readBits(3),a.readBits(1)!==0))return null;let d=L(e);e.skip(-1);let f=4+Math.max(Math.clz32(~d<<24),1)+(c==="uncommon-u16"?2:c==="uncommon-u8"?1:0)+(u==="uncommon-u8"?1:typeof u=="number"?0:2)+1;if(r+f>e.end)return null;let p=ho(e),g=go(e,c),h=ym(e,u);if(h===null||h!==this.audioInfo.sampleRate)return null;let y=e.filePos-r,k=L(e);e.skip(-y),e.skip(-1);let T=km(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}}},Au=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}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 se}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{..._e}}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{for(;;){let n=G(this.demuxer.loadedSamples,t,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){if(this.demuxer.lastSampleLoaded)return null;await this.demuxer.advanceReader();continue}let a=this.demuxer.loadedSamples[n],s=a.blockOffset/this.demuxer.audioInfo.sampleRate,o=a.blockSize/this.demuxer.audioInfo.sampleRate;if(s+o<=t){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,e);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,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=Se;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(_(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 j(n,"key",a,s,t,r.byteSize)}async getFirstPacket(t){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,t)}};var yo=i=>{let t="video/MP2T",e=[...new Set(i.filter(Boolean))];return e.length>0&&(t+=`; codecs="${e.join(", ")}"`),t};var Am="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.",Tm=5,oh=1212435798,ch=1212436562,uh=1146376960,lh=new Set([133,134,162]),wm=new Set,ko=class extends Pe{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=205,r=this.reader.requestSlice(0,e);_(r)&&(r=await r),b(r);let n=U(r,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let a=256;this.minReferencePointByteDistance=a*this.packetStride;let s=this.packetOffset,o=null,c=!1,u=!1;for(;;){let l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(u&&!this.elementaryStreams.some(h=>h.pid===l.pid&&!h.initialized)){s+=this.packetStride;continue}let d=await this.readSection(s,!0,!u);if(!d)break;let m=3,f=32,p=!1;if(!u&&d.pid!==0&&!(d.payload[0]===0&&d.payload[1]===0&&d.payload[2]===1)){let y=new H(d.payload),k=y.readAlignedByte();y.skipBits(8*k),p=y.readBits(8)===2}if(d.pid===0&&!c){let h=new H(d.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(14);let k=h.readBits(10);for(h.skipBits(40);8*(k+m)-h.pos>f;){let T=h.readBits(16);h.skipBits(3);let w=h.readBits(13);if(T!==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((d.pid===o||p)&&!u){let h=new H(d.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(12);let k=h.readBits(12);h.skipBits(43);let T=h.readBits(13);h.skipBits(6);let w=h.readBits(10),S=h.pos+8*w,x=!1;for(;h.pos<S;){let C=h.readBits(8),I=h.readBits(8),A=h.pos+8*I;if(C===Tm&&I>=4){let P=h.readBits(32);x||=P===oh||P===ch}h.pos=A}for(h.pos=S;8*(k+m)-h.pos>f;){let C=h.readBits(8);h.skipBits(3);let I=h.readBits(13);h.skipBits(6);let A=h.readBits(10),P=h.pos+8*A,E=!1,v=!1,M=!1;for(;h.pos<P;){let D=h.readBits(8),q=h.readBits(8),ie=h.pos+8*q;if(D===106)E=!0;else if(D===122||D===204)v=!0;else if(D===123)M=!0;else if(D===Tm&&q>=4){let be=h.readBits(32);M||=(be&4294967040)===uh}h.pos=ie}let O=null,z=x&&lh.has(C)?130:C;switch(z){case 27:case 36:O={type:"video",codec:C===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 D;z===3||z===4?D="mp3":z===15?D="aac":z===129?D="ac3":z===135?D="eac3":D="dts",O={type:"audio",codec:D,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:v?O={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:E?O={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:M&&(O={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:wm.has(C)||(V._warn(`Note: MPEG-TS streams with stream_type 0x${C.toString(16)} are not currently supported.`),wm.add(C))}O&&this.elementaryStreams.push({demuxer:this,pid:I,streamType:C,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:O,referencePesPackets:[]})}u=!0}else{let h=this.elementaryStreams.find(y=>y.pid===d.pid);e:if(h&&!h.initialized){let y=Pn(this,d,!0);if(!y)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${h.pid}`);if(h.firstSection=d,h.canBeTrustedWithKeyPackets=d.randomAccessIndicator===1,this.input._initInput){let w=(await this.input._initInput._getDemuxer()).elementaryStreams.find(S=>S.pid===d.pid&&S.info.codec===h.info.codec&&S.initialized);if(w){h.info=w.info,h.initialized=!0;break e}}let k=new Di(h,y);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=er(k.suppliedPacket.data),!h.info.avcCodecInfo)continue;let w=h.info.avcCodecInfo.sequenceParameterSets[0];b(w);let S=rr(w);h.info.width=S.displayWidth,h.info.height=S.displayHeight;let x=S.pixelAspectRatio.num,C=S.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,x>0&&C>0&&(x>C?h.info.squarePixelWidth=Math.round(h.info.width*x/C):h.info.squarePixelHeight=Math.round(h.info.height*C/x)),h.info.colorSpace={primaries:ft[S.colourPrimaries],transfer:pt[S.transferCharacteristics],matrix:ht[S.matrixCoefficients],fullRange:!!S.fullRangeFlag},h.info.reorderSize=S.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=ir(k.suppliedPacket.data),!h.info.hevcCodecInfo)continue;let S=h.info.hevcCodecInfo.arrays.find(A=>A.nalUnitType===33).nalUnits[0];b(S);let x=Fi(S);h.info.width=x.displayWidth,h.info.height=x.displayHeight;let C=x.pixelAspectRatio.num,I=x.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,C>0&&I>0&&(C>I?h.info.squarePixelWidth=Math.round(h.info.width*C/I):h.info.squarePixelHeight=Math.round(h.info.height*I/C)),h.info.colorSpace={primaries:ft[x.colourPrimaries],transfer:pt[x.transferCharacteristics],matrix:ht[x.matrixCoefficients],fullRange:!!x.fullRangeFlag},h.info.reorderSize=x.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}h.info.decoderConfig={codec:Xr({width:h.info.width,height:h.info.height,codec:h.info.codec,codecDescription:null,colorSpace:h.info.colorSpace,avcType:1,avcCodecInfo:h.info.avcCodecInfo,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=we.tempFromBytes(k.suppliedPacket.data),w=nt(T);if(!w)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");h.info.aacCodecInfo={isMpeg2:!1,objectType:w.objectType},h.info.numberOfChannels=Yt[w.channelConfiguration],h.info.sampleRate=tt[w.samplingFrequencyIndex]}else if(h.info.codec==="mp3"){let T=F(we.tempFromBytes(k.suppliedPacket.data)),w=Zr(T,k.suppliedPacket.data.byteLength);if(!w.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");h.info.numberOfChannels=Jr(w.header.channel),h.info.sampleRate=w.header.sampleRate}else if(h.info.codec==="ac3"){let T=vs(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=na[T.acmod]+T.lfeon,h.info.sampleRate=Ri[T.fscod]}else if(h.info.codec==="eac3"){let T=_s(k.suppliedPacket.data);if(!T)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let w=Rs(T);if(w===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=Fs(T),h.info.sampleRate=w}else if(h.info.codec==="dts"){let T=ca(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:mn({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(u&&this.elementaryStreams.every(h=>h.initialized))break;s+=this.packetStride}if(!u)throw c?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let l of this.elementaryStreams)l.initialized&&(l.info.type==="video"?this.trackBackingEntries.push(new xu(l)):this.trackBackingEntries.push(new Cu(l)))})()}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 yo(e)}async readSection(e,r,n=!1){let a=e,s=e,o=[],c=0,u=null,l=!0,d=0;for(;;){let f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(u){if(f.pid!==u.pid){if(n)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;u=f}let p=!!(f.adaptationFieldControl&2),g=!!(f.adaptationFieldControl&1),h=0;if(p&&(h=1+f.body[0],f===u&&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){l=!1;break}if(Tr(this.sectionEndPositions,a,k=>k)!==-1){l=!1;break}}if(l){let f=G(this.sectionEndPositions,a,p=>p);this.sectionEndPositions.splice(f+1,0,a)}if(!u)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,endPos:r?a:null,pid:u.pid,payload:m,randomAccessIndicator:d}}async readPacketHeader(e){let r=this.reader.requestSlice(e,4);if(_(r)&&(r=await r),!r)return null;if(L(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,u=a&8191,l=L(r),d=l>>6,m=l>>4&3,f=l&15;return{payloadUnitStartIndicator:o,pid:u,adaptationFieldControl:m}}async readPacket(e){let r=this.reader.requestSlice(e,188);if(_(r)&&(r=await r),!r)return null;let n=U(r,188);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,u=s>>13&1,l=s&8191,d=n[3],m=d>>6,f=d>>4&3,p=d&15;return{payloadUnitStartIndicator:c,pid:l,adaptationFieldControl:f,body:n.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){let a=60*9e4;this.timestampWrapInfo={reference:e-a,offset:e>=8589934592-a?-8589934592:8589934592}}let{reference:r,offset:n}=this.timestampWrapInfo;return n<0&&e>=r||n>0&&e<r?e+n:e}},Oi=(i,t,e)=>{if(t.payload.byteLength<3)return null;let r=new H(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(Am);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},Pn=(i,t,e)=>{b(t.endPos!==null);let r=Oi(i,t,e);if(!r)return null;let n=new H(t.payload);n.skipBits(32);let a=n.readBits(16),s=6;n.skipBits(16);let o=n.readBits(8),c=n.pos+8*o;n.pos=c;let u=c/8;b(Number.isInteger(u));let l=t.payload.subarray(u,a>0?s+a:t.payload.byteLength);return{...r,data:l}},To=class i{constructor(t){this.elementaryStream=t;this.packetBuffers=new WeakMap;this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}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 se}getDisposition(){return{..._e,primary:!1}}getTimeResolution(){return 9e4}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 j(r.metadataOnly?Se:t.data,n,t.pts/9e4,Math.max(e/9e4,0),t.sequenceNumber,t.data.byteLength)}async getFirstPacket(t){let e=this.elementaryStream.firstSection;b(e);let r=Pn(this.elementaryStream.demuxer,e,!0);b(r);let n=new Di(this.elementaryStream,r),a=new Ta(this,n),s=await a.readNext();if(!s)return null;let o=this.createEncodedPacket(s.packet,s.duration,t);return this.packetBuffers.set(o,a),this.packetSectionStarts.set(o,s.packet.sectionStartPos),o}async getNextPacket(t,e){let r=this.packetBuffers.get(t);if(r){let l=await r.readNext();if(!l)return null;this.packetBuffers.delete(t);let d=this.createEncodedPacket(l.packet,l.duration,e);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}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=await a.readSection(n,!0);b(s);let o=Pn(a,s,!0);b(o);let c=new Di(this.elementaryStream,o);r=new Ta(this,c);let u=t.sequenceNumber;for(;;){let l=await r.readNext();if(!l)return null;if(l.packet.sequenceNumber>u){let d=this.createEncodedPacket(l.packet,l.duration,e);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}}}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=wr(t*9e4),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:o}=a,c=this.elementaryStream.pid,u=async(w,S,x)=>{let C=w;for(;C<S;){let I=await a.readPacketHeader(C);if(!I)return null;if(I.pid===c&&I.payloadUnitStartIndicator===1){let A=await a.readSection(C,x);if(!A)return null;let P=Oi(a,A,!1);if(P&&P.pts!==null)return{pesPacketHeader:P,section:A}}C+=a.packetStride}return null},l=this.elementaryStream.firstSection;b(l);let d=Oi(a,l,!0);if(b(d),n<d.pts)return null;let m,f=this.elementaryStream.referencePesPackets,p=G(f,n,w=>w.pts),g=p!==-1?f[p]:null;if(g&&n-g.pts<9e4/2)m=g.sectionStartPos;else{let w=0;if(s.fileSize!==null){let S=Math.ceil(s.fileSize/o);if(S>1){let x=0,C=S-1;for(w=x;x<=C;){let I=Math.floor((x+C)/2),A=ps(I*o,a.packetStride)+d.sectionStartPos,P=A+o,E=await u(A,P,!1);if(!E){C=I-1;continue}E.pesPacketHeader.pts<=n?(w=I,x=I+1):C=I-1}}}m=ps(w*o,a.packetStride)+d.sectionStartPos}let y=(await u(m,s.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);let k=this.getReorderSize(),T=async(w,S)=>{let x=await a.readSection(w,!0);b(x);let C=Pn(a,x,!0);b(C);let I=new Di(this.elementaryStream,C),A=new Ta(this,I);for(;!((Y(A.presentationOrderPackets)?.pts??-1/0)>=n||!await A.readNextPacket()););let P=qr(A.presentationOrderPackets,S);if(P===-1)return null;let E=A.presentationOrderPackets[P],v=P===0?0:E.pts-A.presentationOrderPackets[P-1].pts;A.decodeOrderPackets.splice(0,A.decodeOrderPackets.indexOf(E)),A.lastDuration=v;let M=await A.readNext();b(M);let O=this.createEncodedPacket(M.packet,M.duration,r);return this.packetBuffers.set(O,A),this.packetSectionStarts.set(O,M.packet.sectionStartPos),O};if(!e||this.allPacketsAreKeyPackets()){e:for(;;){let w=y.sectionStartPos+a.packetStride;for(;;){let S=await a.readPacketHeader(w);if(!S)break e;if(S.pid===c&&S.payloadUnitStartIndicator===1){let x=await a.readSection(w,!1);if(x){let C=Oi(a,x,!1);if(C&&C.pts!==null){if(C.pts>n)break e;y=C,Pu(this.elementaryStream,y);break}}}w+=a.packetStride}}e:for(let w=0;w<k+1;w++){let S=y.sectionStartPos-a.packetStride;for(;S>=a.packetOffset;){let x=await a.readPacketHeader(S);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){let C=await a.readSection(S,!1);if(C){let I=Oi(a,C,!1);if(I&&I.pts!==null){y=I;break}}}S-=a.packetStride}if(S<a.packetOffset)break}return T(y.sectionStartPos,w=>w.pts<=n)}else{let w=m,S=null,x=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let C=null,I=w<=d.sectionStartPos,A,P=null;if(I)A=d,P=l;else{let O=await u(w,S??s.fileSize??1/0,x);A=O?.pesPacketHeader??null,P=O?.section??null}let E=!1,v=0,M=null;e:for(;A&&!(S!==null&&A.sectionStartPos>=S);){if(A.pts<=n){let z;if(this.elementaryStream.canBeTrustedWithKeyPackets)z=A.randomAccessIndicator===1;else{if(!M){b(P);let D=Pn(a,P,!0);b(D),M=new Di(this.elementaryStream,D)}for(;(!M.suppliedPacket||M.suppliedPacket.sectionStartPos<A.sectionStartPos)&&(M.suppliedPacket=null,await M.markNextPacket(),!!M.suppliedPacket););z=M.suppliedPacket?.sectionStartPos===A.sectionStartPos&&M.suppliedPacket.randomAccessIndicator===1}z&&(C=A)}if(A.pts>n&&(E=!0),E&&(v++,v>k))break;let O=A.sectionStartPos+a.packetStride;for(;;){let z=await a.readPacketHeader(O);if(!z)break e;if(z.pid===c&&z.payloadUnitStartIndicator===1){let D=await a.readSection(O,x);if(D){let q=Oi(a,D,!1);if(q&&q.pts!==null){A=q,P=D,Pu(this.elementaryStream,A);break}}}O+=a.packetStride}}if(C){let O=C;if(v===0)e:for(let D=0;D<k;D++){let q=O.sectionStartPos-a.packetStride;for(;q>=a.packetOffset;){let ie=await a.readPacketHeader(q);if(!ie)break e;if(ie.pid===c&&ie.payloadUnitStartIndicator===1){let be=await a.readSection(q,x);if(be){let Te=Oi(a,be,!1);if(Te&&Te.pts!==null){O=Te;break}}}q-=a.packetStride}if(q<a.packetOffset)break}let z=await T(O.sectionStartPos,D=>D.pts<=n&&D.randomAccessIndicator===1);if(z)return z}if(I)return null;S=w,w=Math.max(ps(w-d.sectionStartPos-o,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},xu=class extends To{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[...Wr]}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}},Cu=class extends To{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}},Pu=(i,t)=>{let e=i.referencePesPackets,r=G(e,t.sectionStartPos,n=>n.sectionStartPos);if(r>=0){let n=e[r];if(t.pts<=n.pts)return!1;let a=i.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-n.sectionStartPos<a)return!1;if(r<e.length-1){let s=e[r+1];if(s.pts<t.pts||s.sectionStartPos-t.sectionStartPos<a)return!1}}return e.splice(r+1,0,t),!0},Di=class{constructor(t,e){this.currentPos=0;this.pesPackets=[];this.currentPesPacketIndex=0;this.currentPesPacketPos=0;this.endPos=0;this.lastSuppliedPesPacket=null;this.nextPts=null;this.suppliedPacket=null;this.elementaryStream=t,this.pid=t.pid,this.demuxer=t.demuxer,this.startingPesPacket=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))}getCurrentPesPacket(){let t=this.pesPackets[this.currentPesPacketIndex];return b(t),t}async bufferData(t){let e=this.endPos+t;for(;this.endPos<e;){let r;if(this.pesPackets.length===0)r=this.startingPesPacket;else{let n=Y(this.pesPackets).sectionEndPos;for(b(n!==null);;){let a=await this.demuxer.readPacketHeader(n);if(!a)return;if(a.pid===this.pid){let s=await this.demuxer.readSection(n,!0);if(!s)return;let o=Pn(this.demuxer,s,!1);if(o){r=o;break}}n+=this.demuxer.packetStride}}this.pesPackets.push(r),this.endPos+=r.data.byteLength}}readBytes(t){let e=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos,n=r+t;if(this.currentPos+=t,n<=e.data.byteLength)return e.data.subarray(r,n);let a=new Uint8Array(t);a.set(e.data.subarray(r));let s=e.data.byteLength-r;for(;;){this.advanceCurrentPacket();let o=this.getCurrentPesPacket(),c=t-s;if(c<=o.data.byteLength){a.set(o.data.subarray(0,c),s);break}a.set(o.data,s),s+=o.data.byteLength}return a}readU8(){let t=this.getCurrentPesPacket(),e=this.currentPos-this.currentPesPacketPos;if(this.currentPos++,e<t.data.byteLength)return t.data[e];do this.advanceCurrentPacket(),t=this.getCurrentPesPacket();while(t.data.byteLength===0);return t.data[0]}seekTo(t){if(t!==this.currentPos){if(t<this.currentPos)for(;t<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){let e=this.getCurrentPesPacket(),r=this.currentPesPacketPos+e.data.byteLength;if(t<r)break;this.currentPesPacketPos+=e.data.byteLength,this.currentPesPacketIndex++}this.currentPos=t}}skip(t){this.seekTo(this.currentPos+t)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}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(_(c)&&(c=await c),c===0)break;let u=this.currentPos,l=this.readBytes(c),d=l.byteLength,m=0;for(;m<d;){let f=l.indexOf(0,m);if(f===-1||f>=d)break;m=f;let p=u+m;if(m+3>=d){this.seekTo(p);break}let g=l[m+1],h=l[m+2],y=l[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 w=m+k,S=w+n,x=6;if(S+(e==="avc"?x:1)>d){this.seekTo(p);break}let I=l[w],A,P,E,v;if(e==="avc")A=Jt(I),P=A===1||A===2||A===5,E=A===6||A===7||A===8||A===9,v=A===9;else{if(A=Rt(I),((I&1)<<5|l[w+1]>>3)>0){m+=k;continue}P=A<=9||A>=16&&A<=21,E=A>=32&&A<=37||A===39||A>=41&&A<=44||A>=48&&A<=55,v=A===35}let M=!1;if(P){let O;if(e==="avc"){let z=l.subarray(S,S+x),D=B(new H(z));O=!s||D<=o,o=D}else O=l[S]>>7===1;O&&(s?M=!0:s=!0)}else E&&s?M=!0:v&&(a=T);if(M){let O=T-a;return this.seekTo(a),this.supplyPacket(O,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);_(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(bt);if(_(c)&&(c=await c),c<bt)return;let u=this.readBytes(bt),l=nt(we.tempFromBytes(u));if(l){this.seekTo(o);let d=this.ensureBuffered(l.frameLength);return _(d)&&(d=await d),this.supplyPacket(d,Math.round(ka*9e4/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(_(c)&&(c=await c),c<4)return;let u=this.readBytes(4),l=N(u).getUint32(0),d=Zr(l,null);if(d.header){this.seekTo(o);let m=this.ensureBuffered(d.header.totalSize);_(m)&&(m=await m);let f=d.header.audioSamplesInFrame*9e4/t.info.sampleRate;return this.supplyPacket(m,Math.round(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(_(c)&&(c=await c),c<5)return;let u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}let l=u[4]>>6,d=u[4]&63;if(l===3||d>37){this.seekTo(o+1);continue}let m=kd[3*d+l];b(m!==void 0),this.seekTo(o),c=this.ensureBuffered(m),_(c)&&(c=await c);let f=Math.round(Td*9e4/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(_(c)&&(c=await c),c<5)return;let u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}let d=(((u[2]&7)<<8|u[3])+1)*2,f=u[4]>>6===3?3:u[4]>>4&3,p=au[f];this.seekTo(o),c=this.ensureBuffered(d),_(c)&&(c=await c);let g=p*256,h=Math.round(g*9e4/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(oa);if(_(c)&&(c=await c),c<oa)return;let u=this.readBytes(oa),l=su(u),d=l?null:ua(u);if(!l&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);let g=Math.min(d.frameSize,Sd),h=this.ensureBuffered(g);_(h)&&(h=await h),d=ua(this.readBytes(h))??d}let m=l?l.frameSize:d.frameSize;if(l){let g=Math.ceil(l.frameSize/4)*4;for(;;){this.seekTo(o);let h=g+Ms,y=this.ensureBuffered(h);if(_(y)&&(y=await y),y<h)break;this.seekTo(o+g);let k=ua(this.readBytes(Ms));if(!k)break;g+=k.frameSize,m=g}}let f=l?.sampleCount??d.asset?.sampleCount;if(f===void 0){this.seekTo(o+1);continue}this.seekTo(o),c=this.ensureBuffered(m),_(c)&&(c=await c);let p=Math.round(f*9e4/t.info.sampleRate);return this.supplyPacket(c,p)}else throw new Error("Unhandled.")}if(n<r)break}}}supplyPacket(t,e){let r=this.getCurrentPesPacket(),n;if(this.lastSuppliedPesPacket===r)b(this.nextPts!==null),n=this.nextPts;else{if(r.pts===null)throw new Error(Am);n=r.pts,Pu(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=n+e;let a=r.sectionStartPos,s=a+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(t),c=r.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){let u=jr(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(u)}}this.suppliedPacket={pts:n,data:o,sequenceNumber:s,sectionStartPos:a,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Ta=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.lastDuration:(r=this.presentationOrderPackets[e+1].pts-t.pts,this.lastDuration=r),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 or="application/vnd.apple.mpegurl",Iu="#EXT-X-STREAM-INF:",Eu="#EXT-X-I-FRAME-STREAM-INF:",vu="#EXT-X-MEDIA:",vn="#EXT-X-DEFINE:",wa="#EXTINF:",_u="#EXT-X-MAP:",Ru="#EXT-X-KEY:",Fu="#EXT-X-MEDIA-SEQUENCE:",Mu="#EXT-X-BYTERANGE:",Bu="#EXT-X-PROGRAM-DATE-TIME:",xm="#EXT-X-DISCONTINUITY",Ou="#EXT-X-TARGETDURATION:",Cm="#EXT-X-ENDLIST",Du="#EXT-X-PLAYLIST-TYPE:",Pm="#EXT-X-I-FRAMES-ONLY",wo=i=>i.length===0||i.startsWith("#")&&!i.startsWith("#EXT"),sr=class{constructor(t,e){this._attributes={};let r="",n="",a=!1,s=!1,o=!1,c=()=>{if(!r)return;let u=r.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,u)&&V._warn(`Duplicate AttributeName "${u}"; using last value`);let l=o||n.startsWith("0x")||n.startsWith("0X");this._attributes[u]=l&&e?e.substitute(n):n,r="",n="",a=!1,o=!1};for(let u=0;u<t.length;u++){let l=t[u];l==='"'?(a&&!s&&n.length===0&&(o=!0),s=!s):l==="="&&!a&&!s?a=!0:l===","&&!s?c():a?n+=l:r+=l}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)}},dh=/^[A-Za-z0-9_-]+$/,mh=/\{\$([A-Za-z0-9_-]+)\}/g,fh=2**26,En=class{constructor(t,e){this.playlistPath=t;this.importedVariables=e;this.variables=new Map;this.totalSubstitutedLength=0}define(t){let e=new sr(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=ed(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(mh,(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>fh)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(!dh.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 So=class{constructor(t,e,r){this.nextInputCacheAge=0;this.inputCache=[];this.trackBackingsPromise=null;this.firstSegment=null;this.firstSegmentFirstTimestamps=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+e.duration:null}async getUnixTimeForTimestamp(t){let e=await this.getSegmentAt(t,{});if(e??=await this.getFirstSegment({}),!e||e.unixEpochTimestamp===null)return null;let r=t-e.timestamp;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=vi(t,n=>n.getType()==="video")+1;t.push(new xo(this,e,r))}else if(e.type==="audio"){let r=vi(t,n=>n.getType()==="audio")+1;t.push(new Co(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=vi(t,s=>s.getType()==="video")+1;t.push(new xo(this,{id:t.length+1,type:"video"},a))}else if(n.type==="audio"){let a=vi(t,s=>s.getType()==="audio")+1;t.push(new Co(this,{id:t.length+1,type:"audio"},a))}}return t})()}async getMediaOffset(t,e){if(!(await e.getFormat()).supportsTimestampedMediaData)return t.timestamp;let n=t.firstSegment??t,a=this.firstSegmentFirstTimestamps.get(n);return a===void 0&&(a=await this.getInputForSegment(n).getFirstTimestamp(),this.firstSegmentFirstTimestamps.set(n,a)),n.timestamp-a}dispose(){for(let t of this.inputCache)t.input.dispose();this.inputCache.length=0}},Ao=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})()}getId(){return this.decl.id}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.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:Gt(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 l=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(m=>m.type===n.track.type&&m.number===n.track.number);if(!l){s=o;continue}let d=await l._backing.getFirstPacket(e);if(d&&r&&d.type!=="key"&&(d=await l._backing.getNextKeyPacket(d,e)),!d){s=o;continue}return this.createAdjustedPacket(d,o,l)}}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)return null;for(await this.hydrate();n;){let a=this.segmentedInput.getInputForSegment(n),o=(await a.getTracks()).find(m=>m.type===this.firstInputTrack.type&&m.number===this.firstInputTrack.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(n,a),u=t-c,l=r?await o._backing.getKeyPacket(u,e):await o._backing.getPacket(u,e);if(!l){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let d=r?await o._backing.getPacket(u,{...e,metadataOnly:!0}):l;if(b(d),u>=d.timestamp+d.duration){let m=await this.segmentedInput.getNextSegment(n,{skipLiveWait:e.skipLiveWait});if(m){let f=this.segmentedInput.getInputForSegment(m),g=(await f.getTracks()).find(y=>y.type===this.firstInputTrack.type&&y.number===this.firstInputTrack.number),h=g?await g._backing.getFirstPacket({...e,metadataOnly:!0}):null;if(h&&r&&h.type!=="key"&&(h=await g._backing.getNextKeyPacket(h,{...e,metadataOnly:!0})),h){let y=await this.segmentedInput.getMediaOffset(m,f);if(h.timestamp+y<=t){n=m;continue}}}}return this.createAdjustedPacket(l,n,o)}return null}},xo=class extends Ao{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())}},Co=class extends Ao{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 Im=Ol(Vu(),1);sn();var Em=typeof Im<"u"?Im:void 0,zu=0,Nu=1/0,Uu=null;typeof FinalizationRegistry<"u"&&(Uu=new FinalizationRegistry(i=>{i()}));var Ne=class extends Je{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,zu,Nu),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 Aa(this,e,r)}_dispatchRead(e,r){this.onread?.(e,r),this._emit("read",{start:e,end:r})}ref(){return new ai(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},ai=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()}},Ye=class extends Ne{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 Ne||a instanceof ai))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=a instanceof Ne?a.ref():a;return s.source._usedForHls||=this._usedForHls,s};return _(r)?r.then(n):n(r)}},Lu=(i,t)=>i.path===t.path,_n=class extends Ye{constructor(){super(...arguments);this._root=null;this._rootRequest=null}_read(e,r,n,a){if(!this._root){if(!this._rootRequest){let s=this._resolveRequest({path:this.rootPath,isRoot:!0}),o=c=>{let u=c instanceof Ne?c.ref():c;return this._root=u,this._rootRequest=null,u};_(s)?this._rootRequest=s.then(o):(o(s),b(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,r,n,a))}return this._root.source._read(e,r,n,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free()).catch(()=>{})}},Po=class extends Ne{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=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(){}},vm=typeof FinalizationRegistry<"u"?new FinalizationRegistry(i=>{i.cancel().catch(()=>{})}):null,Io=class extends Ne{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&&(!ve(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 Sa({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),vm?.unregister(n),a.cancel().catch(()=>{}))},prefetchProfile:Wu.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&&!jt()&&this._options.useStreamReader!==!1?(r=this._blob.slice(e.currentPos).stream().getReader(),vm?.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()}},ph=.5*2**20,hh=(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 V._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)},_m=new Set,Eo=class i extends Ye{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&&(!ve(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));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??hh,this._requestInit={...r.requestInit};let a=null;if(r.requestInit?.headers){let o={...ns(r.requestInit.headers)},c=Object.keys(o).find(u=>u.toLowerCase()==="range");c!==void 0&&(a=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){let o=e.headers.get("Range");if(o!==null){a??=o;let c=new Request(e);c.headers.delete("Range"),this._url=c}}if(a!==null){let o=bh(a);o&&(this._offset=o.offset,this._length=o.length)}let s=2;this._orchestrator=new Sa({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??s,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:o=>this._abortControllers.delete(o),prefetchProfile:Wu.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:J(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=u=>u?(u.offset-=this._offset,u):null;return _(o)?o.then(c):c(o)}async _runWorker(e){for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}let r=new AbortController;this._abortControllers.set(e,r);let n=await Xc(this._options.fetchFn??fetch,this._url,jc(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>r.signal.aborted);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(this._orchestrator.fileSize===null&&!n.headers.has("Content-Encoding")&&(n.status===206||n.type==="basic")){let s=n.headers.get("Content-Range");if(s){let c=/\/(\d+)/.exec(s);if(c){this._orchestrator.supplyFileSize(Number(c[1]));break e}}let o=n.headers.get("Content-Length");if(o){let c=n.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(c+Number(o))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(n.status!==206){if(this._sequentialBacking){n.body.cancel().catch(()=>{});return}if(!this._usedForHls){let s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(_m.has(s.origin)||(V._warn(`HTTP server (origin ${s.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.`),_m.add(s.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(n.body,r);return}let a=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){r.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await a.read()}catch(u){if(r.signal.aborted)throw u;let l=this._getRetryDelay(1,u,this._url);if(l!==null){V._error("Error while reading response stream. Attempting to resume.",u),await Kr(1e3*l);break}else throw u}if(e.aborted)continue;let{done:o,value:c}=s;if(o){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_transitionToSequentialMode(e,r){this._sequentialAbortController=r;let n=e.getReader(),a=0,s=0,o=new ReadableStream({pull:async l=>{for(;;){let d;try{d=await n.read()}catch(f){if(this._disposed)throw f;let p=this._getRetryDelay(1,f,this._url);if(p===null)throw f;V._error("Error while reading response stream. Attempting to resume.",f),await Kr(1e3*p),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();let g=await Xc(this._options.fetchFn??fetch,this._url,jc(this._requestInit,{headers:{Range:`bytes=${a}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!g.ok)throw new Error(`Error fetching ${String(this._url)}: ${g.status} ${g.statusText}`);if(!g.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");n=g.body.getReader(),s=g.status===206?0:a;continue}if(d.done){l.close();return}let m=d.value;if(s>0){let f=Math.min(s,m.length);s-=f,m=m.subarray(f)}if(m.length!==0){a+=m.length,l.enqueue(m);return}}},cancel:()=>n.cancel().catch(()=>{})}),c=new Vi(o,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});c._endIndex=this._orchestrator.fileSize,c._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.",c.on("read",({start:l,end:d})=>this._dispatchRead(l,d)),this._sequentialBacking=c;let u=new Set;for(let l of this._orchestrator.workers){for(let d of l.pendingSlices)u.add(d);l.aborted=!0,l.pendingSlices.length=0}for(let l of this._orchestrator.queuedReads)for(let d of l.pendingSlices)u.add(d);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(let[,l]of this._abortControllers)l.abort();this._abortControllers.clear();for(let l of u){let d=c._read(l.start,l.start+l.bytes.length);_(d)?d.then(m=>{m?(b(m.offset===l.start),l.resolve(m.bytes)):l.resolve(null)},m=>l.reject(m)):(b(d===null),l.resolve(null))}}_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())}},gh=/^bytes=(\d+)-(\d*)$/,bh=i=>{let t=gh.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}},vo=class i extends Ye{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&&(!ve(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Em.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 Rn({getSize:async()=>{let n=await Em.fs.open(e,"r");return this._fileHandle=n,Uu?.register(this,()=>{n.close()},this),(await n.stat()).size},read:async(n,a)=>{b(this._fileHandle);let s=new Uint8Array(a-n);return await this._fileHandle.read(s,0,a-n,n),s},maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:r.handleUnhandledError})}_read(e,r,n,a){return this._customSource._read(e,r,n,a)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Uu?.unregister(this))}},Rn=class extends Ne{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&&(!ve(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._options=e,this._orchestrator=new Sa({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:Wu[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._options.getSize();if(_(s))return 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(_(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 u=Q(c);this._dispatchRead(e.currentPos,e.currentPos+u.length),this._orchestrator.supplyWorkerData(e,u)}}finally{this._readers.delete(s),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?.()}},Fm=Rn,Vi=class extends Ne{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&&(!ve(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=G(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 Rm(e,r,o);this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:c,resolve:u,reject:l}=ee();return this._pendingSlices.push({start:e,end:r,parts:o,resolve:u,reject:l}),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),u=Math.min(a,o.end);c<u&&(o.parts.push({start:c,bytes:r.subarray(c-n,u-n)}),u===o.end&&(o.resolve(Rm(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?.cancel().catch(()=>{})}},Rm=(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}},Wu={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(gs(i,t,s,n.targetPos)){let o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);t=Math.max(t,n.startPos+l)}}return t=Math.max(t,i+ph),{start:i,end:t}}},Sa=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,u=G(this.cache,t,S=>S.start),l=u!==-1?this.cache[u]:null;l&&l.start<=t&&e<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});let d=G(this.cache,s,S=>S.start),m=c?null:new Uint8Array(e-t),f=0,p=s,g=[];if(d!==-1){for(let S=d;S<this.cache.length;S++){let x=this.cache[S];if(x.start>=o)break;if(x.end<=s)continue;let C=Math.max(s,x.start),I=Math.min(o,x.end);if(b(C<=I),p<C&&g.push({start:p,end:C}),p=I,m){let A=Math.max(t,x.start),P=Math.min(e,x.end);if(A<P){let E=A-t;m.set(x.bytes.subarray(A-x.start,P-x.start),E),E===f&&(f=P-t)}}x.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}=ee(),T=[];for(let S of g){let x=Math.max(t,S.start),C=Math.min(e,S.end);x===S.start&&C===S.end?T.push(S):x<C&&T.push({start:x,end:C})}let w=m&&{start:t,bytes:m,holes:T,resolve:y,reject:k};e:for(let S of g){for(let I of this.workers)if(this.checkHoleAgainstWorker(I,S,w?[w]:[])){this.checkQueuedReadsAgainstWorker(I);continue e}let x=S.end<o||this.fileSize!==null,C=this.createWorker(S.start,S.end,x);if(C)w&&(C.pendingSlices=[w]),this.runWorker(C);else{let I=G(this.queuedReads,S.start,P=>P.hole.start),A=I!==-1?this.queuedReads[I]:null;for(A&&S.start<=A.hole.end?(A.hole.end=Math.max(A.hole.end,S.end),A.strictTarget&&=x,w&&A.pendingSlices.push(w)):(I++,A={hole:{start:S.start,end:S.end},strictTarget:x,pendingSlices:w?[w]:[],age:this.nextAge++},this.queuedReads.splice(I,0,A));I+1<this.queuedReads.length;){let P=this.queuedReads[I+1];if(P.hole.start>A.hole.end)break;A.hole.end=Math.max(A.hole.end,P.hole.end),A.pendingSlices.push(...P.pendingSlices),A.strictTarget&&=P.strictTarget,A.age=Math.min(A.age,P.age),this.queuedReads.splice(I+1,1)}}}return c?h.catch(S=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(S);else throw S}):(b(m),c=h.then(S=>S&&{bytes:S,view:N(S),offset:t})),c}checkHoleAgainstWorker(t,e,r){if(gs(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 u=0;u<s.holes.length;u++){let l=s.holes[u];r<=l.start&&n>l.start&&(l.start=n),l.end<=l.start&&(s.holes.splice(u,1),u--)}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||gs(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];if(r.hole.start>=t){for(let n of r.pendingSlices)n.resolve(null);this.queuedReads.splice(e,1),e--}else if(r.hole.end>t){r.hole.end=t,r.strictTarget=!0;for(let n=0;n<r.pendingSlices.length;n++){let a=r.pendingSlices[n];a.start>=t&&(a.resolve(null),r.pendingSlices.splice(n,1),n--)}}}}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.resolve(null)}insertIntoCache(t){if(this.options.maxCacheSize===0)return;let e=G(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 Aa=class extends Ne{constructor(e,r,n){super();this._ref=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(){let e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:J(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._baseSource._read(this._offset+e,this._offset+r,this._offset+n,this._offset+a),o=c=>c?(c.offset-=this._offset,c):null;return _(s)?s.then(o):o(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var yh=/^0[xX][0-9a-fA-F]+$/,kh=/^data:.*;base64,/i,Mm=1e9,xa=class extends So{constructor(e,r,n,a){super(e.input,r,n);this.segments=[];this.nextLines=null;this.currentUpdateSegmentsPromise=null;this.streamHasEnded=!1;this.lastSegmentUpdateTime=-1/0;this.refreshInterval=5;this.rootPath=r,this.demuxer=e,this.nextLines=a}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await Kr(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 A=dt(S,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}));let P=new si(A.source);let E=P.requestSliceRange(0,0,64);_(E)&&(E=await E);if(E&&!he.decode(U(E,E.length)).trimStart().startsWith("#EXTM3U"))throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");let v=await P.requestEntireFile();b(v);e=_o(v,v.length,{ignore:wo});A.source instanceof Ye&&(this.rootPath=A.source.rootPath)}catch(x){var C=x,I=!0}finally{mt(S,C,I)}}let r=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=new En(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),a=!1,s=0,o=null,c=null,u=null,l=0,d=null,m=null,f=null,p=null,g=null,h=null,y=!1,k=Y(this.segments)??null,T=A=>{let P=A.indexOf("@"),E=Number(P===-1?A:A.slice(0,P));if(!Number.isInteger(E)||E<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${A}'.`);let v=null;if(P!==-1&&(v=Number(A.slice(P+1)),!Number.isInteger(v)||v<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${A}'.`);return{length:E,offset:v}},w=A=>{l=A,k&&(b(k.sequenceNumber!==null),k.sequenceNumber<A&&(s=k.timestamp+k.duration,d=k.firstSegment,m=k.initSegment,g=k.lastProgramDateTimeSeconds,o=k.unixEpochTimestamp!==null?k.unixEpochTimestamp+k.duration:null,k=null))};for(let A=0;A<e.length;A++){let P=e[A];if(!a){if(P!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");a=!0;continue}if(!P.startsWith("#")){if(!k){if(c===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let E=u;if(E&&E.method==="AES-128"&&!E.iv){let z=new Uint8Array(Ot),D=N(z);D.setUint32(8,Math.floor(l/2**32)),D.setUint32(12,l),E={...E,iv:z}}let M={path:xe(this.rootPath,n.substitute(P)),offset:p?.offset??0,length:p?.length??null},O={index:this.segments.length,timestamp:s,unixEpochTimestamp:o,firstSegment:d,sequenceNumber:l,location:M,duration:c,encryption:E,initSegment:m,lastProgramDateTimeSeconds:g};d??=O,s+=c,o!==null&&(o+=c),this.segments.push(O)}c=null,p===null?f=null:p=null,w(l+1)}if(P.startsWith(wa)){if(k){y=!0;continue}y||(g===null&&l>0&&h!==null&&(s=l*h),y=!0);let E=P.slice(wa.length),v=E.indexOf(","),M=v===-1?E:E.slice(0,v),O=Number(M);if(!Number.isFinite(O)||O<0||O>Mm)throw new Error(`Invalid #EXTINF tag duration '${M}'.`);c=O}else if(P.startsWith(vn))n.define(P.slice(vn.length));else if(P.startsWith(_u)){let E=new sr(P.slice(_u.length),n),v=E.get("uri");if(!v)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let M=E.get("byterange"),O=null;if(M!==null&&(O=T(M)),O&&O.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!k){let D={path:xe(this.rootPath,v),offset:O?.offset??0,length:O?.length??null};if(u?.method==="AES-128"&&!u.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");m={index:-1,timestamp:s,unixEpochTimestamp:o,firstSegment:null,sequenceNumber:null,location:D,duration:0,encryption:u,initSegment:null,lastProgramDateTimeSeconds:g}}c=null,p===null?f=null:p=null}else if(P.startsWith(Ru)){let E=new sr(P.slice(Ru.length),n),v=E.get("method");if(v==="NONE")u=null;else if(v==="AES-128"){let M=E.get("uri");if(!M)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let O=null,z=E.get("iv");if(z){if(!yh.test(z))throw new Error(`Unsupported IV format '${z}'.`);let q=z.slice(2);q=q.padStart(2*Ot,"0"),q=q.slice(-2*Ot),O=new Uint8Array(Ot);for(let ie=0;ie<Ot;ie++){let be=2*ie;O[ie]=parseInt(q.slice(be,be+2),16)}}let D=E.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.");u={method:"AES-128",keyUri:xe(this.rootPath,M),iv:O,keyFormat:D}}else if(v==="SAMPLE-AES"||v==="SAMPLE-AES-CTR"){let M=E.get("uri");if(!M)throw new Error(`Invalid #EXT-X-KEY: ${v} requires a URI attribute.`);if((E.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 z=null;if(kh.test(M)){let D=M.indexOf(","),q=Ei(M.slice(D+1));if(q.length>=8&&q[4]===112&&q[5]===115&&q[6]===115&&q[7]===104){let ie=N(q).getUint32(0);z=Gs(q.subarray(8,Math.min(ie,q.length)))}}u={method:v,psshBox:z}}else throw new Error(`Unsupported encryption method '${v}'. If you think this method should be supported, please raise an issue.`)}else if(P.startsWith(Fu)){let E=P.slice(Fu.length),v=Number(E);if(!Number.isSafeInteger(v)||v<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${E}'.`);w(v)}else if(P.startsWith(Mu)){let E=T(P.slice(Mu.length));if(E.offset===null){if(f===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");E.offset=f}p=E,f=E.offset+E.length}else if(P.startsWith(Bu)){if(k)continue;let E=P.slice(Bu.length),v=Date.parse(E);if(!Number.isFinite(v))continue;let M=v/1e3;if(g===M)continue;if(g===null&&this.segments.length>0){let O=Y(this.segments),z=O.timestamp+O.duration,D=M-z;for(let q of this.segments)q.unixEpochTimestamp=q.timestamp+D,r&&(q.timestamp=q.unixEpochTimestamp)}g=M,o=M,r&&(s=M)}else if(P===xm)d=null;else if(P.startsWith(Ou)){let E=P.slice(Ou.length),v=Number(E);if(!Number.isFinite(v)||v<0||v>Mm)throw new Error(`Invalid EXT-X-TARGETDURATION value '${E}'.`);this.refreshInterval=J(v,.5,3600),h=v}else if(P===Cm){this.streamHasEnded=!0;break}else P.startsWith(Du)&&P.slice(Du.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!a)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,r){this.segments.length===0&&await this.runUpdateSegments();let n=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let a=G(this.segments,e,o=>o.timestamp);if(a===-1)return null;if(a<this.segments.length-1||this.streamHasEnded||n)return this.segments[a];let s=this.segments[a];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),r.skipLiveWait&&(n=!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(u=>u.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&&(u=>{if(!r.encryption||!(r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR")||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(u);let l=u.psshBoxes,{psshBox:d}=r.encryption;return(d.keyIds===null||d.keyIds.includes(u.keyId))&&!l.some(m=>Qs(m,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...u,psshBoxes:l})})}},o=new oi({source:new _n(r.location.path,async u=>{b(u.isRoot);let l={...u,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(l),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(l);if(m){let k=p.source.slice(r.location.offset,r.location.length??void 0).ref();p.free(),p=k}let g=new si(p.source),h=Ld(g,async()=>{var S=[];try{let y=dt(S,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},Bm));let k=new si(y.source);let T=await k.requestSlice(0,Ot);if(!T)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");let w=U(T,Ot);return{key:w,iv:f.iv}}catch(x){var C=x,I=!0}finally{mt(S,C,I)}},()=>{p.free()});d=new Vi(h).ref()}else b(!1);return d}),formats:this.input._formats.filter(u=>!(u instanceof Ui)),initInput:a??void 0,formatOptions:s});if(o._onFormatDetermined=u=>{if((r.encryption?.method==="SAMPLE-AES"||r.encryption?.method==="SAMPLE-AES-CTR")&&!u._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 u=on(this.inputCache,l=>l.age);b(u!==-1),this.inputCache.splice(u,1)}return o}async getLiveRefreshInterval(){return!this.streamHasEnded&&this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var Th=256,wh=256,Fo=class extends Pe{constructor(e){super(e);this.metadataPromise=null;this.trackBackings=null;this.internalTracks=null;this.segmentedInputs=[];this.hasMasterPlaylist=!0;this.masterPlaylistVariables=null}readMetadata(){return this.metadataPromise??=(async()=>{b(this.input._rootSource instanceof Ye);let e=await this.input._reader.requestEntireFile();b(e);let r=_o(e,e.length,{ignore:wo}),{rootPath:n}=this.input._rootSource,a=new En(n,null),s=[],o=[];for(let d=1;d<r.length;d++){let m=r[d];if(m.startsWith(vn))a.define(m.slice(vn.length));else if(m.startsWith(Iu)){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=xe(n,p),h=new sr(m.slice(Iu.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(Eu)){let f=new sr(m.slice(Eu.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=xe(n,p);s.push({fullPath:h,attributes:f,lineNumber:d,hasOnlyKeyPackets:!0})}else if(m.startsWith(vu)){let f=new sr(m.slice(vu.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=xe(n,y)),o.push({fullPath:h,attributes:f,lineNumber:d})}else if(m!==Pm){if(m.startsWith(wa)){let f=new xa(this,n,null,r);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}}if(s.length>Th||o.length>wh)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(A=>A.trim());else{let P=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),E=await Promise.all(P.map(async v=>({track:v,codec:await v.getCodec()})));g=await Promise.all(E.filter(v=>v.codec!==null).map(v=>v.track.getDecoderConfig().then(M=>M.codec)))}let h=d.attributes.get("video"),y=d.attributes.get("audio"),k=g.some(A=>ce.includes(rt(A))),T=g.some(A=>me.includes(rt(A)));if(h!==null&&!k){let A=o.find(P=>{let E=P.attributes.get("group-id"),v=P.attributes.get("type");return E===h&&v.toLowerCase()==="video"});e:if(A){let P=A.attributes.get("uri");if(P===null)break e;let E=xe(n,P),O=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(D=>D.getType()==="video");if(!O||await O.getCodec()===null)break e;let z=await O.getDecoderConfig().then(D=>D?.codec??null);b(z!==null),g.push(z)}}if(y!==null&&!T){let A=o.find(P=>{let E=P.attributes.get("group-id"),v=P.attributes.get("type");return E===y&&v.toLowerCase()==="audio"});e:if(A){let P=A.attributes.get("uri");if(P===null)break e;let E=xe(n,P),O=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(D=>D.getType()==="audio");if(!O||await O.getCodec()===null)break e;let z=await O.getDecoderConfig().then(D=>D?.codec??null);b(z!==null),g.push(z)}}g=[...new Set(g)];let w=null,S=null,x=d.attributes.getAsNumber("bandwidth");b(x!==null);let C=d.attributes.getAsNumber("average-bandwidth"),I=d.attributes.get("name");for(let A of g){let P=rt(A);if(P!==null){if(ce.includes(P)){if(w!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");w=A;let E=d.attributes.get("video");if(E===null){let v=d.attributes.get("resolution"),M=null,O=null;if(v){let z=v.match(/^(\d+)x(\d+)$/);z&&(M=Number(z[1]),O=Number(z[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:se,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:w,pairingMask:1n<<BigInt(m),peakBitrate:x,averageBitrate:C,name:I,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:M,height:O}})}else for(let v of o){let M=v.attributes.get("group-id"),O=v.attributes.get("type");if(M!==E||O.toLowerCase()!=="video")continue;let z=v.attributes.get("resolution")??d.attributes.get("resolution"),D=null,q=null;if(z){let ie=z.match(/^(\d+)x(\d+)$/);ie&&(D=Number(ie[1]),q=Number(ie[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:Ro(v.attributes),autoselect:Ro(v.attributes)||Om(v.attributes),languageCode:Dm(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:w,pairingMask:1n<<BigInt(m),peakBitrate:v.fullPath===null?x:null,averageBitrate:v.fullPath===null?C:null,name:v.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:D,height:q}})}}else if(me.includes(P)){if(S!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");S=A;let E=d.attributes.get("audio");if(E===null){let v=d.attributes.get("channels"),M=v!==null?Number(v.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:se,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(m),peakBitrate:x,averageBitrate:C,name:I,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:M!==null&&Number.isInteger(M)&&M>0?M:null}})}else for(let v of o){let M=v.attributes.get("group-id"),O=v.attributes.get("type");if(M!==E||O.toLowerCase()!=="audio")continue;let z=v.attributes.get("channels")??d.attributes.get("channels"),D=z!==null?Number(z.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:Ro(v.attributes),autoselect:Ro(v.attributes)||Om(v.attributes),languageCode:Dm(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(m),peakBitrate:v.fullPath===null?x:null,averageBitrate:v.fullPath===null?C:null,name:v.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:D!==null&&Number.isInteger(D)&&D>0?D:null}})}}}}return f})),u=[],l=d=>{let m=u.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===se&&(m.languageCode=d.languageCode)):(d.id=u.length+1,u.push(d))};for(let d of c)for(let m of d)l(m);u.sort((d,m)=>d.lineNumber-m.lineNumber),this.trackBackings=[];for(let d of u)d.info.type==="video"?this.trackBackings.push(new Bo(d)):this.trackBackings.push(new Oo(d));this.internalTracks=u})()}async getTrackBackings(){return await this.readMetadata(),b(this.trackBackings),this.trackBackings}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=>({id:s.id,type:s.info.type}))),r=new xa(this,e,n,null),this.segmentedInputs.push(r),r}async getMetadataTags(){return{}}async getMimeType(){return or}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Mo=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 Bo){for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}else{b(this instanceof Oo);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{..._e,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){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)}},Bo=class extends Mo{constructor(t){super(t)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return rt(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){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()}},Oo=class extends Mo{constructor(t){super(t)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return rt(this.internalTrack.fullCodecString)}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()}},Ro=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}".`)},Om=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}".`)},Dm=i=>{if(i===null)return se;let t=i.split("-")[0];return t||se};var Ze=class{constructor(){this._isIsobmff=!1}},Fn=class extends Ze{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);if(_(r)&&(r=await r),!r)return null;r.skip(4);let n=ue(r,4);return n!=="ftyp"&&n!=="styp"?null:ue(r,4)}_createDemuxer(e){return new $s(e)}get supportsTimestampedMediaData(){return!0}},Ca=class extends Fn{async _canReadInput(t){let e=await this._getMajorBrand(t);if(e!==null)return e!=="qt ";let r=0;for(let n=0;n<10;n++){let a=t._reader.requestSlice(r,8);if(_(a)&&(a=await a),!a)return!1;let s=F(a),o=8;if(s===1){let u=t._reader.requestSlice(r+8,8);if(_(u)&&(u=await u),!u)return!1;s=qe(u),o=16}if(s<o)return!1;let c=ue(a,4);if(c==="moof"||c==="sidx")return!0;if(c==="emsg"||c==="prft"||c==="free")r+=s;else return!1}return!1}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Pa=class extends Fn{async _canReadInput(t){return await this._getMajorBrand(t)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Mn=class extends Ze{async isSupportedEBMLOfDocType(t,e){let r=t._reader.requestSlice(0,xt);if(_(r)&&(r=await r),!r)return!1;let n=mu(r);if(n===null||n<1||n>8||X(r,n)!==440786851)return!1;let s=fu(r);if(typeof s!="number")return!1;let o=t._reader.requestSlice(r.filePos,s);if(_(o)&&(o=await o),!o)return!1;let c=r.filePos;for(;o.filePos<=c+s-$e;){let u=Ct(o);if(!u)break;let{id:l,size:d}=u,m=o.filePos;if(d===void 0||m+d>c+s||d>8&&l!==17026)return!1;switch(l){case 17030:if(X(o,d)!==1)return!1;break;case 17143:if(X(o,d)!==1)return!1;break;case 17026:if(ri(o,d)!==e)return!1;break;case 17031:if(X(o,d)>4)return!1;break}o.filePos=m+d}return!0}_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"matroska")}_createDemuxer(t){return new ao(t)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}get supportsTimestampedMediaData(){return!0}},Ia=class extends Mn{_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Ea=class extends Ze{async _canReadInput(t){let e=0;for(;;){let d=t._reader.requestSlice(e,Fe);if(_(d)&&(d=await d),!d)break;let m=it(d);if(!m)break;e=d.filePos+m.size}let r=await ha(t._reader,e,e+4096);if(!r)return!1;let n=r.header,a=Yr(n.mpegVersionId,n.channel),s=t._reader.requestSlice(r.startPos+a,4);if(_(s)&&(s=await s),!s)return!1;let o=F(s);if(o===$r||o===fn)return!0;e=r.startPos+r.header.totalSize;let u=await ha(t._reader,e,e+4);if(!u)return!1;let l=u.header;return!(n.channel!==l.channel||n.sampleRate!==l.sampleRate)}_createDemuxer(t){return new oo(t)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}get supportsTimestampedMediaData(){return!1}},va=class extends Ze{async _canReadInput(t){let e=t._reader.requestSlice(0,12);if(_(e)&&(e=await e),!e)return!1;let r=ue(e,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(e.skip(4),ue(e,4)==="WAVE")}_createDemuxer(t){return new mo(t)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}get supportsTimestampedMediaData(){return!1}},_a=class extends Ze{async _canReadInput(t){let e=t._reader.requestSlice(0,4);return _(e)&&(e=await e),e?ue(e,4)==="OggS":!1}_createDemuxer(t){return new lo(t)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}get supportsTimestampedMediaData(){return!0}},Ra=class extends Ze{async _canReadInput(t){let e=0;for(;;){let n=t._reader.requestSlice(e,Fe);if(_(n)&&(n=await n),!n)break;let a=it(n);if(!a)break;e=n.filePos+a.size}let r=t._reader.requestSlice(e,4);return _(r)&&(r=await r),r?ue(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}get supportsTimestampedMediaData(){return!1}_createDemuxer(t){return new bo(t)}},Fa=class extends Ze{async _canReadInput(t){let e=0;for(;;){let s=t._reader.requestSlice(e,Fe);if(_(s)&&(s=await s),!s)break;let o=it(s);if(!o)break;e=s.filePos+o.size}let r=t._reader.requestSliceRange(e,Ut,bt);if(_(r)&&(r=await r),!r)return!1;let n=nt(r);if(!n||(e+=n.frameLength,r=t._reader.requestSliceRange(e,Ut,bt),_(r)&&(r=await r),!r))return!1;let a=nt(r);return a?n.objectType===a.objectType&&n.samplingFrequencyIndex===a.samplingFrequencyIndex&&n.channelConfiguration===a.channelConfiguration:!1}_createDemuxer(t){return new fo(t)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}get supportsTimestampedMediaData(){return!1}},Ma=class extends Ze{async _canReadInput(t){let e=205,r=t._reader.requestSlice(0,e);if(_(r)&&(r=await r),!r)return!1;let n=U(r,e);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71?!0:n[4]===71&&n[196]===71}_createDemuxer(t){return new ko(t)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}get supportsTimestampedMediaData(){return!0}},Ui=class extends Ze{async _canReadInput(t){let e=t._reader.requestSlice(0,7);if(_(e)&&(e=await e),!e||!(ue(e,7)==="#EXTM3U"))return!1;if(!(t._rootSource instanceof Ye))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 Fo(t)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return or}get supportsTimestampedMediaData(){return!0}},Do=new Ca,Vo=new Pa,Hu=new Mn,qu=new Ia,Uo=new Ea,Ku=new va,Gu=new _a,zo=new Fa,Qu=new Ra,No=new Ma,Lo=new Ui,Vm=[Lo,Do,Vo,Hu,qu,Ku,Gu,Qu,Uo,zo,No],Um=[Lo,Do,Vo,Uo,zo,No],zm=(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 Wo=new Map,Ho=new Map,Sh=(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&&rt(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&&!kr(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.")},Ah=(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&&rt(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&&!kr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.")},Nm=i=>ce.includes(i)?qo(i):me.includes(i)?Ko(i):!1,qo=async(i,t={})=>{if(!ce.includes(i))return!1;Sh(i,t);let e={...t,codedWidth:t.codedWidth??1280,codedHeight:t.codedHeight??720,codec:t.codec??Vs(i,1280,720,1e6,!1)};e.description??=Rd(e);let r=JSON.stringify(e),n=Wo.get(r);if(n)return n;let a=(async()=>ci.some(o=>o.supports(i,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0)();return Wo.set(r,a),a},Ko=async(i,t={})=>{if(!me.includes(i))return!1;Ah(i,t);let e={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??Ns(i,2,48e3)};if(e.description===void 0){let s=Fd(e);if(s===!1)return!1;e.description=s}let r=JSON.stringify(e),n=Ho.get(r);if(n)return n;let a=(async()=>ui.some(o=>o.supports(i,e))||ne.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0)();return Ho.set(r,a),a},Lm=async()=>{let[i,t]=await Promise.all([ju(),Xu()]);return[...i,...t]},ju=async(i=ce,t)=>{let e=await Promise.all(i.map(r=>qo(r,t)));return i.filter((r,n)=>e[n])},Xu=async(i=me,t)=>{let e=await Promise.all(i.map(r=>Ko(r,t)));return i.filter((r,n)=>e[n])};sn();var Wm=-1/0,Hm=-1/0,Va=null;typeof FinalizationRegistry<"u"&&(Va=new FinalizationRegistry(i=>{let t=performance.now();i.type==="video"?(t-Wm>=1e3&&(V._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."),Wm=t),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(t-Hm>=1e3&&(V._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."),Hm=t),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));var zt=class{constructor(){this._referenceCount=0;this._lastAllocationBuffer=null}},Ua=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],xh=new Set(Ua),Ge=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||!xh.has(e.format))throw new TypeError("init.format must be one of: "+Ua.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 a of e.layout){if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(a.offset)||a.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(a.stride)||a.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(e.visibleRect!==void 0&&ys(e.visibleRect,"init.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??Ph(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 Ni(n)}else if(typeof VideoFrame<"u"&&t instanceof 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&&ys(e.visibleRect,"init.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 Ni({primaries:r!==null&&r in Tt?r:null,transfer:n!==null&&n in wt?n:null,matrix:a!==null&&a in St?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&&ys(e.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new i(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*Qt),duration:Math.trunc((e.duration??0)*Qt)||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:Xt(),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 Ni({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(t instanceof zt){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._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!Ua.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()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=e?.encodeOptions??{},this.pixelAspectRatio=Ar({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(Qt*this.timestamp)}get microsecondDuration(){return Math.trunc(Qt*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 zt?new i(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Oa(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 zt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Oa(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(Gm(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 Oa(this._data)?this._data.allocationSize(t):Qm(this,t).allocationSize}async copyTo(t,e={}){if(!kr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Gm(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),Oa(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 zt){var u=[];try{let f=dt(u,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(l){var d=l,m=!0}finally{mt(u,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(),p=await f.copyTo(t,e);return f.close(),p}let r=Qm(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=Qo(this.format),s;if(this._data instanceof zt){let f=this._data.getDataPlanes();if(_(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.codedHeight/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:Q(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,w={offset:k,stride:p.destinationStride};for(let S=0;S<p.sourceHeight;S++){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 x=h.subarray(y,y+T);n.set(x,k),y+=g,k+=p.destinationStride}o.push(w)}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)for(let g=0;g<r.allocationSize;g+=4){if(f){let h=n[g],y=n[g+2];n[g]=y,n[g+2]=h}p&&(n[g+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(b(this._data!==null),this._data instanceof zt){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(_(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,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Oa(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.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,r,n,a,s,o,c,u){let l=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,g=0,h=this.displayWidth,y=this.displayHeight;if(s!==void 0?(l=e,d=r,m=n,f=a,p=s,g=o,c!==void 0?(h=c,y=u):(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(l))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:l,sy:d,sWidth:m,sHeight:f}=this._unmapSourceRegion(l,d,m,f,this.rotation,this.flip));let k=this.toCanvasImageSource();t.save();let T=p+h/2,w=g+y/2;t.translate(T,w),this.flip&&t.scale(-1,1),t.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:h/y;t.scale(1/S,S),t.drawImage(k,l,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&&li(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],u=e.crop;u&&(u=Bn(u,o,c));let l,d,m,f,{sx:p,sy:g,sWidth:h,sHeight:y}=this._unmapSourceRegion(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??c,a,s);if(e.fit==="fill")l=0,d=0,m=r,f=n;else{let[T,w]=e.crop?[e.crop.width,e.crop.height]:[o,c],S=e.fit==="contain"?Math.min(r/T,n/w):Math.max(r/T,n/w);m=T*S,f=w*S,l=(r-m)/2,d=(n-f)/2}t.save();let k=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/k,k),t.translate(-r/2,-n/2),t.drawImage(this.toCanvasImageSource(),p,g,h,y,l,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,u=r.crop?r.crop.height:o,l=0;2*n<c&&2*a<u&&(l=Math.floor(Math.log2(Math.min(c/n,u/a))));let d=n*2**l,m=a*2**l,{canvas:f,context:p,isNew:g}=l>0?Km(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=l;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",l>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 zt||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&&li(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}=ls(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=Bn(s,n,a));let o=s?s.width:n,c=s?s.height:a,u=o/c,l,d;t.width!==void 0&&t.height===void 0?(l=t.width,d=l/u):t.width===void 0&&t.height!==void 0?(d=t.height,l=d*u):t.width!==void 0&&t.height!==void 0?(l=t.width,d=t.height):(l=o,d=c),l=fs(l,t.roundDimensionsTo??1),d=fs(d,t.roundDimensionsTo??1);let m={width:l,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 $u){let y=h(this,m);if(_(y)&&(y=await y),y!==null)return y}let{canvas:f,context:p,isNew:g}=Km(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})}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()}},$u=[],jm=i=>{$u.includes(i)||$u.push(i)},Ch=3,Ba=[],qm=0,Km=(i,t)=>{for(let n of Ba)if(n.canvas.width===i&&n.canvas.height===t)return n.age=qm++,{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 Ba.length>=Ch&&Ba.splice(on(Ba,n=>n.age),1),Ba.push({canvas:e,context:r,age:qm++}),{canvas:e,context:r,isNew:!0}},Ni=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(Tt);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(wt);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(St);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}}},Oa=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,Bn=(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}},li=(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.")},Gm=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.")}},Ph=(i,t,e)=>{let r=Qo(i),n=[],a=0;for(let s of r){let o=Math.ceil(t/s.widthDivisor),c=Math.ceil(e/s.heightDivisor),u=o*s.sampleBytes,l=u*c;n.push({offset:a,stride:u}),a+=l}return n},Qo=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:ae(i),b(!1)}},Qm=(i,t)=>{let e={left:0,top:0,width:i.codedWidth,height:i.codedHeight},r=t.rect,n=Ih(e,r,i.codedWidth,i.codedHeight,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 vh(n,s,a)},Ih=(i,t,e,r,n)=>{let a={...i};if(t!==void 0){if(t.width===0||t.height===0)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(!Eh(n,a))throw new TypeError("visibleRect alignment is invalid for the format.");return a},Eh=(i,t)=>{if(i===null)return!0;let e=Qo(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},vh=(i,t,e)=>{let r=Qo(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 u=r[c],l=u.sampleBytes,d=u.widthDivisor,m=u.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)*l,f.sourceWidthBytes=Math.floor(Math.trunc(i.width||0)/d)*l,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}},Go=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Dr=class{constructor(){this._referenceCount=0}},Ae=class i{constructor(t){this._closed=!1;if(Da(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 Dr){if(this._data=t,t._referenceCount++,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}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/(cr(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)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*cr(this.format);if(r.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}Va?.register(this,{type:"audio",data:this._data},this)}get microsecondTimestamp(){return Math.trunc(Qt*this.timestamp)}get microsecondDuration(){return Math.trunc(Qt*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>=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=cr(e),s=zi(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(!kr(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 u=this.numberOfFrames,l=this.numberOfChannels,d=a??0;if(d>=u)throw new RangeError("frameOffset out of range");let m=n!==void 0?n:u-d;if(m>u-d)throw new RangeError("frameCount out of range");let f=cr(c),p=zi(c);if(p&&s>=l)throw new RangeError("planeIndex out of range");if(!p&&s!==0)throw new RangeError("planeIndex out of range");let h=(p?m:m*l)*f;if(t.byteLength<h)throw new RangeError("Destination buffer is too small");let y=N(t),k=$m(c);if(Da(this._data))if(jt()&&l>2&&c!==o){_h(this._data,y,o,c,l,s,d,m);return}else try{this._data.copyTo(t,{planeIndex:s,frameOffset:d,frameCount:m,format:c});return}catch(I){if(c==="f32-planar")throw I;o="f32-planar"}let T=Xm(o),w=cr(o),S=zi(o),x;if(this._data instanceof Dr){let I=A=>{let P=this._data.getDataPlane(A);if(!(P instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let E=u*w*(S?1:l);if(P.byteLength!==E)throw new TypeError(`Data plane ${A} has invalid size. Expected exactly ${E} bytes, got ${P.byteLength} bytes.`);return P};if(S)if(p)x=I(s),s=0;else{x=new Uint8Array(u*w*l);for(let A=0;A<l;A++){let P=I(A);x.set(P,A*u*w)}}else x=I(0)}else if(this._data instanceof Uint8Array)x=this._data;else if(b(o==="f32-planar"),p)x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:s})),this._data.copyTo(x,{format:"f32-planar",planeIndex:s}),s=0;else{x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*l);for(let I=0;I<l;I++)this._data.copyTo(x.subarray(I*u*w,(I+1)*u*w),{format:"f32-planar",planeIndex:I})}let C=N(x);for(let I=0;I<m;I++)if(p){let A=I*f,P;S?P=(s*u+(I+d))*w:P=((I+d)*l+s)*w;let E=T(C,P);k(y,A,E)}else for(let A=0;A<l;A++){let E=(I*l+A)*f,v;S?v=(A*u+(I+d))*w:v=((I+d)*l+A)*w;let M=T(C,v);k(y,E,M)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Dr){let t=new i(this._data);return t.setTimestamp(this.timestamp),t}else if(Da(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})}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=cr(this.format),a;if(zi(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})}close(){this._closed||(Va?.unregister(this),this._data instanceof Dr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Da(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 Dr?this._createAudioDataFromData():Da(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.buffer:this._data.slice()})}_createAudioDataFromData(){if(zi(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,u=s;for(;u>0;){let l=Math.min(o,u),d=new Float32Array(n*l);for(let m=0;m<n;m++)t.copyFromChannel(d.subarray(m*l,(m+1)*l),m,c);yield new i({format:"f32-planar",sampleRate:a,numberOfFrames:l,numberOfChannels:n,timestamp:e+c/a,data:d}),c+=l,u-=l}}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,u=s,l=[];for(;u>0;){let d=Math.min(o,u),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});l.push(f),c+=d,u-=d}return l}},cr=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")}},zi=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Xm=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)}},$m=i=>{switch(i){case"u8":case"u8-planar":return(t,e,r)=>t.setUint8(e,J(Math.round(r*128)+128,0,255));case"s16":case"s16-planar":return(t,e,r)=>t.setInt16(e,J(Math.round(r*32768),-32768,32767),!0);case"s32":case"s32-planar":return(t,e,r)=>t.setInt32(e,J(Math.round(r*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(t,e,r)=>t.setFloat32(e,r,!0)}},Da=i=>typeof AudioData<"u"&&i instanceof AudioData,Ym=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}},_h=(i,t,e,r,n,a,s,o)=>{let c=Xm(e),u=$m(r),l=cr(e),d=cr(r),m=zi(e);if(zi(r))if(m){let p=new ArrayBuffer(o*l),g=N(p);i.copyTo(p,{planeIndex:a,frameOffset:s,frameCount:o,format:e});for(let h=0;h<o;h++){let y=h*l,k=h*d,T=c(g,y);u(t,k,T)}}else{let p=new ArrayBuffer(o*n*l),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)*l,k=h*d,T=c(g,y);u(t,k,T)}}else if(m){let p=o*l,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*l,w=(k*n+y)*d,S=c(h,T);u(t,w,S)}}}else{let p=new ArrayBuffer(o*n*l),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*l,w=k*d,S=c(g,T);u(t,w,S)}}},Zm=(i,t)=>{let e=i.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(e);return i.copyTo(r,{format:t,planeIndex:0}),new Ae({data:r,format:t,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration})};var jo=new Map,Xo=new Map,$o=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!ce.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${ce.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 oe))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof oe)&&(!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&&li(i.transform.crop,"config.transform."),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.");tf(i.codec,i)},tf=(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&&rt(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.")},Zu=i=>{let t=i.bitrateMode,e=i.quality._toVideoRateControl(i.codec,i.width,i.height,t),r=(a,s,o)=>({codec:i.fullCodecString??Vs(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,...Bd(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},Yo=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!me.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${me.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0&&!(ne.includes(i.codec)||i.codec==="flac"))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 oe))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof oe)&&(!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.");rf(i.codec,i)},rf=(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&&rt(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},Ju=i=>{let t=i.bitrateMode;return{codec:i.fullCodecString??Ns(i.codec,i.numberOfChannels,i.sampleRate),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:i.quality?._toAudioBitrate(i.codec),bitrateMode:i.quality?._bitrateMode??t,...Od(i.codec)}},oe=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"?!(t.quality in Jm):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"?Jm[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=Rh[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=J(Math.round(Ql(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let u=this._quality;u===void 0&&(b(s!==null&&a),u=J((s-a.worst)/(a.best-a.worst),0,1)),c=ef(t,e,r,Yu(u))}return{quantizer:s,bitrate:c,bitrateMode:o}}_toVideoBitrate(t,e,r){return this._bitrate!==void 0?this._bitrate:(b(this._quality!==void 0),ef(t,e,r,Yu(this._quality)))}_toAudioBitrate(t){if(ne.includes(t)||t==="flac")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 e=Yu(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!n)throw new Error(`Unhandled codec: ${t}`);let a=n*e;return t==="aac"?a=[96e3,128e3,16e4,192e3].reduce((o,c)=>Math.abs(c-a)<Math.abs(o-a)?c:o):t==="opus"||t==="vorbis"?a=Math.max(6e3,a):t==="mp3"&&(a=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,c)=>Math.abs(c-a)<Math.abs(o-a)?c:o)),Math.round(a/1e3)*1e3}},Jm={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Rh={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:($l()??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}},Yu=i=>.3*Math.exp(2.5538*i),ef=(i,t,e,r)=>{let n=t*e,a=1920*1080,s=3e6,o=Math.pow(n/a,.95),c=s*o,u={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/s},d=c*u[i]*r;return Math.ceil(d/1e3)*1e3},el=(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)},nf=new oe("very-low"),af=new oe("low"),sf=new oe("medium"),of=new oe("high"),cf=new oe("very-high"),uf=i=>{if(ce.includes(i))return za(i);if(me.includes(i))return Na(i);if(Xe.includes(i))return La(i);throw new TypeError(`Unknown codec '${i}'.`)},za=async(i,t={})=>{let{width:e=1280,height:r=720,quality:n,bitrate:a,frameRate:s,...o}=t;if(!ce.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 oe))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 oe)&&(!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.");tf(i,o);let c=di(n,a)??new oe("medium"),u;try{u=Zu({codec:i,width:e,height:r,quality:c,framerate:s,...o,alpha:"discard"})}catch{return!1}let l=JSON.stringify(u),d=jo.get(l);if(d)return d;let m=(async()=>{for(let{config:p}of u)if(Dn.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 u){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!Xt()||await new Promise(async y=>{try{let k=new VideoEncoder({output:()=>{},error:()=>y(!1)});k.configure(p);let T=new Uint8Array(e*r*4),w=new VideoFrame(T,{format:"RGBA",codedWidth:e,codedHeight:r,timestamp:0});k.encode(w,g!==null?el(i,g):void 0),w.close(),await k.flush(),y(!0)}catch{y(!1)}}))return!0}return!1})();return jo.set(l,m),m},Na=async(i,t={})=>{let{numberOfChannels:e=2,sampleRate:r=48e3,quality:n,bitrate:a,...s}=t;if(!me.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 oe))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 oe)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");rf(i,s);let o=di(n,a)??new oe("medium"),c=Ju({codec:i,numberOfChannels:e,sampleRate:r,quality:o,...s}),u=JSON.stringify(c),l=Xo.get(u);if(l)return l;let d=(async()=>{if(Vn.some(m=>m.supports(i,c))||ne.includes(i))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return Xo.set(u,d),d},di=(i,t)=>{if(i!==void 0)return i;if(t!==void 0)return t instanceof oe?t:new oe({bitrate:t})},La=async i=>!!Xe.includes(i),lf=async()=>{let[i,t,e]=await Promise.all([tl(),On(),rl()]);return[...i,...t,...e]},tl=async(i=ce,t)=>{let e=await Promise.all(i.map(r=>za(r,t)));return i.filter((r,n)=>e[n])},On=async(i=me,t)=>{let e=await Promise.all(i.map(r=>Na(r,t)));return i.filter((r,n)=>e[n])},rl=async(i=Xe)=>{let t=await Promise.all(i.map(La));return i.filter((e,r)=>t[r])},Zo=async(i,t)=>{for(let e of i)if(await za(e,t))return e;return null},df=async(i,t)=>{for(let e of i)if(await Na(e,t))return e;return null},mf=async i=>{for(let t of i)if(await La(t))return t;return null};var Wa=class{static supports(t,e){return!1}},Ha=class{static supports(t,e){return!1}},qa=class{static supports(t,e){return!1}},Ka=class{static supports(t,e){return!1}},ci=[],ui=[],Dn=[],Vn=[],ff=i=>{if(i.prototype instanceof Wa){let t=i;if(ci.includes(t)){V._warn("Video decoder already registered.");return}ci.push(t),Wo.clear()}else if(i.prototype instanceof Ha){let t=i;if(ui.includes(t)){V._warn("Audio decoder already registered.");return}ui.push(t),Ho.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},pf=i=>{if(i.prototype instanceof qa){let t=i;if(Dn.includes(t)){V._warn("Video encoder already registered.");return}Dn.push(t),jo.clear()}else if(i.prototype instanceof Ka){let t=i;if(Vn.includes(t)){V._warn("Audio encoder already registered.");return}Vn.push(t),Xo.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var hf=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},gf=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},bf=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},yf=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 Li=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.")},Vr=i=>{if(!ve(i))throw new TypeError("timestamp must be a number.")},il=(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,st=class{constructor(t){if(!(t instanceof fi))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(Li(t),this._track.input._disposed)throw new ge;return il(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){Li(t);let e=await this.getFirstPacket(t);return e?e.type==="key"?e:this.getNextKeyPacket(e,t):null}async getPacket(t,e={}){if(Vr(t),Li(e),this._track.input._disposed)throw new ge;return il(this._track,this._track._backing.getPacket(t,e),e)}async getNextPacket(t,e={}){if(!(t instanceof j))throw new TypeError("packet must be an EncodedPacket.");if(Li(e),this._track.input._disposed)throw new ge;return il(this._track,this._track._backing.getNextPacket(t,e),e)}async getKeyPacket(t,e={}){if(Vr(t),Li(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 j))throw new TypeError("packet must be an EncodedPacket.");if(Li(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 j))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 j))throw new TypeError("endPacket must be an EncodedPacket.");if(Li(r),this._track.input._disposed)throw new ge;let n=[],{promise:a,resolve:s}=ee(),{promise:o,resolve:c}=ee(),u=!1,l=!1,d=null,m=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let h=t??await this.getFirstPacket(r);for(;h&&!l&&!this._track.input._disposed&&!(e&&h.sequenceNumber>=e?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:c}=ee()),await o;continue}n.push(h),s(),{promise:a,resolve:s}=ee(),h=await this.getNextPacket(h,r)}u=!0,s()})().catch(h=>{m||(d=h,m=!0,s())});let g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new ge;if(l)return{value:void 0,done:!0};if(m)throw d;if(n.length>0){let h=n.shift(),y=performance.now();for(f.push(y);f.length>0&&y-f[0]>=1e3;)f.shift();return c(),{value:h,done:!1}}else{if(u)return{value:void 0,done:!0};await a}}},async return(){return l=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},kf=4,Ga=class{constructor(t,e){this.onSample=t;this.onError=e;this.onDequeue=null}},Un=class{mediaSamplesInRange(t=-1/0,e=1/0,r){Vr(t),Vr(e);let n=[],a=!1,s=null,{promise:o,resolve:c}=ee(),{promise:u,resolve:l}=ee(),d=!1,m=!1,f=!1,p=null,g=null,h=!1,y={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(A=>{if(l(),A.timestamp>=e&&(m=!0),m){A.close();return}s&&(A.timestamp>t?(n.push(s),a=!0):s.close()),A.timestamp>=t&&(n.push(A),a=!0),s=a?null:A,n.length>0&&(c(),{promise:o,resolve:c}=ee())},A=>{h||(g=A,h=!0,c())}),p.onDequeue=()=>l();let w=this._createPacketSink(),S=await w.getKeyPacket(t,y)??await w.getFirstKeyPacket(y),x=S,I=w.packets(S??void 0,void 0,y);for(await I.next();x&&!m&&!this._track.input._disposed;){if(n.length+p.getDecodeQueueSize()>=kf){({promise:u,resolve:l}=ee()),await u;continue}p.decode(x);let A=await I.next();if(A.done)break;x=A.value}await I.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(()=>{p?.close()});let k=this._track,T=()=>{s?.close();for(let w of n)w.close()};return{async next(){for(;;){if(k.input._disposed)throw f=!0,m=!0,T(),new ge;if(f)return{value:void 0,done:!0};if(h)throw f=!0,m=!0,T(),g;if(n.length>0){let w=n.shift();return l(),{value:w,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,m=!0,l(),c(),T(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,e){Hl(t);let r=Wl(t),n=[],a=[],{promise:s,resolve:o}=ee(),{promise:c,resolve:u}=ee(),l=!1,d=!1,m=null,f=null,p=!1,g=T=>{a.push(T),o(),{promise:s,resolve:o}=ee()},h={...e,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{m=await this._createDecoder(A=>{if(u(),d){A.close();return}let P=0;for(;n.length>0&&A.timestamp-n[0]>-1e-10;)P++,n.shift();if(P>0)for(let E=0;E<P;E++)g(E<P-1?A.clone():A);else A.close()},A=>{p||(f=A,p=!0,o())}),m.onDequeue=()=>u();let T=this._createPacketSink(),w=null,S=null,x=-1,C=async()=>{b(S),b(m);let A=S;for(m.decode(A);A.sequenceNumber<x;){for(;a.length+m.getDecodeQueueSize()>=kf&&!d;)({promise:c,resolve:u}=ee()),await c;if(d)break;let P=await T.getNextPacket(A,h);if(!P)throw new Error("Internal error: couldn't get next packet when one was expected.");m.decode(P),A=P}x=-1},I=async()=>{b(m),await m.flush();for(let A=0;A<n.length;A++)g(null);n.length=0};for await(let A of r){if(Vr(A),d||this._track.input._disposed)break;let P=await T.getPacket(A,h),E=P&&await T.getKeyPacket(A,h);if(!E){x!==-1&&(await C(),await I()),g(null),w=null;continue}w&&(E.sequenceNumber!==S.sequenceNumber||P.timestamp<w.timestamp)&&(await C(),await I()),n.push(P.timestamp),x=Math.max(P.sequenceNumber,x),w=P,S=E}!d&&!this._track.input._disposed&&(x!==-1&&await C(),await I()),l=!0,o()})().catch(T=>{p||(f=T,p=!0,o())}).finally(()=>{m?.close()});let y=this._track,k=()=>{for(let T of a)T?.close()};return{async next(){for(;;){if(y.input._disposed)throw d=!0,k(),new ge;if(d)return{value:void 0,done:!0};if(p)throw d=!0,k(),f;if(a.length>0){let T=a.shift();return b(T!==void 0),u(),{value:T,done:!1}}else if(!l)await s;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),k(),{value:void 0,done:!0}},async throw(T){throw T},[Symbol.asyncIterator](){return this}}}},al=class extends Ga{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 Lr;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];this.currentPacketIndex=0;this.raslSkipped=!1;this.alphaDecoder=null;this.alphaHadKeyframe=!1;this.colorQueue=[];this.alphaQueue=[];this.merger=null;this.decodedAlphaChunkCount=0;this.alphaDecoderQueueSize=0;this.nullAlphaFrameQueue=[];this.currentAlphaPacketIndex=0;this.alphaRaslSkipped=!1;this.finalSamples=[];this.mergeAlphaPromises=[];let u=ci.find(l=>l.supports(n,a));if(u)this.customDecoder=new u,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=l=>{if(!(l instanceof Ge))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoder.onError=l=>{r(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>r(l));else{let l=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(Yn()){if(n==="avc"&&this.decoderConfig.description){let m=tr(Q(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){let f=rr(m.sequenceParameterSets[0]);f&&(f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),f.maxDecFrameBuffering!==0&&f.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[0]=nu(f),this.decoderConfig={...this.decoderConfig,description:un(m)}))}}rn(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{l(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))}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),jt()||qc(this.inputTimestamps,e.timestamp,r=>r),Yn()&&this.currentPacketIndex===0){if(this.codec==="avc"){let r=[],n=!1;for(let s of iu(e.data,this.decoderConfig)){let o=Jt(e.data[s.offset]);if(n||=o>=1&&o<=5,o===9){if(n)break;r.length=0}o>=20&&o<=31||r.push(e.data.subarray(s.offset,s.offset+s.length))}if(!this.decoderConfig.description)for(let s=0;s<r.length;s++){let o=r[s];if(Jt(o[0])!==7)continue;let c=rr(o);c&&c.maxDecFrameBuffering!==0&&c.bitstreamRestrictionFlag!==1&&(r[s]=nu(c));break}let a=md(r,this.decoderConfig);e=new j(a,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){let r=hd(e.data,this.decoderConfig);r&&(e=new j(r,e.type,e.timestamp,e.duration))}}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 sl),!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(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=jr(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}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of Jn(e,this.decoderConfig)){let n=Rt(e[r.offset]);if(n===8||n===9)return!0}return!1}sampleHandler(e){if(jt()){if(this.sampleQueue.length>0&&e.timestamp>=Y(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}qc(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=ee();this.mergeAlphaPromises.push(n.promise);let a={sample:null};this.finalSamples.push(a);try{if(!r)a.sample=new Ge(e);else{b(this.merger);let s=await this.merger.merge(e,r);a.sample=new Ge(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){nn(this.finalSamples,a),this.onError(s)}finally{nn(this.mergeAlphaPromises,n.promise),n.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),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),jt()){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()):(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}},nl=null,sl=class{constructor(){this.workers=[];this.nextWorkerIndex=0;this.pendingRequests=new Map;this.nextRequestId=0}merge(t,e){if(this.workers.length===0){if(!nl){let o=new Blob([`(${Fh.toString()})()`],{type:"application/javascript"});nl=URL.createObjectURL(o)}let s=J(navigator.hardwareConcurrency,1,4);for(let o=0;o<s;o++){let c=new Worker(nl);c.addEventListener("message",u=>{let l=u.data,d=this.pendingRequests.get(l.id);d&&(this.pendingRequests.delete(l.id),"error"in l?d.reject(new Error(l.error)):d.resolve(l.frame))}),c.addEventListener("error",u=>{let l=new Error(u.message||"Color/alpha merge worker error.");for(let d of this.pendingRequests.values())d.reject(l);this.pendingRequests.clear()}),this.workers.push(c)}}let r=this.nextRequestId++,n=ee();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()}},Fh=()=>{let i=null,t=null,e=Promise.resolve();self.addEventListener("message",c=>{let{id:u,color:l,alpha:d}=c.data;e=e.then(async()=>{try{let m=await r(l,d);self.postMessage({id:u,frame:m},{transfer:[m]})}catch(m){self.postMessage({id:u,error:m.message})}finally{l.close(),d.close()}})});let r=async(c,u)=>{let l=c.format,d=u.format;if(!l||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let m=l.includes("P10"),f=l.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: '${l}', alpha: '${d}').`);if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await n(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await a(c,u,l);if(l==="NV12")return await s(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},n=async(c,u,l)=>{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(u,d,m,1);for(let k=0,T=3;k<f;k++,T+=4)p[T]=g[k];let y={format:l==="RGBX"||l==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:m,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},a=async(c,u,l)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=l.includes("P10"),p=l.includes("P12"),g=f||p?2:1,h,y;l.startsWith("I420")?(h=Math.ceil(d/2),y=Math.ceil(m/2)):l.startsWith("I422")?(h=Math.ceil(d/2),y=m):(h=d,y=m);let k=d*m,T=h*y,w=k*g,S=T*g,x=k*g,C=w+2*S+x,I=new Uint8Array(C);await c.copyTo(I);let A=await o(u,d,m,g),P=w+2*S;I.set(A,P);let v={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:d,codedHeight:m,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[I.buffer]};return new VideoFrame(I,v)},s=async(c,u)=>{let l=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,m=l*d,f=Math.ceil(l/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,w=m;for(let C=0;C<g;C++)y[k+C]=t[w+C*2],y[T+C]=t[w+C*2+1];let S=await o(u,l,d,1);y.set(S,m+2*g);let x={format:"I420A",codedWidth:l,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,x)},o=async(c,u,l,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=u*l;for(let h=0;h<g;h++)i[h]=i[h*4+p];return i.subarray(0,g)}else{let p=i.subarray(0,u*l*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,u*l):p;for(let w=0;w<T.length;w++){let S=Math.round((T[w]-h)*k/(y-h));T[w]=Math.min(Math.max(S,0),k)}}return p}}},Tf=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.")},mi=class extends Un{constructor(t,e={}){if(!(t instanceof ur))throw new TypeError("videoTrack must be an InputVideoTrack.");Tf(e),super(),this._track=t,this._decoderOptions=e}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(an("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 al(t,e,r,s,n,a,o)}_createPacketSink(){return new st(this._track)}async getSample(t,e={}){Vr(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)}},Jo=class{constructor(t,e={}){this._rotation=0;this._flip=!1;this._initPromise=null;this._nextCanvasIndex=0;if(!(t instanceof ur))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&&li(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&&Tf(e.decoderOptions),this._videoTrack=t,this._alpha=e.alpha??!1,this._options=e,this._fit=e.fit??"fill",this._videoSampleSink=new mi(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],u=t.crop;u&&(u=Bn(u,o,c));let[l,d]=u?[u.width,u.height]:[o,c],m=l/d;t.width!==void 0&&t.height===void 0?(l=t.width,d=Math.round(l/m)):t.width===void 0&&t.height!==void 0?(d=t.height,l=Math.round(d*m)):t.width!==void 0&&t.height!==void 0&&(l=t.width,d=t.height),this._width=l,this._height=d,this._rotation=r,this._flip=n,this._crop=u})()}_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||Xt()});b(s),t._drawWithFitAndMipmapping(n,s,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&Xt()});let o={canvas:n,timestamp:t.timestamp,duration:t.duration};return t.close(),o}async getCanvas(t,e){Vr(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*$n(this._videoSampleSink.samples(t,e,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,e){await this._ensureInit(),yield*$n(this._videoSampleSink.samplesAtTimestamps(t,e),r=>r&&this._videoSampleToWrappedCanvas(r))}},ol=class extends Ga{constructor(e,r,n,a){super(e,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Lr;this.customDecoderQueueSize=0;this.currentTimestamp=null;this.expectedFirstTimestamp=null;this.timestampOffset=0;let s=c=>{let u=c.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-u),u+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(u-this.currentTimestamp)>=c.duration)&&(this.currentTimestamp=u);let l=this.currentTimestamp;if(this.currentTimestamp+=c.duration,c.numberOfFrames===0){c.close();return}let d=a.sampleRate;c.setTimestamp(Math.round(l*d)/d),e(c)},o=ui.find(c=>c.supports(n,a));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=c=>{if(!(c instanceof Ae))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoder.onError=c=>{r(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>r(c));else{let c=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:u=>{try{s(new Ae(u))}catch(l){this.onError(l)}},error:u=>{u.stack=c,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){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()})):(b(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.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.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(b(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}},cl=class extends Ga{constructor(e,r,n){super(e,r);this.decoderConfig=n;this.currentTimestamp=null;b(ne.includes(n.codec)),this.codec=n.codec;let{dataType:a,sampleSize:s,littleEndian:o}=Re(this.codec);switch(this.inputSampleSize=s,s){case 1:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:a==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):a==="ulaw"?this.readInputValue=(c,u)=>gf(c.getUint8(u)):a==="alaw"?this.readInputValue=(c,u)=>yf(c.getUint8(u)):b(!1);break;case 2:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:a==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):b(!1);break;case 3:a==="unsigned"?this.readInputValue=(c,u)=>Ci(c,u,o)-2**23:a==="signed"?this.readInputValue=(c,u)=>ql(c,u,o):b(!1);break;case 4:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:a==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):a==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):b(!1);break;case 8:a==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):b(!1);break;default:ae(s),b(!1)}switch(s){case 1:a==="ulaw"||a==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,u,l)=>c.setUint8(u,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l<<8,!0);break;case 4:this.outputSampleSize=4,a==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0);break;default:ae(s),b(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=N(e.data),n=Math.floor(e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize),a=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(a),o=new DataView(s);for(let d=0;d<n*this.decoderConfig.numberOfChannels;d++){let m=d*this.inputSampleSize,f=d*this.outputSampleSize,p=this.readInputValue(r,m);this.writeOutputValue(o,f,p)}let c=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=e.timestamp);let u=this.currentTimestamp;this.currentTimestamp+=c;let l=new Ae({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:u});this.onSample(l)}async flush(){}close(){}},Wi=class extends Un{constructor(t){if(!(t instanceof lr))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(an("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),ne.includes(n.codec)?new cl(t,e,n):new ol(t,e,r,n)}_createPacketSink(){return new st(this._track)}async getSample(t,e={}){Vr(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)}},ec=class{constructor(t){if(!(t instanceof lr))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Wi(t)}_audioSampleToWrappedArrayBuffer(t){let e={buffer:t.toAudioBuffer(),timestamp:t.timestamp,duration:t.duration};return t.close(),e}async getBuffer(t,e){Vr(t);let r=await this._audioSampleSink.getSample(t,e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(t,e,r){return $n(this._audioSampleSink.samples(t,e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(t,e){return $n(this._audioSampleSink.samplesAtTimestamps(t,e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}};var fi=class i{constructor(t,e){this.input=t,this._backing=e}isVideoTrack(){return this instanceof ur}isAudioTrack(){return this instanceof lr}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ye(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ye(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ye(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ye(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 ye(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(t){let e=await this._backing.getPacket(1/0,{metadataOnly:!0,...t}),r=(e?.timestamp??0)+(e?.duration??0);return Gt(r,await this.getTimeResolution())}async getDurationFromMetadata(t={}){return this._backing.getDurationFromMetadata(t)}async computePacketStats(t=1/0,e){let r=new st(this),n=1/0,a=-1/0,s=0,o=0;for await(let c of r.packets(void 0,void 0,{metadataOnly:!0,...e})){if(s>=t&&c.timestamp>=a)break;n=Math.min(n,c.timestamp),a=Math.max(a,c.timestamp+c.duration),s++,o+=c.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-n)).toPrecision(16)):0,averageBitrate:s?Number((8*o/(a-n)).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(pi({filter:e=>e.canBePairedWith(this)},t))}async getPairableVideoTracks(t){return this.input.getVideoTracks(pi({filter:e=>e.canBePairedWith(this)},t))}async getPairableAudioTracks(t){return this.input.getAudioTracks(pi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableVideoTrack(t){return this.input.getPrimaryVideoTrack(pi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableAudioTrack(t){return this.input.getPrimaryAudioTrack(pi({filter:e=>e.canBePairedWith(this)},t))}async hasPairableTrack(t){t&&=ul(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&&=ul(t),this.hasPairableTrack(async e=>e.isVideoTrack()&&(!t||await t(e)))}hasPairableAudioTrack(t){return t&&=ul(t),this.hasPairableTrack(async e=>e.isAudioTrack()&&(!t||await t(e)))}},ye=(i,t,e)=>{if(_(i))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${e}()' instead.`);return i},ul=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.then(e):e(r)}:void 0},ur=class extends fi{constructor(e,r){super(e,r);this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ye(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 ye(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ye(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Si(await this._backing.getTransformationMatrix())}get rotation(){return Si(ye(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return Lc(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ye(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ye(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=wf(await this.getSquarePixelWidth()*await this.getCodedHeight(),await this.getSquarePixelHeight()*await this.getCodedWidth())}get pixelAspectRatio(){return this._pixelAspectRatioCache??=wf(ye(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ye(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),ye(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ye(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=ye(e,"displayWidth","getDisplayWidth");if(a!==null)return a}let n=Si(ye(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ye(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=ye(e,"displayHeight","getDisplayHeight");if(a!==null)return a}let n=Si(ye(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ye(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}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),ci.some(a=>a.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return V._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof j))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),jr(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&&(!ve(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 st(this),s=[],o=-1/0,c=0;for await(let E of a.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=n&&E.timestamp>=o)break;s.push(E.timestamp),o=Math.max(o,E.timestamp),c++}let u=new Float64Array(s.length);for(let E=0;E<s.length;E++)u[E]=Math.round(s[E]*r);u.sort();let l=1;for(let E=1;E<u.length;E++)u[E]!==u[l-1]&&(u[l++]=u[E]);if(l<2)return{underlyingFrameRate:null,bestGuessFrameRate:r,minFrameRate:r,maxFrameRate:r,averageFrameRate:r,medianFrameRate:r,frameRateIsConstant:!0,probedPacketCount:c};let d=u.subarray(0,l),m=Mh(d,r),f=m??r,p=m!==null?r/m:null,g=new Map,h=1/0,y=-1/0,k=0;for(let E=1;E<l;E++){let v=d[E]-d[E-1],M=p!==null?Math.max(1,Math.round(v/p)):v;g.set(M,(g.get(M)??0)+1),h=Math.min(h,M),y=Math.max(y,M),k+=M}let T=l-1,w=[...g.keys()].sort((E,v)=>E-v),S=T-1>>1,x=T>>1,C=0,I=0,A=0;for(let E of w)if(A+=g.get(E),C===0&&A>S&&(C=E),A>x){I=E;break}let P=(f/C+f/I)/2;return{underlyingFrameRate:m,bestGuessFrameRate:m!==null?m:Bh(P),minFrameRate:f/y,maxFrameRate:f/h,averageFrameRate:f*T/k,medianFrameRate:P,frameRateIsConstant:m!==null&&h===1&&y===1,probedPacketCount:c}}},wf=(i,t)=>i===0||t===0?{num:1,den:1}:Ar({num:i,den:t}),lr=class extends fi{constructor(t,e){super(t,e)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ye(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ye(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ye(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 canDecode(){try{let t=await this._backing.getDecoderConfig();if(!t)return!1;let e=await this._backing.getCodec();return b(e!==null),ui.some(r=>r.supports(e,t))||ne.includes(t.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0}catch(t){return V._error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof j))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}},Af=i=>i??1/0,Qa=i=>-(i??-1/0),hi=i=>-i,zn=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.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.then(e):e(r)}:void 0}},pi=(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.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)||_(n)?Promise.all([r,n]).then(([s,o])=>a(s,o)):a(r,n)}:void 0}),tc=async(i,t)=>{let e=i;if(t?.filter){let s=i.map(c=>t.filter(c));if(s.some(c=>_(c))){let c=await Promise.all(s);e=i.filter((u,l)=>c[l])}else e=i.filter((c,u)=>s[u])}if(!t?.sortBy)return e;let r=e.map(s=>t.sortBy(s)),a=r.some(s=>_(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],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let d=0;d<l;d++){let m=c[d]??0,f=u[d]??0;if(m!==f)return m-f}return 0}).map(s=>s.track)},Mh=(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 C=1;C<i.length;C++){let I=i[C]-i[C-1];if(!(I>0))return null;o[C-1]=I}let c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)];for(let C=0;C<6;C++){let I=0,A=0;for(let E of o){let v=Math.max(1,Math.round(E/u));Math.abs(E-v*u)>=n||(I+=E,A+=v)}if(A===0)return null;let P=I/A;if(Math.abs(P-u)<=1e-12*Math.max(1,u)){u=P;break}u=P}let l=0,d=0,m=0;for(let C of o){let I=Math.max(1,Math.round(C/u));Math.abs(C-I*u)>=n||(l++,d+=C,m+=I)}if(l/o.length<.98)return null;u=d/m;let f=1/Math.min(m,a),p=Math.max(Number.EPSILON,u-f),g=u+f,h=t/g,y=t/p,k=t/u,T=null,w=1/0;for(let C of s){if(C<h||C>y)continue;let I=Math.abs(C/k-1);I<w&&(T=C,w=I)}if(T===null){let C=Sf(p,g,1e6),I=Sf(h,y,1e6);if(I&&(!C||I.den<C.den||I.den===C.den&&I.num<=C.num))T=I.num/I.den;else if(C)T=t*C.den/C.num;else return null}let S=t/T,x=0;for(let C of o){let I=Math.max(1,Math.round(C/S));Math.abs(C-I*S)<n&&x++}return x/o.length<.98?null:T},Sf=(i,t,e)=>{for(let r=1;r<=e;r++){let n=Math.floor(i*r)+1;if(n/r<t)return Ar({num:n,den:r})}return null},Bh=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};sn();var Oh=1,Bm=2,oi=class i extends Je{constructor(e){super();this._demuxerPromise=null;this._format=null;this._trackBackingsCache=null;this._backingToTrack=new Map;this._disposed=!1;this._nextSourceCacheAge=0;this._sourceRefs=[];this._sourceCache=[];this._sourceCachePromises=[];this._onFormatDetermined=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof Ze)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ne||e.source instanceof ai))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ne&&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&&zm(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Ne?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get disposed(){return this._disposed}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){b(this._rootSource instanceof Ye);let r=await this._rootSource._resolveRequest(e);return this._emit("source",{source:r.source,request:e,isRoot:e.isRoot}),r}_getSourceCached(e,r=Oh){let n=this._sourceCache.find(o=>o.cacheGroup===r&&Lu(o.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let a=this._sourceCachePromises.find(o=>o.cacheGroup===r&&Lu(o.request,e));if(a)return a.promise.then(o=>o.sourceRef.source.ref());let s=(async()=>{let o=await this._getSourceUncached(e);if(this._disposed)throw o.free(),new ge;if(vi(this._sourceCache,m=>m.cacheGroup===r&&m.sourceRef.source._refCount===1)>=4){let m=on(this._sourceCache,p=>p.cacheGroup===r&&p.sourceRef.source._refCount===1?p.age:1/0);b(m!==-1);let f=this._sourceCache[m];this._sourceCache.splice(m,1),f.sourceRef.free(),nn(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(o);let l=this._sourceCachePromises.findIndex(m=>m.request===e);return b(l!==-1),this._sourceCachePromises.splice(l,1),{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 si(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new Nn})()}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 Nn)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._backing.getFirstPacket({metadataOnly:!0}))),a=Math.min(...n.map(s=>s?.timestamp??1/0));return a===1/0?0:a}async computeDuration(e,r){e??=await this.getTracks();let n=e.filter(s=>s!==null);if(n.length===0)return 0;let a=await Promise.all(n.map(s=>s.computeDuration(r)));return Math.max(...a)}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&&=zn(e);let n=(await this._getTrackBackings()).map(a=>this._wrapBackingAsTrack(a));return tc(n,e)}async getVideoTracks(e){e&&=zn(e);let n=(await this.getTracks()).filter(a=>a.isVideoTrack());return tc(n,e)}async getAudioTracks(e){e&&=zn(e);let n=(await this.getTracks()).filter(a=>a.isAudioTrack());return tc(n,e)}async getPrimaryVideoTrack(e){e&&=zn(e);let r=pi(e,{sortBy:async a=>[hi((await a.getDisposition()).default),hi(await a.hasPairableAudioTrack()),hi(!await a.hasOnlyKeyPackets()),Qa(await a.getBitrate())]});return(await this.getVideoTracks(r))[0]??null}async getPrimaryAudioTrack(e){e&&=zn(e);let r=await this.getPrimaryVideoTrack(),n=pi(e,{sortBy:async s=>[hi(!r||s.canBePairedWith(r)),hi((await s.getDisposition()).default),Qa(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 ur(this,e):new lr(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._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},Nn=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 si=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 we(a,N(a),0,t,t)}let r=t+e,n=this.source._read(t,r,zu,Nu);return _(n)?n.then(a=>a?new we(a.bytes,a.view,a.offset,t,r):null):n?new we(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,J(this.fileSizeNonStrict-t,e,r));{let n=this.requestSlice(t,r),a=s=>s||(b(this.fileSizeNonStrict!==null),this.requestSlice(t,J(this.fileSizeNonStrict-t,e,r)));return _(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(_(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 we(n,N(n),0,0,r)})()}},we=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)}},ot=(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)=>{ot(i,t);let e=i.bytes.subarray(i.bufferPos,i.bufferPos+t);return i.bufferPos+=t,e},L=i=>(ot(i,1),i.view.getUint8(i.bufferPos++)),Cn=(i,t)=>{ot(i,2);let e=i.view.getUint16(i.bufferPos,t);return i.bufferPos+=2,e},fe=i=>{ot(i,2);let t=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,t},Dt=i=>{ot(i,3);let t=Ci(i.view,i.bufferPos,!1);return i.bufferPos+=3,t},ma=i=>{ot(i,2);let t=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,t},Or=(i,t)=>{ot(i,4);let e=i.view.getUint32(i.bufferPos,t);return i.bufferPos+=4,e},F=i=>{ot(i,4);let t=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,t},ni=i=>{ot(i,4);let t=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,t},Rr=i=>{ot(i,4);let t=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,t},Dh=i=>{ot(i,4);let t=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,t},wu=(i,t)=>{let e,r;return t?(e=Or(i,!0),r=Or(i,!0)):(r=Or(i,!1),e=Or(i,!1)),r*4294967296+e},qe=i=>{let t=F(i),e=F(i);return t*4294967296+e},em=i=>{let t=Rr(i),e=F(i);return t*4294967296+e},fm=i=>{let t=ni(i);return Dh(i)*4294967296+t},sm=i=>{ot(i,4);let t=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,t},eo=i=>{ot(i,8);let t=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,t},ue=(i,t)=>{ot(i,t);let e="";for(let r=0;r<t;r++)e+=String.fromCharCode(i.bytes[i.bufferPos++]);return e},_o=(i,t,e)=>he.decode(U(i,t)).split(`
9
- `).map(a=>a.trim()).filter(a=>a.length>0&&!e?.ignore?.(a));var ga=128,Fe=10,Wn=["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"],um=(i,t)=>{let e=i.filePos;t.raw??={},t.raw.TAG??=U(i,ga-3),i.filePos=e;let r=Ln(i,30);r&&(t.title??=r);let n=Ln(i,30);n&&(t.artist??=n);let a=Ln(i,30);a&&(t.album??=a);let s=Ln(i,4),o=Number.parseInt(s,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(String(o)));let c=U(i,30),u;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(t.trackNumber??=d),i.skip(-30),u=Ln(i,28),i.skip(2)}else i.skip(-30),u=Ln(i,30);u&&(t.comment??=u);let l=L(i);l<Wn.length&&(t.genre??=Wn[l])},Ln=(i,t)=>{let e=U(i,t),r=Ii(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()},it=i=>{let t=i.filePos,e=ue(i,3),r=L(i),n=L(i),a=L(i),s=F(i);if(e!=="ID3"||r===255||n===255||(s&2155905152)!==0)return i.filePos=t,null;let o=qs(s);return a&16&&(o+=Fe),{majorVersion:r,revision:n,flags:a,size:o}},ii=(i,t,e)=>{if(![2,3,4].includes(t.majorVersion)){V._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=t.flags&16?t.size-Fe:t.size,n=U(i,r),a=new ll(t,n);if(t.flags&128&&t.majorVersion===3&&a.ununsynchronizeAll(),t.flags&64){if(a.bytes.length<4)return;let s=a.readU32();t.majorVersion===3?a.pos+=s:a.pos+=s-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let s=a.readId3V2Frame();if(!s)break;let o=a.pos,c=Math.min(a.pos+s.size,a.bytes.length),u=c,l=!1,d=!1,m=!1;if(t.majorVersion===3?(l=!!(s.flags&64),d=!!(s.flags&128)):t.majorVersion===4&&(l=!!(s.flags&4),d=!!(s.flags&8),m=!!(s.flags&2)||!!(t.flags&128)),l){V._warn(`Skipping encrypted ID3v2 frame ${s.id}`),a.pos=c;continue}if(d){V._warn(`Skipping compressed ID3v2 frame ${s.id}`),a.pos=c;continue}m&&(u=a.ununsynchronizeRegion(a.pos,u));let f=p=>{if(u-a.pos<p)throw new Error(`Invalid ID3v2 ${s.id} frame: too short.`)};if(e.raw??={},s.id==="TXXX"){let p=e.raw.TXXX??={};f(1);let g=a.readId3V2TextEncoding(),h=a.readId3V2Text(g,u),y=a.readId3V2Text(g,u);p[h]??=y}else s.id[0]==="T"?e.raw[s.id]??=a.readId3V2EncodingAndText(u):e.raw[s.id]??=a.readBytes(u-a.pos);switch(a.pos=o,s.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 g=a.readId3V2EncodingAndText(u).split("/"),h=Number.parseInt(g[0],10),y=g[1]&&Number.parseInt(g[1],10);Number.isInteger(h)&&h>0&&(e.trackNumber??=h),y&&Number.isInteger(y)&&y>0&&(e.tracksTotal??=y)}break;case"TPOS":case"TPA":{let g=a.readId3V2EncodingAndText(u).split("/"),h=Number.parseInt(g[0],10),y=g[1]&&Number.parseInt(g[1],10);Number.isInteger(h)&&h>0&&(e.discNumber??=h),y&&Number.isInteger(y)&&y>0&&(e.discsTotal??=y)}break;case"TCON":case"TCO":{let p=a.readId3V2EncodingAndText(u),g=/^\((\d+)\)/.exec(p);if(g){let h=Number.parseInt(g[1]);if(Wn[h]!==void 0){e.genre??=Wn[h];break}}if(g=/^\d+$/.exec(p),g){let h=Number.parseInt(g[0]);if(Wn[h]!==void 0){e.genre??=Wn[h];break}}e.genre??=p}break;case"TDRC":case"TDAT":{let p=a.readId3V2EncodingAndText(u),g=new Date(p);Number.isNaN(g.getTime())||(e.date??=g)}break;case"TYER":case"TYE":{let p=a.readId3V2EncodingAndText(u),g=Number.parseInt(p,10);Number.isInteger(g)&&(e.date??=new Date(String(g)))}break;case"TBPM":case"TBP":{let p=a.readId3V2EncodingAndText(u),g=Number.parseInt(p,10);Number.isInteger(g)&&(e.beatsPerMinute??=g)}break;case"USLT":case"ULT":{f(4);let p=a.readU8();a.pos+=3,a.readId3V2Text(p,u),e.lyrics??=a.readId3V2Text(p,u)}break;case"COMM":case"COM":{f(4);let p=a.readU8();a.pos+=3,a.readId3V2Text(p,u),e.comment??=a.readId3V2Text(p,u)}break;case"APIC":case"PIC":{f(1);let p=a.readId3V2TextEncoding(),g;if(t.majorVersion===2){f(3);let T=a.readAscii(3);g=T==="PNG"?"image/png":T==="JPG"?"image/jpeg":"image/*"}else g=a.readId3V2Text(p,u);f(1);let h=a.readU8(),y=a.readId3V2Text(p,u).trimEnd(),k=u-a.pos;if(k>=0){let T=a.readBytes(k);e.images||(e.images=[]),e.images.push({data:T,mimeType:g,kind:h===3?"coverFront":h===4?"coverBack":"unknown",description:y})}}break;default:a.pos+=s.size;break}a.pos=c}},ll=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=[];for(let e=0;e<this.bytes.length;e++){let r=this.bytes[e];t.push(r),r===255&&e!==this.bytes.length-1&&this.bytes[e]===0&&e++}this.bytes=new Uint8Array(t),this.view=new DataView(this.bytes.buffer)}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=this.header.majorVersion===4?qs(e):e,n=this.readU16(),a=this.pos,s=o=>{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!s(r)){let o=this.header.majorVersion===4?e:qs(e);s(o)&&(r=o)}return this.pos=a,{id:t,size:r,flags:n}}}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 xi("utf-16le"),s=Ii(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 xi("utf-16be"),s=Ii(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{let a=Ii(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),he.decode(n.subarray(0,a))}case 2:{let a=new xi("utf-16be"),s=Ii(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=Ii(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),he.decode(n.subarray(0,a))}}}readId3V2EncodingAndText(t){if(this.pos>=t)return"";let e=this.readId3V2TextEncoding();return this.readId3V2Text(e,t)}},gi=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 _t(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 u=t.tracksTotal!==void 0?`${c}/${t.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",u),n.add("TRCK")}break;case"discNumber":{let u=t.discsTotal!==void 0?`${c}/${t.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",u),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 u={coverFront:3,coverBack:4,unknown:0};for(let l of c){let d=u[l.kind]??0,m=l.description??"";this.writeId3V2ApicFrame(l.mimeType,d,m,l.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ae(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 u;if(typeof c=="string")if(vt(c)){u=new Uint8Array(c.length+2),u[0]=0;for(let d=0;d<c.length;d++)u[d+1]=c.charCodeAt(d)}else{let d=Z.encode(c);u=new Uint8Array(d.byteLength+2),u[0]=3,u.set(d,1)}else if(c instanceof Uint8Array)u=c;else if(o==="TXXX"&&ks(c)){for(let l in c){let d=c[l],m=vt(l)&&vt(d),f=m?null:Z.encode(l),p=m?null:Z.encode(d),g=m?l.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(l),this.writeIsoString(d)):(this.writer.write(f),this.writeU8(0),this.writer.write(p),this.writeU8(0))}continue}else continue;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(Vd(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=Z.encode(t);this.writer.write(e),this.writeU8(0)}writeId3V2TextFrame(t,e){let r=vt(e),a=1+(r?e.length:Z.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=vt(t),r="",n=4+r.length+1+t.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(e?0:3),this.writeAscii("und"),e?(this.writeIsoString(r),this.writeIsoString(t)):(this.writeUtf8String(r),this.writeUtf8String(t))}writeId3V2CommentFrame(t){let e=vt(t),r=e?t.length:Z.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=vt(t)&&vt(r),s=a?r.length:Z.encode(r).byteLength,o=1+t.length+1+1+s+1+n.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),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 Ie=class{constructor(t){this.mutex=new He;this.trackTimestampInfo=new WeakMap;this.output=t}onTrackClose(t){}validateTimestamp(t,e,r){let n=this.trackTimestampInfo.get(t);if(n){if(r&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&e<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 ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,e)}else{if(!r)throw new Error("First packet must be a key packet.");n={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,n)}}};var rc=class extends Ie{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();this.writer=await this.output._getRootWriter(!0),Cr(this.output._metadataTags)||new gi(this.writer).writeId3V2Tag(this.output._metadataTags),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){Ce(n,e.source._codec);let s=n?.decoderConfig?.description;if(this.inputIsAdts=!s,!this.inputIsAdts){let o=Zt(Q(s)),c=Ts(o);this.header=c.header,this.headerBitstream=c.bitstream}}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;ws(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 xf=new Uint8Array([102,76,97,67]),Vh=38,Uh=34,ic=class extends Ie{constructor(e,r){super(e);this.metadataWritten=!1;this.blockSizes=[];this.frameSizes=[];this.sampleRate=null;this.channels=null;this.bitsPerSample=null;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(xf);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Ce({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.applyDecoderConfig(r.metadata.decoderConfig)),e()}applyDecoderConfig(e){b(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;let r=new H(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:u}){b(this.writer.getPos()===4);let l=!Cr(this.output._metadataTags),d=new H(new Uint8Array(4));d.writeBits(1,+!l),d.writeBits(7,0),d.writeBits(24,Uh),this.writer.write(d.bytes);let m=new H(new Uint8Array(18));if(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),u>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");m.writeBits(4,0),m.writeBits(32,u),this.writer.write(m.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=32+e.mimeType.length+(e.description?.length??0)+e.data.length,n=new Uint8Array(r),a=0,s=N(n);s.setUint32(a,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),a+=4,s.setUint32(a,e.mimeType.length),a+=4,n.set(Z.encode(e.mimeType),8),a+=e.mimeType.length,s.setUint32(a,e.description?.length??0),a+=4,n.set(Z.encode(e.description??""),a),a+=e.description?.length??0,a+=16,s.setUint32(a,e.data.length),a+=4,n.set(e.data,a),a+=e.data.length,b(a===r);let o=new H(new Uint8Array(4));o.writeBits(1,0),o.writeBits(7,6),o.writeBits(24,r),this.writer.write(o.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(Vh+xf.byteLength),Cr(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let a of e)this.writePictureBlock(a);let r=ia(new Uint8Array(0),this.output._metadataTags,!1),n=new H(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&&(Ce(n,e.source._codec),b(n),b(n.decoderConfig),this.applyDecoderConfig(n.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=we.tempFromBytes(r.data);s.skip(2);let o=U(s,2),c=new H(o),u=po(c.readBits(4));if(u===null)throw new Error("Invalid FLAC frame: Invalid block size.");ho(s);let l=go(s,u);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(r.data.length));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=1/0,n=0,a=1/0,s=0,o=0;for(let c=0;c<this.blockSizes.length;c++)a=Math.min(a,this.frameSizes[c]),s=Math.max(s,this.frameSizes[c]),n=Math.max(n,this.blockSizes[c]),o+=this.blockSizes[c],c!==this.blockSizes.length-1&&(r=Math.min(r,this.blockSizes[c]));this.blockSizes.length===0&&(r=16,n=65535,a=0,s=0),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:o})}e()}};var ja=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,zh=/^WEBVTT(.|\n)*?\n{2}/,Hn=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,nc=class{constructor(t){this.preambleText=null;this.preambleEmitted=!1;this.options=t}parse(t){t=t.replaceAll(`\r
8
+ "use strict";var Mediabunny=(()=>{var ip=Object.create;var is=Object.defineProperty;var np=Object.getOwnPropertyDescriptor;var ap=Object.getOwnPropertyNames;var sp=Object.getPrototypeOf,op=Object.prototype.hasOwnProperty;var Fl=(i,t)=>(t=Symbol[i])?t:Symbol.for("Symbol."+i),Ml=i=>{throw TypeError(i)};var cp=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),up=(i,t)=>{for(var e in t)is(i,e,{get:t[e],enumerable:!0})},Bl=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ap(t))!op.call(i,n)&&n!==e&&is(i,n,{get:()=>t[n],enumerable:!(r=np(t,n))||r.enumerable});return i};var Ol=(i,t,e)=>(e=i!=null?ip(sp(i)):{},Bl(t||!i||!i.__esModule?is(e,"default",{value:i,enumerable:!0}):e,i)),lp=i=>Bl(is({},"__esModule",{value:!0}),i);var dt=(i,t,e)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&Ml("Object expected");var r,n;e&&(r=t[Fl("asyncDispose")]),r===void 0&&(r=t[Fl("dispose")],e&&(n=r)),typeof r!="function"&&Ml("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},mt=(i,t,e)=>{var r=typeof SuppressedError=="function"?SuppressedError:function(s,o,c,u){return u=Error(c),u.name="SuppressedError",u.error=s,u.suppressed=o,u},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 Vu=cp(()=>{});var mb={};up(mb,{ADTS:()=>zo,ALL_FORMATS:()=>Vm,ALL_TRACK_TYPES:()=>Fc,AUDIO_CODECS:()=>me,AdtsInputFormat:()=>Fa,AdtsOutputFormat:()=>Ec,AppendOnlyStreamTarget:()=>oc,AttachedFile:()=>xr,AudioBufferSink:()=>ec,AudioBufferSource:()=>Tc,AudioSample:()=>Ae,AudioSampleResource:()=>Dr,AudioSampleSink:()=>Wi,AudioSampleSource:()=>Gn,AudioSource:()=>gr,BaseMediaSampleSink:()=>Un,BlobSource:()=>Io,BufferSource:()=>Po,BufferTarget:()=>yi,CanvasSink:()=>Jo,CanvasSource:()=>yc,CmafOutputFormat:()=>Ki,ConcurrentRunner:()=>as,Conversion:()=>Oc,ConversionCanceledError:()=>jn,CustomAudioDecoder:()=>Ha,CustomAudioEncoder:()=>Ka,CustomPathedSource:()=>_n,CustomSource:()=>Rn,CustomVideoDecoder:()=>Wa,CustomVideoEncoder:()=>qa,EncodedAudioPacketSource:()=>zr,EncodedPacket:()=>j,EncodedPacketSink:()=>st,EncodedVideoPacketSource:()=>Ur,EventEmitter:()=>Je,FLAC:()=>Qu,FilePathSource:()=>vo,FilePathTarget:()=>cc,FlacInputFormat:()=>Ra,FlacOutputFormat:()=>vc,HLS:()=>Lo,HLS_FORMATS:()=>Um,HlsInputFormat:()=>Ui,HlsOutputFormat:()=>Rc,Input:()=>oi,InputAudioTrack:()=>lr,InputDisposedError:()=>ge,InputFormat:()=>Ze,InputTrack:()=>fi,InputVideoTrack:()=>ur,IsobmffInputFormat:()=>Fn,IsobmffOutputFormat:()=>Yi,LogLevel:()=>Yc,Logging:()=>V,MATROSKA:()=>Hu,MP3:()=>Uo,MP4:()=>Do,MPEG_TS:()=>No,MatroskaInputFormat:()=>Mn,MediaSource:()=>ji,MediaStreamAudioTrackSource:()=>wc,MediaStreamVideoTrackSource:()=>kc,MkvOutputFormat:()=>Qn,MovOutputFormat:()=>Gi,Mp3InputFormat:()=>Ea,Mp3OutputFormat:()=>Cc,Mp4InputFormat:()=>Ca,Mp4OutputFormat:()=>Zi,MpegTsInputFormat:()=>Ma,MpegTsOutputFormat:()=>_c,NON_PCM_AUDIO_CODECS:()=>At,NullTarget:()=>ki,OGG:()=>Gu,OggInputFormat:()=>_a,OggOutputFormat:()=>Ic,Output:()=>br,OutputAudioTrack:()=>es,OutputFormat:()=>Le,OutputSubtitleTrack:()=>ts,OutputTrack:()=>Ji,OutputTrackGroup:()=>lt,OutputVideoTrack:()=>Ja,PCM_AUDIO_CODECS:()=>ne,PathedSource:()=>Ye,PathedTarget:()=>ut,QTFF:()=>Vo,QUALITY_HIGH:()=>of,QUALITY_LOW:()=>af,QUALITY_MEDIUM:()=>sf,QUALITY_VERY_HIGH:()=>cf,QUALITY_VERY_LOW:()=>nf,Quality:()=>oe,QuickTimeInputFormat:()=>Pa,RangedSource:()=>Aa,RangedTarget:()=>$a,ReadableStreamSource:()=>Vi,RichImageData:()=>gt,SUBTITLE_CODECS:()=>Xe,Source:()=>Ne,SourceRef:()=>ai,StreamSource:()=>Fm,StreamTarget:()=>Kn,SubtitleSource:()=>$i,Target:()=>Me,TextSubtitleSource:()=>Sc,UnsupportedInputFormatError:()=>Nn,UrlSource:()=>Eo,VIDEO_CODECS:()=>ce,VIDEO_SAMPLE_PIXEL_FORMATS:()=>Ua,VideoSample:()=>Ge,VideoSampleColorSpace:()=>Ni,VideoSampleResource:()=>zt,VideoSampleSink:()=>mi,VideoSampleSource:()=>Xi,VideoSource:()=>hr,WAVE:()=>Ku,WEBM:()=>qu,WavOutputFormat:()=>Pc,WaveInputFormat:()=>va,WebMInputFormat:()=>Ia,WebMOutputFormat:()=>Ti,asc:()=>Af,canDecode:()=>Nm,canDecodeAudio:()=>Ko,canDecodeVideo:()=>qo,canEncode:()=>uf,canEncodeAudio:()=>Na,canEncodeSubtitles:()=>La,canEncodeVideo:()=>za,desc:()=>Qa,getDecodableAudioCodecs:()=>Xu,getDecodableCodecs:()=>Lm,getDecodableVideoCodecs:()=>ju,getEncodableAudioCodecs:()=>On,getEncodableCodecs:()=>lf,getEncodableSubtitleCodecs:()=>rl,getEncodableVideoCodecs:()=>tl,getFirstEncodableAudioCodec:()=>df,getFirstEncodableSubtitleCodec:()=>mf,getFirstEncodableVideoCodec:()=>Zo,prefer:()=>hi,registerDecoder:()=>ff,registerEncoder:()=>pf,registerVideoSampleTransformer:()=>jm});function b(i){if(!i)throw new Error("Assertion failed.")}var ss=Math.PI/180,os=180/Math.PI,yr=i=>{let t=(i%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw new Error(`Invalid rotation ${i}.`)},Wr=[1,0,0,0,1,0,0,0,1],cs=(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 Ht(Ht(Dl(-t/2,-e/2),i),Dl(o/2,c/2))},Si=i=>{let[t,e]=i,r=Math.atan2(e,Lc(i)?-t:t);return yr(fs(r*os,90))},Lc=i=>{let[t,e,,r,n]=i;return t*n-e*r<0},tn=i=>{let t=i*ss,e=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[e,r,0,-r,e,0,0,0,1]},Dl=(i,t)=>[1,0,0,0,1,0,i,t,1],us=(i,t)=>[i,0,0,0,t,0,0,0,1],Ht=(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},ls=(i,t,e,r)=>({rotation:yr(i+(t?-e:e)),flip:t!==r}),Y=i=>i&&i[i.length-1],qt=i=>i>=0&&i<2**32,Ul=i=>i>=-(2**31)&&i<2**31,O=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)},Ai=(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)},Kt=i=>{let t=O(i);return t%2===0?-(t/2):(t+1)/2},zl=(i,t,e,r)=>{for(let n=t;n<e;n++){let a=Math.floor(n/8),s=i[a],o=7-(n&7);s&=~(1<<o),s|=(r&1<<e-n-1)>>e-n-1<<o,i[a]=s}},Q=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),dp=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)}},xi=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 u=s===224?160:s===240?144:128,l=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<u||m>l)break;c=c<<6|m&63,u=128,l=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 u=a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1];if(c+=2,u>=55296&&u<=56319){let l=c+1<e.length?a?e[c]|e[c+1]<<8:e[c]<<8|e[c+1]:-1;l>=56320&&l<=57343?(r.push(u,l),c+=2):r.push(65533)}else u>=56320&&u<=57343?r.push(65533):r.push(u)}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}},he=new xi,Z=new dp,vt=i=>{for(let t=0;t<i.length;t++)if(i.charCodeAt(t)>255)return!1;return!0},Wc=i=>Object.fromEntries(Object.entries(i).map(([t,e])=>[e,t])),Tt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ft=Wc(Tt),wt={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},pt=Wc(wt),St={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ht=Wc(St),rn=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,ds=i=>!i||i.primaries==null&&i.transfer==null&&i.matrix==null&&i.fullRange==null,ms={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},kr=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i),He=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}},Nl=/^[0-9a-fA-F]+$/,Hr=i=>[...i].map(t=>t.toString(16).padStart(2,"0")).join(""),Ll=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},Hc=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),Tr=(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},G=(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},qc=(i,t,e)=>{let r=G(i,e(t),e);i.splice(r+1,0,t)},ee=()=>{let i,t;return{promise:new Promise((r,n)=>{i=r,t=n}),resolve:i,reject:t}},nn=(i,t)=>{let e=i.indexOf(t);e!==-1&&i.splice(e,1)},Kc=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return i[e]},qr=(i,t)=>{for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1},Wl=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},Hl=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},ae=i=>{throw new Error(`Unexpected value: ${i}`)},Ci=(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},ql=(i,t,e)=>Ci(i,t,e)<<8>>8,Pi=(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))},Kl=(i,t,e,r)=>{e=J(e,-8388608,8388607),e<0&&(e=e+16777216&16777215),Pi(i,t,e,r)},Gl=(i,t,e,r)=>{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),!0),i.setUint32(t+4,e,!0))},$n=(i,t)=>({async next(){let e=await i.next();return e.done?{value:void 0,done:!0}:{value:t(e.value),done:!1}},return(){return i.return()},throw(e){return i.throw(e)},[Symbol.asyncIterator](){return this}}),J=(i,t,e)=>Math.max(t,Math.min(e,i)),Ql=(i,t,e)=>i+(t-i)*e,Gc=(i,t)=>i-Math.floor(i/t)*t,se="und",wr=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,Gt=(i,t)=>Math.round(i*t)/t,ps=(i,t)=>Math.floor(i/t)*t,Qc=(i,t)=>Math.floor(i*t)/t,jl=i=>{let t=0;for(;i;)t++,i>>=1;return t},hs=i=>{let t=0;for(;i!==0;)i&=i-1,t++;return t},mp=/^[a-z]{3}$/,Sr=i=>mp.test(i),Qt=1e6*(1+Number.EPSILON),jc=(i,t)=>{let e={...i,...t};if(i.headers||t.headers){let r=i.headers?ns(i.headers):{},n=t.headers?ns(t.headers):{},a={...r};Object.entries(n).forEach(([s,o])=>{let c=Object.keys(a).find(u=>u.toLowerCase()===s.toLowerCase());c&&delete a[c],a[s]=o}),e.headers=a}return e},ns=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},Xc=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(V._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 Kr(1e3*o),n())throw s}},Xl=(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),u=c*a+r,l=c*s+n;if(l>t)return{num:e*a,den:s};if(r=a,n=s,a=u,s=l,o=1/(o-c),!isFinite(o))break}return{num:e*a,den:s}},Lr=class{constructor(){this.currentPromise=Promise.resolve()}call(t){return this.currentPromise=this.currentPromise.then(t)}},Vc=null,jt=()=>Vc!==null?Vc:Vc=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),Uc=null,Xt=()=>Uc!==null?Uc:Uc=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),zc=null,Yn=()=>zc!==null?zc:zc=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Nc=null,$l=()=>{if(Nc!==null)return Nc;if(typeof navigator>"u")return null;let i=/\bChrome\/(\d+)/.exec(navigator.userAgent);return i?Nc=Number(i[1]):null},an=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.`,Yl=i=>i instanceof DOMException&&i.name==="QuotaExceededError"&&/reclaimed/i.test(i.message),fp=(async()=>{})().constructor,_=i=>i instanceof fp||i instanceof Promise?!0:typeof i?.then=="function",Ii=(i,t)=>i!==-1?i:t,gs=(i,t,e,r)=>i<=r&&e<=t,_t=function*(i){for(let t in i){let e=i[t];e!==void 0&&(yield{key:t,value:e})}},Zl=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}},Ei=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},Jl=i=>{let t="";for(let e=0;e<i.length;e++)t+=String.fromCharCode(i[e]);return btoa(t)},bs=(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},sn=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},ve=i=>typeof i=="number"&&!Number.isNaN(i),xe=(i,t)=>{if(t.includes("://"))return t;if(i.includes("://")){let o=i.indexOf("?");o!==-1&&(i=i.slice(0,o))}let e;if(t.startsWith("/")){let o=i.indexOf("://");if(o===-1)e=t;else{let c=i.indexOf("/",o+3);c===-1?e=i+t:e=i.slice(0,c)+t}}else{let o=i.lastIndexOf("/");o===-1?e=t:e=i.slice(0,o+1)+t}let r="",n=e.indexOf("://");if(n!==-1){let o=e.indexOf("/",n+3);o!==-1&&(r=e.slice(0,o),e=e.slice(o))}let a=e.split("/"),s=[];for(let o of a)o===".."?s.pop():o!=="."&&s.push(o);return r+s.join("/")},ed=(i,t)=>{let e=i.indexOf("?");if(e===-1)return null;let r=i.indexOf("#",e),n=i.slice(e+1,r===-1?void 0:r);for(let a of n.split("&")){let s=a.indexOf("="),o=s===-1?a:a.slice(0,s),c=s===-1?"":a.slice(s+1);try{if(decodeURIComponent(o)===t)return decodeURIComponent(c)}catch{}}return null},vi=(i,t)=>{let e=0;for(let r=0;r<i.length;r++)t(i[r])&&e++;return e},on=(i,t)=>{let e=-1,r=1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);a<r&&(r=a,e=n)}return e},td=(i,t)=>{let e=-1,r=-1/0;for(let n=0;n<i.length;n++){let a=t(i[n]);a>r&&(r=a,e=n)}return e},Ar=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}},ys=(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.`)},Xn,pp=1,Vl=new Map,$c=new Map,rd=()=>typeof window>"u",hp=()=>{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}}},id=()=>{if(Xn)return Xn;let i=`(${hp.toString()})();`,t=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));return Xn=new Worker(t),URL.revokeObjectURL(t),Xn.onmessage=e=>{let r=e.data,n=Vl.get(r.timerId);if(n){Vl.delete(r.timerId),n();return}let a=$c.get(r.timerId);a&&a()},Xn};var nd=(i,t)=>{if(rd())return{id:setInterval(i,t)};let e=pp++;return $c.set(e,()=>{i()}),id().postMessage({type:"set-interval",timerId:e,delay:t}),{id:e}},ad=i=>{if(rd()){clearInterval(i.id);return}b(typeof i.id=="number"),$c.delete(i.id),id().postMessage({type:"clear-interval",timerId:i.id})},Kr=i=>new Promise(t=>setTimeout(t,i));var $t=i=>Array.isArray(i)?i:[i],Je=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){try{a.fn(r)}catch(s){console.error(s)}a.once&&n.delete(a)}}},_i=i=>Math.ceil(i/2)*2,as=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(()=>nn(this._queue,e)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}},ks=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(t=>typeof t=="string");var Yc=(n=>(n[n.Silent=0]="Silent",n[n.Errors=1]="Errors",n[n.Warnings=2]="Warnings",n[n.Info=3]="Info",n))(Yc||{}),et=class et{constructor(){}static get level(){return et._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.");et._level=t}static get _emitter(){return et._emitterInstance??=new Je}static on(t,e,r){return et._emitter.on(t,e,r)}static _error(...t){et._emitter._emit("error",t),et._level>=1&&console.error(...t)}static _warn(...t){et._emitter._emit("warn",t),et._level>=2&&console.warn(...t)}static _info(...t){et._emitter._emit("info",t),et._level>=3&&console.info(...t)}};et._level=3,et._emitterInstance=null;var V=et;var gt=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.")}},xr=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.")}},Zn=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.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(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)&&!(t instanceof gt)&&!(t instanceof xr)&&!ks(t))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Cr=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),_e={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},sd=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 H=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<<=1,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);s&=~(1<<o),s|=(e&1<<r-n-1)>>r-n-1<<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 tt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Yt=[-1,1,2,3,4,5,6,8],Zt=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");let t=new H(i),e=Zc(t),{frequencyIndex:r,sampleRate:n}=Jc(t),a=t.readBits(4),s=null;a>=1&&a<=7&&(s=Yt[a]);let o=e,c=!1,u=n;if(e===5||e===29)c=e===29,u=Jc(t).sampleRate,o=Zc(t),o===22&&t.skipBits(4);else for(;t.getBitsLeft()>15;){let l=t.pos;if(t.readBits(11)!==695){t.pos=l+1;continue}Zc(t)===5&&t.readBits(1)&&(u=Jc(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,outputSampleRate:u,outputNumberOfChannels:c&&s===1?2:s}},Zc=i=>{let t=i.readBits(5);return t===31?32+i.readBits(6):t},Jc=i=>{let t=i.readBits(4);return t===15?{frequencyIndex:t,sampleRate:i.readBits(24)}:{frequencyIndex:t,sampleRate:t<tt.length?tt[t]:null}},cn=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=Yt.indexOf(n);if(a===-1)throw new TypeError(`Unsupported number of channels: ${i.outputNumberOfChannels}`);let s=16;i.objectType>=32&&(s+=6),eu(r)===15&&(s+=24),t&&(s+=9,eu(i.outputSampleRate)===15&&(s+=24));let o=Math.ceil(s/8),c=new Uint8Array(o),u=new H(c);return od(u,i.objectType),cd(u,r),u.writeBits(4,a),t&&(cd(u,i.outputSampleRate),od(u,2)),u.writeBits(3,0),c},od=(i,t)=>{t<32?i.writeBits(5,t):(i.writeBits(5,31),i.writeBits(6,t-32))},cd=(i,t)=>{let e=eu(t);i.writeBits(4,e),e===15&&i.writeBits(24,t)},eu=i=>{let t=tt.indexOf(i);return t===-1?15:t},Ts=i=>{let t=new Uint8Array(7),e=new H(t),{coreObjectType:r,frequencyIndex:n,channelConfiguration:a}=i,s=r-1;return e.writeBits(12,4095),e.writeBits(1,0),e.writeBits(2,0),e.writeBits(1,1),e.writeBits(2,s),e.writeBits(4,n),e.writeBits(1,0),e.writeBits(3,a),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.writeBits(1,0),e.skipBits(13),e.writeBits(11,2047),e.writeBits(2,0),{header:t,bitstream:e}},ws=(i,t)=>{i.pos=30,i.writeBits(13,t)};var Ri=[48e3,44100,32e3],tu=[24e3,22050,16e3];var gp="1.62.1",Pr=`Mediabunny v${gp}`;var Gr=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})},As=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=Ci(r,e,!1):(b(t===4),n=r.getUint32(e,!1)),e+=t,yield{offset:e,length:n},e+=n}},iu=(i,t)=>{if(t.description){let n=(Q(t.description)[4]&3)+1;return As(i,n)}else return Gr(i)},Jt=i=>i&31,xs=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)},bp=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)},ru=new Uint8Array([0,0,0,1]),ta=i=>{let t=i.reduce((n,a)=>n+ru.byteLength+a.byteLength,0),e=new Uint8Array(t),r=0;for(let n of i)e.set(ru,r),r+=ru.byteLength,e.set(n,r),r+=n.byteLength;return e},Cs=(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:Pi(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},md=(i,t)=>{if(t.description){let n=(Q(t.description)[4]&3)+1;return Cs(i,n)}else return ta(i)},er=i=>{try{let t=[],e=[],r=[];for(let o of Gr(i)){let c=i.subarray(o.offset,o.offset+o.length),u=Jt(c[0]);u===7&&t.length<31?t.push(c):u===8&&e.length<255?e.push(c):u===13&&r.length<255&&r.push(c)}if(t.length===0||e.length===0)return null;let n=t[0],a=rr(n);if(!a)return null;let s=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;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 V._error("Error building AVC Decoder Configuration Record:",t),null}},un=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((i.avcProfileIndication===100||i.avcProfileIndication===110||i.avcProfileIndication===122||i.avcProfileIndication===144)&&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)},tr=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,u=[];for(let f=0;f<c;f++){let p=t.getUint16(e,!1);e+=2,u.push(i.subarray(e,e+p)),e+=p}let l=t.getUint8(e++),d=[];for(let f=0;f<l;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:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((n===100||n===110||n===122||n===144)&&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 w=t.getUint16(e,!1);e+=2,y.push(i.subarray(e,e+w)),e+=w}m.sequenceParameterSetExt=y}return m}catch(t){return V._error("Error deserializing AVC Decoder Configuration Record:",t),null}},fd={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}},rr=i=>{try{let t=xs(i),e=new H(t);if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;let n=e.readAlignedByte(),a=e.readAlignedByte(),s=e.readAlignedByte();O(e);let o=1,c=0,u=0,l=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(o=O(e),o===3&&(l=e.readBits(1)),c=O(e),u=O(e),e.skipBits(1),e.readBits(1))){for(let D=0;D<(o!==3?8:12);D++)if(e.readBits(1)){let ie=D<6?16:64,be=8,Te=8;for(let Wt=0;Wt<ie;Wt++){if(Te!==0){let yt=Kt(e);Te=(be+yt+256)%256}be=Te===0?be:Te}}}O(e);let d=O(e);if(d===0)O(e);else if(d===1){e.skipBits(1),Kt(e),Kt(e);let z=O(e);for(let D=0;D<z;D++)Kt(e)}O(e),e.skipBits(1);let m=O(e),f=O(e),p=16*(m+1),g=16*(f+1),h=p,y=g,k=e.readBits(1);if(k||e.skipBits(1),e.skipBits(1),e.readBits(1)){let z=O(e),D=O(e),q=O(e),ie=O(e),be,Te;if((l===0?o:0)===0)be=1,Te=2-k;else{let yt=o===3?1:2,Qe=o===1?2:1;be=yt,Te=Qe*(2-k)}h-=be*(z+D),y-=Te*(q+ie)}if(h<=0||y<=0)return null;let T=2,S=2,x=2,C=0,P={num:1,den:1},A=null,I=null,E=null,v=null,R=e.pos;if(e.readBits(1)){if(e.readBits(1)){let yt=e.readBits(8);if(yt===255)P={num:e.readBits(16),den:e.readBits(16)};else{let Qe=fd[yt];Qe&&(P=Qe)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),C=e.readBits(1),e.readBits(1)&&(T=e.readBits(8),S=e.readBits(8),x=e.readBits(8))),e.readBits(1)&&(O(e),O(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));let Te=e.readBits(1);Te&&ud(e);let Wt=e.readBits(1);Wt&&ud(e),(Te||Wt)&&e.skipBits(1),e.skipBits(1),E=e.pos,v=e.readBits(1),v&&(e.skipBits(1),O(e),O(e),O(e),O(e),A=Math.min(O(e),16),I=Math.min(O(e),16))}if(A===null){b(I===null);let z=a&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&z)A=0,I=0;else{let D=m+1,q=f+1,ie=(2-k)*q,be=ea.find(Wt=>Wt.level>=s)??Y(ea),Te=Math.min(Math.floor(be.maxDpbMbs/(D*ie)),16);A=Te,I=Te}}return b(I!==null),{emulationUnpreventedBytes:t,profileIdc:n,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:u,codedWidth:p,codedHeight:g,displayWidth:h,displayHeight:y,pixelAspectRatio:P,colourPrimaries:T,matrixCoefficients:x,transferCharacteristics:S,fullRangeFlag:C,numReorderFrames:A,maxDecFrameBuffering:I,vuiParametersFlagBitOffset:R,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:v}}catch(t){return V._error("Error parsing AVC SPS:",t),null}},ud=i=>{let t=O(i);i.skipBits(4),i.skipBits(4);for(let e=0;e<=t;e++)O(i),O(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},nu=i=>{b(i.bitstreamRestrictionFlag!==1);let t=new Uint8Array(i.emulationUnpreventedBytes.byteLength+64),e=new H(i.emulationUnpreventedBytes),r=new H(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),Ai(r,2),Ai(r,1),Ai(r,16),Ai(r,16),Ai(r,i.numReorderFrames),Ai(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)),bp(t.subarray(0,n))},yp=(i,t)=>{if(t.description){let n=(Q(t.description)[21]&3)+1;return Cs(i,n)}else return ta(i)},Jn=(i,t)=>{if(t.description){let n=(Q(t.description)[21]&3)+1;return As(i,n)}else return Gr(i)},Rt=i=>i>>1&63,Fi=i=>{try{let t=new H(xs(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:u}=kp(t,e);O(t);let l=O(t),d=0;l===3&&(d=t.readBits(1));let m=O(t),f=O(t),p=m,g=f;if(t.readBits(1)){let v=O(t),R=O(t),B=O(t),z=O(t),D=1,q=1,ie=d===0?l:0;ie===1?(D=2,q=2):ie===2&&(D=2,q=1),p-=(v+R)*D,g-=(B+z)*q}if(p<=0||g<=0)return null;let h=O(t),y=O(t);O(t);let w=t.readBits(1)?0:e,T=0;for(let v=w;v<=e;v++)O(t),T=O(t),O(t);O(t),O(t),O(t),O(t),O(t),O(t),t.readBits(1)&&t.readBits(1)&&Tp(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),O(t),O(t),t.skipBits(1));let S=O(t);if(wp(t,S),t.readBits(1)){let v=O(t);for(let R=0;R<v;R++)O(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let x=2,C=2,P=2,A=0,I=0,E={num:1,den:1};if(t.readBits(1)){let v=Ap(t,e);E=v.pixelAspectRatio,x=v.colourPrimaries,C=v.transferCharacteristics,P=v.matrixCoefficients,A=v.fullRangeFlag,I=v.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:E,colourPrimaries:x,transferCharacteristics:C,matrixCoefficients:P,fullRangeFlag:A,maxDecFrameBuffering:Math.min(T+1,16),spsMaxSubLayersMinus1:e,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:s,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:l,bitDepthLumaMinus8:h,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:I}}catch(t){return V._error("Error parsing HEVC SPS:",t),null}},ir=i=>{try{let t=[],e=[],r=[],n=[];for(let l of Gr(i)){let d=i.subarray(l.offset,l.offset+l.length),m=Rt(d[0]);m===32&&t.length<65535?t.push(d):m===33&&e.length<65535?e.push(d):m===34&&r.length<65535?r.push(d):(m===39||m===40)&&n.length<65535&&n.push(d)}if(e.length===0||r.length===0)return null;let s=Fi(e[0]);if(!s)return null;let o=0;if(r.length>0){let l=r[0],d=new H(xs(l));d.skipBits(16),O(d),O(d),d.skipBits(1),d.skipBits(1),d.skipBits(3),d.skipBits(1),d.skipBits(1),O(d),O(d),Kt(d),d.skipBits(1),d.skipBits(1),d.readBits(1)&&O(d),Kt(d),Kt(d),d.skipBits(1),d.skipBits(1),d.skipBits(1),d.skipBits(1);let m=d.readBits(1),f=d.readBits(1);!m&&!f?o=0:m&&!f?o=2:!m&&f?o=3:o=0}let c=[...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:1,nalUnitType:Rt(n[0][0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(t){return V._error("Error building HEVC Decoder Configuration Record:",t),null}},kp=(i,t)=>{let e=i.readBits(2),r=i.readBits(1),n=i.readBits(5),a=0;for(let l=0;l<32;l++)a=a<<1|i.readBits(1);let s=new Uint8Array(6);for(let l=0;l<6;l++)s[l]=i.readBits(8);let o=i.readBits(8),c=[],u=[];for(let l=0;l<t;l++)c.push(i.readBits(1)),u.push(i.readBits(1));if(t>0)for(let l=t;l<8;l++)i.skipBits(2);for(let l=0;l<t;l++)c[l]&&i.skipBits(88),u[l]&&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}},Tp=i=>{for(let t=0;t<4;t++)for(let e=0;e<(t===3?2:6);e++)if(!i.readBits(1))O(i);else{let n=Math.min(64,1<<4+(t<<1));t>1&&Kt(i);for(let a=0;a<n;a++)Kt(i)}},wp=(i,t)=>{let e=[];for(let r=0;r<t;r++)e[r]=Sp(i,r,t,e)},Sp=(i,t,e,r)=>{let n=0,a=0,s=0;if(t!==0&&(a=i.readBits(1)),a){if(t===e){let c=O(i);s=t-(c+1)}else s=t-1;i.readBits(1),O(i);let o=r[s]??0;for(let c=0;c<=o;c++)i.readBits(1)||i.readBits(1);n=r[s]}else{let o=O(i),c=O(i);for(let u=0;u<o;u++)O(i),i.readBits(1);for(let u=0;u<c;u++)O(i),i.readBits(1);n=o+c}return n},Ap=(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 u=fd[c];u&&(o=u)}}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)&&(O(i),O(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(O(i),O(i),O(i),O(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&O(i),i.readBits(1)&&xp(i,!0,t)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),s=O(i),O(i),O(i),O(i),O(i)),{pixelAspectRatio:o,colourPrimaries:e,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:a,minSpatialSegmentationIdc:s}},xp=(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 u=!1;c?O(i):u=i.readBits(1)===1;let l=1;u||(l=O(i)+1),r&&ld(i,l,a),n&&ld(i,l,a)}},ld=(i,t,e)=>{for(let r=0;r<t;r++)O(i),O(i),e&&(O(i),O(i)),i.readBits(1)},pd=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)},ln=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 u=i.subarray(e,e+6);e+=6;let l=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,w=y>>3&7,T=y>>2&1,S=y&3,x=t.getUint8(e++),C=[];for(let P=0;P<x;P++){let A=t.getUint8(e++),I=A>>7&1,E=A&63,v=t.getUint16(e,!1);e+=2;let R=[];for(let B=0;B<v;B++){let z=t.getUint16(e,!1);e+=2,R.push(i.subarray(e,e+z)),e+=z}C.push({arrayCompleteness:I,nalUnitType:E,nalUnits:R})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:l,minSpatialSegmentationIdc:d,parallelismType:m,chromaFormatIdc:f,bitDepthLumaMinus8:p,bitDepthChromaMinus8:g,avgFrameRate:h,constantFrameRate:k,numTemporalLayers:w,temporalIdNested:T,lengthSizeMinusOne:S,arrays:C}}catch(t){return V._error("Error deserializing HEVC Decoder Configuration Record:",t),null}};var hd=(i,t)=>{let e=new Set,r=0;for(let a of Jn(i,t)){if(r===4){e.add(a.offset);continue}let s=Rt(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 Jn(i,t))e.has(a.offset)||n.push(i.subarray(a.offset,a.offset+a.length));return yp(n,t)},Cp={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}},dn=i=>{let t=new H(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 u=8;a>=2&&(u=t.readBits(1)?12:10);let l=t.readBits(3),d=0,m=0;if(l!==7)if(m=t.readBits(1),a===1||a===3){let P=t.readBits(1),A=t.readBits(1);d=!P&&!A?3:P&&!A?2:1,t.skipBits(1)}else d=1;else d=3,m=1;let f=t.readBits(16),p=t.readBits(16),g=f+1,h=p+1,y=g*h,k=Y(Ir).level;for(let C of Ir)if(y<=C.maxPictureSize){k=C.level;break}let w=Cp[l],T=w?.colourPrimaries??2,S=w?.transferCharacteristics??2,x=w?.matrixCoefficients??2;return{profile:a,level:k,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:m,colourPrimaries:T,transferCharacteristics:S,matrixCoefficients:x}},gd=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,bd=function*(i){let t=new H(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)}},Mi=i=>{for(let{type:t,data:e}of bd(i)){if(t!==1)continue;let r=new H(e),n=r.readBits(3),a=r.readBits(1),s=r.readBits(1),o=0,c=0,u=0;if(s)o=r.readBits(5);else{let I=r.readBits(1),E=0;if(I){if(r.skipBits(32),r.skipBits(32),r.readBits(1)){let z=0;for(;z<32&&!r.readBits(1);)z++;z<32&&r.skipBits(z)}E=r.readBits(1),E&&(u=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5))}let v=r.readBits(1),R=r.readBits(5);for(let B=0;B<=R;B++){r.skipBits(12);let z=r.readBits(5);if(B===0&&(o=z),z>7){let D=r.readBits(1);B===0&&(c=D)}if(E&&r.readBits(1)){let q=u+1;r.skipBits(q),r.skipBits(q),r.skipBits(1)}v&&r.readBits(1)&&r.skipBits(4)}}let l=r.readBits(4),d=r.readBits(4),m=l+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 I=r.readBits(1);I&&(r.skipBits(1),r.skipBits(1));let E=r.readBits(1),v=0;E?v=2:v=r.readBits(1),v>0&&(r.readBits(1)||r.skipBits(1)),I&&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,w=2,T=2;r.readBits(1)&&(k=r.readBits(8),w=r.readBits(8),T=r.readBits(8));let x=0,C=1,P=1,A=0;return y?x=r.readBits(1):k===1&&w===13&&T===0?(x=1,C=0,P=0):(x=r.readBits(1),n===0?(C=1,P=1):n===1?(C=0,P=0):h===12?(C=r.readBits(1),P=C?r.readBits(1):0):(C=1,P=0),C&&P&&(A=r.readBits(2))),{profile:n,level:o,tier:c,bitDepth:h,monochrome:y,chromaSubsamplingX:C,chromaSubsamplingY:P,chromaSamplePosition:A,videoFullRangeFlag:x,colourPrimaries:k,transferCharacteristics:w,matrixCoefficients:T}}return null},Ps=i=>i.colourPrimaries!==2||i.transferCharacteristics!==2||i.matrixCoefficients!==2,Is=i=>{if(i.length<36)return null;let e=N(i);return e.getUint32(4)!==1768124518||e.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:e.getUint8(22),transferCharacteristics:e.getUint8(23),matrixCoefficients:e.getUint8(24)}},Qr=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,21+e)),{outputChannelCount:e,preSkip:r,inputSampleRate:n,outputGain:a,channelMappingFamily:s,channelMappingTable:o}},Pp=[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],yd=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:Pp[t]*r}},Es=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 H(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 u=c;n.pos=0,n.skipBits(a);let l=Array(u).fill(0);for(let d=u-1;d>=0;d--)n.skipBits(40),l[d]=n.readBits(1);return{modeBlockflags:l}},jr=(i,t,e)=>{switch(i){case"avc":{for(let r of iu(e,t)){let n=e[r.offset],a=Jt(n);if(a>=1&&a<=4)return"delta";if(a===5)return"key";if(a===6&&!Yn()){let s=e.subarray(r.offset,r.offset+r.length),o=xs(s),c=1;do{let u=0;for(;;){let m=o[c++];if(m===void 0||(u+=m,m<255))break}let l=0;for(;;){let m=o[c++];if(m===void 0||(l+=m,m<255))break}if(u===6){let m=new H(o);m.pos=8*c;let f=-1;try{f=O(m)}catch{}let p=m.readBits(1);if(f===0&&p===1)return"key"}c+=l}while(c<o.length-1)}}return"delta"}case"hevc":{for(let r of Jn(e,t)){let n=Rt(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 H(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 bd(e))if(n===1){let s=new H(a);s.skipBits(4),r=!!s.readBits(1)}else if(n===3||n===6||n===7){if(r)return"key";let s=new H(a);return s.readBits(1)?null:s.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:ae(i),b(!1)}};var ra=(i,t)=>{let e=N(i),r=0;if(i.length<4)return;let n=e.getUint32(r,!0);r+=4;let a=he.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 u=he.decode(i.subarray(r,r+c));r+=c;let l=u.indexOf("=");if(l===-1)continue;let d=u.slice(0,l).toUpperCase(),m=u.slice(l+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=new Date(m);Number.isNaN(f.getTime())||(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=Ei(m),p=N(f),g=p.getUint32(0,!1),h=p.getUint32(4,!1),y=he.decode(f.subarray(8,8+h)),k=p.getUint32(8+h,!1),w=he.decode(f.subarray(12+h,12+h+k)),T=p.getUint32(h+k+28),S=f.subarray(h+k+32,h+k+32+T);t.images??=[],t.images.push({data:S,mimeType:y,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:w||void 0})}catch{}break}}},ia=(i,t,e)=>{let r=[i],n=Z.encode(Pr),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=Z.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 _t(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 x=0;x<g.mimeType.length;x++)y[x]=g.mimeType.charCodeAt(x);let k=Z.encode(g.description??""),w=new Uint8Array(8+y.length+4+k.length+16+4+g.data.length),T=N(w);T.setUint32(0,h,!1),T.setUint32(4,y.length,!1),w.set(y,8),T.setUint32(8+y.length,k.length,!1),w.set(k,12+y.length),T.setUint32(28+y.length+k.length,g.data.length,!1),w.set(g.data,32+y.length+k.length);let S=Jl(w);c("METADATA_BLOCK_PICTURE",S)}}break;case"raw":break;default:ae(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))){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 u=new Uint8Array(4);N(u).setUint32(0,o.length,!0),r.splice(2,0,u);let l=r.reduce((f,p)=>f+p.length,0),d=new Uint8Array(l),m=0;for(let f of r)d.set(f,m),m+=f.length;return d},na=[2,1,2,3,3,4,4,5],vs=i=>{if(i.length<7||i[0]!==11||i[1]!==119)return null;let t=new H(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}},kd=[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],Td=1536,aa=new Uint8Array([5,4,65,67,45,51]),sa=new Uint8Array([5,4,69,65,67,51]),au=[1,2,3,6],_s=i=>{if(i.length<6||i[0]!==11||i[1]!==119)return null;let t=new H(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),u=t.readBits(5);if(u<11||u>16)return null;let l=au[s],d;return n<3?d=Ri[n]/1e3:d=tu[a]/1e3,{dataRate:Math.round((r+1)*d/(l*16)),substreams:[{fscod:n,fscod2:a,bsid:u,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},wd=i=>{if(i.length<2)return null;let t=new H(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),u=t.readBits(3),l=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:u,lfeon:l,numDepSub:d,chanLoc:m})}return n.length===0?null:{dataRate:e,substreams:n}},Rs=i=>{let t=i.substreams[0];return b(t),t.fscod<3?Ri[t.fscod]:t.fscod2!==null&&t.fscod2<3?tu[t.fscod2]:null},Fs=i=>{let t=i.substreams[0];b(t);let e=na[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<<8-n&&(e+=r[n])}return e};var Ip=1683496997,oa=18,Ms=10,Sd=4096,dd=32,Bs=20,Ep=8,vp=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],_p=[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],Rp=[16,16,20,20,0,24,24,0],Ss=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Fp=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Mp=8,Bp=44646,Op=[32e3,44100,48e3,0],Dp=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ad=[512,1024,2048,4096],ca=i=>{let t=su(i),e=N(i),r=t?Math.ceil(t.frameSize/4)*4:0,n=null;for(;r+4<=i.length&&e.getUint32(r)===Ip;){let s=ua(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}},Os=i=>{let t=ca(i);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},su=i=>{if(i.length<oa||i[0]!==127||i[1]!==254||i[2]!==128||i[3]!==1)return null;let t=new H(i);if(t.skipBits(32),t.skipBits(1),t.readBits(5)!==dd-1)return null;let e=t.readBits(1),r=t.readBits(7)+1;if(r%Ep!==0)return null;let n=t.readBits(14)+1;if(n<96)return null;let a=t.readBits(6);if(a>=Ss.length)return null;let s=vp[t.readBits(4)];if(s===0)return null;let o=_p[t.readBits(5)];if(t.readBits(1)!==0)return null;t.skipBits(4),t.skipBits(5);let c=t.readBits(2);if(c===3)return null;t.skipBits(1),e&&t.skipBits(16),t.skipBits(7);let u=Rp[t.readBits(3)];if(u===0)return null;let l=c!==0;return{frameSize:n,sampleRate:s,numberOfChannels:Ss[a]+(l?1:0),sampleCount:r*dd,channelLayout:Fp[a]|(l?Mp:0),amode:a,lfePresent:l,bitRate:o,pcmResolution:u}},ua=i=>{if(i.length<Ms||i[0]!==100||i[1]!==88||i[2]!==32||i[3]!==37)return null;let t=new H(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=Op[t.readBits(2)],u=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let l=t.readBits(3)+1,d=t.readBits(3)+1,m=[];for(let y=0;y<l;y++)m.push(t.readBits(e+1));for(let y of m)t.skipBits(8*hs(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=Dp[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(u*p/c),channelLayout:h,pcmResolution:f}}},xd=i=>{if(i.length<Bs)return null;let t=N(i),e=t.getUint32(0);if(e===0)return null;let r=new H(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=Vp(o):s<Ss.length&&(c=Ss[s]+a),{sampleRate:e,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:i[12],sampleCount:Ad[n],channelLayout:o,numberOfChannels:c}},Cd=i=>{let t=new Uint8Array(Bs),e=N(t);e.setUint32(0,i.sampleRate),e.setUint32(4,i.bitRate),e.setUint32(8,i.bitRate),t[12]=i.pcmResolution;let r=i.core&&!i.hasExtensions?1:0,n=new H(t);return n.seekToByte(13),n.writeBits(2,Math.max(Ad.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},Vp=i=>hs(i)+hs(i&Bp);var ce=["avc","hevc","vp9","av1","vp8","prores"],ne=["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"],At=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],me=[...At,...ne],Xe=["webvtt"],ea=[{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}],Pd=[{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}],Ir=[{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}],Id=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],Ed=".01.01.01.01.00",vd=".0.110.01.01.01.0",Er=["ap4x","ap4h","apch","apcn","apcs","apco"],la=["dtsc","dtsh","dtsl","dtse"],Up=[{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}],Vs=(i,t,e,r,n)=>{if(i==="avc"){let s=Math.ceil(t/16)*Math.ceil(e/16),o=ea.find(m=>s<=m.maxMacroblocks&&r<=m.maxBitrate)??Y(ea),c=o?o.level:0,u="64".padStart(2,"0"),l="00",d=c.toString(16).padStart(2,"0");return`avc1.${u}${l}${d}`}else if(i==="hevc"){let a="",o="6",c=t*e,u=Pd.find(d=>c<=d.maxPictureSize&&r<=d.maxBitrate)??Y(Pd);return`hev1.${a}1.${o}.${u.tier}${u.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){let a="00",s=t*e,o=Ir.find(u=>s<=u.maxPictureSize&&r<=u.maxBitrate)??Y(Ir);return`vp09.${a}.${o.level.toString().padStart(2,"0")}.08`}else if(i==="av1"){let s=t*e,o=Id.find(l=>s<=l.maxPictureSize&&r<=l.maxBitrate)??Y(Id);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=Up.filter(l=>l.alpha===n),c=o[0].fourCc,u=1/0;for(let{fourCc:l,bitrate:d}of o){let m=Math.abs(d*s-r);m<u&&(u=m,c=l)}return c}else ae(i)}throw new TypeError(`Unhandled codec '${String(i)}'.`)},_d=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]},Us=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,u=s.slice(-1)==="H"?1:0,l=Number(t[3]),d=l===8?0:1,m=l===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=(u<<7)+(d<<6)+(m<<5)+(f<<4)+(p<<3)+(g<<2)+h;return[n,c,y,0]},Xr=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 u=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${i.avcType}.${Hr(u)}`}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}.${Hr(e.subarray(1,4))}`}else if(t==="hevc"){let u,l,d,m,f,p;if(a)u=a.generalProfileSpace,l=a.generalProfileIdc,d=Hc(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);u=y>>6&3,l=y&31,d=Hc(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="hev1.";for(g+=["","A","B","C"][u]+l,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"){if(!s){let k=i.width*i.height,w=Y(Ir).level;for(let T of Ir)if(k<=T.maxPictureSize){w=T.level;break}return`vp09.00.${w.toString().padStart(2,"0")}.08`}let u=s.profile.toString().padStart(2,"0"),l=s.level.toString().padStart(2,"0"),d=s.bitDepth.toString().padStart(2,"0"),m=s.chromaSubsampling.toString().padStart(2,"0"),f=s.colourPrimaries.toString().padStart(2,"0"),p=s.transferCharacteristics.toString().padStart(2,"0"),g=s.matrixCoefficients.toString().padStart(2,"0"),h=s.videoFullRangeFlag.toString().padStart(2,"0"),y=`vp09.${u}.${l}.${d}.${m}`;return y+=`.${f}.${p}.${g}.${h}`,y.endsWith(Ed)&&(y=y.slice(0,-Ed.length)),y}else if(t==="av1"){if(!o){let T=i.width*i.height,S=Y(Ir).level;for(let x of Ir)if(T<=x.maxPictureSize){S=x.level;break}return`av01.0.${S.toString().padStart(2,"0")}M.08`}let u=o.profile,l=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;Ps(o)?(g=o.colourPrimaries,h=o.transferCharacteristics,y=o.matrixCoefficients,k=o.videoFullRangeFlag):(g=r?.primaries?Tt[r.primaries]:1,h=r?.transfer?wt[r.transfer]:1,y=r?.matrix?St[r.matrix]:1,k=r?.fullRange?1:0);let w=`av01.${u}.${l}${d}.${m}`;return w+=`.${f}.${p.toString().padStart(3,"0")}`,w+=`.${g.toString().padStart(2,"0")}`,w+=`.${h.toString().padStart(2,"0")}`,w+=`.${y.toString().padStart(2,"0")}`,w+=`.${k}`,w.endsWith(vd)&&(w=w.slice(0,-vd.length)),w}else{if(t==="prores")return c??"apch";t!==null&&ae(t)}}throw new TypeError(`Unhandled codec '${t}'.`)},zs=i=>{switch(i.codec){case"avc":{let t=i.avcCodecInfo?.sequenceParameterSets[0];if(!t&&i.codecDescription&&(t=tr(i.codecDescription)?.sequenceParameterSets[0]),t){let e=rr(t);if(e)return{primaries:ft[e.colourPrimaries],transfer:pt[e.transferCharacteristics],matrix:ht[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=ln(i.codecDescription)?.arrays.find(e=>e.nalUnitType===33)?.nalUnits[0]),t){let e=Fi(t);if(e)return{primaries:ft[e.colourPrimaries],transfer:pt[e.transferCharacteristics],matrix:ht[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(i.vp9CodecInfo)return{primaries:ft[i.vp9CodecInfo.colourPrimaries],transfer:pt[i.vp9CodecInfo.transferCharacteristics],matrix:ht[i.vp9CodecInfo.matrixCoefficients],fullRange:!!i.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(i.av1CodecInfo)return{primaries:ft[i.av1CodecInfo.colourPrimaries],transfer:pt[i.av1CodecInfo.transferCharacteristics],matrix:ht[i.av1CodecInfo.matrixCoefficients],fullRange:!!i.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(i.proresCodecInfo)return{primaries:ft[i.proresCodecInfo.colourPrimaries],transfer:pt[i.proresCodecInfo.transferCharacteristics],matrix:ht[i.proresCodecInfo.matrixCoefficients],fullRange:i.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Ns=(i,t,e)=>{if(i==="aac")return t>=2&&e<=24e3?"mp4a.40.29":e<=24e3?"mp4a.40.5":"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(ne.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},mn=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=Zt(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&&ne.includes(t))return t}throw new TypeError(`Unhandled codec '${t}'.`)},Rd=i=>{},Fd=i=>{switch(i.codec){case"flac":{let t=Ei("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=Ei("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}},Ft=48e3,Md=/^pcm-([usf])(\d+)(be)?$/,Re=i=>{if(b(ne.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=Md.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}},rt=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":Er.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"?"flac":i==="ac-3"||i==="ac3"?"ac3":i==="ec-3"||i==="eac3"?"eac3":la.includes(i)?"dts":i==="ulaw"?"ulaw":i==="alaw"?"alaw":Md.test(i)?i:i==="webvtt"?"webvtt":null,Bd=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},Od=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},zp=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Er],Np=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Lp=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Wp=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Hp=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,nr=(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(!zp.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&&!kr(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(Tt);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(wt);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(St);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(!Np.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(!Lp.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(!Wp.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(!Hp.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(Er.some(e=>i.decoderConfig.codec.startsWith(e))&&!Er.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: ${Er.join(", ")}.`);if(t!==null&&rt(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}'.`)},qp=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],Ce=(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(!qp.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&&!kr(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.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("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!ne.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ne.join(", ")}).`);if(t!==null&&rt(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}'.`)},Ls=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 ou=[44100,48e3,32e3],Ws=[-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],$r=1483304551,fn=1231971951,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,Dd=(i,t,e,r)=>t===0?0:t===1?144*e/(r<<i):t===2?144*e/r:12*e/r*4,Yr=(i,t)=>i===3?t===3?21:36:t===3?13:21,Zr=(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,u=r>>1&3,l=n>>4&15,d=(n>>2&3)%3,m=n>>1&1,f=a>>6&3,p=a>>4&3,g=a>>3&1,h=a>>2&1,y=a&3,k=Ws[s*16*4+u*16+l];if(k===-1)return{header:null,bytesAdvanced:1};let w=k*1e3,T=ou[d]>>s+o,S=Hs(s,u,w,T,m);if(t!==null&&t<S)return{header:null,bytesAdvanced:1};let x;return c===3?x=u===3?384:1152:u===3?x=384:u===2?x=1152:x=576,{header:{totalSize:S,mpegVersionId:c,lowSamplingFrequency:s,layer:u,bitrate:w,frequencyIndex:d,sampleRate:T,channel:f,modeExtension:p,copyright:g,original:h,emphasis:y,audioSamplesInFrame:x},bytesAdvanced:1}},Vd=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},qs=i=>{let t=2130706432,e=0;for(;t!==0;)e>>=1,e|=i&t,t>>=8;return e};var Jr=i=>i===3?1:2;var Pe=class{constructor(t){this.input=t}dispose(){}};var Se=new Uint8Array(0),j=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===Se&&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===Se}get microsecondTimestamp(){return Math.trunc(Qt*this.timestamp)}get microsecondDuration(){return Math.trunc(Qt*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,this.byteLength,t?.sideData??this.sideData)}};var Ks=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},Gs=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=Hr(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(Hr(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)}},Qs=(i,t)=>i.systemId===t.systemId&&bs(i.data,t.data);var Mt=8,vr=16,_r=i=>{let t=M(i),e=ue(i,4),r=8;t===1&&(t=qe(i),r=16);let a=t-r;return a<0?null:{name:e,totalSize:t,headerSize:r,contentSize:a}},ei=i=>Rr(i)/65536,js=i=>Rr(i)/1073741824,cu=i=>{let t=0;for(let e=0;e<4;e++){t<<=7;let r=L(i);if(t|=r&127,(r&128)===0)break}return t},Xs=i=>{if(L(i)!==3)throw new Error("Invalid esds: expected ES_Descriptor.");cu(i),i.skip(2);let e=L(i),r=(e&128)!==0,n=(e&64)!==0,a=(e&32)!==0;if(r&&i.skip(2),n){let d=L(i);i.skip(d)}if(a&&i.skip(2),L(i)!==4)throw new Error("Invalid esds: expected DecoderConfigDescriptor.");let o=cu(i),c=i.filePos,u=L(i);i.skip(12);let l=null;if(o>i.filePos-c){if(L(i)!==5)throw new Error("Invalid esds: expected DecoderSpecificInfo.");let m=cu(i);l=U(i,m)}return{objectTypeIndication:u,decoderSpecificInfo:l}},Bt=i=>{let t=fe(i);return i.skip(2),t=Math.min(t,i.remainingLength),he.decode(U(i,t))},Ud=i=>{let t=_r(i);if(!t||t.name!=="data"||t.contentSize<8||i.remainingLength<8)return null;let e=M(i);i.skip(4);let r=U(i,t.contentSize-8);switch(e){case 1:return he.decode(r);case 2:return new xi("utf-16be").decode(r);case 13:return new gt(r,"image/jpeg");case 14:return new gt(r,"image/png");case 27:return new gt(r,"image/bmp");default:return r}};var Ot=16,Fr=new Uint32Array(256),pn=new Uint32Array(256),hn=new Uint32Array(256),gn=new Uint32Array(256),bn=new Uint32Array(256),Ue=new Uint32Array(256),zd=new Uint32Array(10),Nd=!1,Kp=()=>{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);Fr[a]=s<<24|s<<16|s<<8|s,Ue[a]=o<<24|o<<16|o<<8|o;let c=r(o,14),u=r(o,9),l=r(o,13),d=r(o,11),m=c<<24|u<<16|l<<8|d;pn[a]=m,hn[a]=m>>>8|m<<24,gn[a]=m>>>16|m<<16,bn[a]=m>>>24|m<<8}let n=1;for(let a=0;a<10;a++)zd[a]=n<<24,n=n<<1^(n&128?283:0);Nd=!0},da=class{constructor(){this.roundkey=new Uint32Array(44);this.iv=new Uint32Array(Ot/Uint32Array.BYTES_PER_ELEMENT);this.in=new Uint8Array(Ot);this.out=new Uint8Array(Ot);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),Nd||Kp();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]^Fr[s>>>16&255]&4278190080^Fr[s>>>8&255]&16711680^Fr[s>>>0&255]&65280^Fr[s>>>24&255]&255^zd[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]=pn[Fr[o>>>24&255]&255]^hn[Fr[o>>>16&255]&255]^gn[Fr[o>>>8&255]&255]^bn[Fr[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),u,l,d,m;for(let y=1;y<10;y++){let k=y*4;u=pn[t>>>24]^hn[n>>>16&255]^gn[r>>>8&255]^bn[e&255]^this.roundkey[k],l=pn[e>>>24]^hn[t>>>16&255]^gn[n>>>8&255]^bn[r&255]^this.roundkey[k+1],d=pn[r>>>24]^hn[e>>>16&255]^gn[t>>>8&255]^bn[n&255]^this.roundkey[k+2],m=pn[n>>>24]^hn[r>>>16&255]^gn[e>>>8&255]^bn[t&255]^this.roundkey[k+3],t=u,e=l,r=d,n=m}let f=Ue[t>>>24&255]&4278190080^Ue[n>>>16&255]&16711680^Ue[r>>>8&255]&65280^Ue[e>>>0&255]&255^this.roundkey[40],p=Ue[e>>>24&255]&4278190080^Ue[t>>>16&255]&16711680^Ue[n>>>8&255]&65280^Ue[r>>>0&255]&255^this.roundkey[41],g=Ue[r>>>24&255]&4278190080^Ue[e>>>16&255]&16711680^Ue[t>>>8&255]&65280^Ue[n>>>0&255]&255^this.roundkey[42],h=Ue[n>>>24&255]&4278190080^Ue[r>>>16&255]&16711680^Ue[e>>>8&255]&65280^Ue[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}},Ld=(i,t,e)=>{let r=!1,n=0,a=2**16,s=16,o=new da;return new ReadableStream({pull:async c=>{r||(o.init(await t()),r=!0);let u=a+s,l=i.requestSliceRange(n,0,u);if(_(l)&&(l=await l),!l||l.length===0)throw new Error("Invalid ciphertext.");let d=l.length;if(d%16!==0)throw new Error("Invalid ciphertext.");let m=d===u?d-s:d,f=U(l,m),p=new Uint8Array(m);for(let g=0;g<m;g+=16)o.in.set(f.subarray(g,g+16)),o.decrypt(),p.set(o.out,g);if(m<d)c.enqueue(p),n+=m;else{let g=p[m-1];if(g===0||g>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let h=p.subarray(0,m-g);c.enqueue(h),c.close(),e()}},cancel:()=>{e()}})};var Gp=64,$s=class i extends Pe{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=Wr;this.isQuickTime=!1;this.metadataTags={};this.currentMetadataKeys=null;this.isFragmented=!1;this.fragmentTrackDefaults=new Map;this.psshBoxes=[];this.currentFragment=null;this.isReadingTraf=!1;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 Ks({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,Mt,vr);if(_(a)&&(a=await a),!a)break;let s=e,o=_r(a);if(!o)break;if((o.name==="ftyp"||o.name==="styp")&&a.remainingLength>=4){let c=ue(a,4);this.isQuickTime=c==="qt "}else if(o.name==="moov"){let c=this.reader.requestSlice(a.filePos,o.contentSize);if(_(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 u of this.tracks){let l=u.editListPreviousSegmentDurations/this.movieTimescale;u.editListOffset-=Math.round(l*u.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);_(a)&&(a=await a),b(a);let s=M(a),o=this.reader.fileSize-s;if(o>=0&&o<=this.reader.fileSize-vr){let c=this.reader.requestSliceRange(o,Mt,vr);if(_(c)&&(c=await c),c){let u=_r(c);if(u&&u.name==="mfra"){let l=this.reader.requestSlice(c.filePos,u.contentSize);_(l)&&(l=await l),l&&this.readContiguousBoxes(l)}}}}for(let a of this.tracks){let s=a.fragmentLookupTable;s.sort((c,u)=>c.timestamp-u.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:[],currentFragmentState:null,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 Zs(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 Js(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(u){throw e.sampleTable=null,u}finally{this.currentTrack=null}let a=Y(r.sampleTimingEntries),s=G(r.sampleToChunk,r.chunkOffsets.length-1,u=>u.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),Kd(r.sampleTimingEntries,r.sampleCount),Kd(r.sampleCompositionTimeOffsets,r.sampleCount),e.info?.type==="audio"&&e.info.codec&&ne.includes(e.info.codec)&&r.sampleCompositionTimeOffsets.length===0&&r.sampleTimingEntries.length>0){b(e.info?.type==="audio");let u=Re(e.info.codec),l=[],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,w=k+f.samplesPerChunk,T=G(r.sampleTimingEntries,k,R=>R.startIndex),S=r.sampleTimingEntries[T],x=G(r.sampleTimingEntries,w,R=>R.startIndex),C=r.sampleTimingEntries[x],P=S.startDecodeTimestamp+(k-S.startIndex)*S.delta,I=C.startDecodeTimestamp+(w-C.startIndex)*C.delta-P,E=Y(l);E&&E.delta===I?E.count++:l.push({startIndex:d.length,startDecodeTimestamp:P,count:1,delta:I});let v=f.samplesPerChunk*u.sampleSize*e.info.numberOfChannels;d.push(v)}f.startSampleIndex=h,f.samplesPerChunk=1}r.sampleTimingEntries=l,r.sampleSizes=d,r.sampleCount=d.length}if(r.sampleCompositionTimeOffsets.length>0){let u=r.sampleCompositionTimeOffsets,l=Y(u),d=l.startIndex+l.count;d<r.sampleCount&&u.push({startIndex:d,count:r.sampleCount-d,offset:0,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1});let m=u.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 u=0;u<r.sampleSizes.length;u++)r.cumulativeSampleSizes.push(r.cumulativeSampleSizes[u]+r.sampleSizes[u])}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,Mt,vr);_(r)&&(r=await r),b(r);let n=_r(r);b(n?.name==="moof");let a=this.reader.requestSlice(e,n.totalSize);if(_(a)&&(a=await a),!a)return null;this.traverseBox(a);let s=this.lastReadFragment;b(s&&s.moofOffset===e),this.fragmentSummaries.set(e,{moofSize:s.moofSize,trackIds:new Set(s.trackData.keys())});for(let[,o]of s.trackData){let c=o.track,{fragmentPositionCache:u}=c;if(!o.startTimestampIsFinal){let f=Tr(c.fragmentLookupTable,s.moofOffset,h=>h.moofOffset),p=c.fragmentLookupTable[f];if(p&&o.trunSampleCounts.length>=p.trunNumber&&o.trunSampleCounts[p.trunNumber-1]>=p.sampleNumber){let h=0;for(let w=1;w<p.trunNumber;w++)h+=o.trunSampleCounts[w-1];h+=p.sampleNumber-1;let y=o.samples[h];b(y);let k=p.timestamp-y.presentationTimestamp;uu(o,k)}else{let h=G(u,s.moofOffset-1,y=>y.moofOffset);if(h!==-1){let y=u[h];uu(o,y.endTimestamp)}}o.startTimestampIsFinal=!0}let l=G(u,o.startTimestamp,f=>f.startTimestamp),d=u[l],m=u[l+1];if((!d||d.moofOffset<s.moofOffset)&&(!m||m.moofOffset>s.moofOffset)&&u.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp}),o.encryptionAuxInfo&&c.encryptionInfo){let f=await Zd(this.reader,c.encryptionInfo,o.encryptionAuxInfo);for(let p=0;p<Math.min(o.samples.length,f.length);p++){let g=f[p];o.samples[p].encryption=g}}}return s}readContiguousBoxes(e){if(this.boxNestingDepth===Gp)throw new Error("Invalid file: boxes are nested too deeply.");let r=e.filePos;this.boxNestingDepth++;try{for(;e.filePos-r<=e.length-Mt&&this.traverseBox(e););}finally{this.boxNestingDepth--}}*iterateContiguousBoxes(e){let r=e.filePos;for(;e.filePos-r<=e.length-Mt;){let n=e.filePos,a=_r(e);if(!a)break;yield{boxInfo:a,slice:e},e.filePos=n+a.totalSize}}traverseBox(e){let r=e.filePos,n=_r(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=L(e);if(e.skip(3),o===1?(e.skip(16),this.movieTimescale=M(e),this.movieDurationInTimescale=qe(e)):(e.skip(8),this.movieTimescale=M(e),this.movieDurationInTimescale=M(e)),this.movieTimescale===0)throw new Error("Invalid mvhd box: timescale must not be 0.");e.skip(8+2*4),this.movieMatrix=Wd(e)}break;case"trak":{if(this.currentFragment||this.currentTrack)break;let o={id:-1,demuxer:this,trackBacking:null,disposition:{..._e,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:Wr,internalCodecId:null,name:null,languageCode:se,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,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 Zs(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 Js(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=L(e),l=!!(Dt(e)&1);if(o.disposition.default=l,c===0)e.skip(8),o.id=M(e),e.skip(4),o.durationInMovieTimescale=M(e);else if(c===1)e.skip(16),o.id=M(e),e.skip(4),o.durationInMovieTimescale=qe(e);else throw new Error(`Incorrect track header version ${c}.`);e.skip(2*4+2+2+2+2);let d=Wd(e);o.matrix=Ht(d,this.movieMatrix)}break;case"elst":{let o=this.currentTrack;if(!o)break;let c=L(e);e.skip(3);let u=!1,l=0,d=M(e);for(let m=0;m<d;m++){let f=c===1?qe(e):M(e),p=c===1?em(e):Rr(e),g=ei(e);if(u){V._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(p===-1){l+=f;continue}if(g!==1){V._warn("Unsupported edit list entry: media rate must be 1.");break}o.editListPreviousSegmentDurations=l,o.editListOffset=p,u=!0}}break;case"mdhd":{let o=this.currentTrack;if(!o)break;let c=L(e);if(e.skip(3),c===0?(e.skip(8),o.timescale=M(e),o.durationInMediaTimescale=M(e)):c===1&&(e.skip(16),o.timescale=M(e),o.durationInMediaTimescale=qe(e)),o.timescale===0)throw new Error("Invalid mdhd box: timescale must not be 0.");let u=fe(e);if(u>0){o.languageCode="";for(let l=0;l<3;l++)o.languageCode=String.fromCharCode(96+(u&31))+o.languageCode,u>>=5;Sr(o.languageCode)||(o.languageCode=se)}}break;case"hdlr":{let o=this.currentTrack;if(!o)break;e.skip(8);let c=ue(e,4);c==="vide"?o.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...ms},avcType:null,avcCodecInfo: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=L(e);e.skip(3);let u=M(e);for(let l=0;l<u;l++){let d=e.filePos,m=_r(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":p==="vp08"?o.info.codec="vp8":p==="vp09"?o.info.codec="vp9":p==="av01"?o.info.codec="av1":Er.includes(f)?(o.info.codec="prores",o.info.proresFormat=f):p===null?V._warn("Unknown encrypted video codec due to missing frma box."):V._warn(`Unsupported video codec (sample entry type '${m.name}').`)}else{e.skip(6*1+2);let p=fe(e);e.skip(3*2);let g=fe(e),h=fe(e);e.skip(2*2);let y=M(e)/65536,k=null;c===0&&p>0&&(p===1?(e.skip(4),h=8*M(e),e.skip(2*4)):p===2&&(e.skip(4),y=eo(e),g=M(e),e.skip(4),h=M(e),k=M(e),e.skip(2*4))),o.info.numberOfChannels=g,o.info.sampleRate=y,o.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,d+m.totalSize-e.filePos));let w=f==="enca"?o.frmaCodecString:f;if(o.frmaCodecString=null,w!=="mp4a")if(w==="opus")o.info.codec="opus",o.info.sampleRate=Ft;else if(w==="flac")o.info.codec="flac";else if(w==="ulaw")o.info.codec="ulaw";else if(w==="alaw")o.info.codec="alaw";else if(w==="ac-3")o.info.codec="ac3";else if(w==="ec-3")o.info.codec="eac3";else if(la.includes(w))o.info.codec="dts",o.info.dtsFormat=w;else if(w==="twos")h===8?o.info.codec="pcm-s8":h===16?o.info.codec=o.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(V._warn(`Unsupported sample size ${h} for codec 'twos'.`),o.info.codec=null);else if(w==="sowt")h===8?o.info.codec="pcm-s8":h===16?o.info.codec="pcm-s16":(V._warn(`Unsupported sample size ${h} for codec 'sowt'.`),o.info.codec=null);else if(w==="raw ")o.info.codec="pcm-u8";else if(w==="in24")o.info.codec=o.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(w==="in32")o.info.codec=o.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(w==="fl32")o.info.codec=o.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(w==="fl64")o.info.codec=o.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(w==="ipcm"){let T=o.info.pcmSampleSize;o.info.pcmLittleEndian?T===16?o.info.codec="pcm-s16":T===24?o.info.codec="pcm-s24":T===32?o.info.codec="pcm-s32":(V._warn(`Invalid ipcm sample size ${T}.`),o.info.codec=null):T===16?o.info.codec="pcm-s16be":T===24?o.info.codec="pcm-s24be":T===32?o.info.codec="pcm-s32be":(V._warn(`Invalid ipcm sample size ${T}.`),o.info.codec=null)}else if(w==="fpcm"){let T=o.info.pcmSampleSize;o.info.pcmLittleEndian?T===32?o.info.codec="pcm-f32":T===64?o.info.codec="pcm-f64":(V._warn(`Invalid fpcm sample size ${T}.`),o.info.codec=null):T===32?o.info.codec="pcm-f32be":T===64?o.info.codec="pcm-f64be":(V._warn(`Invalid fpcm sample size ${T}.`),o.info.codec=null)}else if(w==="lpcm"&&k!==null){let T=h+7>>3,S=!!(k&1),x=!!(k&2),C=k&4?-1:0;h>0&&h<=64&&(S?h===32&&(o.info.codec=x?"pcm-f32be":"pcm-f32"):C&1<<T-1?T===1?o.info.codec="pcm-s8":T===2?o.info.codec=x?"pcm-s16be":"pcm-s16":T===3?o.info.codec=x?"pcm-s24be":"pcm-s24":T===4&&(o.info.codec=x?"pcm-s32be":"pcm-s32"):T===1&&(o.info.codec="pcm-u8")),o.info.codec===null&&V._warn("Unsupported PCM format.")}else w===null?V._warn("Unknown encrypted audio codec due to missing frma box."):V._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 u=ue(e,4).toLowerCase();o.frmaCodecString=u}break;case"schm":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=ue(e,4);c==="cenc"||c==="cens"||c==="cbcs"?o.encryptionInfo={scheme:c,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:V._warn(`Unsupported encryption scheme '${c}'.`)}break;case"tenc":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=L(e);e.skip(3),e.skip(1);let u=L(e);if(c>0?(o.encryptionInfo.defaultCryptByteBlock=u>>4,o.encryptionInfo.defaultSkipByteBlock=u&15):(o.encryptionInfo.defaultCryptByteBlock=0,o.encryptionInfo.defaultSkipByteBlock=0),o.encryptionInfo.defaultIsProtected=L(e)!==0,o.encryptionInfo.defaultPerSampleIvSize=L(e),o.encryptionInfo.defaultKid=Hr(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 l=L(e);if(l>16)throw new Error("Invalid tenc box: IV size must not exceed 16 bytes.");let d=new Uint8Array(16);d.set(U(e,l),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=tr(o.info.codecDescription)?.sequenceParameterSets[0],u=c&&rr(c);u&&Hd(o,u.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=ln(o.info.codecDescription)?.arrays.find(l=>l.nalUnitType===33)?.nalUnits[0],u=c&&Fi(c);u&&Hd(o,u.pixelAspectRatio)}break;case"vpcC":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;e.skip(4);let c=L(e),u=L(e),l=L(e),d=l>>4,m=l>>1&7,f=l&1,p=L(e),g=L(e),h=L(e);o.info.vp9CodecInfo={profile:c,level:u,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=L(e),u=c>>5,l=c&31,d=L(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,w=u===2&&f?p?12:10:f?10:8;e.skip(1);let T=U(e,n.contentSize-4),S=Mi(T);o.info.av1CodecInfo={profile:u,level:l,tier:m,bitDepth:w,monochrome:g,chromaSubsamplingX:h,chromaSubsamplingY:y,chromaSamplePosition:k,videoFullRangeFlag:S?.videoFullRangeFlag??0,colourPrimaries:S?.colourPrimaries??2,transferCharacteristics:S?.transferCharacteristics??2,matrixCoefficients:S?.matrixCoefficients??2}}break;case"colr":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=ue(e,4);if(c!=="nclx"&&c!=="nclc")break;let u=fe(e),l=fe(e),d=fe(e),m;c==="nclx"&&(m=!!(L(e)&128)),o.info.colorSpace={primaries:ft[u],transfer:pt[l],matrix:ht[d],fullRange:m}}break;case"pasp":{let o=this.currentTrack;if(!o||o.info?.type!=="video")break;let c=M(e),u=M(e);c>0&&u>0&&(o.info.squarePixelWidth=o.info.width,o.info.squarePixelHeight=o.info.height,c>u?o.info.squarePixelWidth=Math.round(o.info.width*c/u):o.info.squarePixelHeight=Math.round(o.info.height*u/c))}break;case"btrt":{let o=this.currentTrack;if(!o)break;e.skip(4);let c=M(e),u=M(e);o.maxBitrate=c>0?c:null,o.avgBitrate=u>0?u: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:u}=Xs(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":V._warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),u&&(o.info.codecDescription=u,o.info.codec==="aac")){let l=Zt(o.info.codecDescription);l.outputNumberOfChannels!==null&&(o.info.numberOfChannels=l.outputNumberOfChannels),l.outputSampleRate!==null&&(o.info.sampleRate=l.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=L(e);o.info.pcmLittleEndian=!!(c&1),o.info.pcmSampleSize=L(e)}break;case"dOps":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;e.skip(1);let c=L(e),u=fe(e),l=M(e),d=ma(e),m=L(e),f;m!==0?f=U(e,2+c):f=new Uint8Array(0);let 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,u,!0),g.setUint32(12,l,!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,u=128,l=e.filePos;for(;e.filePos<s;){let g=L(e),h=Dt(e);if((g&c)===0){e.skip(10);let k=M(e),w=k>>>12,T=(k>>9&7)+1;o.info.sampleRate=w,o.info.numberOfChannels=T,e.skip(20)}else e.skip(h);if(g&u)break}let d=e.filePos;e.filePos=l;let m=U(e,d-l),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),u=new H(c),l=u.readBits(2);u.skipBits(8);let d=u.readBits(3),m=u.readBits(1);l<3&&(o.info.sampleRate=Ri[l]),o.info.numberOfChannels=na[d]+m}break;case"dec3":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=U(e,n.contentSize),u=wd(c);if(!u){V._warn("Invalid dec3 box contents, ignoring.");break}let l=Rs(u);l!==null&&(o.info.sampleRate=l),o.info.numberOfChannels=Fs(u)}break;case"ddts":{let o=this.currentTrack;if(!o||o.info?.type!=="audio")break;let c=U(e,Math.min(n.contentSize,Bs)),u=xd(c);if(!u){V._warn("Invalid ddts box contents, ignoring.");break}o.info.sampleRate=u.sampleRate,u.numberOfChannels!==null&&(o.info.numberOfChannels=u.numberOfChannels)}break;case"stts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=M(e),u=0,l=0;for(let d=0;d<c;d++){let m=M(e),f=M(e);o.sampleTable.sampleTimingEntries.push({startIndex:u,startDecodeTimestamp:l,count:m,delta:f}),u+=m,l+=m*f}}break;case"ctts":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=M(e),u=0;for(let l=0;l<c;l++){let d=M(e),m=Rr(e);o.sampleTable.sampleCompositionTimeOffsets.push({startIndex:u,count:d,offset:m,startTimestamp:-1,lastTimestamp:-1,maxLastTimestamp:-1}),u+=d}}break;case"stsz":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=M(e),u=M(e);if(c===0)for(let l=0;l<u;l++){let d=M(e);o.sampleTable.sampleSizes.push(d)}else o.sampleTable.sampleSizes.push(c);o.sampleTable.sampleCount=u}break;case"stz2":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),e.skip(3);let c=L(e),u=M(e);if(c!==4&&c!==8&&c!==16)throw new Error(`Invalid stz2 box: unsupported field size ${c}.`);let l=U(e,Math.ceil(u*c/8)),d=new H(l);for(let m=0;m<u;m++){let f=d.readBits(c);o.sampleTable.sampleSizes.push(f)}o.sampleTable.sampleCount=u}break;case"stss":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4),o.sampleTable.keySampleIndices=[];let c=M(e);for(let u=0;u<c;u++){let l=M(e)-1;o.sampleTable.keySampleIndices.push(l)}o.sampleTable.keySampleIndices.sort((u,l)=>u-l),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=M(e),u=0;for(let d=0;d<c;d++){let m=M(e)-1,f=M(e),p=M(e),g=Y(o.sampleTable.sampleToChunk);if(g&&m<=g.startChunkIndex){u++;continue}o.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:m,samplesPerChunk:f,sampleDescriptionIndex:p})}u>0&&V._warn(`Skipped ${u} invalid stsc entries whose chunk indices weren't strictly increasing.`);let l=0;for(let d=0;d<o.sampleTable.sampleToChunk.length;d++)if(o.sampleTable.sampleToChunk[d].startSampleIndex=l,d<o.sampleTable.sampleToChunk.length-1){let f=o.sampleTable.sampleToChunk[d+1].startChunkIndex-o.sampleTable.sampleToChunk[d].startChunkIndex;l+=f*o.sampleTable.sampleToChunk[d].samplesPerChunk}}break;case"stco":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=M(e);for(let u=0;u<c;u++){let l=M(e);o.sampleTable.chunkOffsets.push(l)}}break;case"co64":{let o=this.currentTrack;if(!o||!o.sampleTable)break;e.skip(4);let c=M(e);for(let u=0;u<c;u++){let l=qe(e);o.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(a,n.contentSize));break;case"mehd":{let o=L(e);e.skip(3);let c=o===1?qe(e):M(e);this.movieDurationInTimescale=c}break;case"trex":{e.skip(4);let o=M(e),c=M(e),u=M(e),l=M(e),d=M(e);this.fragmentTrackDefaults.set(o,{trackId:o,defaultSampleDescriptionIndex:c,defaultSampleDuration:u,defaultSampleSize:l,defaultSampleFlags:d})}break;case"tfra":{let o=L(e);e.skip(3);let c=M(e),u=this.idToTrack.get(c);if(!u)break;let l=M(e),d=(l&48)>>4,m=(l&12)>>2,f=l&3,p=[L,fe,Dt,M],g=p[d],h=p[m],y=p[f],k=M(e);for(let w=0;w<k;w++){let T=o===1?qe(e):M(e),S=o===1?qe(e):M(e);g(e);let x=h(e),C=y(e);x>=1&&C>=1&&u.fragmentLookupTable.push({timestamp:T,moofOffset:S,trunNumber:x,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)),this.lastReadFragment=this.currentFragment}finally{this.currentFragment=null,this.currentTrack=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}if(this.currentTrack){let o=this.currentFragment.trackData.get(this.currentTrack.id);e:if(o){if(o.samples.length===0){this.currentFragment.trackData.delete(this.currentTrack.id);break e}o.presentationTimestamps=o.samples.map((d,m)=>({presentationTimestamp:d.presentationTimestamp,sampleIndex:m})).sort((d,m)=>d.presentationTimestamp-m.presentationTimestamp);for(let d=0;d<o.presentationTimestamps.length;d++){let m=o.presentationTimestamps[d],f=o.samples[m.sampleIndex];if(o.firstKeyFrameTimestamp===null&&f.isKeyFrame&&(o.firstKeyFrameTimestamp=f.presentationTimestamp),d<o.presentationTimestamps.length-1){let g=o.presentationTimestamps[d+1].presentationTimestamp-m.presentationTimestamp;f.duration=g}}let c=o.samples[o.presentationTimestamps[0].sampleIndex],u=o.samples[Y(o.presentationTimestamps).sampleIndex];o.startTimestamp=c.presentationTimestamp,o.endTimestamp=u.presentationTimestamp+u.duration;let{currentFragmentState:l}=this.currentTrack;b(l),l.startTimestamp!==null&&(uu(o,l.startTimestamp),o.startTimestampIsFinal=!0),l.encryptionAuxInfo&&!o.samples[0].encryption&&(o.encryptionAuxInfo=l.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let o=Gs(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.currentTrack)break;e.skip(1);let o=Dt(e),c=!!(o&1),u=!!(o&2),l=!!(o&8),d=!!(o&16),m=!!(o&32),f=!!(o&65536),p=!!(o&131072),g=M(e),h=this.idToTrack.get(g);if(!h)break;if(this.currentFragment.trackData.has(g)){V._warn(`Multiple traf boxes for track ${g} in the same moof box; skipping.`);break}let y=this.fragmentTrackDefaults.get(g);this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:y?.defaultSampleDescriptionIndex??null,defaultSampleDuration:y?.defaultSampleDuration??null,defaultSampleSize:y?.defaultSampleSize??null,defaultSampleFlags:y?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},c?h.currentFragmentState.baseDataOffset=qe(e):p&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),u&&(h.currentFragmentState.sampleDescriptionIndex=M(e)),l&&(h.currentFragmentState.defaultSampleDuration=M(e)),d&&(h.currentFragmentState.defaultSampleSize=M(e)),m&&(h.currentFragmentState.defaultSampleFlags=M(e)),f&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let o=this.currentTrack;if(!o?.currentFragmentState)break;let c=L(e);e.skip(3);let u=c===0?M(e):qe(e);o.currentFragmentState.startTimestamp=u}break;case"trun":{let o=this.currentTrack;if(!o?.currentFragmentState||!this.currentFragment)break;e.skip(1);let c=Dt(e),u=!!(c&1),l=!!(c&4),d=!!(c&256),m=!!(c&512),f=!!(c&1024),p=!!(c&2048),g=M(e),{defaultSampleDuration:h,defaultSampleSize:y,defaultSampleFlags:k}=o.currentFragmentState;if(g>0&&(!d&&h===null||!m&&y===null||!f&&k===null))throw new Error("Invalid trun box: sample values are missing and there are no defaults.");if(this.currentFragment.sampleCount+=g,this.currentFragment.sampleCount>2**20)throw new Error("Too many (> 2^20) samples in fragment.");let w=null;u&&(w=Rr(e));let T=null;l&&(T=M(e));let S;this.currentFragment.trackData.has(o.id)?(S=this.currentFragment.trackData.get(o.id),w!==null&&(S.currentOffset=o.currentFragmentState.baseDataOffset+w)):(S={track:o,currentTimestamp:0,currentOffset:o.currentFragmentState.baseDataOffset+(w??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,trunSampleCounts:[],encryptionAuxInfo:null},this.currentFragment.trackData.set(o.id,S)),S.trunSampleCounts.push(g);for(let x=0;x<g;x++){let C;d?C=M(e):C=h;let P;m?P=M(e):P=y;let A;f?A=M(e):A=k,x===0&&T!==null&&(A=T);let I=0;p&&(I=Rr(e));let E=!(A&65536);S.samples.push({presentationTimestamp:S.currentTimestamp+I,duration:C,byteOffset:S.currentOffset,byteSize:P,isKeyFrame:E,encryption:null}),S.currentOffset+=P,S.currentTimestamp+=C}this.currentFragment.implicitBaseDataOffset=S.currentOffset}break;case"saiz":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;if(e.skip(1),Dt(e)&1){let f=ue(e,4),p=M(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let u=L(e),l=M(e),d=null;u===0&&l>0&&(d=U(e,l));let m=Gd(o);m.defaultSampleInfoSize=u,m.sampleSizes=d,m.sampleCount=l}break;case"saio":{let o=this.currentTrack;if(!o||!o.encryptionInfo)break;let c=L(e);if(Dt(e)&1){let f=ue(e,4),p=M(e);if(f!==o.encryptionInfo.scheme||p!==0)break}let l=M(e);if(l===0)break;l>1&&V._warn("Multiple saio entries are not supported; using the first offset only.");let d=c===0?M(e):Number(qe(e));this.currentFragment&&(d+=this.currentFragment.moofOffset);let m=Gd(o);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 l=!!(Dt(e)&2),d=M(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(l){let y=fe(e);g=[];for(let k=0;k<y;k++){let w=fe(e),T=M(e);g.push({clearLen:w,protectedLen:T})}}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:u}of o){if(c.name!=="meta"&&!this.currentTrack){let l=u.filePos;this.metadataTags.raw??={},c.name[0]==="\xA9"?this.metadataTags.raw[c.name]??=Bt(u):this.metadataTags.raw[c.name]??=U(u,c.contentSize),u.filePos=l}switch(c.name){case"meta":u.skip(-c.headerSize),this.traverseBox(u);break;case"\xA9nam":case"name":this.currentTrack?this.currentTrack.name=he.decode(U(u,c.contentSize)):this.metadataTags.title??=Bt(u);break;case"\xA9des":this.currentTrack||(this.metadataTags.description??=Bt(u));break;case"\xA9ART":this.currentTrack||(this.metadataTags.artist??=Bt(u));break;case"\xA9alb":this.currentTrack||(this.metadataTags.album??=Bt(u));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Bt(u));break;case"\xA9gen":this.currentTrack||(this.metadataTags.genre??=Bt(u));break;case"\xA9day":if(!this.currentTrack){let l=new Date(Bt(u));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"\xA9cmt":this.currentTrack||(this.metadataTags.comment??=Bt(u));break;case"\xA9lyr":this.currentTrack||(this.metadataTags.lyrics??=Bt(u));break}}}break;case"meta":{if(this.currentTrack)break;let c=M(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=M(e);for(let c=0;c<o;c++){let u=M(e);if(u<8)throw new Error("Invalid keys box: key size must be at least 8.");e.skip(4);let l=he.decode(U(e,u-8));this.currentMetadataKeys.set(c+1,l)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let o=this.iterateContiguousBoxes(e.slice(a,n.contentSize));for(let{boxInfo:c,slice:u}of o){let l=c.name,d=(l.charCodeAt(0)<<24)+(l.charCodeAt(1)<<16)+(l.charCodeAt(2)<<8)+l.charCodeAt(3);this.currentMetadataKeys.has(d)&&(l=this.currentMetadataKeys.get(d));let m=Ud(u);switch(this.metadataTags.raw??={},this.metadataTags.raw[l]??=m,l){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=new Date(m);Number.isNaN(f.getTime())||(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 gt?(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}},Ys=class{constructor(t){this.internalTrack=t;this.packetToSampleIndex=new WeakMap;this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}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?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.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,t)}mapTimestampIntoTimescale(t){return wr(t*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(t,e){let r=this.mapTimestampIntoTimescale(t),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=lu(n,r),s=await this.fetchPacketForSampleIndex(a,e);return!qd(n)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=G(c.presentationTimestamps,r,m=>m.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,e)}async getNextPacket(t,e){let r=this.packetToSampleIndex.get(t);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,e);let n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,a=>{if(a===n.fragment){let s=a.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<s.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(a.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=Qp(n,r),s=await this.fetchPacketForSampleIndex(a,e);return!qd(n)||!this.internalTrack.demuxer.isFragmented?s:this.performFragmentedLookup(null,o=>{let c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};let u=qr(c.presentationTimestamps,m=>c.samples[m.sampleIndex].isKeyFrame&&m.presentationTimestamp<=r),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,e)}async getNextKeyPacket(t,e){let r=this.packetToSampleIndex.get(t);if(r!==void 0){let a=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=$p(a,r);return this.fetchPacketForSampleIndex(s,e)}let n=this.packetToFragmentLocation.get(t);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,a=>{if(a===n.fragment){let s=a.trackData.get(this.internalTrack.id);for(let o=n.sampleIndex+1;o<s.samples.length;o++)if(s.samples[o].isKeyFrame)return{sampleIndex:o,correctSampleFound:!0}}else{let s=a.trackData.get(this.internalTrack.id);if(s&&s.firstKeyFrameTimestamp!==null){let o=s.samples.findIndex(c=>c.isKeyFrame);return b(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,e)}async fetchPacketForSampleIndex(t,e){if(t===-1)return null;let r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=jp(r,t);if(!n)return null;let a;if(e.metadataOnly)a=Se;else{let u=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(_(u)&&(u=await u),!u)return null;if(a=U(u,n.sampleSize),this.internalTrack.encryptionInfo){let l=null;if(this.internalTrack.encryptionAuxInfo){let d=await Zd(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);t<d.length&&(l=d[t])}l??=Qd(this.internalTrack.encryptionInfo),l&&(a=await jd(this.internalTrack,l,a,null))}}let s=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,c=new j(a,n.isKeyFrame?"key":"delta",s,o,t,n.sampleSize);return this.packetToSampleIndex.set(c,t),c}async fetchPacketInFragment(t,e,r){if(e===-1)return null;let a=t.trackData.get(this.internalTrack.id).samples[e];b(a);let s;if(r.metadataOnly)s=Se;else{let l=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);if(_(l)&&(l=await l),!l)return null;if(s=U(l,a.byteSize),this.internalTrack.encryptionInfo){let d=a.encryption??Qd(this.internalTrack.encryptionInfo);d&&(s=await jd(this.internalTrack,d,s,t))}}let o=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=a.duration/this.internalTrack.timescale,u=new j(s,a.isKeyFrame?"key":"delta",o,c,t.moofOffset+e,a.byteSize);return this.packetToFragmentLocation.set(u,{fragment:t,sampleIndex:e}),u}async performFragmentedLookup(t,e,r,n,a,s=1/0,o=0){let c=this.internalTrack.demuxer,u=null,l=null,d=-1;if(t){let{sampleIndex:T,correctSampleFound:S}=e(t);if(S)return this.fetchPacketInFragment(t,T,a);T!==-1&&(l=t,d=T)}let m=G(this.internalTrack.fragmentLookupTable,r,T=>T.timestamp),f=m!==-1?this.internalTrack.fragmentLookupTable[m]:null,p=G(this.internalTrack.fragmentPositionCache,r,T=>T.startTimestamp),g=p!==-1?this.internalTrack.fragmentPositionCache[p]:null,h=Math.max(f?.moofOffset??0,g?.moofOffset??0)||null,y=!!f&&f.moofOffset>=(g?.moofOffset??0),k;t?h===null||t.moofOffset>=h?(k=t.moofOffset+t.moofSize,u=t):k=h:k=h??0;let w=u?u.moofOffset:k;for(;k<s;){if(u){let P=u.trackData.get(this.internalTrack.id);if(P&&P.startTimestamp>n)break;u=null}let T=c.fragmentSummaries.get(k);if(T&&!T.trackIds.has(this.internalTrack.id)){k+=T.moofSize;continue}let S=c.reader.requestSliceRange(k,Mt,vr);if(_(S)&&(S=await S),!S)break;let x=k,C=_r(S);if(!C)break;if(C.name==="moof"){if(u=await c.readFragment(x),!u)break;let{sampleIndex:P,correctSampleFound:A}=e(u);if(A)return this.fetchPacketInFragment(u,P,a);P!==-1&&(l=u,d=P)}k=x+C.totalSize}if(h!==null&&(!l||l.moofOffset<h)){let T=1<<o,x=(y?this.internalTrack.fragmentLookupTable[m-T]?.timestamp:this.internalTrack.fragmentPositionCache[p-T]?.startTimestamp)??-1/0;return this.performFragmentedLookup(null,e,x,n,a,w,o+1)}return l?this.fetchPacketInFragment(l,d,a):null}},Zs=class extends Ys{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&&er(r.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){let r=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=r&&ir(r.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!gd(this.internalTrack.info.vp9CodecInfo))){let r=await this.getFirstPacket({}),n=r&&dn(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||!Ps(this.internalTrack.info.av1CodecInfo))){let r=await this.getFirstPacket({}),n=r&&Mi(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&&Is(r.data)}if(!rn(this.internalTrack.info.colorSpace)){let r=zs(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:Xr(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}},Js=class extends Ys{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&&Os(e.data)}return{codec:mn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}},lu=(i,t)=>{if(i.sortedCompositionTimeOffsets)return $d(i,t,!1);{let e=G(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)}},Qp=(i,t)=>{if(!i.keySampleIndices)return lu(i,t);if(i.sortedCompositionTimeOffsets)return $d(i,t,!0);{let e=lu(i,t),r=G(i.keySampleIndices,e,n=>n);return i.keySampleIndices[r]??-1}},jp=(i,t)=>{if(t>=i.sampleCount)return null;let e=G(i.sampleTimingEntries,t,h=>h.startIndex),r=i.sampleTimingEntries[e],a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,s=G(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)],u=G(i.sampleToChunk,t,h=>h.startSampleIndex),l=i.sampleToChunk[u],d=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),m=i.chunkOffsets[d],f=l.startSampleIndex+(d-l.startChunkIndex)*l.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=Xp(i,t,a);h!==null&&(g=h-a)}return{presentationTimestamp:a,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:m,isKeyFrame:i.keySampleIndices?Tr(i.keySampleIndices,t,h=>h)!==-1:!0}},$d=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=-1,a=-1/0,s=G(r,t,o=>o.startTimestamp);for(let o=s;o>=0;o--){let c=r[o];if(c.maxLastTimestamp<a)break;let u=c.lastTimestamp<=t?c.startIndex+c.count-1:Yd(i,c,(d,m)=>m>t)-1;if(e){let d=G(i.keySampleIndices,u,m=>m);u=i.keySampleIndices[d]??-1}if(u<c.startIndex)continue;let l=du(i,u)+c.offset;(l>a||l===a&&u>n)&&(n=u,a=l)}return n},Xp=(i,t,e)=>{let r=i.sortedCompositionTimeOffsets,n=G(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=Yd(i,o,(l,d)=>d>e||d===e&&l>t);if(c===o.startIndex+o.count)continue;let u=du(i,c)+o.offset;(a===null||u<a)&&(a=u)}return a},Yd=(i,t,e)=>{let r=t.startIndex,n=t.startIndex+t.count;for(;r<n;){let a=Math.floor((r+n)/2);e(a,du(i,a)+t.offset)?n=a:r=a+1}return r},du=(i,t)=>{let e=G(i.sampleTimingEntries,t,n=>n.startIndex),r=i.sampleTimingEntries[e];return r.startDecodeTimestamp+(t-r.startIndex)*r.delta},$p=(i,t)=>{if(!i.keySampleIndices)return t+1;let e=G(i.keySampleIndices,t,r=>r);return i.keySampleIndices[e+1]??-1},uu=(i,t)=>{i.startTimestamp+=t,i.endTimestamp+=t;for(let e of i.samples)e.presentationTimestamp+=t;for(let e of i.presentationTimestamps)e.presentationTimestamp+=t},Wd=i=>[ei(i),ei(i),js(i),ei(i),ei(i),js(i),ei(i),ei(i),js(i)],Hd=(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)))},qd=i=>i.sampleSizes.length===0,Kd=(i,t)=>{for(;i.length>0&&Y(i).startIndex>=t;)i.pop();let e=Y(i);e&&(e.count=Math.min(e.count,t-e.startIndex))},Gd=i=>i.currentFragmentState?i.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:i.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Zd=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(_(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],u=new Uint8Array(16);if(a>0)u.set(U(n,a),0);else if(t.defaultConstantIv)u.set(t.defaultConstantIv,0);else throw new Error("Invalid file: encrypted sample has no IV.");let l=null;if(c>a){let d=fe(n);l=[];for(let m=0;m<d;m++){let f=fe(n),p=M(n);l.push({clearLen:f,protectedLen:p})}}s.push({iv:u,subsamples:l})}return e.resolved=s,s},Qd=i=>i.defaultConstantIv?{iv:i.defaultConstantIv,subsamples:null}:null,jd=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 u=i.demuxer.psshBoxes;if(r){u=[...u,...r.psshBoxes].filter(d=>d.keyIds===null||d.keyIds.includes(a));for(let d=0;d<u.length-1;d++)for(let m=d+1;m<u.length;m++)Qs(u[d],u[m])&&(u.splice(m,1),m--)}let l=await i.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:u});if(!(typeof l=="string"&&l.length===32&&Nl.test(l)||l instanceof Uint8Array&&l.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return l instanceof Uint8Array?l:Ll(l)})();i.demuxer.decryptionKeyCache.set(a,c),s=await c}return n.scheme==="cenc"||n.scheme==="cens"?Yp(s,n,t,e):Zp(s,n,t,e)},Yp=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=Jd(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 u=new Uint8Array(c),l=0;for(let p of o)for(let g of p.perSubsample)u.set(r.subarray(g.offset,g.offset+g.length),l),l+=g.length;let d=await s(u),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},Zp=(i,t,e,r)=>{let n=new da;n.init({key:i,iv:e.iv});let a=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(b(a!==null&&s!==null),!e.subsamples){let l=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(),l.set(n.out,f)}return l}if(a===0&&s===0)throw new Error("cbcs with subsamples requires pattern encryption.");let o=new Uint8Array(r),c=Jd(e.subsamples,a,s,r.length),u=new DataView(e.iv.buffer,e.iv.byteOffset,16);for(let l of c){n.iv[0]=u.getUint32(0,!1),n.iv[1]=u.getUint32(4,!1),n.iv[2]=u.getUint32(8,!1),n.iv[3]=u.getUint32(12,!1);for(let d of l.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},Jd=(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 u=o.protectedLen,l=s;for(;u>0&&!(u<16*t);){let d=16*t;c.push({offset:l,length:d}),l+=d,u-=d;let m=Math.min(16*e,u);l+=m,u-=m}s+=o.protectedLen}n.push({perSubsample:c})}return n};var ti=class{constructor(t){this.value=t}},yn=class{constructor(t){this.value=t}},fa=class{constructor(t){this.value=t}},Vt=class{constructor(t){this.value=t}};var Jp=[440786851,408125543],kn=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],pa=[...Jp,...kn],tm=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,rm=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,im=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,eh=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)},to=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=tm(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=rm(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=im(t)){t<0&&(t+=2**(e*8)),this.writeUnsignedInt(t,e)}writeVarInt(t,e=eh(t)){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)){let e=this.writer.getPos(),r=t.size===-1?1:t.size??4;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??tm(t.data);this.writeVarInt(e),this.writeUnsignedInt(t.data,e)}else if(typeof t.data=="bigint"){let e=t.size??rm(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 ti)this.writeVarInt(4),this.writeFloat32(t.data.value);else if(t.data instanceof yn)this.writeVarInt(8),this.writeFloat64(t.data.value);else if(t.data instanceof fa){let e=t.size??im(t.data.value);this.writeVarInt(e),this.writeSignedInt(t.data.value,e)}else if(t.data instanceof Vt){let e=Z.encode(t.data.value);this.writeVarInt(e.length),this.writer.write(e)}else ae(t.data)}},nm=8,$e=2,xt=2*nm,mu=i=>{if(i.remainingLength<1)return null;let t=L(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},Tn=i=>{if(i.remainingLength<1)return null;let t=L(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+=L(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+=L(i);return e},am=(i,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let e=0n;for(let r=0;r<t;r++)e<<=8n,e+=BigInt(L(i));return e};var ro=i=>{let t=mu(i);return t===null||i.remainingLength<t?null:X(i,t)},fu=i=>{if(i.remainingLength<1)return null;if(L(i)===255)return;i.skip(-1);let e=Tn(i);if(e===null)return null;if(e!==72057594037927940)return e},Ct=i=>{b(i.remainingLength>=$e);let t=ro(i);if(t===null)return null;let e=fu(i);return e===null?null:{id:t,size:e}},ri=(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},wn=(i,t)=>{let e=U(i,t),r=0;for(;r<t&&e[r]!==0;)r+=1;return he.decode(e.subarray(0,r))},Sn=(i,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw new Error("Bad float size "+t);return t===4?sm(i):eo(i)},io=async(i,t,e,r)=>{let n=new Set(e),a=t;for(;r===null||a<r;){let s=i.requestSliceRange(a,$e,xt);if(_(s)&&(s=await s),!s)break;let o=Ct(s);if(!o)break;if(n.has(o.id))return{pos:a,found:!0};ar(o.size),a=s.filePos+o.size}return{pos:r!==null&&r>a?r:a,found:!1}},pu=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(_(o)&&(o=await o),!o||o.length===0)break;let c=Math.max(o.length-nm,1);for(let u=0;u<c;u++){o.filePos=s;let l=ro(o);if(l!==null&&a.has(l))return s;s++}}return null},ze={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function ar(i){if(i===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}var no=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 hu=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],cm=10*2**20,th=64,ao=class extends Pe{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.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 no({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,$e,xt);if(_(r)&&(r=await r),!r)break;let n=Ct(r);if(!n)break;let a=n.id,s=n.size,o=r.filePos;if(a===440786851){ar(s);let c=this.reader.requestSlice(o,s);if(_(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 io(this.reader,o,pa,this.reader.fileSize)).pos-o);let c=Y(this.segments);c&&(c.elementEndPos=o+s)}ar(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,$e,xt);if(_(c)&&(c=await c),!c)break;let u=n,l=Ct(c);if(!l||!kn.includes(l.id)&&l.id!==236){let g=await pu(this.reader,u+1,kn,Math.min(this.currentSegment.elementEndPos??1/0,u+cm));if(g){n=g;continue}else break}let{id:d,size:m}=l,f=c.filePos,p=hu.findIndex(g=>g.id===d);if(p!==-1){let g=hu[p].flag;this.currentSegment[g]=!0,d===290298740&&a.add(u-e),ar(m);let h=this.reader.requestSlice(f,m);_(h)&&(h=await h),h&&this.readContiguousElements(h)}else if(d===307544935||d===423732329){d===307544935?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ar(m);let g=this.reader.requestSlice(f,m);_(g)&&(g=await g),g&&this.readContiguousElements(g)}else if(d===524531317){this.currentSegment.clusterSeekStartPos=u;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 u=this.currentSegment.seekEntries[c];if(u.id!==290298740||a.has(u.segmentPosition)||(a.add(u.segmentPosition),!this.claimSeekTarget(e+u.segmentPosition)))continue;let l=this.reader.requestSliceRange(e+u.segmentPosition,$e,xt);if(_(l)&&(l=await l),!l)continue;let d=Ct(l);if(!d||d.id!==290298740)continue;let{size:m}=d;ar(m);let f=this.reader.requestSlice(l.filePos,m);_(f)&&(f=await f),f&&this.readContiguousElements(f)}if(this.currentSegment.seekEntries.sort((c,u)=>c.segmentPosition-u.segmentPosition),this.reader.fileSize!==null)for(let c of this.currentSegment.seekEntries){let u=hu.find(g=>g.id===c.id);if(!u||this.currentSegment[u.flag]||!this.claimSeekTarget(e+c.segmentPosition))continue;let l=this.reader.requestSliceRange(e+c.segmentPosition,$e,xt);if(_(l)&&(l=await l),!l)continue;let d=Ct(l);if(!d)continue;let{id:m,size:f}=d;if(m!==u.id)continue;ar(f),this.currentSegment[u.flag]=!0;let p=this.reader.requestSlice(l.filePos,f);_(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);for(let c of this.currentSegment.cuePoints){let u=this.currentSegment.idToTrack.get(c.trackId);u&&u.cuePoints.push(c)}for(let c of this.currentSegment.tracks){let u=c.cuePoints;u.sort((d,m)=>d.time-m.time);let l=0;for(let d of u)(l===0||d.time!==u[l-1].time)&&(u[l++]=d);u.length=l}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,$e,xt);_(n)&&(n=await n),b(n);let a=e,s=Ct(n);b(s);let o=s.id;b(o===524531317);let c=s.size,u=n.filePos;c===void 0&&(c=(await io(this.reader,u,pa,r.elementEndPos)).pos-u);let l=this.reader.requestSlice(u,c);_(l)&&(l=await l);let d={segment:r,elementStartPos:a,elementEndPos:u+c,dataStartPos:u,timestamp:-1,trackData:new Map};if(l){this.currentCluster=d;try{let m=this.readContiguousElements(l,pa);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 T=0;T<m.blocks.length;T++){let S=m.blocks[T];S.timestamp+=d.timestamp,p||=S.lacing!==0}m.presentationTimestamps=m.blocks.map((T,S)=>({timestamp:T.timestamp,blockIndex:S})).sort((T,S)=>T.timestamp-S.timestamp);for(let T=0;T<m.presentationTimestamps.length;T++){let S=m.presentationTimestamps[T],x=m.blocks[S.blockIndex];if(m.firstKeyFrameTimestamp===null&&x.isKeyFrame&&(m.firstKeyFrameTimestamp=x.timestamp),T<m.presentationTimestamps.length-1){let C=m.presentationTimestamps[T+1];x.duration=C.timestamp-x.timestamp}else x.duration===0&&f.defaultDuration!=null&&x.lacing===0&&(x.duration=f.defaultDuration)}p&&(m.blocks=this.expandLacedBlocks(m.blocks,f),m.presentationTimestamps=m.blocks.map((T,S)=>({timestamp:T.timestamp,blockIndex:S})).sort((T,S)=>T.timestamp-S.timestamp));let g=m.blocks[m.presentationTimestamps[0].blockIndex],h=m.blocks[Y(m.presentationTimestamps).blockIndex];m.startTimestamp=g.timestamp,m.endTimestamp=h.timestamp+h.duration;let y=G(f.clusterPositionCache,m.startTimestamp,T=>T.startTimestamp),k=f.clusterPositionCache[y],w=f.clusterPositionCache[y+1];(!k||k.elementStartPos<a)&&(!w||w.elementStartPos>a)&&f.clusterPositionCache.splice(y+1,0,{elementStartPos:d.elementStartPos,startTimestamp:m.startTimestamp})}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=we.tempFromBytes(a.data);if(s.length===0)throw new Error("Invalid laced block: no data.");let o=[],c=L(s)+1;switch(a.lacing){case 1:{let l=0;for(let d=0;d<c-1;d++){let m=0;for(;s.bufferPos<s.length;){let f=L(s);if(m+=f,f<255){o.push(m),l+=m;break}}}o.push(s.length-(s.bufferPos+l))}break;case 2:{let l=s.length-1,d=Math.floor(l/c);for(let m=0;m<c;m++)o.push(d)}break;case 3:{let l=Tn(s);if(l===null)throw new Error("Invalid EBML lacing: bad frame size.");let d=l;o.push(d);let m=d;for(let f=1;f<c-1;f++){let p=s.bufferPos,g=Tn(s);if(g===null)throw new Error("Invalid EBML lacing: bad frame size.");let h=g,k=(1<<(s.bufferPos-p)*7-1)-1,w=h-k;d+=w,o.push(d),m+=d}o.push(s.length-(s.bufferPos+m))}break;default:b(!1)}if(o.length!==c||o.some(l=>l<=0))throw new Error("Invalid block lacing: frame sizes don't match the block.");let u=a.duration||c*(r.defaultDuration??0);for(let l=0;l<c;l++){let d=o[l],m=U(s,d),f=a.timestamp+u*l/c,p=u/c;n.push({timestamp:f,duration:p,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,$e,xt);if(_(n)&&(n=await n),!n)continue;let a=Ct(n);if(!a||a.id!==r.id)continue;let{size:s}=a;ar(s);let o=this.reader.requestSlice(n.filePos,s);if(_(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===th)throw new Error("Invalid file: elements are nested too deeply.");this.elementNestingDepth++;try{for(;e.remainingLength>=$e;){let n=e.filePos;if(!this.traverseElement(e,r))return n}return e.filePos}finally{this.elementNestingDepth--}}traverseElement(e,r){let n=Ct(e);if(!n||r&&r.includes(n.id))return!1;let{id:a,size:s}=n,o=e.filePos;if(ar(s),o+s>e.end)return!1;switch(a){case 17026:this.isWebM=ri(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=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=Sn(e,s)}break;case 174:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{..._e,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,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)&&(V._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentSegment.idToTrack.has(this.currentTrack.id)&&(V._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("/"),u=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){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let d=this.currentTrack.info.displayWidth*this.currentTrack.info.height,m=this.currentTrack.info.displayHeight*this.currentTrack.info.width;d>0&&m>0&&(d>m?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*d/m):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*m/d))}if(this.currentTrack.codecId===ze.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===ze.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(u===ze.vp8)this.currentTrack.info.codec="vp8";else if(u===ze.vp9)this.currentTrack.info.codec="vp9";else if(u===ze.av1)this.currentTrack.info.codec="av1";else if(u===ze.prores){let d=this.currentTrack.codecPrivate?he.decode(this.currentTrack.codecPrivate):"";Er.includes(d)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=d)}let l=this.currentTrack;this.currentTrack.trackBacking=new gu(l),this.currentSegment.tracks.push(this.currentTrack),this.currentSegment.idToTrack.set(this.currentTrack.id,this.currentTrack)}else if(this.currentTrack.info.type==="audio"){u===ze.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ze.mp3?this.currentTrack.info.codec="mp3":u===ze.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Ft):u===ze.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):u===ze.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")):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 l=this.currentTrack;this.currentTrack.trackBacking=new bu(l),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:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...ms},alphaMode:!1,proresFormat:null}:c===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case 185:{if(!this.currentTrack)break;X(e,s)||(this.currentTrack=null)}break;case 136:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!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=ri(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 21358:{if(!this.currentTrack)break;this.currentTrack.name=wn(e,s)}break;case 2274716:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ri(e,s),Sr(this.currentTrack.languageCode)||(this.currentTrack.languageCode=se)}break;case 2274717:{if(!this.currentTrack)break;let u=ri(e,s).split("-")[0];u?this.currentTrack.languageCode=u:this.currentTrack.languageCode=se,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 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=X(e,s),u=ht[c];this.currentTrack.info.colorSpace.matrix=u}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=X(e,s),u=pt[c];this.currentTrack.info.colorSpace.transfer=u}break;case 21947:{if(this.currentTrack?.info?.type!=="video")break;let c=X(e,s),u=ft[c];this.currentTrack.info.colorSpace.primaries=u}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,s))}break;case 30323:{if(this.currentTrack?.info?.type!=="video")break;let c=Sn(e,s);try{let u=yr(c);this.currentTrack.info.horizontalScale=Math.round(Math.cos(u*ss))}catch{}}break;case 30324:{if(this.currentTrack?.info?.type!=="video")break;let c=Sn(e,s);try{let u=yr(c);this.currentTrack.info.verticalScale=Math.round(Math.cos(u*ss))}catch{}}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let u=-Sn(e,s);try{this.currentTrack.info.rotation=yr(u)}catch{}}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=Sn(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 159:{if(this.currentTrack?.info?.type!=="audio")break;let c=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),u=Tn(c);if(u===null||c.remainingLength<3)break;let l=this.getTrackDataInCluster(this.currentCluster,u);if(!l)break;let d=ma(c),m=L(c),f=m>>1&3,p=!!(m&128);l.track.info?.type==="audio"&&l.track.info.codec&&(p=!0);let g=U(c,c.remainingLength),h=l.track.decodingInstructions.length>0;l.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),u=Tn(c);if(u===null||c.remainingLength<3)break;let l=this.getTrackDataInCluster(this.currentCluster,u);if(!l)break;let d=ma(c),f=L(c)>>1&3,p=U(c,c.remainingLength),g=l.track.decodingInstructions.length>0;this.currentBlock={timestamp:d,duration:0,isKeyFrame:!0,data:p,lacing:f,decoded:!g,postProcessed:!1,mainAdditional:null},l.blocks.push(this.currentBlock)}break;case 30113:this.readContiguousElements(e.slice(o,s));break;case 166:{let c=this.currentBlock;if(!c)break;let u={addId:1,data:null};this.currentBlockAdditional=u,this.readContiguousElements(e.slice(o,s)),u.data&&u.addId===1&&(c.mainAdditional=u.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=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: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=wn(e,s);break;case 17543:{if(!this.currentSimpleTagName)break;let c=wn(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 xr(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 u=this.currentAttachedFile.fileName,l="unknown";if(u){let d=u.toLowerCase();d.startsWith("cover.")?l="coverFront":d.startsWith("back.")&&(l="coverBack")}c.images??=[],c.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:l,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=am(e,s)}break;case 18030:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=wn(e,s)}break;case 18016:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ri(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=wn(e,s)}break;case 28032:{let c=this.currentTrack;if(!c)break;this.readContiguousElements(e.slice(o,s)),c.decodingInstructions.sort((u,l)=>l.order-u.order)}break;case 25152:{let c=this.currentTrack;if(!c)break;let u={order:0,scope:1,data:null};this.currentDecodingInstruction=u,this.readContiguousElements(e.slice(o,s)),u.data&&c.decodingInstructions.push(u),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=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=new Date(r);Number.isNaN(a.getTime())||(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){return e.duration<=0?null:e.duration/e.timestampFactor}},so=class{constructor(t){this.internalTrack=t;this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}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)break;return r}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 wr(t*this.internalTrack.segment.timestampFactor)}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=G(a.presentationTimestamps,r,u=>u.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=qr(a.presentationTimestamps,u=>a.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=r),o=s!==-1?a.presentationTimestamps[s].blockIndex:-1,c=s!==-1&&r<a.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,e)}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 m=new Uint8Array(a.data.length+8);N(m).setUint32(0,m.length,!1),m[4]=105,m[5]=99,m[6]=112,m[7]=102,m.set(a.data,8),a.data=m}a.postProcessed=!0}let s=r.metadataOnly?Se:a.data,o=a.timestamp/this.internalTrack.segment.timestampFactor,c=a.duration/this.internalTrack.segment.timestampFactor,u={};a.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=r.metadataOnly?Se:a.mainAdditional,u.alphaByteLength=a.mainAdditional.byteLength);let l=new j(s,a.isKeyFrame?"key":"delta",o,c,t.dataStartPos+e,a.data.byteLength,u);return this.packetToClusterLocation.set(l,{cluster:t,blockIndex:e}),l}async performClusterLookup(t,e,r,n,a,s=1/0,o=0){let{demuxer:c,segment:u}=this.internalTrack,l=null,d=null,m=-1;if(t){let{blockIndex:S,correctBlockFound:x}=e(t);if(x)return this.fetchPacketInCluster(t,S,a);S!==-1&&(d=t,m=S)}let f=G(this.internalTrack.cuePoints,r,S=>S.time),p=f!==-1?this.internalTrack.cuePoints[f]:null,g=G(this.internalTrack.clusterPositionCache,r,S=>S.startTimestamp),h=g!==-1?this.internalTrack.clusterPositionCache[g]:null,y=Math.max(p?.clusterPosition??0,h?.elementStartPos??0)||null,k=!!p&&p.clusterPosition>=(h?.elementStartPos??0),w;t?y===null||t.elementStartPos>=y?(w=t.elementEndPos,l=t):w=y:w=y??u.clusterSeekStartPos;let T=l?l.elementStartPos:w;for(;(u.elementEndPos===null||w<=u.elementEndPos-$e)&&w<s;){if(l){let R=l.trackData.get(this.internalTrack.id);if(R&&R.startTimestamp>n)break;l=null}let S=u.clusterSummaries.get(w);if(S&&!S.trackIds.has(this.internalTrack.id)){w=S.elementEndPos;continue}let x=c.reader.requestSliceRange(w,$e,xt);if(_(x)&&(x=await x),!x)break;let C=w,P=Ct(x);if(!P||!kn.includes(P.id)&&P.id!==236){let R=await pu(c.reader,C+1,kn,Math.min(u.elementEndPos??1/0,C+cm));if(R){w=R;continue}else break}let A=P.id,I=P.size,E=x.filePos;if(A===524531317){l=await c.readCluster(C,u),I=l.elementEndPos-E;let{blockIndex:R,correctBlockFound:B}=e(l);if(B)return this.fetchPacketInCluster(l,R,a);R!==-1&&(d=l,m=R)}I===void 0&&(b(A!==524531317),I=(await io(c.reader,E,pa,u.elementEndPos)).pos-E);let v=E+I;if(u.elementEndPos===null){let R=c.reader.requestSliceRange(v,$e,xt);if(_(R)&&(R=await R),!R)break;if(ro(R)===408125543){u.elementEndPos=v;break}}w=v}if(y!==null&&(!d||d.elementStartPos<y)){let S=1<<o,C=(k?this.internalTrack.cuePoints[f-S]?.time:this.internalTrack.clusterPositionCache[g-S]?.startTimestamp)??-1/0;return this.performClusterLookup(null,e,C,n,a,T,o+1)}return d?this.fetchPacketInCluster(d,m,a):null}},gu=class extends so{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=Ht(us(e.horizontalScale,e.verticalScale),tn(e.rotation));return cs(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=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let n={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"&&e?er(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?ir(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?dn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Mi(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Is(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!rn(this.internalTrack.info.colorSpace)){let s=zs(n);this.internalTrack.info.colorSpace.primaries??=s.primaries,this.internalTrack.info.colorSpace.transfer??=s.transfer,this.internalTrack.info.colorSpace.matrix??=s.matrix,this.internalTrack.info.colorSpace.fullRange??=s.fullRange}let a={codec:Xr(n),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)&&(a.displayAspectWidth=this.internalTrack.info.squarePixelWidth,a.displayAspectHeight=this.internalTrack.info.squarePixelHeight),a})():null}},bu=class extends so{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&&Os(e.data)}return{codec:mn({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 ha=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(_(o)&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let c=o.filePos,u=M(o),l=i.fileSize!==null?i.fileSize-a:null,d=Zr(u,l);if(d.header&&(!r||d.header.sampleRate===r.sampleRate&&d.header.mpegVersionId===r.mpegVersionId&&d.header.layer===r.layer&&Jr(d.header.channel)===Jr(r.channel)))return{header:d.header,startPos:a};o.filePos=c+d.bytesAdvanced,a=o.filePos}}return null};var oo=class extends Pe{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 He;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();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 yu(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let c=this.reader.requestSlice(this.lastLoadedPos,Fe);if(_(c)&&(c=await c),!c){this.lastSampleLoaded=!0;return}let u=it(c);if(!u)break;this.lastLoadedPos=c.filePos+u.size}let e=await ha(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let r=e.header;this.lastLoadedPos=e.startPos+r.totalSize-1;let n=Yr(r.mpegVersionId,r.channel),a=this.reader.requestSlice(e.startPos+n,4);if(_(a)&&(a=await a),a){let c=M(a);if(c===$r||c===fn){if(this.xingFrameHeader||(this.xingFrameHeader=r,this.xingFrameHeaderPos=e.startPos),!this.xingData){let l=this.reader.requestSlice(e.startPos+n+4,12);if(_(l)&&(l=await l),l){let d=U(l,12),m=N(d),f=m.getUint32(0,!1);this.xingData={frameCount:f&1?m.getUint32(4,!1):null,fileSize:f&2?m.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=r,this.firstFrameHeaderPos=e.startPos);let s=r.audioSamplesInFrame/this.firstFrameHeader.sampleRate,o={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:r.totalSize};this.loadedSamples.push(o),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,Fe);if(_(a)&&(a=await a),!a)break;let s=it(a);if(!s)break;n=!0;let o=this.reader.requestSlice(a.filePos,s.size);if(_(o)&&(o=await o),!o)break;ii(o,s,this.metadataTags),r=a.filePos+s.size}if(!n&&this.reader.fileSize!==null&&this.reader.fileSize>=ga){let a=this.reader.requestSlice(this.reader.fileSize-ga,ga);_(a)&&(a=await a),b(a),ue(a,3)==="TAG"&&um(a,this.metadataTags)}return this.metadataTags}finally{e()}}},yu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let t=this.demuxer;if(b(t.firstFrameHeader!==null),b(t.firstFrameHeaderPos!==null),t.xingData){if(t.xingData.frameCount!==null)return t.xingData.frameCount*t.firstFrameHeader.audioSamplesInFrame/t.firstFrameHeader.sampleRate}else if(t.reader.fileSize!==null){let e=Dd(t.firstFrameHeader.lowSamplingFrequency,t.firstFrameHeader.layer,t.firstFrameHeader.bitrate,t.firstFrameHeader.sampleRate),r=(t.reader.fileSize-t.firstFrameHeaderPos)/e;return Math.round(r)*t.firstFrameHeader.audioSamplesInFrame/t.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return se}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return b(this.demuxer.firstFrameHeader),Jr(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{..._e}}async getDecoderConfig(){return b(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Jr(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=Se;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(_(a)&&(a=await a),!a)return null;n=U(a,r.dataSize)}return new j(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=Tr(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{for(;;){let n=G(this.demuxer.loadedSamples,t,a=>a.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,e);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var ba=1399285583,ih=79764919,lm=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^ih:t<<1;lm[i]=t>>>0&4294967295}var dm=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^lm[r>>>24^a])>>>0}return t.setUint32(22,e,!0),r},ya=(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<<jl(a-1))-1<<1,c=(i[0]&o)>>1;if(c>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=e,l=t.vorbisInfo.modeBlockflags[c];if(n=t.vorbisInfo.blocksizes[l],l===1){let d=(o|1)+1,m=i[0]&d?1:0;u=t.vorbisInfo.blocksizes[m]}r=u!==null?u+n>>2:0}else t.codec==="opus"&&(r=yd(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:n}},co=i=>{let t="audio/ogg";if(i.codecStrings){let e=[...new Set(i.codecStrings)];t+=`; codecs="${e.join(", ")}"`}return t};var Br=27,Bi=282,uo=Bi+255*255,An=i=>{let t=i.filePos;if(ni(i)!==ba)return null;i.skip(1);let r=L(i),n=fm(i),a=ni(i),s=ni(i),o=ni(i),c=L(i);if(c===0||i.remainingLength<c)return null;let u=new Uint8Array(c);for(let f=0;f<c;f++)u[f]=L(i);let l=27+c,d=u.reduce((f,p)=>f+p,0),m=l+d;return{headerStartPos:t,totalSize:m,dataStartPos:t+l,dataSize:d,headerType:r,granulePosition:n,serialNumber:a,sequenceNumber:s,checksum:o,lacingValues:u}},mm=(i,t,e)=>{for(;i.filePos<t-3;){let r=ni(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===ba){if(e===void 0||i.filePos+18>i.end)return!0;i.skip(14);let u=ni(i);if(i.skip(-18),u===e)return!0}i.skip(1)}}return!1};var pm=64,nh=30,ah=19,lo=class extends Pe{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,Br,Bi);if(_(r)&&(r=await r),!r)break;let n=An(r);if(!n||!!!(n.headerType&2))break;if(this.bitstreams.length===pm)throw new Error(`Too many (> ${pm}) 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>=nh&&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>=ah&&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 ku(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),u=o.getUint32(12,!0);if(c===0||u===0)throw new Error("Invalid Vorbis identification header: channel count and sample rate must not be 0.");let l=[],d=p=>{for(;l.push(Math.min(255,p)),!(p<255);)p-=255};d(e.data.length),d(a.data.length);let m=new Uint8Array(1+l.length+e.data.length+a.data.length+s.data.length);m[0]=2,m.set(l,1),m.set(e.data,1+l.length),m.set(a.data,1+l.length+e.data.length),m.set(s.data,1+l.length+e.data.length+a.data.length),r.codecInfo.codec="vorbis",r.description=m,r.lastMetadataPacket=s,r.numberOfChannels=c,r.sampleRate=u;let f=o.getUint8(28);r.codecInfo.vorbisInfo={blocksizes:[1<<(f&15),1<<(f>>4)],modeBlockflags:Es(s.data).modeBlockflags},ra(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=Qr(e.data);r.numberOfChannels=s.outputChannelCount,r.sampleRate=Ft,r.codecInfo.opusInfo={preSkip:s.preSkip},ra(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(_(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,Br,Bi);if(_(g)&&(g=await g),!g)return null;let h=An(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 u=c.reduce((m,f)=>m+f.length,0);if(u===0)return null;let l=new Uint8Array(u),d=0;for(let m=0;m<c.length;m++){let f=c[m];l.set(f,d),d+=f.length}return{data:l,endPage:a,endSegmentIndex:o}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let n=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let a=this.reader.requestSliceRange(n,Br,Bi);if(_(a)&&(a=await a),!a)return null;let s=An(a);if(!s)return null;if(s.serialNumber===e.endPage.serialNumber)return{startPage:s,startSegmentIndex:0};n=s.headerStartPos+s.totalSize}}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.trackBackings.map(r=>r.getDecoderConfig().then(n=>n?.codec??null)));return co({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},ku=class{constructor(t,e){this.bitstream=t;this.demuxer=e;this.encodedPacketToMetadata=new WeakMap;this.sequentialScanCache=[];this.sequentialScanMutex=new He;this.firstTimestampInSamplesPromise=null;this.internalSampleRate=t.codecInfo.codec==="opus"?Ft:t.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}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 se}getDisposition(){return{..._e,primary:!1}}granulePositionToTimestampInSamples(t){return this.bitstream.codecInfo.codec==="opus"?(b(this.bitstream.codecInfo.opusInfo),t-this.bitstream.codecInfo.opusInfo.preSkip):t}createEncodedPacketFromOggPacket(t,e,r){if(!t)return null;let n=ya(t.data,this.bitstream.codecInfo,e.vorbisLastBlocksize),{vorbisBlockSize:a}=n,{durationInSamples:s}=n;if(!!(t.endPage.headerType&4)&&t.endSegmentIndex===t.endPage.lacingValues.length-1){let d=this.granulePositionToTimestampInSamples(t.endPage.granulePosition);s=J(d-e.timestampInSamples,0,s)}let c=Math.max(e.timestampInSamples,0),u=Math.max(e.timestampInSamples+s,0),l=new j(r.metadataOnly?Se:t.data,"key",c/this.internalSampleRate,(u-c)/this.internalSampleRate,t.endPage.headerStartPos+t.endSegmentIndex,t.data.byteLength);return this.encodedPacketToMetadata.set(l,{packet:t,timestampInSamples:e.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:e.vorbisLastBlocksize,vorbisBlockSize:a}),l}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;for(;e;){let s=await this.demuxer.readPacket(e.startPage,e.startSegmentIndex);if(!s||(r??=s.endPage,s.endPage.headerStartPos!==r.headerStartPos))break;let{durationInSamples:o,vorbisBlockSize:c}=ya(s.data,this.bitstream.codecInfo,a);n+=o,a=c,e=await this.demuxer.findNextPacketStart(s)}return r?t+Math.max(r.granulePosition-n,0):t})()}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=wr(t*this.internalSampleRate),n=await this.getFirstTimestampInSamples();if(r===Math.max(n,0))return this.getFirstPacket(e);if(r<Math.max(n,0))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 w=s.headerStartPos,T=Math.floor((w+o)/2),S=T;for(;;){let x=Math.min(S+uo,o-Br),C=this.demuxer.reader.requestSlice(S,Math.max(x-S,0));if(_(C)&&(C=await C),!C||!mm(C,x,this.bitstream.serialNumber)){if(o<=T+Br)break e;o=T+Br;continue e}let P=C.filePos,A=this.demuxer.reader.requestSliceRange(P,Br,Bi);_(A)&&(A=await A);let I=A&&An(A);if(!I||I.serialNumber!==this.bitstream.serialNumber){S=P+4;continue}if(I.granulePosition===-1){S=I.headerStartPos+I.totalSize;continue}this.granulePositionToTimestampInSamples(I.granulePosition)>r?o=I.headerStartPos:(s=I,c.push(I));continue e}}let u=a.startPage;for(let w of c){if(w.granulePosition===s.granulePosition)break;(!u||w.headerStartPos>u.headerStartPos)&&(u=w)}let l=u,d=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){let w=l.headerStartPos+l.totalSize,T=this.demuxer.reader.requestSliceRange(w,Br,Bi);_(T)&&(T=await T);let S=T&&An(T);if(!S){l=s,d.push(s);break}l=S,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}let m=null,f,p,g=l,h=0;if(l.headerStartPos===a.startPage.headerStartPos)f=n,p=!0,m=0;else{b(l.granulePosition!==-1),f=0,p=!1;for(let S=l.lacingValues.length-1;S>=0;S--)if(l.lacingValues[S]<255){m=S+1;break}if(m===null)throw new Error("Invalid page with granule position: no packets end on this page.");h=m-1;let w={data:Se,endPage:g,endSegmentIndex:h},T=await this.demuxer.findNextPacketStart(w);if(T){let S=gm(d,l,m);b(S);let x=hm(d,S.page,S.segmentIndex);x?(l=x.page,m=x.segmentIndex):(l=T.startPage,m=T.startSegmentIndex)}else for(;;){let S=gm(d,l,m);if(!S)break;let x=hm(d,S.page,S.segmentIndex);if(!x)break;if(l=x.page,m=x.segmentIndex,S.page.headerStartPos!==g.headerStartPos){g=S.page,h=S.segmentIndex;break}}}let y=null,k=null;for(;l!==null;){b(m!==null);let w=await this.demuxer.readPacket(l,m);if(!w)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let x=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f,vorbisLastBlocksize:k?.vorbisBlockSize??null},e);b(x);let C=this.encodedPacketToMetadata.get(x);if(b(C),!p&&w.endPage.headerStartPos===g.headerStartPos&&w.endSegmentIndex===h?(f=this.granulePositionToTimestampInSamples(l.granulePosition),p=!0,x=this.createEncodedPacketFromOggPacket(w,{timestampInSamples:f-C.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},e),b(x),C=this.encodedPacketToMetadata.get(x),b(C)):f+=C.durationInSamples,y=x,k=C,p&&(Math.max(f,0)>r||Math.max(C.timestampInSamples,0)===r))break}let S=await this.demuxer.findNextPacketStart(w);if(!S)break;l=S.startPage,m=S.startSegmentIndex}return y}async getPacketSequential(t,e){let r=await this.sequentialScanMutex.acquire();try{let n=wr(t*this.internalSampleRate);t=n/this.internalSampleRate;let a=G(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 u=this.encodedPacketToMetadata.get(s);b(u),this.sequentialScanCache.length>0&&b(Y(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return s}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}},hm=(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=Kc(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}},gm=(i,t,e)=>{if(e>0)return{page:t,segmentIndex:e-1};let r=Kc(i,n=>n.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var mo=class extends Pe{constructor(e){super(e);this.metadataPromise=null;this.dataStart=-1;this.dataSize=-1;this.audioInfo=null;this.trackBackings=[];this.lastKnownPacketIndex=0;this.metadataTags={};this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);_(e)&&(e=await e),b(e);let r=ue(e,4),n=r!=="RIFX",a=r==="RF64",s=Or(e,n),o=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(ue(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let u=0,l=null,d=e.filePos;for(;o===null||d<o;){let f=this.reader.requestSlice(d,8);if(_(f)&&(f=await f),!f)break;let p=ue(f,4),g=Or(f,n),h=f.filePos;if(a&&u===0&&p!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(p==="fmt ")await this.parseFmtChunk(h,g,n);else if(p==="data"){if(l??=g,this.dataStart=f.filePos,this.dataSize=Math.max(Math.min(l,(o??1/0)-this.dataStart),0),this.reader.fileSize===null)break}else if(p==="ds64"){let y=this.reader.requestSlice(h,g);if(_(y)&&(y=await y),!y)break;if(g<16)throw new Error('Invalid RF64 file: "ds64" chunk is too small.');let k=wu(y,n);l=wu(y,n),o=Math.min(k+8,this.reader.fileSize??1/0)}else p==="LIST"?await this.parseListChunk(h,g,n):(p==="ID3 "||p==="id3 ")&&await this.parseId3Chunk(h,g);d=h+g+(g&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 m=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/m)*m,this.trackBackings.push(new Tu(this))})()}async parseFmtChunk(e,r,n){let a=this.reader.requestSlice(e,r);if(_(a)&&(a=await a),!a)return;if(r<14)throw new Error('Invalid WAVE file - "fmt " chunk is too small');let s=Cn(a,n),o=Cn(a,n),c=Or(a,n);a.skip(4);let u=Cn(a,n);if(o===0||c===0||u===0)throw new Error("Invalid WAVE file - channel count, sample rate and block align must be positive");let l;if(r<16?l=8:l=Cn(a,n),r>=18&&s!==357){let d=Cn(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.`);this.audioInfo={format:s,numberOfChannels:o,sampleRate:c,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:u}}async parseListChunk(e,r,n){if(r<4)return;let a=this.reader.requestSlice(e,r);if(_(a)&&(a=await a),!a)return;let s=ue(a,4);if(s!=="INFO"&&s!=="INF0")return;let o=a.filePos;for(;o<=e+r-8;){a.filePos=o;let c=ue(a,4),u=Or(a,n);if(u>a.remainingLength)break;let l=U(a,u),d="";for(let m=0;m<l.length&&l[m]!==0;m++)d+=String.fromCharCode(l[m]);switch(this.metadataTags.raw??={},this.metadataTags.raw[c]=d,c){case"INAM":case"TITL":this.metadataTags.title??=d;break;case"TIT3":this.metadataTags.description??=d;break;case"IART":this.metadataTags.artist??=d;break;case"IPRD":this.metadataTags.album??=d;break;case"IPRT":case"ITRK":case"TRCK":{let m=d.split("/"),f=Number.parseInt(m[0],10),p=m[1]&&Number.parseInt(m[1],10);Number.isInteger(f)&&f>0&&(this.metadataTags.trackNumber??=f),p&&Number.isInteger(p)&&p>0&&(this.metadataTags.tracksTotal??=p)}break;case"ICRD":case"IDIT":{let m=new Date(d);Number.isNaN(m.getTime())||(this.metadataTags.date??=m)}break;case"YEAR":{let m=Number.parseInt(d,10);Number.isInteger(m)&&m>0&&(this.metadataTags.date??=new Date(m,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=d;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=d;break}o+=8+u+(u&1)}}async parseId3Chunk(e,r){if(r<Fe)return;let n=this.reader.requestSlice(e,r);if(_(n)&&(n=await n),!n)return;let a=it(n);if(a){let s=r-Fe;if(a.size=Math.min(a.size,s),a.size>0){let o=n.slice(e+Fe,a.size);ii(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)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},xn=2048,Tu=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}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.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return se}getDisposition(){return{..._e}}async getPacketAtIndex(t,e){b(t>=0),b(this.demuxer.audioInfo);let r=t*xn*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let n=Math.min(xn*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,n);if(_(c)&&(c=await c),!c)return null}let a;if(e.metadataOnly)a=Se;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,n);_(c)&&(c=await c),b(c),a=U(c,n)}let s=t*xn/this.demuxer.audioInfo.sampleRate,o=n/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(t,this.demuxer.lastKnownPacketIndex),new j(a,"key",s,o,t,n)}getFirstPacket(t){return this.getPacketAtIndex(0,t)}async getPacket(t,e){b(this.demuxer.audioInfo);let r=Math.floor(Math.min(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);if(n)return n;if(r===0)return null;b(this.demuxer.reader.fileSize===null);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,e);for(;a;){let s=await this.getNextPacket(a,e);if(!s)break;a=s}return a}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 Ut=7,bt=9,nt=i=>{let t=i.filePos;if(i.remainingLength<Ut)return null;let e=U(i,Ut),r=new H(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>=tt.length)return null;r.skipBits(1);let u=r.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let l=r.readBits(13);r.skipBits(11);let d=r.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let m=null;if(s===0){if(i.remainingLength<2)return null;m=fe(i)}return l<i.filePos-t?null:{objectType:o,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:d,crcCheck:m,startPos:t}};var ka=1024,fo=class extends Pe{constructor(e){super(e);this.metadataPromise=null;this.firstFrameHeader=null;this.loadedSamples=[];this.metadataTags=null;this.trackBackings=[];this.readingMutex=new He;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();b(this.firstFrameHeader),this.trackBackings=[new Su(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Fe);if(_(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}let c=it(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Ut,bt);if(_(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}let r=nt(e);if(!r){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&r.startPos+r.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=r);let n=tt[r.samplingFrequencyIndex];b(n!==void 0);let a=ka/n,s={timestamp:this.nextTimestampInSamples/n,duration:a,dataStart:r.startPos,dataSize:r.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=ka,this.lastLoadedPos=r.startPos+r.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,Fe);if(_(n)&&(n=await n),!n)break;let a=it(n);if(!a)break;let s=this.reader.requestSlice(n.filePos,a.size);if(_(s)&&(s=await s),!s)break;ii(s,a,this.metadataTags),r=n.filePos+a.size}return this.metadataTags}finally{e()}}},Su=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ka}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 se}getCodec(){return"aac"}getInternalCodecId(){return b(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){b(this.demuxer.firstFrameHeader);let t=Yt[this.demuxer.firstFrameHeader.channelConfiguration];return b(t!==void 0),t}getSampleRate(){b(this.demuxer.firstFrameHeader);let t=tt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return b(t!==void 0),t}getDisposition(){return{..._e}}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=Se;else{let a=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(_(a)&&(a=await a),!a)return null;n=U(a,r.dataSize)}return new j(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=Tr(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{for(;;){let n=G(this.demuxer.loadedSamples,t,a=>a.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,e);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,e);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(t,e){return this.getPacket(t,e)}getNextKeyPacket(t,e){return this.getNextPacket(t,e)}};var po=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,bm=(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}},ho=i=>{let t=0,e=new H(U(i,1));for(;e.readBits(1)===1;)t++;if(t===0)return e.readBits(7);let r=[],n=t-1,a=new H(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 u=0;u<8;u++){let l=a.readBits(1);u<2||r.unshift(l)}return r.reduce((c,u,l)=>c|u<<l,0)},go=(i,t)=>{if(t==="uncommon-u16")return fe(i)+1;if(t==="uncommon-u8")return L(i)+1;if(typeof t=="number")return t;ae(t),b(!1)},ym=(i,t)=>t==="uncommon-u16"?fe(i):t==="uncommon-u16-10"?fe(i)*10:t==="uncommon-u8"?L(i):typeof t=="number"?t:null,km=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 bo=class extends Pe{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 He;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,Fe);if(_(r)&&(r=await r),!r)break;let n=it(r);if(!n)break;let a=this.reader.requestSlice(r.filePos,n.size);_(a)&&(a=await a),b(a),ii(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=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);b(r);let n=L(r),a=Dt(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(_(c)&&(c=await c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let u=U(c,34),l=new H(u),d=l.readBits(16),m=l.readBits(16),f=l.readBits(24),p=l.readBits(24),g=l.readBits(20);if(g===0)throw new Error("Invalid StreamInfo block: sample rate is 0. Corrupted file.");let h=l.readBits(3)+1;l.readBits(5);let y=l.readBits(36);l.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(u,8),this.audioInfo={numberOfChannels:h,sampleRate:g,totalSamples:y,minimumBlockSize:d,maximumBlockSize:m,minimumFrameSize:f,maximumFrameSize:p,description:k},this.trackBacking=new Au(this);break}case 4:{let c=this.reader.requestSlice(e,a);if(_(c)&&(c=await c),!c)throw new Error(`Vorbis comment block at position ${e} exceeds the file. Corrupted file.`);ra(U(c,a),this.metadataTags);break}case 6:{let c=this.reader.requestSlice(e,a);if(_(c)&&(c=await c),!c)throw new Error(`Picture block at position ${e} exceeds the file. Corrupted file.`);try{let u=M(c),l=M(c),d=he.decode(U(c,l)),m=M(c),f=he.decode(U(c,m));c.skip(16);let p=M(c),g=U(c,p);this.metadataTags.images??=[],this.metadataTags.images.push({data:g,mimeType:d,kind:u===3?"coverFront":u===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,u=(this.audioInfo.maximumFrameSize||s)+n,l=await this.reader.requestSliceRange(e,n,u);if(!l)return null;let d=this.readFlacFrameHeader(l);if(!d)return null;for(l.filePos=e+o;;){if(l.filePos>l.end-r)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:l.end-e,isLastFrame:!0};if(L(l)===255){let f=l.filePos,p=L(l),g=this.blockingBit===1?249:248;if(p!==g){l.filePos=f;continue}l.skip(-2);let h=l.filePos-e,y=this.readFlacFrameHeader(l);if(!y){l.filePos=f;continue}if(this.blockingBit===0){if(y.num-d.num!==1){l.filePos=f;continue}}else if(y.num-d.num!==d.blockSize){l.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 H(n);if(a.readBits(15)!==32764)return null;let o=a.readBits(1);if(this.blockingBit!==null&&o!==this.blockingBit)return null;let c=po(a.readBits(4));if(!c)return null;b(this.audioInfo);let u=bm(a.readBits(4),this.audioInfo.sampleRate);if(!u||(a.readBits(4),a.readBits(3),a.readBits(1)!==0))return null;let d=L(e);e.skip(-1);let f=4+Math.max(Math.clz32(~d<<24),1)+(c==="uncommon-u16"?2:c==="uncommon-u8"?1:0)+(u==="uncommon-u8"?1:typeof u=="number"?0:2)+1;if(r+f>e.end)return null;let p=ho(e),g=go(e,c),h=ym(e,u);if(h===null||h!==this.audioInfo.sampleRate)return null;let y=e.filePos-r,k=L(e);e.skip(-y),e.skip(-1);let w=km(U(e,y));return k!==w?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}}},Au=class{constructor(t){this.demuxer=t}getType(){return"audio"}getId(){return 1}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 se}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{..._e}}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{for(;;){let n=G(this.demuxer.loadedSamples,t,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){if(this.demuxer.lastSampleLoaded)return null;await this.demuxer.advanceReader();continue}let a=this.demuxer.loadedSamples[n],s=a.blockOffset/this.demuxer.audioInfo.sampleRate,o=a.blockSize/this.demuxer.audioInfo.sampleRate;if(s+o<=t){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,e);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,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=Se;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(_(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 j(n,"key",a,s,t,r.byteSize)}async getFirstPacket(t){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,t)}};var yo=i=>{let t="video/MP2T",e=[...new Set(i.filter(Boolean))];return e.length>0&&(t+=`; codecs="${e.join(", ")}"`),t};var Am="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.",Tm=5,oh=1212435798,ch=1212436562,uh=1146376960,lh=new Set([133,134,162]),wm=new Set,ko=class extends Pe{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=205,r=this.reader.requestSlice(0,e);_(r)&&(r=await r),b(r);let n=U(r,e);if(n[0]===71&&n[188]===71)this.packetOffset=0,this.packetStride=188;else if(n[0]===71&&n[204]===71)this.packetOffset=0,this.packetStride=204;else if(n[4]===71&&n[196]===71)this.packetOffset=4,this.packetStride=192;else throw new Error("Unreachable.");let a=256;this.minReferencePointByteDistance=a*this.packetStride;let s=this.packetOffset,o=null,c=!1,u=!1;for(;;){let l=await this.readPacketHeader(s);if(!l)break;if(l.payloadUnitStartIndicator===0){s+=this.packetStride;continue}if(u&&!this.elementaryStreams.some(h=>h.pid===l.pid&&!h.initialized)){s+=this.packetStride;continue}let d=await this.readSection(s,!0,!u);if(!d)break;let m=3,f=32,p=!1;if(!u&&d.pid!==0&&!(d.payload[0]===0&&d.payload[1]===0&&d.payload[2]===1)){let y=new H(d.payload),k=y.readAlignedByte();y.skipBits(8*k),p=y.readBits(8)===2}if(d.pid===0&&!c){let h=new H(d.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(14);let k=h.readBits(10);for(h.skipBits(40);8*(k+m)-h.pos>f;){let w=h.readBits(16);h.skipBits(3);let T=h.readBits(13);if(w!==0){if(o!==null)throw new Error("Only files with a single program are supported.");o=T}}if(o===null)throw new Error("Program Association Table must link to a Program Map Table.");c=!0}else if((d.pid===o||p)&&!u){let h=new H(d.payload),y=h.readAlignedByte();h.skipBits(8*y),h.skipBits(12);let k=h.readBits(12);h.skipBits(43);let w=h.readBits(13);h.skipBits(6);let T=h.readBits(10),S=h.pos+8*T,x=!1;for(;h.pos<S;){let C=h.readBits(8),P=h.readBits(8),A=h.pos+8*P;if(C===Tm&&P>=4){let I=h.readBits(32);x||=I===oh||I===ch}h.pos=A}for(h.pos=S;8*(k+m)-h.pos>f;){let C=h.readBits(8);h.skipBits(3);let P=h.readBits(13);h.skipBits(6);let A=h.readBits(10),I=h.pos+8*A,E=!1,v=!1,R=!1;for(;h.pos<I;){let D=h.readBits(8),q=h.readBits(8),ie=h.pos+8*q;if(D===106)E=!0;else if(D===122||D===204)v=!0;else if(D===123)R=!0;else if(D===Tm&&q>=4){let be=h.readBits(32);R||=(be&4294967040)===uh}h.pos=ie}let B=null,z=x&&lh.has(C)?130:C;switch(z){case 27:case 36:B={type:"video",codec:C===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 D;z===3||z===4?D="mp3":z===15?D="aac":z===129?D="ac3":z===135?D="eac3":D="dts",B={type:"audio",codec:D,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:v?B={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:E?B={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:R&&(B={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:wm.has(C)||(V._warn(`Note: MPEG-TS streams with stream_type 0x${C.toString(16)} are not currently supported.`),wm.add(C))}B&&this.elementaryStreams.push({demuxer:this,pid:P,streamType:C,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:B,referencePesPackets:[]})}u=!0}else{let h=this.elementaryStreams.find(y=>y.pid===d.pid);e:if(h&&!h.initialized){let y=Pn(this,d,!0);if(!y)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${h.pid}`);if(h.firstSection=d,h.canBeTrustedWithKeyPackets=d.randomAccessIndicator===1,this.input._initInput){let T=(await this.input._initInput._getDemuxer()).elementaryStreams.find(S=>S.pid===d.pid&&S.info.codec===h.info.codec&&S.initialized);if(T){h.info=T.info,h.initialized=!0;break e}}let k=new Di(h,y);if(h.info.type==="video"){for(;;){let w=k;if(w.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=er(k.suppliedPacket.data),!h.info.avcCodecInfo)continue;let T=h.info.avcCodecInfo.sequenceParameterSets[0];b(T);let S=rr(T);h.info.width=S.displayWidth,h.info.height=S.displayHeight;let x=S.pixelAspectRatio.num,C=S.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,x>0&&C>0&&(x>C?h.info.squarePixelWidth=Math.round(h.info.width*x/C):h.info.squarePixelHeight=Math.round(h.info.height*C/x)),h.info.colorSpace={primaries:ft[S.colourPrimaries],transfer:pt[S.transferCharacteristics],matrix:ht[S.matrixCoefficients],fullRange:!!S.fullRangeFlag},h.info.reorderSize=S.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=ir(k.suppliedPacket.data),!h.info.hevcCodecInfo)continue;let S=h.info.hevcCodecInfo.arrays.find(A=>A.nalUnitType===33).nalUnits[0];b(S);let x=Fi(S);h.info.width=x.displayWidth,h.info.height=x.displayHeight;let C=x.pixelAspectRatio.num,P=x.pixelAspectRatio.den;h.info.squarePixelWidth=h.info.width,h.info.squarePixelHeight=h.info.height,C>0&&P>0&&(C>P?h.info.squarePixelWidth=Math.round(h.info.width*C/P):h.info.squarePixelHeight=Math.round(h.info.height*P/C)),h.info.colorSpace={primaries:ft[x.colourPrimaries],transfer:pt[x.transferCharacteristics],matrix:ht[x.matrixCoefficients],fullRange:!!x.fullRangeFlag},h.info.reorderSize=x.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}h.info.decoderConfig={codec:Xr({width:h.info.width,height:h.info.height,codec:h.info.codec,codecDescription:null,colorSpace:h.info.colorSpace,avcType:1,avcCodecInfo:h.info.avcCodecInfo,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 w=we.tempFromBytes(k.suppliedPacket.data),T=nt(w);if(!T)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");h.info.aacCodecInfo={isMpeg2:!1,objectType:T.objectType},h.info.numberOfChannels=Yt[T.channelConfiguration],h.info.sampleRate=tt[T.samplingFrequencyIndex]}else if(h.info.codec==="mp3"){let w=M(we.tempFromBytes(k.suppliedPacket.data)),T=Zr(w,k.suppliedPacket.data.byteLength);if(!T.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");h.info.numberOfChannels=Jr(T.header.channel),h.info.sampleRate=T.header.sampleRate}else if(h.info.codec==="ac3"){let w=vs(k.suppliedPacket.data);if(!w)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(w.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=na[w.acmod]+w.lfeon,h.info.sampleRate=Ri[w.fscod]}else if(h.info.codec==="eac3"){let w=_s(k.suppliedPacket.data);if(!w)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let T=Rs(w);if(T===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");h.info.numberOfChannels=Fs(w),h.info.sampleRate=T}else if(h.info.codec==="dts"){let w=ca(k.suppliedPacket.data);if(!w)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");h.info.numberOfChannels=w.numberOfChannels,h.info.sampleRate=w.sampleRate,w.core&&(h.info.dtsFormat=w.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");h.info.decoderConfig={codec:mn({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(u&&this.elementaryStreams.every(h=>h.initialized))break;s+=this.packetStride}if(!u)throw c?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(let l of this.elementaryStreams)l.initialized&&(l.info.type==="video"?this.trackBackingEntries.push(new xu(l)):this.trackBackingEntries.push(new Cu(l)))})()}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 yo(e)}async readSection(e,r,n=!1){let a=e,s=e,o=[],c=0,u=null,l=!0,d=0;for(;;){let f=await this.readPacket(s);if(s+=this.packetStride,!f)break;if(u){if(f.pid!==u.pid){if(n)break;continue}if(f.payloadUnitStartIndicator===1)break}else{if(f.payloadUnitStartIndicator===0)break;u=f}let p=!!(f.adaptationFieldControl&2),g=!!(f.adaptationFieldControl&1),h=0;if(p&&(h=1+f.body[0],f===u&&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){l=!1;break}if(Tr(this.sectionEndPositions,a,k=>k)!==-1){l=!1;break}}if(l){let f=G(this.sectionEndPositions,a,p=>p);this.sectionEndPositions.splice(f+1,0,a)}if(!u)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,endPos:r?a:null,pid:u.pid,payload:m,randomAccessIndicator:d}}async readPacketHeader(e){let r=this.reader.requestSlice(e,4);if(_(r)&&(r=await r),!r)return null;if(L(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,u=a&8191,l=L(r),d=l>>6,m=l>>4&3,f=l&15;return{payloadUnitStartIndicator:o,pid:u,adaptationFieldControl:m}}async readPacket(e){let r=this.reader.requestSlice(e,188);if(_(r)&&(r=await r),!r)return null;let n=U(r,188);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,u=s>>13&1,l=s&8191,d=n[3],m=d>>6,f=d>>4&3,p=d&15;return{payloadUnitStartIndicator:c,pid:l,adaptationFieldControl:f,body:n.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){let a=60*9e4;this.timestampWrapInfo={reference:e-a,offset:e>=8589934592-a?-8589934592:8589934592}}let{reference:r,offset:n}=this.timestampWrapInfo;return n<0&&e>=r||n>0&&e<r?e+n:e}},Oi=(i,t,e)=>{if(t.payload.byteLength<3)return null;let r=new H(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(Am);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:o,randomAccessIndicator:t.randomAccessIndicator}},Pn=(i,t,e)=>{b(t.endPos!==null);let r=Oi(i,t,e);if(!r)return null;let n=new H(t.payload);n.skipBits(32);let a=n.readBits(16),s=6;n.skipBits(16);let o=n.readBits(8),c=n.pos+8*o;n.pos=c;let u=c/8;b(Number.isInteger(u));let l=t.payload.subarray(u,a>0?s+a:t.payload.byteLength);return{...r,data:l}},To=class i{constructor(t){this.elementaryStream=t;this.packetBuffers=new WeakMap;this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}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 se}getDisposition(){return{..._e,primary:!1}}getTimeResolution(){return 9e4}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 j(r.metadataOnly?Se:t.data,n,t.pts/9e4,Math.max(e/9e4,0),t.sequenceNumber,t.data.byteLength)}async getFirstPacket(t){let e=this.elementaryStream.firstSection;b(e);let r=Pn(this.elementaryStream.demuxer,e,!0);b(r);let n=new Di(this.elementaryStream,r),a=new Ta(this,n),s=await a.readNext();if(!s)return null;let o=this.createEncodedPacket(s.packet,s.duration,t);return this.packetBuffers.set(o,a),this.packetSectionStarts.set(o,s.packet.sectionStartPos),o}async getNextPacket(t,e){let r=this.packetBuffers.get(t);if(r){let l=await r.readNext();if(!l)return null;this.packetBuffers.delete(t);let d=this.createEncodedPacket(l.packet,l.duration,e);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}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=await a.readSection(n,!0);b(s);let o=Pn(a,s,!0);b(o);let c=new Di(this.elementaryStream,o);r=new Ta(this,c);let u=t.sequenceNumber;for(;;){let l=await r.readNext();if(!l)return null;if(l.packet.sequenceNumber>u){let d=this.createEncodedPacket(l.packet,l.duration,e);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}}}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=wr(t*9e4),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:o}=a,c=this.elementaryStream.pid,u=async(T,S,x)=>{let C=T;for(;C<S;){let P=await a.readPacketHeader(C);if(!P)return null;if(P.pid===c&&P.payloadUnitStartIndicator===1){let A=await a.readSection(C,x);if(!A)return null;let I=Oi(a,A,!1);if(I&&I.pts!==null)return{pesPacketHeader:I,section:A}}C+=a.packetStride}return null},l=this.elementaryStream.firstSection;b(l);let d=Oi(a,l,!0);if(b(d),n<d.pts)return null;let m,f=this.elementaryStream.referencePesPackets,p=G(f,n,T=>T.pts),g=p!==-1?f[p]:null;if(g&&n-g.pts<9e4/2)m=g.sectionStartPos;else{let T=0;if(s.fileSize!==null){let S=Math.ceil(s.fileSize/o);if(S>1){let x=0,C=S-1;for(T=x;x<=C;){let P=Math.floor((x+C)/2),A=ps(P*o,a.packetStride)+d.sectionStartPos,I=A+o,E=await u(A,I,!1);if(!E){C=P-1;continue}E.pesPacketHeader.pts<=n?(T=P,x=P+1):C=P-1}}}m=ps(T*o,a.packetStride)+d.sectionStartPos}let y=(await u(m,s.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);let k=this.getReorderSize(),w=async(T,S)=>{let x=await a.readSection(T,!0);b(x);let C=Pn(a,x,!0);b(C);let P=new Di(this.elementaryStream,C),A=new Ta(this,P);for(;!((Y(A.presentationOrderPackets)?.pts??-1/0)>=n||!await A.readNextPacket()););let I=qr(A.presentationOrderPackets,S);if(I===-1)return null;let E=A.presentationOrderPackets[I],v=I===0?0:E.pts-A.presentationOrderPackets[I-1].pts;A.decodeOrderPackets.splice(0,A.decodeOrderPackets.indexOf(E)),A.lastDuration=v;let R=await A.readNext();b(R);let B=this.createEncodedPacket(R.packet,R.duration,r);return this.packetBuffers.set(B,A),this.packetSectionStarts.set(B,R.packet.sectionStartPos),B};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 x=await a.readSection(T,!1);if(x){let C=Oi(a,x,!1);if(C&&C.pts!==null){if(C.pts>n)break e;y=C,Pu(this.elementaryStream,y);break}}}T+=a.packetStride}}e:for(let T=0;T<k+1;T++){let S=y.sectionStartPos-a.packetStride;for(;S>=a.packetOffset;){let x=await a.readPacketHeader(S);if(!x)break e;if(x.pid===c&&x.payloadUnitStartIndicator===1){let C=await a.readSection(S,!1);if(C){let P=Oi(a,C,!1);if(P&&P.pts!==null){y=P;break}}}S-=a.packetStride}if(S<a.packetOffset)break}return w(y.sectionStartPos,T=>T.pts<=n)}else{let T=m,S=null,x=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let C=null,P=T<=d.sectionStartPos,A,I=null;if(P)A=d,I=l;else{let B=await u(T,S??s.fileSize??1/0,x);A=B?.pesPacketHeader??null,I=B?.section??null}let E=!1,v=0,R=null;e:for(;A&&!(S!==null&&A.sectionStartPos>=S);){if(A.pts<=n){let z;if(this.elementaryStream.canBeTrustedWithKeyPackets)z=A.randomAccessIndicator===1;else{if(!R){b(I);let D=Pn(a,I,!0);b(D),R=new Di(this.elementaryStream,D)}for(;(!R.suppliedPacket||R.suppliedPacket.sectionStartPos<A.sectionStartPos)&&(R.suppliedPacket=null,await R.markNextPacket(),!!R.suppliedPacket););z=R.suppliedPacket?.sectionStartPos===A.sectionStartPos&&R.suppliedPacket.randomAccessIndicator===1}z&&(C=A)}if(A.pts>n&&(E=!0),E&&(v++,v>k))break;let B=A.sectionStartPos+a.packetStride;for(;;){let z=await a.readPacketHeader(B);if(!z)break e;if(z.pid===c&&z.payloadUnitStartIndicator===1){let D=await a.readSection(B,x);if(D){let q=Oi(a,D,!1);if(q&&q.pts!==null){A=q,I=D,Pu(this.elementaryStream,A);break}}}B+=a.packetStride}}if(C){let B=C;if(v===0)e:for(let D=0;D<k;D++){let q=B.sectionStartPos-a.packetStride;for(;q>=a.packetOffset;){let ie=await a.readPacketHeader(q);if(!ie)break e;if(ie.pid===c&&ie.payloadUnitStartIndicator===1){let be=await a.readSection(q,x);if(be){let Te=Oi(a,be,!1);if(Te&&Te.pts!==null){B=Te;break}}}q-=a.packetStride}if(q<a.packetOffset)break}let z=await w(B.sectionStartPos,D=>D.pts<=n&&D.randomAccessIndicator===1);if(z)return z}if(P)return null;S=T,T=Math.max(ps(T-d.sectionStartPos-o,a.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}},xu=class extends To{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[...Wr]}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}},Cu=class extends To{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}},Pu=(i,t)=>{let e=i.referencePesPackets,r=G(e,t.sectionStartPos,n=>n.sectionStartPos);if(r>=0){let n=e[r];if(t.pts<=n.pts)return!1;let a=i.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-n.sectionStartPos<a)return!1;if(r<e.length-1){let s=e[r+1];if(s.pts<t.pts||s.sectionStartPos-t.sectionStartPos<a)return!1}}return e.splice(r+1,0,t),!0},Di=class{constructor(t,e){this.currentPos=0;this.pesPackets=[];this.currentPesPacketIndex=0;this.currentPesPacketPos=0;this.endPos=0;this.lastSuppliedPesPacket=null;this.nextPts=null;this.suppliedPacket=null;this.elementaryStream=t,this.pid=t.pid,this.demuxer=t.demuxer,this.startingPesPacket=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))}getCurrentPesPacket(){let t=this.pesPackets[this.currentPesPacketIndex];return b(t),t}async bufferData(t){let e=this.endPos+t;for(;this.endPos<e;){let r;if(this.pesPackets.length===0)r=this.startingPesPacket;else{let n=Y(this.pesPackets).sectionEndPos;for(b(n!==null);;){let a=await this.demuxer.readPacketHeader(n);if(!a)return;if(a.pid===this.pid){let s=await this.demuxer.readSection(n,!0);if(!s)return;let o=Pn(this.demuxer,s,!1);if(o){r=o;break}}n+=this.demuxer.packetStride}}this.pesPackets.push(r),this.endPos+=r.data.byteLength}}readBytes(t){let e=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos,n=r+t;if(this.currentPos+=t,n<=e.data.byteLength)return e.data.subarray(r,n);let a=new Uint8Array(t);a.set(e.data.subarray(r));let s=e.data.byteLength-r;for(;;){this.advanceCurrentPacket();let o=this.getCurrentPesPacket(),c=t-s;if(c<=o.data.byteLength){a.set(o.data.subarray(0,c),s);break}a.set(o.data,s),s+=o.data.byteLength}return a}readU8(){let t=this.getCurrentPesPacket(),e=this.currentPos-this.currentPesPacketPos;if(this.currentPos++,e<t.data.byteLength)return t.data[e];do this.advanceCurrentPacket(),t=this.getCurrentPesPacket();while(t.data.byteLength===0);return t.data[0]}seekTo(t){if(t!==this.currentPos){if(t<this.currentPos)for(;t<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){let e=this.getCurrentPesPacket(),r=this.currentPesPacketPos+e.data.byteLength;if(t<r)break;this.currentPesPacketPos+=e.data.byteLength,this.currentPesPacketIndex++}this.currentPos=t}}skip(t){this.seekTo(this.currentPos+t)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}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(_(c)&&(c=await c),c===0)break;let u=this.currentPos,l=this.readBytes(c),d=l.byteLength,m=0;for(;m<d;){let f=l.indexOf(0,m);if(f===-1||f>=d)break;m=f;let p=u+m;if(m+3>=d){this.seekTo(p);break}let g=l[m+1],h=l[m+2],y=l[m+3],k=0;if(g===0&&h===0&&y===1?k=4:g===0&&h===1&&(k=3),k===0){m++;continue}let w=p;a??=w;let T=m+k,S=T+n,x=6;if(S+(e==="avc"?x:1)>d){this.seekTo(p);break}let P=l[T],A,I,E,v;if(e==="avc")A=Jt(P),I=A===1||A===2||A===5,E=A===6||A===7||A===8||A===9,v=A===9;else{if(A=Rt(P),((P&1)<<5|l[T+1]>>3)>0){m+=k;continue}I=A<=9||A>=16&&A<=21,E=A>=32&&A<=37||A===39||A>=41&&A<=44||A>=48&&A<=55,v=A===35}let R=!1;if(I){let B;if(e==="avc"){let z=l.subarray(S,S+x),D=O(new H(z));B=!s||D<=o,o=D}else B=l[S]>>7===1;B&&(s?R=!0:s=!0)}else E&&s?R=!0:v&&(a=w);if(R){let B=w-a;return this.seekTo(a),this.supplyPacket(B,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);_(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(bt);if(_(c)&&(c=await c),c<bt)return;let u=this.readBytes(bt),l=nt(we.tempFromBytes(u));if(l){this.seekTo(o);let d=this.ensureBuffered(l.frameLength);return _(d)&&(d=await d),this.supplyPacket(d,Math.round(ka*9e4/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(_(c)&&(c=await c),c<4)return;let u=this.readBytes(4),l=N(u).getUint32(0),d=Zr(l,null);if(d.header){this.seekTo(o);let m=this.ensureBuffered(d.header.totalSize);_(m)&&(m=await m);let f=d.header.audioSamplesInFrame*9e4/t.info.sampleRate;return this.supplyPacket(m,Math.round(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(_(c)&&(c=await c),c<5)return;let u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}let l=u[4]>>6,d=u[4]&63;if(l===3||d>37){this.seekTo(o+1);continue}let m=kd[3*d+l];b(m!==void 0),this.seekTo(o),c=this.ensureBuffered(m),_(c)&&(c=await c);let f=Math.round(Td*9e4/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(_(c)&&(c=await c),c<5)return;let u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}let d=(((u[2]&7)<<8|u[3])+1)*2,f=u[4]>>6===3?3:u[4]>>4&3,p=au[f];this.seekTo(o),c=this.ensureBuffered(d),_(c)&&(c=await c);let g=p*256,h=Math.round(g*9e4/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(oa);if(_(c)&&(c=await c),c<oa)return;let u=this.readBytes(oa),l=su(u),d=l?null:ua(u);if(!l&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);let g=Math.min(d.frameSize,Sd),h=this.ensureBuffered(g);_(h)&&(h=await h),d=ua(this.readBytes(h))??d}let m=l?l.frameSize:d.frameSize;if(l){let g=Math.ceil(l.frameSize/4)*4;for(;;){this.seekTo(o);let h=g+Ms,y=this.ensureBuffered(h);if(_(y)&&(y=await y),y<h)break;this.seekTo(o+g);let k=ua(this.readBytes(Ms));if(!k)break;g+=k.frameSize,m=g}}let f=l?.sampleCount??d.asset?.sampleCount;if(f===void 0){this.seekTo(o+1);continue}this.seekTo(o),c=this.ensureBuffered(m),_(c)&&(c=await c);let p=Math.round(f*9e4/t.info.sampleRate);return this.supplyPacket(c,p)}else throw new Error("Unhandled.")}if(n<r)break}}}supplyPacket(t,e){let r=this.getCurrentPesPacket(),n;if(this.lastSuppliedPesPacket===r)b(this.nextPts!==null),n=this.nextPts;else{if(r.pts===null)throw new Error(Am);n=r.pts,Pu(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=n+e;let a=r.sectionStartPos,s=a+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(t),c=r.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){let u=jr(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(u)}}this.suppliedPacket={pts:n,data:o,sequenceNumber:s,sectionStartPos:a,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Ta=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.lastDuration:(r=this.presentationOrderPackets[e+1].pts-t.pts,this.lastDuration=r),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 or="application/vnd.apple.mpegurl",Iu="#EXT-X-STREAM-INF:",Eu="#EXT-X-I-FRAME-STREAM-INF:",vu="#EXT-X-MEDIA:",vn="#EXT-X-DEFINE:",wa="#EXTINF:",_u="#EXT-X-MAP:",Ru="#EXT-X-KEY:",Fu="#EXT-X-MEDIA-SEQUENCE:",Mu="#EXT-X-BYTERANGE:",Bu="#EXT-X-PROGRAM-DATE-TIME:",xm="#EXT-X-DISCONTINUITY",Ou="#EXT-X-TARGETDURATION:",Cm="#EXT-X-ENDLIST",Du="#EXT-X-PLAYLIST-TYPE:",Pm="#EXT-X-I-FRAMES-ONLY",wo=i=>i.length===0||i.startsWith("#")&&!i.startsWith("#EXT"),sr=class{constructor(t,e){this._attributes={};let r="",n="",a=!1,s=!1,o=!1,c=()=>{if(!r)return;let u=r.trim().toLowerCase();Object.prototype.hasOwnProperty.call(this._attributes,u)&&V._warn(`Duplicate AttributeName "${u}"; using last value`);let l=o||n.startsWith("0x")||n.startsWith("0X");this._attributes[u]=l&&e?e.substitute(n):n,r="",n="",a=!1,o=!1};for(let u=0;u<t.length;u++){let l=t[u];l==='"'?(a&&!s&&n.length===0&&(o=!0),s=!s):l==="="&&!a&&!s?a=!0:l===","&&!s?c():a?n+=l:r+=l}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)}},dh=/^[A-Za-z0-9_-]+$/,mh=/\{\$([A-Za-z0-9_-]+)\}/g,fh=2**26,En=class{constructor(t,e){this.playlistPath=t;this.importedVariables=e;this.variables=new Map;this.totalSubstitutedLength=0}define(t){let e=new sr(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=ed(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(mh,(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>fh)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(!dh.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 So=class{constructor(t,e,r){this.nextInputCacheAge=0;this.inputCache=[];this.trackBackingsPromise=null;this.firstSegment=null;this.firstSegmentFirstTimestamps=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+e.duration:null}async getUnixTimeForTimestamp(t){let e=await this.getSegmentAt(t,{});if(e??=await this.getFirstSegment({}),!e||e.unixEpochTimestamp===null)return null;let r=t-e.timestamp;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=vi(t,n=>n.getType()==="video")+1;t.push(new xo(this,e,r))}else if(e.type==="audio"){let r=vi(t,n=>n.getType()==="audio")+1;t.push(new Co(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=vi(t,s=>s.getType()==="video")+1;t.push(new xo(this,{id:t.length+1,type:"video"},a))}else if(n.type==="audio"){let a=vi(t,s=>s.getType()==="audio")+1;t.push(new Co(this,{id:t.length+1,type:"audio"},a))}}return t})()}async getMediaOffset(t,e){if(!(await e.getFormat()).supportsTimestampedMediaData)return t.timestamp;let n=t.firstSegment??t,a=this.firstSegmentFirstTimestamps.get(n);return a===void 0&&(a=await this.getInputForSegment(n).getFirstTimestamp(),this.firstSegmentFirstTimestamps.set(n,a)),n.timestamp-a}dispose(){for(let t of this.inputCache)t.input.dispose();this.inputCache.length=0}},Ao=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})()}getId(){return this.decl.id}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.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:Gt(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 l=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(m=>m.type===n.track.type&&m.number===n.track.number);if(!l){s=o;continue}let d=await l._backing.getFirstPacket(e);if(d&&r&&d.type!=="key"&&(d=await l._backing.getNextKeyPacket(d,e)),!d){s=o;continue}return this.createAdjustedPacket(d,o,l)}}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)return null;for(await this.hydrate();n;){let a=this.segmentedInput.getInputForSegment(n),o=(await a.getTracks()).find(m=>m.type===this.firstInputTrack.type&&m.number===this.firstInputTrack.number);if(!o){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let c=await this.segmentedInput.getMediaOffset(n,a),u=t-c,l=r?await o._backing.getKeyPacket(u,e):await o._backing.getPacket(u,e);if(!l){n=await this.segmentedInput.getPreviousSegment(n,{skipLiveWait:e.skipLiveWait});continue}let d=r?await o._backing.getPacket(u,{...e,metadataOnly:!0}):l;if(b(d),u>=d.timestamp+d.duration){let m=await this.segmentedInput.getNextSegment(n,{skipLiveWait:e.skipLiveWait});if(m){let f=this.segmentedInput.getInputForSegment(m),g=(await f.getTracks()).find(y=>y.type===this.firstInputTrack.type&&y.number===this.firstInputTrack.number),h=g?await g._backing.getFirstPacket({...e,metadataOnly:!0}):null;if(h&&r&&h.type!=="key"&&(h=await g._backing.getNextKeyPacket(h,{...e,metadataOnly:!0})),h){let y=await this.segmentedInput.getMediaOffset(m,f);if(h.timestamp+y<=t){n=m;continue}}}}return this.createAdjustedPacket(l,n,o)}return null}},xo=class extends Ao{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())}},Co=class extends Ao{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 Im=Ol(Vu(),1);sn();var Em=typeof Im<"u"?Im:void 0,zu=0,Nu=1/0,Uu=null;typeof FinalizationRegistry<"u"&&(Uu=new FinalizationRegistry(i=>{i()}));var Ne=class extends Je{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,zu,Nu),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 Aa(this,e,r)}_dispatchRead(e,r){this.onread?.(e,r),this._emit("read",{start:e,end:r})}ref(){return new ai(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},ai=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()}},Ye=class extends Ne{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 Ne||a instanceof ai))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");let s=a instanceof Ne?a.ref():a;return s.source._usedForHls||=this._usedForHls,s};return _(r)?r.then(n):n(r)}},Lu=(i,t)=>i.path===t.path,_n=class extends Ye{constructor(){super(...arguments);this._root=null;this._rootRequest=null}_read(e,r,n,a){if(!this._root){if(!this._rootRequest){let s=this._resolveRequest({path:this.rootPath,isRoot:!0}),o=c=>{let u=c instanceof Ne?c.ref():c;return this._root=u,this._rootRequest=null,u};_(s)?this._rootRequest=s.then(o):(o(s),b(this._root))}if(this._rootRequest)return this._rootRequest.then(s=>s.source._read(e,r,n,a))}return this._root.source._read(e,r,n,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free()).catch(()=>{})}},Po=class extends Ne{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=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(){}},vm=typeof FinalizationRegistry<"u"?new FinalizationRegistry(i=>{i.cancel().catch(()=>{})}):null,Io=class extends Ne{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&&(!ve(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 Sa({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),vm?.unregister(n),a.cancel().catch(()=>{}))},prefetchProfile:Wu.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&&!jt()&&this._options.useStreamReader!==!1?(r=this._blob.slice(e.currentPos).stream().getReader(),vm?.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()}},ph=.5*2**20,hh=(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 V._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)},_m=new Set,Eo=class i extends Ye{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&&(!ve(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));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??hh,this._requestInit={...r.requestInit};let a=null;if(r.requestInit?.headers){let o={...ns(r.requestInit.headers)},c=Object.keys(o).find(u=>u.toLowerCase()==="range");c!==void 0&&(a=o[c],delete o[c],this._requestInit.headers=o)}if(e instanceof Request){let o=e.headers.get("Range");if(o!==null){a??=o;let c=new Request(e);c.headers.delete("Range"),this._url=c}}if(a!==null){let o=bh(a);o&&(this._offset=o.offset,this._length=o.length)}let s=2;this._orchestrator=new Sa({maxCacheSize:r.maxCacheSize??64*2**20,maxWorkerCount:r.parallelism??s,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:o=>this._abortControllers.delete(o),prefetchProfile:Wu.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:J(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=u=>u?(u.offset-=this._offset,u):null;return _(o)?o.then(c):c(o)}async _runWorker(e){for(;;){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}let r=new AbortController;this._abortControllers.set(e,r);let n=await Xc(this._options.fetchFn??fetch,this._url,jc(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>r.signal.aborted);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(this._orchestrator.fileSize===null&&!n.headers.has("Content-Encoding")&&(n.status===206||n.type==="basic")){let s=n.headers.get("Content-Range");if(s){let c=/\/(\d+)/.exec(s);if(c){this._orchestrator.supplyFileSize(Number(c[1]));break e}}let o=n.headers.get("Content-Length");if(o){let c=n.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(c+Number(o))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(n.status!==206){if(this._sequentialBacking){n.body.cancel().catch(()=>{});return}if(!this._usedForHls){let s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(_m.has(s.origin)||(V._warn(`HTTP server (origin ${s.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.`),_m.add(s.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(n.body,r);return}let a=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){r.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await a.read()}catch(u){if(r.signal.aborted)throw u;let l=this._getRetryDelay(1,u,this._url);if(l!==null){V._error("Error while reading response stream. Attempting to resume.",u),await Kr(1e3*l);break}else throw u}if(e.aborted)continue;let{done:o,value:c}=s;if(o){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}}_transitionToSequentialMode(e,r){this._sequentialAbortController=r;let n=e.getReader(),a=0,s=0,o=new ReadableStream({pull:async l=>{for(;;){let d;try{d=await n.read()}catch(f){if(this._disposed)throw f;let p=this._getRetryDelay(1,f,this._url);if(p===null)throw f;V._error("Error while reading response stream. Attempting to resume.",f),await Kr(1e3*p),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();let g=await Xc(this._options.fetchFn??fetch,this._url,jc(this._requestInit,{headers:{Range:`bytes=${a}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!g.ok)throw new Error(`Error fetching ${String(this._url)}: ${g.status} ${g.statusText}`);if(!g.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");n=g.body.getReader(),s=g.status===206?0:a;continue}if(d.done){l.close();return}let m=d.value;if(s>0){let f=Math.min(s,m.length);s-=f,m=m.subarray(f)}if(m.length!==0){a+=m.length,l.enqueue(m);return}}},cancel:()=>n.cancel().catch(()=>{})}),c=new Vi(o,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});c._endIndex=this._orchestrator.fileSize,c._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.",c.on("read",({start:l,end:d})=>this._dispatchRead(l,d)),this._sequentialBacking=c;let u=new Set;for(let l of this._orchestrator.workers){for(let d of l.pendingSlices)u.add(d);l.aborted=!0,l.pendingSlices.length=0}for(let l of this._orchestrator.queuedReads)for(let d of l.pendingSlices)u.add(d);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(let[,l]of this._abortControllers)l.abort();this._abortControllers.clear();for(let l of u){let d=c._read(l.start,l.start+l.bytes.length);_(d)?d.then(m=>{m?(b(m.offset===l.start),l.resolve(m.bytes)):l.resolve(null)},m=>l.reject(m)):(b(d===null),l.resolve(null))}}_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())}},gh=/^bytes=(\d+)-(\d*)$/,bh=i=>{let t=gh.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}},vo=class i extends Ye{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&&(!ve(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Em.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 Rn({getSize:async()=>{let n=await Em.fs.open(e,"r");return this._fileHandle=n,Uu?.register(this,()=>{n.close()},this),(await n.stat()).size},read:async(n,a)=>{b(this._fileHandle);let s=new Uint8Array(a-n);return await this._fileHandle.read(s,0,a-n,n),s},maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:r.handleUnhandledError})}_read(e,r,n,a){return this._customSource._read(e,r,n,a)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Uu?.unregister(this))}},Rn=class extends Ne{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&&(!ve(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._options=e,this._orchestrator=new Sa({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:Wu[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._options.getSize();if(_(s))return 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(_(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 u=Q(c);this._dispatchRead(e.currentPos,e.currentPos+u.length),this._orchestrator.supplyWorkerData(e,u)}}finally{this._readers.delete(s),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?.()}},Fm=Rn,Vi=class extends Ne{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&&(!ve(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=G(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 Rm(e,r,o);this._currentIndex>s&&this._throwDueToCacheMiss();let{promise:c,resolve:u,reject:l}=ee();return this._pendingSlices.push({start:e,end:r,parts:o,resolve:u,reject:l}),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),u=Math.min(a,o.end);c<u&&(o.parts.push({start:c,bytes:r.subarray(c-n,u-n)}),u===o.end&&(o.resolve(Rm(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?.cancel().catch(()=>{})}},Rm=(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}},Wu={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(gs(i,t,s,n.targetPos)){let o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);t=Math.max(t,n.startPos+l)}}return t=Math.max(t,i+ph),{start:i,end:t}}},Sa=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,u=G(this.cache,t,S=>S.start),l=u!==-1?this.cache[u]:null;l&&l.start<=t&&e<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});let d=G(this.cache,s,S=>S.start),m=c?null:new Uint8Array(e-t),f=0,p=s,g=[];if(d!==-1){for(let S=d;S<this.cache.length;S++){let x=this.cache[S];if(x.start>=o)break;if(x.end<=s)continue;let C=Math.max(s,x.start),P=Math.min(o,x.end);if(b(C<=P),p<C&&g.push({start:p,end:C}),p=P,m){let A=Math.max(t,x.start),I=Math.min(e,x.end);if(A<I){let E=A-t;m.set(x.bytes.subarray(A-x.start,I-x.start),E),E===f&&(f=I-t)}}x.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}=ee(),w=[];for(let S of g){let x=Math.max(t,S.start),C=Math.min(e,S.end);x===S.start&&C===S.end?w.push(S):x<C&&w.push({start:x,end:C})}let T=m&&{start:t,bytes:m,holes:w,resolve:y,reject:k};e:for(let S of g){for(let P of this.workers)if(this.checkHoleAgainstWorker(P,S,T?[T]:[])){this.checkQueuedReadsAgainstWorker(P);continue e}let x=S.end<o||this.fileSize!==null,C=this.createWorker(S.start,S.end,x);if(C)T&&(C.pendingSlices=[T]),this.runWorker(C);else{let P=G(this.queuedReads,S.start,I=>I.hole.start),A=P!==-1?this.queuedReads[P]:null;for(A&&S.start<=A.hole.end?(A.hole.end=Math.max(A.hole.end,S.end),A.strictTarget&&=x,T&&A.pendingSlices.push(T)):(P++,A={hole:{start:S.start,end:S.end},strictTarget:x,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(P,0,A));P+1<this.queuedReads.length;){let I=this.queuedReads[P+1];if(I.hole.start>A.hole.end)break;A.hole.end=Math.max(A.hole.end,I.hole.end),A.pendingSlices.push(...I.pendingSlices),A.strictTarget&&=I.strictTarget,A.age=Math.min(A.age,I.age),this.queuedReads.splice(P+1,1)}}}return c?h.catch(S=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(S);else throw S}):(b(m),c=h.then(S=>S&&{bytes:S,view:N(S),offset:t})),c}checkHoleAgainstWorker(t,e,r){if(gs(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 u=0;u<s.holes.length;u++){let l=s.holes[u];r<=l.start&&n>l.start&&(l.start=n),l.end<=l.start&&(s.holes.splice(u,1),u--)}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||gs(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];if(r.hole.start>=t){for(let n of r.pendingSlices)n.resolve(null);this.queuedReads.splice(e,1),e--}else if(r.hole.end>t){r.hole.end=t,r.strictTarget=!0;for(let n=0;n<r.pendingSlices.length;n++){let a=r.pendingSlices[n];a.start>=t&&(a.resolve(null),r.pendingSlices.splice(n,1),n--)}}}}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.resolve(null)}insertIntoCache(t){if(this.options.maxCacheSize===0)return;let e=G(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 Aa=class extends Ne{constructor(e,r,n){super();this._ref=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(){let e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:J(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._baseSource._read(this._offset+e,this._offset+r,this._offset+n,this._offset+a),o=c=>c?(c.offset-=this._offset,c):null;return _(s)?s.then(o):o(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}};var yh=/^0[xX][0-9a-fA-F]+$/,kh=/^data:.*;base64,/i,Mm=1e9,xa=class extends So{constructor(e,r,n,a){super(e.input,r,n);this.segments=[];this.nextLines=null;this.currentUpdateSegmentsPromise=null;this.streamHasEnded=!1;this.lastSegmentUpdateTime=-1/0;this.refreshInterval=5;this.rootPath=r,this.demuxer=e,this.nextLines=a}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await Kr(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 A=dt(S,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}));let I=new si(A.source);let E=I.requestSliceRange(0,0,64);_(E)&&(E=await E);if(E&&!he.decode(U(E,E.length)).trimStart().startsWith("#EXTM3U"))throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");let v=await I.requestEntireFile();b(v);e=_o(v,v.length,{ignore:wo});A.source instanceof Ye&&(this.rootPath=A.source.rootPath)}catch(x){var C=x,P=!0}finally{mt(S,C,P)}}let r=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,n=new En(this.rootPath,this.demuxer.hasMasterPlaylist?this.demuxer.masterPlaylistVariables:null),a=!1,s=0,o=null,c=null,u=null,l=0,d=null,m=null,f=null,p=null,g=null,h=null,y=!1,k=Y(this.segments)??null,w=A=>{let I=A.indexOf("@"),E=Number(I===-1?A:A.slice(0,I));if(!Number.isInteger(E)||E<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${A}'.`);let v=null;if(I!==-1&&(v=Number(A.slice(I+1)),!Number.isInteger(v)||v<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${A}'.`);return{length:E,offset:v}},T=A=>{l=A,k&&(b(k.sequenceNumber!==null),k.sequenceNumber<A&&(s=k.timestamp+k.duration,d=k.firstSegment,m=k.initSegment,g=k.lastProgramDateTimeSeconds,o=k.unixEpochTimestamp!==null?k.unixEpochTimestamp+k.duration:null,k=null))};for(let A=0;A<e.length;A++){let I=e[A];if(!a){if(I!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");a=!0;continue}if(!I.startsWith("#")){if(!k){if(c===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let E=u;if(E&&E.method==="AES-128"&&!E.iv){let z=new Uint8Array(Ot),D=N(z);D.setUint32(8,Math.floor(l/2**32)),D.setUint32(12,l),E={...E,iv:z}}let R={path:xe(this.rootPath,n.substitute(I)),offset:p?.offset??0,length:p?.length??null},B={index:this.segments.length,timestamp:s,unixEpochTimestamp:o,firstSegment:d,sequenceNumber:l,location:R,duration:c,encryption:E,initSegment:m,lastProgramDateTimeSeconds:g};d??=B,s+=c,o!==null&&(o+=c),this.segments.push(B)}c=null,p===null?f=null:p=null,T(l+1)}if(I.startsWith(wa)){if(k){y=!0;continue}y||(g===null&&l>0&&h!==null&&(s=l*h),y=!0);let E=I.slice(wa.length),v=E.indexOf(","),R=v===-1?E:E.slice(0,v),B=Number(R);if(!Number.isFinite(B)||B<0||B>Mm)throw new Error(`Invalid #EXTINF tag duration '${R}'.`);c=B}else if(I.startsWith(vn))n.define(I.slice(vn.length));else if(I.startsWith(_u)){let E=new sr(I.slice(_u.length),n),v=E.get("uri");if(!v)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let R=E.get("byterange"),B=null;if(R!==null&&(B=w(R)),B&&B.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!k){let D={path:xe(this.rootPath,v),offset:B?.offset??0,length:B?.length??null};if(u?.method==="AES-128"&&!u.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");m={index:-1,timestamp:s,unixEpochTimestamp:o,firstSegment:null,sequenceNumber:null,location:D,duration:0,encryption:u,initSegment:null,lastProgramDateTimeSeconds:g}}c=null,p===null?f=null:p=null}else if(I.startsWith(Ru)){let E=new sr(I.slice(Ru.length),n),v=E.get("method");if(v==="NONE")u=null;else if(v==="AES-128"){let R=E.get("uri");if(!R)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let B=null,z=E.get("iv");if(z){if(!yh.test(z))throw new Error(`Unsupported IV format '${z}'.`);let q=z.slice(2);q=q.padStart(2*Ot,"0"),q=q.slice(-2*Ot),B=new Uint8Array(Ot);for(let ie=0;ie<Ot;ie++){let be=2*ie;B[ie]=parseInt(q.slice(be,be+2),16)}}let D=E.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.");u={method:"AES-128",keyUri:xe(this.rootPath,R),iv:B,keyFormat:D}}else if(v==="SAMPLE-AES"||v==="SAMPLE-AES-CTR"){let R=E.get("uri");if(!R)throw new Error(`Invalid #EXT-X-KEY: ${v} requires a URI attribute.`);if((E.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 z=null;if(kh.test(R)){let D=R.indexOf(","),q=Ei(R.slice(D+1));if(q.length>=8&&q[4]===112&&q[5]===115&&q[6]===115&&q[7]===104){let ie=N(q).getUint32(0);z=Gs(q.subarray(8,Math.min(ie,q.length)))}}u={method:v,psshBox:z}}else throw new Error(`Unsupported encryption method '${v}'. If you think this method should be supported, please raise an issue.`)}else if(I.startsWith(Fu)){let E=I.slice(Fu.length),v=Number(E);if(!Number.isSafeInteger(v)||v<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${E}'.`);T(v)}else if(I.startsWith(Mu)){let E=w(I.slice(Mu.length));if(E.offset===null){if(f===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");E.offset=f}p=E,f=E.offset+E.length}else if(I.startsWith(Bu)){if(k)continue;let E=I.slice(Bu.length),v=Date.parse(E);if(!Number.isFinite(v))continue;let R=v/1e3;if(g===R)continue;if(g===null&&this.segments.length>0){let B=Y(this.segments),z=B.timestamp+B.duration,D=R-z;for(let q of this.segments)q.unixEpochTimestamp=q.timestamp+D,r&&(q.timestamp=q.unixEpochTimestamp)}g=R,o=R,r&&(s=R)}else if(I===xm)d=null;else if(I.startsWith(Ou)){let E=I.slice(Ou.length),v=Number(E);if(!Number.isFinite(v)||v<0||v>Mm)throw new Error(`Invalid EXT-X-TARGETDURATION value '${E}'.`);this.refreshInterval=J(v,.5,3600),h=v}else if(I===Cm){this.streamHasEnded=!0;break}else I.startsWith(Du)&&I.slice(Du.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!a)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,r){this.segments.length===0&&await this.runUpdateSegments();let n=!!r.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let a=G(this.segments,e,o=>o.timestamp);if(a===-1)return null;if(a<this.segments.length-1||this.streamHasEnded||n)return this.segments[a];let s=this.segments[a];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),r.skipLiveWait&&(n=!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(u=>u.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&&(u=>{if(!r.encryption||!(r.encryption.method==="SAMPLE-AES"||r.encryption.method==="SAMPLE-AES-CTR")||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(u);let l=u.psshBoxes,{psshBox:d}=r.encryption;return(d.keyIds===null||d.keyIds.includes(u.keyId))&&!l.some(m=>Qs(m,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...u,psshBoxes:l})})}},o=new oi({source:new _n(r.location.path,async u=>{b(u.isRoot);let l={...u,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(l),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(l);if(m){let k=p.source.slice(r.location.offset,r.location.length??void 0).ref();p.free(),p=k}let g=new si(p.source),h=Ld(g,async()=>{var S=[];try{let y=dt(S,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},Bm));let k=new si(y.source);let w=await k.requestSlice(0,Ot);if(!w)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");let T=U(w,Ot);return{key:T,iv:f.iv}}catch(x){var C=x,P=!0}finally{mt(S,C,P)}},()=>{p.free()});d=new Vi(h).ref()}else b(!1);return d}),formats:this.input._formats.filter(u=>!(u instanceof Ui)),initInput:a??void 0,formatOptions:s});if(o._onFormatDetermined=u=>{if((r.encryption?.method==="SAMPLE-AES"||r.encryption?.method==="SAMPLE-AES-CTR")&&!u._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 u=on(this.inputCache,l=>l.age);b(u!==-1),this.inputCache.splice(u,1)}return o}async getLiveRefreshInterval(){return!this.streamHasEnded&&this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}};var Th=256,wh=256,Fo=class extends Pe{constructor(e){super(e);this.metadataPromise=null;this.trackBackings=null;this.internalTracks=null;this.segmentedInputs=[];this.hasMasterPlaylist=!0;this.masterPlaylistVariables=null}readMetadata(){return this.metadataPromise??=(async()=>{b(this.input._rootSource instanceof Ye);let e=await this.input._reader.requestEntireFile();b(e);let r=_o(e,e.length,{ignore:wo}),{rootPath:n}=this.input._rootSource,a=new En(n,null),s=[],o=[];for(let d=1;d<r.length;d++){let m=r[d];if(m.startsWith(vn))a.define(m.slice(vn.length));else if(m.startsWith(Iu)){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=xe(n,p),h=new sr(m.slice(Iu.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(Eu)){let f=new sr(m.slice(Eu.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=xe(n,p);s.push({fullPath:h,attributes:f,lineNumber:d,hasOnlyKeyPackets:!0})}else if(m.startsWith(vu)){let f=new sr(m.slice(vu.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=xe(n,y)),o.push({fullPath:h,attributes:f,lineNumber:d})}else if(m!==Pm){if(m.startsWith(wa)){let f=new xa(this,n,null,r);this.segmentedInputs=[f],this.hasMasterPlaylist=!1,this.trackBackings=await f.getTrackBackings();return}}}if(s.length>Th||o.length>wh)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(A=>A.trim());else{let I=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),E=await Promise.all(I.map(async v=>({track:v,codec:await v.getCodec()})));g=await Promise.all(E.filter(v=>v.codec!==null).map(v=>v.track.getDecoderConfig().then(R=>R.codec)))}let h=d.attributes.get("video"),y=d.attributes.get("audio"),k=g.some(A=>ce.includes(rt(A))),w=g.some(A=>me.includes(rt(A)));if(h!==null&&!k){let A=o.find(I=>{let E=I.attributes.get("group-id"),v=I.attributes.get("type");return E===h&&v.toLowerCase()==="video"});e:if(A){let I=A.attributes.get("uri");if(I===null)break e;let E=xe(n,I),B=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(D=>D.getType()==="video");if(!B||await B.getCodec()===null)break e;let z=await B.getDecoderConfig().then(D=>D?.codec??null);b(z!==null),g.push(z)}}if(y!==null&&!w){let A=o.find(I=>{let E=I.attributes.get("group-id"),v=I.attributes.get("type");return E===y&&v.toLowerCase()==="audio"});e:if(A){let I=A.attributes.get("uri");if(I===null)break e;let E=xe(n,I),B=(await this.getSegmentedInputForPath(E).getTrackBackings()).find(D=>D.getType()==="audio");if(!B||await B.getCodec()===null)break e;let z=await B.getDecoderConfig().then(D=>D?.codec??null);b(z!==null),g.push(z)}}g=[...new Set(g)];let T=null,S=null,x=d.attributes.getAsNumber("bandwidth");b(x!==null);let C=d.attributes.getAsNumber("average-bandwidth"),P=d.attributes.get("name");for(let A of g){let I=rt(A);if(I!==null){if(ce.includes(I)){if(T!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");T=A;let E=d.attributes.get("video");if(E===null){let v=d.attributes.get("resolution"),R=null,B=null;if(v){let z=v.match(/^(\d+)x(\d+)$/);z&&(R=Number(z[1]),B=Number(z[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:se,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(m),peakBitrate:x,averageBitrate:C,name:P,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:R,height:B}})}else for(let v of o){let R=v.attributes.get("group-id"),B=v.attributes.get("type");if(R!==E||B.toLowerCase()!=="video")continue;let z=v.attributes.get("resolution")??d.attributes.get("resolution"),D=null,q=null;if(z){let ie=z.match(/^(\d+)x(\d+)$/);ie&&(D=Number(ie[1]),q=Number(ie[2]))}f.push({id:-1,demuxer:this,backingTrack:null,default:Ro(v.attributes),autoselect:Ro(v.attributes)||Om(v.attributes),languageCode:Dm(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:T,pairingMask:1n<<BigInt(m),peakBitrate:v.fullPath===null?x:null,averageBitrate:v.fullPath===null?C:null,name:v.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:D,height:q}})}}else if(me.includes(I)){if(S!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");S=A;let E=d.attributes.get("audio");if(E===null){let v=d.attributes.get("channels"),R=v!==null?Number(v.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:se,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(m),peakBitrate:x,averageBitrate:C,name:P,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:R!==null&&Number.isInteger(R)&&R>0?R:null}})}else for(let v of o){let R=v.attributes.get("group-id"),B=v.attributes.get("type");if(R!==E||B.toLowerCase()!=="audio")continue;let z=v.attributes.get("channels")??d.attributes.get("channels"),D=z!==null?Number(z.split("/")[0]):null;f.push({id:-1,demuxer:this,backingTrack:null,default:Ro(v.attributes),autoselect:Ro(v.attributes)||Om(v.attributes),languageCode:Dm(v.attributes.get("language")),lineNumber:v.lineNumber,fullPath:v.fullPath??d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(m),peakBitrate:v.fullPath===null?x:null,averageBitrate:v.fullPath===null?C:null,name:v.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:D!==null&&Number.isInteger(D)&&D>0?D:null}})}}}}return f})),u=[],l=d=>{let m=u.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===se&&(m.languageCode=d.languageCode)):(d.id=u.length+1,u.push(d))};for(let d of c)for(let m of d)l(m);u.sort((d,m)=>d.lineNumber-m.lineNumber),this.trackBackings=[];for(let d of u)d.info.type==="video"?this.trackBackings.push(new Bo(d)):this.trackBackings.push(new Oo(d));this.internalTracks=u})()}async getTrackBackings(){return await this.readMetadata(),b(this.trackBackings),this.trackBackings}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=>({id:s.id,type:s.info.type}))),r=new xa(this,e,n,null),this.segmentedInputs.push(r),r}async getMetadataTags(){return{}}async getMimeType(){return or}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Mo=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 Bo){for(let a of n)if(await a.getCodec()===this.getCodec()){e=a;break}}else{b(this instanceof Oo);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{..._e,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){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)}},Bo=class extends Mo{constructor(t){super(t)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return rt(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){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()}},Oo=class extends Mo{constructor(t){super(t)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return rt(this.internalTrack.fullCodecString)}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()}},Ro=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}".`)},Om=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}".`)},Dm=i=>{if(i===null)return se;let t=i.split("-")[0];return t||se};var Ze=class{constructor(){this._isIsobmff=!1}},Fn=class extends Ze{constructor(){super(...arguments);this._isIsobmff=!0}async _getMajorBrand(e){let r=e._reader.requestSlice(0,12);if(_(r)&&(r=await r),!r)return null;r.skip(4);let n=ue(r,4);return n!=="ftyp"&&n!=="styp"?null:ue(r,4)}_createDemuxer(e){return new $s(e)}get supportsTimestampedMediaData(){return!0}},Ca=class extends Fn{async _canReadInput(t){let e=await this._getMajorBrand(t);if(e!==null)return e!=="qt ";let r=0;for(let n=0;n<10;n++){let a=t._reader.requestSlice(r,8);if(_(a)&&(a=await a),!a)return!1;let s=M(a),o=8;if(s===1){let u=t._reader.requestSlice(r+8,8);if(_(u)&&(u=await u),!u)return!1;s=qe(u),o=16}if(s<o)return!1;let c=ue(a,4);if(c==="moof"||c==="sidx")return!0;if(c==="emsg"||c==="prft"||c==="free")r+=s;else return!1}return!1}get name(){return"MP4"}get mimeType(){return"video/mp4"}},Pa=class extends Fn{async _canReadInput(t){return await this._getMajorBrand(t)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},Mn=class extends Ze{async isSupportedEBMLOfDocType(t,e){let r=t._reader.requestSlice(0,xt);if(_(r)&&(r=await r),!r)return!1;let n=mu(r);if(n===null||n<1||n>8||X(r,n)!==440786851)return!1;let s=fu(r);if(typeof s!="number")return!1;let o=t._reader.requestSlice(r.filePos,s);if(_(o)&&(o=await o),!o)return!1;let c=r.filePos;for(;o.filePos<=c+s-$e;){let u=Ct(o);if(!u)break;let{id:l,size:d}=u,m=o.filePos;if(d===void 0||m+d>c+s||d>8&&l!==17026)return!1;switch(l){case 17030:if(X(o,d)!==1)return!1;break;case 17143:if(X(o,d)!==1)return!1;break;case 17026:if(ri(o,d)!==e)return!1;break;case 17031:if(X(o,d)>4)return!1;break}o.filePos=m+d}return!0}_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"matroska")}_createDemuxer(t){return new ao(t)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}get supportsTimestampedMediaData(){return!0}},Ia=class extends Mn{_canReadInput(t){return this.isSupportedEBMLOfDocType(t,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},Ea=class extends Ze{async _canReadInput(t){let e=0;for(;;){let d=t._reader.requestSlice(e,Fe);if(_(d)&&(d=await d),!d)break;let m=it(d);if(!m)break;e=d.filePos+m.size}let r=await ha(t._reader,e,e+4096);if(!r)return!1;let n=r.header,a=Yr(n.mpegVersionId,n.channel),s=t._reader.requestSlice(r.startPos+a,4);if(_(s)&&(s=await s),!s)return!1;let o=M(s);if(o===$r||o===fn)return!0;e=r.startPos+r.header.totalSize;let u=await ha(t._reader,e,e+4);if(!u)return!1;let l=u.header;return!(n.channel!==l.channel||n.sampleRate!==l.sampleRate)}_createDemuxer(t){return new oo(t)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}get supportsTimestampedMediaData(){return!1}},va=class extends Ze{async _canReadInput(t){let e=t._reader.requestSlice(0,12);if(_(e)&&(e=await e),!e)return!1;let r=ue(e,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(e.skip(4),ue(e,4)==="WAVE")}_createDemuxer(t){return new mo(t)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}get supportsTimestampedMediaData(){return!1}},_a=class extends Ze{async _canReadInput(t){let e=t._reader.requestSlice(0,4);return _(e)&&(e=await e),e?ue(e,4)==="OggS":!1}_createDemuxer(t){return new lo(t)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}get supportsTimestampedMediaData(){return!0}},Ra=class extends Ze{async _canReadInput(t){let e=0;for(;;){let n=t._reader.requestSlice(e,Fe);if(_(n)&&(n=await n),!n)break;let a=it(n);if(!a)break;e=n.filePos+a.size}let r=t._reader.requestSlice(e,4);return _(r)&&(r=await r),r?ue(r,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}get supportsTimestampedMediaData(){return!1}_createDemuxer(t){return new bo(t)}},Fa=class extends Ze{async _canReadInput(t){let e=0;for(;;){let s=t._reader.requestSlice(e,Fe);if(_(s)&&(s=await s),!s)break;let o=it(s);if(!o)break;e=s.filePos+o.size}let r=t._reader.requestSliceRange(e,Ut,bt);if(_(r)&&(r=await r),!r)return!1;let n=nt(r);if(!n||(e+=n.frameLength,r=t._reader.requestSliceRange(e,Ut,bt),_(r)&&(r=await r),!r))return!1;let a=nt(r);return a?n.objectType===a.objectType&&n.samplingFrequencyIndex===a.samplingFrequencyIndex&&n.channelConfiguration===a.channelConfiguration:!1}_createDemuxer(t){return new fo(t)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}get supportsTimestampedMediaData(){return!1}},Ma=class extends Ze{async _canReadInput(t){let e=205,r=t._reader.requestSlice(0,e);if(_(r)&&(r=await r),!r)return!1;let n=U(r,e);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71?!0:n[4]===71&&n[196]===71}_createDemuxer(t){return new ko(t)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}get supportsTimestampedMediaData(){return!0}},Ui=class extends Ze{async _canReadInput(t){let e=t._reader.requestSlice(0,7);if(_(e)&&(e=await e),!e||!(ue(e,7)==="#EXTM3U"))return!1;if(!(t._rootSource instanceof Ye))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 Fo(t)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return or}get supportsTimestampedMediaData(){return!0}},Do=new Ca,Vo=new Pa,Hu=new Mn,qu=new Ia,Uo=new Ea,Ku=new va,Gu=new _a,zo=new Fa,Qu=new Ra,No=new Ma,Lo=new Ui,Vm=[Lo,Do,Vo,Hu,qu,Ku,Gu,Qu,Uo,zo,No],Um=[Lo,Do,Vo,Uo,zo,No],zm=(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 Wo=new Map,Ho=new Map,Sh=(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&&rt(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&&!kr(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.")},Ah=(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&&rt(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&&!kr(t.description))throw new TypeError("options.description, when provided, must be a buffer source.")},Nm=i=>ce.includes(i)?qo(i):me.includes(i)?Ko(i):!1,qo=async(i,t={})=>{if(!ce.includes(i))return!1;Sh(i,t);let e={...t,codedWidth:t.codedWidth??1280,codedHeight:t.codedHeight??720,codec:t.codec??Vs(i,1280,720,1e6,!1)};e.description??=Rd(e);let r=JSON.stringify(e),n=Wo.get(r);if(n)return n;let a=(async()=>ci.some(o=>o.supports(i,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0)();return Wo.set(r,a),a},Ko=async(i,t={})=>{if(!me.includes(i))return!1;Ah(i,t);let e={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??Ns(i,2,48e3)};if(e.description===void 0){let s=Fd(e);if(s===!1)return!1;e.description=s}let r=JSON.stringify(e),n=Ho.get(r);if(n)return n;let a=(async()=>ui.some(o=>o.supports(i,e))||ne.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0)();return Ho.set(r,a),a},Lm=async()=>{let[i,t]=await Promise.all([ju(),Xu()]);return[...i,...t]},ju=async(i=ce,t)=>{let e=await Promise.all(i.map(r=>qo(r,t)));return i.filter((r,n)=>e[n])},Xu=async(i=me,t)=>{let e=await Promise.all(i.map(r=>Ko(r,t)));return i.filter((r,n)=>e[n])};sn();var Wm=-1/0,Hm=-1/0,Va=null;typeof FinalizationRegistry<"u"&&(Va=new FinalizationRegistry(i=>{let t=performance.now();i.type==="video"?(t-Wm>=1e3&&(V._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."),Wm=t),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(t-Hm>=1e3&&(V._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."),Hm=t),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));var zt=class{constructor(){this._referenceCount=0;this._lastAllocationBuffer=null}},Ua=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],xh=new Set(Ua),Ge=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||!xh.has(e.format))throw new TypeError("init.format must be one of: "+Ua.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 a of e.layout){if(!a||typeof a!="object"||Array.isArray(a))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(a.offset)||a.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(a.stride)||a.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(e.visibleRect!==void 0&&ys(e.visibleRect,"init.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??Ph(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 Ni(n)}else if(typeof VideoFrame<"u"&&t instanceof 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&&ys(e.visibleRect,"init.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 Ni({primaries:r!==null&&r in Tt?r:null,transfer:n!==null&&n in wt?n:null,matrix:a!==null&&a in St?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&&ys(e.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new i(new VideoFrame(t,{timestamp:Math.trunc(e.timestamp*Qt),duration:Math.trunc((e.duration??0)*Qt)||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:Xt(),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 Ni({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(t instanceof zt){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._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!Ua.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()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=e?.encodeOptions??{},this.pixelAspectRatio=Ar({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(Qt*this.timestamp)}get microsecondDuration(){return Math.trunc(Qt*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 zt?new i(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Oa(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 zt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Oa(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(t={}){if(Gm(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 Oa(this._data)?this._data.allocationSize(t):Qm(this,t).allocationSize}async copyTo(t,e={}){if(!kr(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Gm(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),Oa(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 zt){var u=[];try{let f=dt(u,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(l){var d=l,m=!0}finally{mt(u,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(),p=await f.copyTo(t,e);return f.close(),p}let r=Qm(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=Qo(this.format),s;if(this._data instanceof zt){let f=this._data.getDataPlanes();if(_(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.codedHeight/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:Q(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,w=p.sourceWidthBytes,T={offset:k,stride:p.destinationStride};for(let S=0;S<p.sourceHeight;S++){if(y+w>h.byteLength)throw new Error("Source buffer OOB read.");if(k+w>n.byteLength)throw new Error("Destination buffer OOB write.");let x=h.subarray(y,y+w);n.set(x,k),y+=g,k+=p.destinationStride}o.push(T)}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)for(let g=0;g<r.allocationSize;g+=4){if(f){let h=n[g],y=n[g+2];n[g]=y,n[g+2]=h}p&&(n[g+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(b(this._data!==null),this._data instanceof zt){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(_(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,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return Oa(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.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(t,e,r,n,a,s,o,c,u){let l=0,d=0,m=this.displayWidth,f=this.displayHeight,p=0,g=0,h=this.displayWidth,y=this.displayHeight;if(s!==void 0?(l=e,d=r,m=n,f=a,p=s,g=o,c!==void 0?(h=c,y=u):(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(l))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:l,sy:d,sWidth:m,sHeight:f}=this._unmapSourceRegion(l,d,m,f,this.rotation,this.flip));let k=this.toCanvasImageSource();t.save();let w=p+h/2,T=g+y/2;t.translate(w,T),this.flip&&t.scale(-1,1),t.rotate(this.rotation*Math.PI/180);let S=this.rotation%180===0?1:h/y;t.scale(1/S,S),t.drawImage(k,l,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&&li(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],u=e.crop;u&&(u=Bn(u,o,c));let l,d,m,f,{sx:p,sy:g,sWidth:h,sHeight:y}=this._unmapSourceRegion(e.crop?.left??0,e.crop?.top??0,e.crop?.width??o,e.crop?.height??c,a,s);if(e.fit==="fill")l=0,d=0,m=r,f=n;else{let[w,T]=e.crop?[e.crop.width,e.crop.height]:[o,c],S=e.fit==="contain"?Math.min(r/w,n/T):Math.max(r/w,n/T);m=w*S,f=T*S,l=(r-m)/2,d=(n-f)/2}t.save();let k=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/k,k),t.translate(-r/2,-n/2),t.drawImage(this.toCanvasImageSource(),p,g,h,y,l,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,u=r.crop?r.crop.height:o,l=0;2*n<c&&2*a<u&&(l=Math.floor(Math.log2(Math.min(c/n,u/a))));let d=n*2**l,m=a*2**l,{canvas:f,context:p,isNew:g}=l>0?Km(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=l;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",l>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 zt||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&&li(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}=ls(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=Bn(s,n,a));let o=s?s.width:n,c=s?s.height:a,u=o/c,l,d;t.width!==void 0&&t.height===void 0?(l=t.width,d=l/u):t.width===void 0&&t.height!==void 0?(d=t.height,l=d*u):t.width!==void 0&&t.height!==void 0?(l=t.width,d=t.height):(l=o,d=c),l=fs(l,t.roundDimensionsTo??1),d=fs(d,t.roundDimensionsTo??1);let m={width:l,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 $u){let y=h(this,m);if(_(y)&&(y=await y),y!==null)return y}let{canvas:f,context:p,isNew:g}=Km(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})}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()}},$u=[],jm=i=>{$u.includes(i)||$u.push(i)},Ch=3,Ba=[],qm=0,Km=(i,t)=>{for(let n of Ba)if(n.canvas.width===i&&n.canvas.height===t)return n.age=qm++,{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 Ba.length>=Ch&&Ba.splice(on(Ba,n=>n.age),1),Ba.push({canvas:e,context:r,age:qm++}),{canvas:e,context:r,isNew:!0}},Ni=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(Tt);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(wt);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(St);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}}},Oa=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,Bn=(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}},li=(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.")},Gm=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.")}},Ph=(i,t,e)=>{let r=Qo(i),n=[],a=0;for(let s of r){let o=Math.ceil(t/s.widthDivisor),c=Math.ceil(e/s.heightDivisor),u=o*s.sampleBytes,l=u*c;n.push({offset:a,stride:u}),a+=l}return n},Qo=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:ae(i),b(!1)}},Qm=(i,t)=>{let e={left:0,top:0,width:i.codedWidth,height:i.codedHeight},r=t.rect,n=Ih(e,r,i.codedWidth,i.codedHeight,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 vh(n,s,a)},Ih=(i,t,e,r,n)=>{let a={...i};if(t!==void 0){if(t.width===0||t.height===0)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(!Eh(n,a))throw new TypeError("visibleRect alignment is invalid for the format.");return a},Eh=(i,t)=>{if(i===null)return!0;let e=Qo(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},vh=(i,t,e)=>{let r=Qo(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 u=r[c],l=u.sampleBytes,d=u.widthDivisor,m=u.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)*l,f.sourceWidthBytes=Math.floor(Math.trunc(i.width||0)/d)*l,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}},Go=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Dr=class{constructor(){this._referenceCount=0}},Ae=class i{constructor(t){this._closed=!1;if(Da(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 Dr){if(this._data=t,t._referenceCount++,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}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/(cr(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)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*cr(this.format);if(r.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}Va?.register(this,{type:"audio",data:this._data},this)}get microsecondTimestamp(){return Math.trunc(Qt*this.timestamp)}get microsecondDuration(){return Math.trunc(Qt*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>=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=cr(e),s=zi(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(!kr(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 u=this.numberOfFrames,l=this.numberOfChannels,d=a??0;if(d>=u)throw new RangeError("frameOffset out of range");let m=n!==void 0?n:u-d;if(m>u-d)throw new RangeError("frameCount out of range");let f=cr(c),p=zi(c);if(p&&s>=l)throw new RangeError("planeIndex out of range");if(!p&&s!==0)throw new RangeError("planeIndex out of range");let h=(p?m:m*l)*f;if(t.byteLength<h)throw new RangeError("Destination buffer is too small");let y=N(t),k=$m(c);if(Da(this._data))if(jt()&&l>2&&c!==o){_h(this._data,y,o,c,l,s,d,m);return}else try{this._data.copyTo(t,{planeIndex:s,frameOffset:d,frameCount:m,format:c});return}catch(P){if(c==="f32-planar")throw P;o="f32-planar"}let w=Xm(o),T=cr(o),S=zi(o),x;if(this._data instanceof Dr){let P=A=>{let I=this._data.getDataPlane(A);if(!(I instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");let E=u*T*(S?1:l);if(I.byteLength!==E)throw new TypeError(`Data plane ${A} has invalid size. Expected exactly ${E} bytes, got ${I.byteLength} bytes.`);return I};if(S)if(p)x=P(s),s=0;else{x=new Uint8Array(u*T*l);for(let A=0;A<l;A++){let I=P(A);x.set(I,A*u*T)}}else x=P(0)}else if(this._data instanceof Uint8Array)x=this._data;else if(b(o==="f32-planar"),p)x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:s})),this._data.copyTo(x,{format:"f32-planar",planeIndex:s}),s=0;else{x=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*l);for(let P=0;P<l;P++)this._data.copyTo(x.subarray(P*u*T,(P+1)*u*T),{format:"f32-planar",planeIndex:P})}let C=N(x);for(let P=0;P<m;P++)if(p){let A=P*f,I;S?I=(s*u+(P+d))*T:I=((P+d)*l+s)*T;let E=w(C,I);k(y,A,E)}else for(let A=0;A<l;A++){let E=(P*l+A)*f,v;S?v=(A*u+(P+d))*T:v=((P+d)*l+A)*T;let R=w(C,v);k(y,E,R)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Dr){let t=new i(this._data);return t.setTimestamp(this.timestamp),t}else if(Da(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})}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=cr(this.format),a;if(zi(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})}close(){this._closed||(Va?.unregister(this),this._data instanceof Dr?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Da(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 Dr?this._createAudioDataFromData():Da(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.buffer:this._data.slice()})}_createAudioDataFromData(){if(zi(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,u=s;for(;u>0;){let l=Math.min(o,u),d=new Float32Array(n*l);for(let m=0;m<n;m++)t.copyFromChannel(d.subarray(m*l,(m+1)*l),m,c);yield new i({format:"f32-planar",sampleRate:a,numberOfFrames:l,numberOfChannels:n,timestamp:e+c/a,data:d}),c+=l,u-=l}}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,u=s,l=[];for(;u>0;){let d=Math.min(o,u),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});l.push(f),c+=d,u-=d}return l}},cr=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")}},zi=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Xm=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)}},$m=i=>{switch(i){case"u8":case"u8-planar":return(t,e,r)=>t.setUint8(e,J(Math.round(r*128)+128,0,255));case"s16":case"s16-planar":return(t,e,r)=>t.setInt16(e,J(Math.round(r*32768),-32768,32767),!0);case"s32":case"s32-planar":return(t,e,r)=>t.setInt32(e,J(Math.round(r*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(t,e,r)=>t.setFloat32(e,r,!0)}},Da=i=>typeof AudioData<"u"&&i instanceof AudioData,Ym=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}},_h=(i,t,e,r,n,a,s,o)=>{let c=Xm(e),u=$m(r),l=cr(e),d=cr(r),m=zi(e);if(zi(r))if(m){let p=new ArrayBuffer(o*l),g=N(p);i.copyTo(p,{planeIndex:a,frameOffset:s,frameCount:o,format:e});for(let h=0;h<o;h++){let y=h*l,k=h*d,w=c(g,y);u(t,k,w)}}else{let p=new ArrayBuffer(o*n*l),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)*l,k=h*d,w=c(g,y);u(t,k,w)}}else if(m){let p=o*l,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 w=k*l,T=(k*n+y)*d,S=c(h,w);u(t,T,S)}}}else{let p=new ArrayBuffer(o*n*l),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,w=k*l,T=k*d,S=c(g,w);u(t,T,S)}}},Zm=(i,t)=>{let e=i.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(e);return i.copyTo(r,{format:t,planeIndex:0}),new Ae({data:r,format:t,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration})};var jo=new Map,Xo=new Map,$o=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!ce.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${ce.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 oe))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof oe)&&(!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&&li(i.transform.crop,"config.transform."),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.");tf(i.codec,i)},tf=(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&&rt(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.")},Zu=i=>{let t=i.bitrateMode,e=i.quality._toVideoRateControl(i.codec,i.width,i.height,t),r=(a,s,o)=>({codec:i.fullCodecString??Vs(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,...Bd(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},Yo=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!me.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${me.join(", ")}.`);let t=i.bitrate;if(i.quality===void 0&&t===void 0&&!(ne.includes(i.codec)||i.codec==="flac"))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 oe))throw new TypeError("config.quality, when provided, must be a Quality.");if(t!==void 0&&!(t instanceof oe)&&(!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.");rf(i.codec,i)},rf=(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&&rt(t.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},Ju=i=>{let t=i.bitrateMode;return{codec:i.fullCodecString??Ns(i.codec,i.numberOfChannels,i.sampleRate),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:i.quality?._toAudioBitrate(i.codec),bitrateMode:i.quality?._bitrateMode??t,...Od(i.codec)}},oe=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"?!(t.quality in Jm):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"?Jm[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=Rh[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=J(Math.round(Ql(a.worst,a.best,this._quality)),a.min,a.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let u=this._quality;u===void 0&&(b(s!==null&&a),u=J((s-a.worst)/(a.best-a.worst),0,1)),c=ef(t,e,r,Yu(u))}return{quantizer:s,bitrate:c,bitrateMode:o}}_toVideoBitrate(t,e,r){return this._bitrate!==void 0?this._bitrate:(b(this._quality!==void 0),ef(t,e,r,Yu(this._quality)))}_toAudioBitrate(t){if(ne.includes(t)||t==="flac")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 e=Yu(this._quality),n={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[t];if(!n)throw new Error(`Unhandled codec: ${t}`);let a=n*e;return t==="aac"?a=[96e3,128e3,16e4,192e3].reduce((o,c)=>Math.abs(c-a)<Math.abs(o-a)?c:o):t==="opus"||t==="vorbis"?a=Math.max(6e3,a):t==="mp3"&&(a=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,c)=>Math.abs(c-a)<Math.abs(o-a)?c:o)),Math.round(a/1e3)*1e3}},Jm={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},Rh={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:($l()??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}},Yu=i=>.3*Math.exp(2.5538*i),ef=(i,t,e,r)=>{let n=t*e,a=1920*1080,s=3e6,o=Math.pow(n/a,.95),c=s*o,u={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/s},d=c*u[i]*r;return Math.ceil(d/1e3)*1e3},el=(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)},nf=new oe("very-low"),af=new oe("low"),sf=new oe("medium"),of=new oe("high"),cf=new oe("very-high"),uf=i=>{if(ce.includes(i))return za(i);if(me.includes(i))return Na(i);if(Xe.includes(i))return La(i);throw new TypeError(`Unknown codec '${i}'.`)},za=async(i,t={})=>{let{width:e=1280,height:r=720,quality:n,bitrate:a,frameRate:s,...o}=t;if(!ce.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 oe))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 oe)&&(!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.");tf(i,o);let c=di(n,a)??new oe("medium"),u;try{u=Zu({codec:i,width:e,height:r,quality:c,framerate:s,...o,alpha:"discard"})}catch{return!1}let l=JSON.stringify(u),d=jo.get(l);if(d)return d;let m=(async()=>{for(let{config:p}of u)if(Dn.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 u){try{if(!(await VideoEncoder.isConfigSupported(p)).supported)continue}catch{continue}if(!Xt()||await new Promise(async y=>{try{let k=new VideoEncoder({output:()=>{},error:()=>y(!1)});k.configure(p);let w=new Uint8Array(e*r*4),T=new VideoFrame(w,{format:"RGBA",codedWidth:e,codedHeight:r,timestamp:0});k.encode(T,g!==null?el(i,g):void 0),T.close(),await k.flush(),y(!0)}catch{y(!1)}}))return!0}return!1})();return jo.set(l,m),m},Na=async(i,t={})=>{let{numberOfChannels:e=2,sampleRate:r=48e3,quality:n,bitrate:a,...s}=t;if(!me.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 oe))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 oe)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");rf(i,s);let o=di(n,a)??new oe("medium"),c=Ju({codec:i,numberOfChannels:e,sampleRate:r,quality:o,...s}),u=JSON.stringify(c),l=Xo.get(u);if(l)return l;let d=(async()=>{if(Vn.some(m=>m.supports(i,c))||ne.includes(i))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return Xo.set(u,d),d},di=(i,t)=>{if(i!==void 0)return i;if(t!==void 0)return t instanceof oe?t:new oe({bitrate:t})},La=async i=>!!Xe.includes(i),lf=async()=>{let[i,t,e]=await Promise.all([tl(),On(),rl()]);return[...i,...t,...e]},tl=async(i=ce,t)=>{let e=await Promise.all(i.map(r=>za(r,t)));return i.filter((r,n)=>e[n])},On=async(i=me,t)=>{let e=await Promise.all(i.map(r=>Na(r,t)));return i.filter((r,n)=>e[n])},rl=async(i=Xe)=>{let t=await Promise.all(i.map(La));return i.filter((e,r)=>t[r])},Zo=async(i,t)=>{for(let e of i)if(await za(e,t))return e;return null},df=async(i,t)=>{for(let e of i)if(await Na(e,t))return e;return null},mf=async i=>{for(let t of i)if(await La(t))return t;return null};var Wa=class{static supports(t,e){return!1}},Ha=class{static supports(t,e){return!1}},qa=class{static supports(t,e){return!1}},Ka=class{static supports(t,e){return!1}},ci=[],ui=[],Dn=[],Vn=[],ff=i=>{if(i.prototype instanceof Wa){let t=i;if(ci.includes(t)){V._warn("Video decoder already registered.");return}ci.push(t),Wo.clear()}else if(i.prototype instanceof Ha){let t=i;if(ui.includes(t)){V._warn("Audio decoder already registered.");return}ui.push(t),Ho.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},pf=i=>{if(i.prototype instanceof qa){let t=i;if(Dn.includes(t)){V._warn("Video encoder already registered.");return}Dn.push(t),jo.clear()}else if(i.prototype instanceof Ka){let t=i;if(Vn.includes(t)){V._warn("Audio encoder already registered.");return}Vn.push(t),Xo.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};var hf=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},gf=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},bf=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},yf=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 Li=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.")},Vr=i=>{if(!ve(i))throw new TypeError("timestamp must be a number.")},il=(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,st=class{constructor(t){if(!(t instanceof fi))throw new TypeError("track must be an InputTrack.");this._track=t}async getFirstPacket(t={}){if(Li(t),this._track.input._disposed)throw new ge;return il(this._track,this._track._backing.getFirstPacket(t),t)}async getFirstKeyPacket(t={}){Li(t);let e=await this.getFirstPacket(t);return e?e.type==="key"?e:this.getNextKeyPacket(e,t):null}async getPacket(t,e={}){if(Vr(t),Li(e),this._track.input._disposed)throw new ge;return il(this._track,this._track._backing.getPacket(t,e),e)}async getNextPacket(t,e={}){if(!(t instanceof j))throw new TypeError("packet must be an EncodedPacket.");if(Li(e),this._track.input._disposed)throw new ge;return il(this._track,this._track._backing.getNextPacket(t,e),e)}async getKeyPacket(t,e={}){if(Vr(t),Li(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 j))throw new TypeError("packet must be an EncodedPacket.");if(Li(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 j))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 j))throw new TypeError("endPacket must be an EncodedPacket.");if(Li(r),this._track.input._disposed)throw new ge;let n=[],{promise:a,resolve:s}=ee(),{promise:o,resolve:c}=ee(),u=!1,l=!1,d=null,m=!1,f=[],p=()=>Math.max(2,f.length);(async()=>{let h=t??await this.getFirstPacket(r);for(;h&&!l&&!this._track.input._disposed&&!(e&&h.sequenceNumber>=e?.sequenceNumber);){if(n.length>p()){({promise:o,resolve:c}=ee()),await o;continue}n.push(h),s(),{promise:a,resolve:s}=ee(),h=await this.getNextPacket(h,r)}u=!0,s()})().catch(h=>{m||(d=h,m=!0,s())});let g=this._track;return{async next(){for(;;){if(g.input._disposed)throw new ge;if(l)return{value:void 0,done:!0};if(m)throw d;if(n.length>0){let h=n.shift(),y=performance.now();for(f.push(y);f.length>0&&y-f[0]>=1e3;)f.shift();return c(),{value:h,done:!1}}else{if(u)return{value:void 0,done:!0};await a}}},async return(){return l=!0,c(),s(),{value:void 0,done:!0}},async throw(h){throw h},[Symbol.asyncIterator](){return this}}}},kf=4,Ga=class{constructor(t,e){this.onSample=t;this.onError=e;this.onDequeue=null}},Un=class{mediaSamplesInRange(t=-1/0,e=1/0,r){Vr(t),Vr(e);let n=[],a=!1,s=null,{promise:o,resolve:c}=ee(),{promise:u,resolve:l}=ee(),d=!1,m=!1,f=!1,p=null,g=null,h=!1,y={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(A=>{if(l(),A.timestamp>=e&&(m=!0),m){A.close();return}s&&(A.timestamp>t?(n.push(s),a=!0):s.close()),A.timestamp>=t&&(n.push(A),a=!0),s=a?null:A,n.length>0&&(c(),{promise:o,resolve:c}=ee())},A=>{h||(g=A,h=!0,c())}),p.onDequeue=()=>l();let T=this._createPacketSink(),S=await T.getKeyPacket(t,y)??await T.getFirstKeyPacket(y),x=S,P=T.packets(S??void 0,void 0,y);for(await P.next();x&&!m&&!this._track.input._disposed;){if(n.length+p.getDecodeQueueSize()>=kf){({promise:u,resolve:l}=ee()),await u;continue}p.decode(x);let A=await P.next();if(A.done)break;x=A.value}await P.return(),!f&&!this._track.input._disposed&&await p.flush(),!a&&s&&(n.push(s),s=null),d=!0,c()})().catch(T=>{h||(g=T,h=!0,c())}).finally(()=>{p?.close()});let k=this._track,w=()=>{s?.close();for(let T of n)T.close()};return{async next(){for(;;){if(k.input._disposed)throw f=!0,m=!0,w(),new ge;if(f)return{value:void 0,done:!0};if(h)throw f=!0,m=!0,w(),g;if(n.length>0){let T=n.shift();return l(),{value:T,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return f=!0,m=!0,l(),c(),w(),{value:void 0,done:!0}},async throw(T){throw T},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(t,e){Hl(t);let r=Wl(t),n=[],a=[],{promise:s,resolve:o}=ee(),{promise:c,resolve:u}=ee(),l=!1,d=!1,m=null,f=null,p=!1,g=w=>{a.push(w),o(),{promise:s,resolve:o}=ee()},h={...e,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{m=await this._createDecoder(A=>{if(u(),d){A.close();return}let I=0;for(;n.length>0&&A.timestamp-n[0]>-1e-10;)I++,n.shift();if(I>0)for(let E=0;E<I;E++)g(E<I-1?A.clone():A);else A.close()},A=>{p||(f=A,p=!0,o())}),m.onDequeue=()=>u();let w=this._createPacketSink(),T=null,S=null,x=-1,C=async()=>{b(S),b(m);let A=S;for(m.decode(A);A.sequenceNumber<x;){for(;a.length+m.getDecodeQueueSize()>=kf&&!d;)({promise:c,resolve:u}=ee()),await c;if(d)break;let I=await w.getNextPacket(A,h);if(!I)throw new Error("Internal error: couldn't get next packet when one was expected.");m.decode(I),A=I}x=-1},P=async()=>{b(m),await m.flush();for(let A=0;A<n.length;A++)g(null);n.length=0};for await(let A of r){if(Vr(A),d||this._track.input._disposed)break;let I=await w.getPacket(A,h),E=I&&await w.getKeyPacket(A,h);if(!E){x!==-1&&(await C(),await P()),g(null),T=null;continue}T&&(E.sequenceNumber!==S.sequenceNumber||I.timestamp<T.timestamp)&&(await C(),await P()),n.push(I.timestamp),x=Math.max(I.sequenceNumber,x),T=I,S=E}!d&&!this._track.input._disposed&&(x!==-1&&await C(),await P()),l=!0,o()})().catch(w=>{p||(f=w,p=!0,o())}).finally(()=>{m?.close()});let y=this._track,k=()=>{for(let w of a)w?.close()};return{async next(){for(;;){if(y.input._disposed)throw d=!0,k(),new ge;if(d)return{value:void 0,done:!0};if(p)throw d=!0,k(),f;if(a.length>0){let w=a.shift();return b(w!==void 0),u(),{value:w,done:!1}}else if(!l)await s;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),k(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}},al=class extends Ga{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 Lr;this.customDecoderQueueSize=0;this.inputTimestamps=[];this.sampleQueue=[];this.currentPacketIndex=0;this.raslSkipped=!1;this.alphaDecoder=null;this.alphaHadKeyframe=!1;this.colorQueue=[];this.alphaQueue=[];this.merger=null;this.decodedAlphaChunkCount=0;this.alphaDecoderQueueSize=0;this.nullAlphaFrameQueue=[];this.currentAlphaPacketIndex=0;this.alphaRaslSkipped=!1;this.finalSamples=[];this.mergeAlphaPromises=[];let u=ci.find(l=>l.supports(n,a));if(u)this.customDecoder=new u,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=l=>{if(!(l instanceof Ge))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoder.onError=l=>{r(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>r(l));else{let l=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(Yn()){if(n==="avc"&&this.decoderConfig.description){let m=tr(Q(this.decoderConfig.description));if(m&&m.sequenceParameterSets.length>0){let f=rr(m.sequenceParameterSets[0]);f&&(f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),f.maxDecFrameBuffering!==0&&f.bitstreamRestrictionFlag!==1&&(m.sequenceParameterSets[0]=nu(f),this.decoderConfig={...this.decoderConfig,description:un(m)}))}}rn(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{l(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))}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),jt()||qc(this.inputTimestamps,e.timestamp,r=>r),Yn()&&this.currentPacketIndex===0){if(this.codec==="avc"){let r=[],n=!1;for(let s of iu(e.data,this.decoderConfig)){let o=Jt(e.data[s.offset]);if(n||=o>=1&&o<=5,o===9){if(n)break;r.length=0}o>=20&&o<=31||r.push(e.data.subarray(s.offset,s.offset+s.length))}if(!this.decoderConfig.description)for(let s=0;s<r.length;s++){let o=r[s];if(Jt(o[0])!==7)continue;let c=rr(o);c&&c.maxDecFrameBuffering!==0&&c.bitstreamRestrictionFlag!==1&&(r[s]=nu(c));break}let a=md(r,this.decoderConfig);e=new j(a,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){let r=hd(e.data,this.decoderConfig);r&&(e=new j(r,e.type,e.timestamp,e.duration))}}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 sl),!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(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=jr(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}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let r of Jn(e,this.decoderConfig)){let n=Rt(e[r.offset]);if(n===8||n===9)return!0}return!1}sampleHandler(e){if(jt()){if(this.sampleQueue.length>0&&e.timestamp>=Y(this.sampleQueue).timestamp){for(let r of this.sampleQueue)this.finalizeAndEmitSample(r);this.sampleQueue.length=0}qc(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=ee();this.mergeAlphaPromises.push(n.promise);let a={sample:null};this.finalSamples.push(a);try{if(!r)a.sample=new Ge(e);else{b(this.merger);let s=await this.merger.merge(e,r);a.sample=new Ge(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){let s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){nn(this.finalSamples,a),this.onError(s)}finally{nn(this.mergeAlphaPromises,n.promise),n.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(b(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),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),jt()){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()):(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}},nl=null,sl=class{constructor(){this.workers=[];this.nextWorkerIndex=0;this.pendingRequests=new Map;this.nextRequestId=0}merge(t,e){if(this.workers.length===0){if(!nl){let o=new Blob([`(${Fh.toString()})()`],{type:"application/javascript"});nl=URL.createObjectURL(o)}let s=J(navigator.hardwareConcurrency,1,4);for(let o=0;o<s;o++){let c=new Worker(nl);c.addEventListener("message",u=>{let l=u.data,d=this.pendingRequests.get(l.id);d&&(this.pendingRequests.delete(l.id),"error"in l?d.reject(new Error(l.error)):d.resolve(l.frame))}),c.addEventListener("error",u=>{let l=new Error(u.message||"Color/alpha merge worker error.");for(let d of this.pendingRequests.values())d.reject(l);this.pendingRequests.clear()}),this.workers.push(c)}}let r=this.nextRequestId++,n=ee();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()}},Fh=()=>{let i=null,t=null,e=Promise.resolve();self.addEventListener("message",c=>{let{id:u,color:l,alpha:d}=c.data;e=e.then(async()=>{try{let m=await r(l,d);self.postMessage({id:u,frame:m},{transfer:[m]})}catch(m){self.postMessage({id:u,error:m.message})}finally{l.close(),d.close()}})});let r=async(c,u)=>{let l=c.format,d=u.format;if(!l||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");let m=l.includes("P10"),f=l.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: '${l}', alpha: '${d}').`);if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await n(c,u,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await a(c,u,l);if(l==="NV12")return await s(c,u);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},n=async(c,u,l)=>{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(u,d,m,1);for(let k=0,w=3;k<f;k++,w+=4)p[w]=g[k];let y={format:l==="RGBX"||l==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:m,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[p.buffer]};return new VideoFrame(p,y)},a=async(c,u,l)=>{let d=c.visibleRect?.width??c.codedWidth,m=c.visibleRect?.height??c.codedHeight,f=l.includes("P10"),p=l.includes("P12"),g=f||p?2:1,h,y;l.startsWith("I420")?(h=Math.ceil(d/2),y=Math.ceil(m/2)):l.startsWith("I422")?(h=Math.ceil(d/2),y=m):(h=d,y=m);let k=d*m,w=h*y,T=k*g,S=w*g,x=k*g,C=T+2*S+x,P=new Uint8Array(C);await c.copyTo(P);let A=await o(u,d,m,g),I=T+2*S;P.set(A,I);let v={format:l.slice(0,4)+"A"+l.slice(4),codedWidth:d,codedHeight:m,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[P.buffer]};return new VideoFrame(P,v)},s=async(c,u)=>{let l=c.visibleRect?.width??c.codedWidth,d=c.visibleRect?.height??c.codedHeight,m=l*d,f=Math.ceil(l/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,w=m+g,T=m;for(let C=0;C<g;C++)y[k+C]=t[T+C*2],y[w+C]=t[T+C*2+1];let S=await o(u,l,d,1);y.set(S,m+2*g);let x={format:"I420A",codedWidth:l,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,x)},o=async(c,u,l,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=u*l;for(let h=0;h<g;h++)i[h]=i[h*4+p];return i.subarray(0,g)}else{let p=i.subarray(0,u*l*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,w=d===2?new Uint16Array(p.buffer,0,u*l):p;for(let T=0;T<w.length;T++){let S=Math.round((w[T]-h)*k/(y-h));w[T]=Math.min(Math.max(S,0),k)}}return p}}},Tf=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.")},mi=class extends Un{constructor(t,e={}){if(!(t instanceof ur))throw new TypeError("videoTrack must be an InputVideoTrack.");Tf(e),super(),this._track=t,this._decoderOptions=e}async _createDecoder(t,e){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(an("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 al(t,e,r,s,n,a,o)}_createPacketSink(){return new st(this._track)}async getSample(t,e={}){Vr(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)}},Jo=class{constructor(t,e={}){this._rotation=0;this._flip=!1;this._initPromise=null;this._nextCanvasIndex=0;if(!(t instanceof ur))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&&li(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&&Tf(e.decoderOptions),this._videoTrack=t,this._alpha=e.alpha??!1,this._options=e,this._fit=e.fit??"fill",this._videoSampleSink=new mi(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],u=t.crop;u&&(u=Bn(u,o,c));let[l,d]=u?[u.width,u.height]:[o,c],m=l/d;t.width!==void 0&&t.height===void 0?(l=t.width,d=Math.round(l/m)):t.width===void 0&&t.height!==void 0?(d=t.height,l=Math.round(d*m)):t.width!==void 0&&t.height!==void 0&&(l=t.width,d=t.height),this._width=l,this._height=d,this._rotation=r,this._flip=n,this._crop=u})()}_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||Xt()});b(s),t._drawWithFitAndMipmapping(n,s,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&Xt()});let o={canvas:n,timestamp:t.timestamp,duration:t.duration};return t.close(),o}async getCanvas(t,e){Vr(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*$n(this._videoSampleSink.samples(t,e,r),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(t,e){await this._ensureInit(),yield*$n(this._videoSampleSink.samplesAtTimestamps(t,e),r=>r&&this._videoSampleToWrappedCanvas(r))}},ol=class extends Ga{constructor(e,r,n,a){super(e,r);this.decoder=null;this.customDecoder=null;this.customDecoderCallSerializer=new Lr;this.customDecoderQueueSize=0;this.currentTimestamp=null;this.expectedFirstTimestamp=null;this.timestampOffset=0;let s=c=>{let u=c.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-u),u+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(u-this.currentTimestamp)>=c.duration)&&(this.currentTimestamp=u);let l=this.currentTimestamp;if(this.currentTimestamp+=c.duration,c.numberOfFrames===0){c.close();return}let d=a.sampleRate;c.setTimestamp(Math.round(l*d)/d),e(c)},o=ui.find(c=>c.supports(n,a));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=a,this.customDecoder.onSample=c=>{if(!(c instanceof Ae))throw new TypeError("The argument passed to onSample must be an AudioSample.");s(c)},this.customDecoder.onError=c=>{r(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(c=>r(c));else{let c=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:u=>{try{s(new Ae(u))}catch(l){this.onError(l)}},error:u=>{u.stack=c,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){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(r=>this.onError(r)).finally(()=>{this.customDecoderQueueSize--,this.onDequeue?.()})):(b(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.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.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(b(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}},cl=class extends Ga{constructor(e,r,n){super(e,r);this.decoderConfig=n;this.currentTimestamp=null;b(ne.includes(n.codec)),this.codec=n.codec;let{dataType:a,sampleSize:s,littleEndian:o}=Re(this.codec);switch(this.inputSampleSize=s,s){case 1:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint8(u)-2**7:a==="signed"?this.readInputValue=(c,u)=>c.getInt8(u):a==="ulaw"?this.readInputValue=(c,u)=>gf(c.getUint8(u)):a==="alaw"?this.readInputValue=(c,u)=>yf(c.getUint8(u)):b(!1);break;case 2:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint16(u,o)-2**15:a==="signed"?this.readInputValue=(c,u)=>c.getInt16(u,o):b(!1);break;case 3:a==="unsigned"?this.readInputValue=(c,u)=>Ci(c,u,o)-2**23:a==="signed"?this.readInputValue=(c,u)=>ql(c,u,o):b(!1);break;case 4:a==="unsigned"?this.readInputValue=(c,u)=>c.getUint32(u,o)-2**31:a==="signed"?this.readInputValue=(c,u)=>c.getInt32(u,o):a==="float"?this.readInputValue=(c,u)=>c.getFloat32(u,o):b(!1);break;case 8:a==="float"?this.readInputValue=(c,u)=>c.getFloat64(u,o):b(!1);break;default:ae(s),b(!1)}switch(s){case 1:a==="ulaw"||a==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(c,u,l)=>c.setUint8(u,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(c,u,l)=>c.setInt16(u,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l<<8,!0);break;case 4:this.outputSampleSize=4,a==="float"?(this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(c,u,l)=>c.setInt32(u,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(c,u,l)=>c.setFloat32(u,l,!0);break;default:ae(s),b(!1)}}getDecodeQueueSize(){return 0}decode(e){let r=N(e.data),n=Math.floor(e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize),a=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,s=new ArrayBuffer(a),o=new DataView(s);for(let d=0;d<n*this.decoderConfig.numberOfChannels;d++){let m=d*this.inputSampleSize,f=d*this.outputSampleSize,p=this.readInputValue(r,m);this.writeOutputValue(o,f,p)}let c=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=c)&&(this.currentTimestamp=e.timestamp);let u=this.currentTimestamp;this.currentTimestamp+=c;let l=new Ae({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:u});this.onSample(l)}async flush(){}close(){}},Wi=class extends Un{constructor(t){if(!(t instanceof lr))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(an("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),ne.includes(n.codec)?new cl(t,e,n):new ol(t,e,r,n)}_createPacketSink(){return new st(this._track)}async getSample(t,e={}){Vr(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)}},ec=class{constructor(t){if(!(t instanceof lr))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Wi(t)}_audioSampleToWrappedArrayBuffer(t){let e={buffer:t.toAudioBuffer(),timestamp:t.timestamp,duration:t.duration};return t.close(),e}async getBuffer(t,e){Vr(t);let r=await this._audioSampleSink.getSample(t,e);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(t,e,r){return $n(this._audioSampleSink.samples(t,e,r),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(t,e){return $n(this._audioSampleSink.samplesAtTimestamps(t,e),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}};var fi=class i{constructor(t,e){this.input=t,this._backing=e}isVideoTrack(){return this instanceof ur}isAudioTrack(){return this instanceof lr}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ye(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ye(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ye(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ye(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 ye(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){return(await this._backing.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async computeDuration(t){let e=await this._backing.getPacket(1/0,{metadataOnly:!0,...t}),r=(e?.timestamp??0)+(e?.duration??0);return Gt(r,await this.getTimeResolution())}async getDurationFromMetadata(t={}){return this._backing.getDurationFromMetadata(t)}async computePacketStats(t=1/0,e){let r=new st(this),n=1/0,a=-1/0,s=0,o=0;for await(let c of r.packets(void 0,void 0,{metadataOnly:!0,...e})){if(s>=t&&c.timestamp>=a)break;n=Math.min(n,c.timestamp),a=Math.max(a,c.timestamp+c.duration),s++,o+=c.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-n)).toPrecision(16)):0,averageBitrate:s?Number((8*o/(a-n)).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(pi({filter:e=>e.canBePairedWith(this)},t))}async getPairableVideoTracks(t){return this.input.getVideoTracks(pi({filter:e=>e.canBePairedWith(this)},t))}async getPairableAudioTracks(t){return this.input.getAudioTracks(pi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableVideoTrack(t){return this.input.getPrimaryVideoTrack(pi({filter:e=>e.canBePairedWith(this)},t))}async getPrimaryPairableAudioTrack(t){return this.input.getPrimaryAudioTrack(pi({filter:e=>e.canBePairedWith(this)},t))}async hasPairableTrack(t){t&&=ul(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&&=ul(t),this.hasPairableTrack(async e=>e.isVideoTrack()&&(!t||await t(e)))}hasPairableAudioTrack(t){return t&&=ul(t),this.hasPairableTrack(async e=>e.isAudioTrack()&&(!t||await t(e)))}},ye=(i,t,e)=>{if(_(i))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${e}()' instead.`);return i},ul=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.then(e):e(r)}:void 0},ur=class extends fi{constructor(e,r){super(e,r);this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ye(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 ye(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ye(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return Si(await this._backing.getTransformationMatrix())}get rotation(){return Si(ye(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return Lc(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ye(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ye(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=wf(await this.getSquarePixelWidth()*await this.getCodedHeight(),await this.getSquarePixelHeight()*await this.getCodedWidth())}get pixelAspectRatio(){return this._pixelAspectRatioCache??=wf(ye(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ye(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),ye(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ye(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=ye(e,"displayWidth","getDisplayWidth");if(a!==null)return a}let n=Si(ye(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ye(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=ye(e,"displayHeight","getDisplayHeight");if(a!==null)return a}let n=Si(ye(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ye(n,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pq"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}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),ci.some(a=>a.supports(r,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return V._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof j))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),jr(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&&(!ve(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 st(this),s=[],o=-1/0,c=0;for await(let E of a.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=n&&E.timestamp>=o)break;s.push(E.timestamp),o=Math.max(o,E.timestamp),c++}let u=new Float64Array(s.length);for(let E=0;E<s.length;E++)u[E]=Math.round(s[E]*r);u.sort();let l=1;for(let E=1;E<u.length;E++)u[E]!==u[l-1]&&(u[l++]=u[E]);if(l<2)return{underlyingFrameRate:null,bestGuessFrameRate:r,minFrameRate:r,maxFrameRate:r,averageFrameRate:r,medianFrameRate:r,frameRateIsConstant:!0,probedPacketCount:c};let d=u.subarray(0,l),m=Mh(d,r),f=m??r,p=m!==null?r/m:null,g=new Map,h=1/0,y=-1/0,k=0;for(let E=1;E<l;E++){let v=d[E]-d[E-1],R=p!==null?Math.max(1,Math.round(v/p)):v;g.set(R,(g.get(R)??0)+1),h=Math.min(h,R),y=Math.max(y,R),k+=R}let w=l-1,T=[...g.keys()].sort((E,v)=>E-v),S=w-1>>1,x=w>>1,C=0,P=0,A=0;for(let E of T)if(A+=g.get(E),C===0&&A>S&&(C=E),A>x){P=E;break}let I=(f/C+f/P)/2;return{underlyingFrameRate:m,bestGuessFrameRate:m!==null?m:Bh(I),minFrameRate:f/y,maxFrameRate:f/h,averageFrameRate:f*w/k,medianFrameRate:I,frameRateIsConstant:m!==null&&h===1&&y===1,probedPacketCount:c}}},wf=(i,t)=>i===0||t===0?{num:1,den:1}:Ar({num:i,den:t}),lr=class extends fi{constructor(t,e){super(t,e)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ye(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ye(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ye(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 canDecode(){try{let t=await this._backing.getDecoderConfig();if(!t)return!1;let e=await this._backing.getCodec();return b(e!==null),ui.some(r=>r.supports(e,t))||ne.includes(t.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0}catch(t){return V._error("Error during decodability check:",t),!1}}async determinePacketType(t){if(!(t instanceof j))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}},Af=i=>i??1/0,Qa=i=>-(i??-1/0),hi=i=>-i,zn=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.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.then(e):e(r)}:void 0}},pi=(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.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)||_(n)?Promise.all([r,n]).then(([s,o])=>a(s,o)):a(r,n)}:void 0}),tc=async(i,t)=>{let e=i;if(t?.filter){let s=i.map(c=>t.filter(c));if(s.some(c=>_(c))){let c=await Promise.all(s);e=i.filter((u,l)=>c[l])}else e=i.filter((c,u)=>s[u])}if(!t?.sortBy)return e;let r=e.map(s=>t.sortBy(s)),a=r.some(s=>_(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],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let d=0;d<l;d++){let m=c[d]??0,f=u[d]??0;if(m!==f)return m-f}return 0}).map(s=>s.track)},Mh=(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 C=1;C<i.length;C++){let P=i[C]-i[C-1];if(!(P>0))return null;o[C-1]=P}let c=o.slice();c.sort();let u=c[Math.floor(c.length*.05)];for(let C=0;C<6;C++){let P=0,A=0;for(let E of o){let v=Math.max(1,Math.round(E/u));Math.abs(E-v*u)>=n||(P+=E,A+=v)}if(A===0)return null;let I=P/A;if(Math.abs(I-u)<=1e-12*Math.max(1,u)){u=I;break}u=I}let l=0,d=0,m=0;for(let C of o){let P=Math.max(1,Math.round(C/u));Math.abs(C-P*u)>=n||(l++,d+=C,m+=P)}if(l/o.length<.98)return null;u=d/m;let f=1/Math.min(m,a),p=Math.max(Number.EPSILON,u-f),g=u+f,h=t/g,y=t/p,k=t/u,w=null,T=1/0;for(let C of s){if(C<h||C>y)continue;let P=Math.abs(C/k-1);P<T&&(w=C,T=P)}if(w===null){let C=Sf(p,g,1e6),P=Sf(h,y,1e6);if(P&&(!C||P.den<C.den||P.den===C.den&&P.num<=C.num))w=P.num/P.den;else if(C)w=t*C.den/C.num;else return null}let S=t/w,x=0;for(let C of o){let P=Math.max(1,Math.round(C/S));Math.abs(C-P*S)<n&&x++}return x/o.length<.98?null:w},Sf=(i,t,e)=>{for(let r=1;r<=e;r++){let n=Math.floor(i*r)+1;if(n/r<t)return Ar({num:n,den:r})}return null},Bh=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};sn();var Oh=1,Bm=2,oi=class i extends Je{constructor(e){super();this._demuxerPromise=null;this._format=null;this._trackBackingsCache=null;this._backingToTrack=new Map;this._disposed=!1;this._nextSourceCacheAge=0;this._sourceRefs=[];this._sourceCache=[];this._sourceCachePromises=[];this._onFormatDetermined=null;if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(r=>!(r instanceof Ze)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ne||e.source instanceof ai))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ne&&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&&zm(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Ne?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get disposed(){return this._disposed}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){b(this._rootSource instanceof Ye);let r=await this._rootSource._resolveRequest(e);return this._emit("source",{source:r.source,request:e,isRoot:e.isRoot}),r}_getSourceCached(e,r=Oh){let n=this._sourceCache.find(o=>o.cacheGroup===r&&Lu(o.request,e));if(n)return n.age++,Promise.resolve(n.sourceRef.source.ref());let a=this._sourceCachePromises.find(o=>o.cacheGroup===r&&Lu(o.request,e));if(a)return a.promise.then(o=>o.sourceRef.source.ref());let s=(async()=>{let o=await this._getSourceUncached(e);if(this._disposed)throw o.free(),new ge;if(vi(this._sourceCache,m=>m.cacheGroup===r&&m.sourceRef.source._refCount===1)>=4){let m=on(this._sourceCache,p=>p.cacheGroup===r&&p.sourceRef.source._refCount===1?p.age:1/0);b(m!==-1);let f=this._sourceCache[m];this._sourceCache.splice(m,1),f.sourceRef.free(),nn(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(o);let l=this._sourceCachePromises.findIndex(m=>m.request===e);return b(l!==-1),this._sourceCachePromises.splice(l,1),{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 si(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new Nn})()}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 Nn)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._backing.getFirstPacket({metadataOnly:!0}))),a=Math.min(...n.map(s=>s?.timestamp??1/0));return a===1/0?0:a}async computeDuration(e,r){e??=await this.getTracks();let n=e.filter(s=>s!==null);if(n.length===0)return 0;let a=await Promise.all(n.map(s=>s.computeDuration(r)));return Math.max(...a)}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&&=zn(e);let n=(await this._getTrackBackings()).map(a=>this._wrapBackingAsTrack(a));return tc(n,e)}async getVideoTracks(e){e&&=zn(e);let n=(await this.getTracks()).filter(a=>a.isVideoTrack());return tc(n,e)}async getAudioTracks(e){e&&=zn(e);let n=(await this.getTracks()).filter(a=>a.isAudioTrack());return tc(n,e)}async getPrimaryVideoTrack(e){e&&=zn(e);let r=pi(e,{sortBy:async a=>[hi((await a.getDisposition()).default),hi(await a.hasPairableAudioTrack()),hi(!await a.hasOnlyKeyPackets()),Qa(await a.getBitrate())]});return(await this.getVideoTracks(r))[0]??null}async getPrimaryAudioTrack(e){e&&=zn(e);let r=await this.getPrimaryVideoTrack(),n=pi(e,{sortBy:async s=>[hi(!r||s.canBePairedWith(r)),hi((await s.getDisposition()).default),Qa(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 ur(this,e):new lr(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._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}},Nn=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 si=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 we(a,N(a),0,t,t)}let r=t+e,n=this.source._read(t,r,zu,Nu);return _(n)?n.then(a=>a?new we(a.bytes,a.view,a.offset,t,r):null):n?new we(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,J(this.fileSizeNonStrict-t,e,r));{let n=this.requestSlice(t,r),a=s=>s||(b(this.fileSizeNonStrict!==null),this.requestSlice(t,J(this.fileSizeNonStrict-t,e,r)));return _(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(_(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 we(n,N(n),0,0,r)})()}},we=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)}},ot=(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)=>{ot(i,t);let e=i.bytes.subarray(i.bufferPos,i.bufferPos+t);return i.bufferPos+=t,e},L=i=>(ot(i,1),i.view.getUint8(i.bufferPos++)),Cn=(i,t)=>{ot(i,2);let e=i.view.getUint16(i.bufferPos,t);return i.bufferPos+=2,e},fe=i=>{ot(i,2);let t=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,t},Dt=i=>{ot(i,3);let t=Ci(i.view,i.bufferPos,!1);return i.bufferPos+=3,t},ma=i=>{ot(i,2);let t=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,t},Or=(i,t)=>{ot(i,4);let e=i.view.getUint32(i.bufferPos,t);return i.bufferPos+=4,e},M=i=>{ot(i,4);let t=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,t},ni=i=>{ot(i,4);let t=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,t},Rr=i=>{ot(i,4);let t=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,t},Dh=i=>{ot(i,4);let t=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,t},wu=(i,t)=>{let e,r;return t?(e=Or(i,!0),r=Or(i,!0)):(r=Or(i,!1),e=Or(i,!1)),r*4294967296+e},qe=i=>{let t=M(i),e=M(i);return t*4294967296+e},em=i=>{let t=Rr(i),e=M(i);return t*4294967296+e},fm=i=>{let t=ni(i);return Dh(i)*4294967296+t},sm=i=>{ot(i,4);let t=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,t},eo=i=>{ot(i,8);let t=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,t},ue=(i,t)=>{ot(i,t);let e="";for(let r=0;r<t;r++)e+=String.fromCharCode(i.bytes[i.bufferPos++]);return e},_o=(i,t,e)=>he.decode(U(i,t)).split(`
9
+ `).map(a=>a.trim()).filter(a=>a.length>0&&!e?.ignore?.(a));var ga=128,Fe=10,Wn=["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"],um=(i,t)=>{let e=i.filePos;t.raw??={},t.raw.TAG??=U(i,ga-3),i.filePos=e;let r=Ln(i,30);r&&(t.title??=r);let n=Ln(i,30);n&&(t.artist??=n);let a=Ln(i,30);a&&(t.album??=a);let s=Ln(i,4),o=Number.parseInt(s,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(String(o)));let c=U(i,30),u;if(c[28]===0&&c[29]!==0){let d=c[29];d>0&&(t.trackNumber??=d),i.skip(-30),u=Ln(i,28),i.skip(2)}else i.skip(-30),u=Ln(i,30);u&&(t.comment??=u);let l=L(i);l<Wn.length&&(t.genre??=Wn[l])},Ln=(i,t)=>{let e=U(i,t),r=Ii(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()},it=i=>{let t=i.filePos,e=ue(i,3),r=L(i),n=L(i),a=L(i),s=M(i);if(e!=="ID3"||r===255||n===255||(s&2155905152)!==0)return i.filePos=t,null;let o=qs(s);return a&16&&(o+=Fe),{majorVersion:r,revision:n,flags:a,size:o}},ii=(i,t,e)=>{if(![2,3,4].includes(t.majorVersion)){V._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=t.flags&16?t.size-Fe:t.size,n=U(i,r),a=new ll(t,n);if(t.flags&128&&t.majorVersion===3&&a.ununsynchronizeAll(),t.flags&64){if(a.bytes.length<4)return;let s=a.readU32();t.majorVersion===3?a.pos+=s:a.pos+=s-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let s=a.readId3V2Frame();if(!s)break;let o=a.pos,c=Math.min(a.pos+s.size,a.bytes.length),u=c,l=!1,d=!1,m=!1;if(t.majorVersion===3?(l=!!(s.flags&64),d=!!(s.flags&128)):t.majorVersion===4&&(l=!!(s.flags&4),d=!!(s.flags&8),m=!!(s.flags&2)||!!(t.flags&128)),l){V._warn(`Skipping encrypted ID3v2 frame ${s.id}`),a.pos=c;continue}if(d){V._warn(`Skipping compressed ID3v2 frame ${s.id}`),a.pos=c;continue}m&&(u=a.ununsynchronizeRegion(a.pos,u));let f=p=>{if(u-a.pos<p)throw new Error(`Invalid ID3v2 ${s.id} frame: too short.`)};if(e.raw??={},s.id==="TXXX"){let p=e.raw.TXXX??={};f(1);let g=a.readId3V2TextEncoding(),h=a.readId3V2Text(g,u),y=a.readId3V2Text(g,u);p[h]??=y}else s.id[0]==="T"?e.raw[s.id]??=a.readId3V2EncodingAndText(u):e.raw[s.id]??=a.readBytes(u-a.pos);switch(a.pos=o,s.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 g=a.readId3V2EncodingAndText(u).split("/"),h=Number.parseInt(g[0],10),y=g[1]&&Number.parseInt(g[1],10);Number.isInteger(h)&&h>0&&(e.trackNumber??=h),y&&Number.isInteger(y)&&y>0&&(e.tracksTotal??=y)}break;case"TPOS":case"TPA":{let g=a.readId3V2EncodingAndText(u).split("/"),h=Number.parseInt(g[0],10),y=g[1]&&Number.parseInt(g[1],10);Number.isInteger(h)&&h>0&&(e.discNumber??=h),y&&Number.isInteger(y)&&y>0&&(e.discsTotal??=y)}break;case"TCON":case"TCO":{let p=a.readId3V2EncodingAndText(u),g=/^\((\d+)\)/.exec(p);if(g){let h=Number.parseInt(g[1]);if(Wn[h]!==void 0){e.genre??=Wn[h];break}}if(g=/^\d+$/.exec(p),g){let h=Number.parseInt(g[0]);if(Wn[h]!==void 0){e.genre??=Wn[h];break}}e.genre??=p}break;case"TDRC":case"TDAT":{let p=a.readId3V2EncodingAndText(u),g=new Date(p);Number.isNaN(g.getTime())||(e.date??=g)}break;case"TYER":case"TYE":{let p=a.readId3V2EncodingAndText(u),g=Number.parseInt(p,10);Number.isInteger(g)&&(e.date??=new Date(String(g)))}break;case"TBPM":case"TBP":{let p=a.readId3V2EncodingAndText(u),g=Number.parseInt(p,10);Number.isInteger(g)&&(e.beatsPerMinute??=g)}break;case"USLT":case"ULT":{f(4);let p=a.readU8();a.pos+=3,a.readId3V2Text(p,u),e.lyrics??=a.readId3V2Text(p,u)}break;case"COMM":case"COM":{f(4);let p=a.readU8();a.pos+=3,a.readId3V2Text(p,u),e.comment??=a.readId3V2Text(p,u)}break;case"APIC":case"PIC":{f(1);let p=a.readId3V2TextEncoding(),g;if(t.majorVersion===2){f(3);let w=a.readAscii(3);g=w==="PNG"?"image/png":w==="JPG"?"image/jpeg":"image/*"}else g=a.readId3V2Text(p,u);f(1);let h=a.readU8(),y=a.readId3V2Text(p,u).trimEnd(),k=u-a.pos;if(k>=0){let w=a.readBytes(k);e.images||(e.images=[]),e.images.push({data:w,mimeType:g,kind:h===3?"coverFront":h===4?"coverBack":"unknown",description:y})}}break;default:a.pos+=s.size;break}a.pos=c}},ll=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=[];for(let e=0;e<this.bytes.length;e++){let r=this.bytes[e];t.push(r),r===255&&e!==this.bytes.length-1&&this.bytes[e]===0&&e++}this.bytes=new Uint8Array(t),this.view=new DataView(this.bytes.buffer)}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=this.header.majorVersion===4?qs(e):e,n=this.readU16(),a=this.pos,s=o=>{let c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;let u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!s(r)){let o=this.header.majorVersion===4?e:qs(e);s(o)&&(r=o)}return this.pos=a,{id:t,size:r,flags:n}}}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 xi("utf-16le"),s=Ii(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 xi("utf-16be"),s=Ii(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{let a=Ii(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),he.decode(n.subarray(0,a))}case 2:{let a=new xi("utf-16be"),s=Ii(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=Ii(n.findIndex(s=>s===0),n.length);return this.pos=r+Math.min(a+1,n.length),he.decode(n.subarray(0,a))}}}readId3V2EncodingAndText(t){if(this.pos>=t)return"";let e=this.readId3V2TextEncoding();return this.readId3V2Text(e,t)}},gi=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 _t(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 u=t.tracksTotal!==void 0?`${c}/${t.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",u),n.add("TRCK")}break;case"discNumber":{let u=t.discsTotal!==void 0?`${c}/${t.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",u),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 u={coverFront:3,coverBack:4,unknown:0};for(let l of c){let d=u[l.kind]??0,m=l.description??"";this.writeId3V2ApicFrame(l.mimeType,d,m,l.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ae(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 u;if(typeof c=="string")if(vt(c)){u=new Uint8Array(c.length+2),u[0]=0;for(let d=0;d<c.length;d++)u[d+1]=c.charCodeAt(d)}else{let d=Z.encode(c);u=new Uint8Array(d.byteLength+2),u[0]=3,u.set(d,1)}else if(c instanceof Uint8Array)u=c;else if(o==="TXXX"&&ks(c)){for(let l in c){let d=c[l],m=vt(l)&&vt(d),f=m?null:Z.encode(l),p=m?null:Z.encode(d),g=m?l.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(l),this.writeIsoString(d)):(this.writer.write(f),this.writeU8(0),this.writer.write(p),this.writeU8(0))}continue}else continue;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(Vd(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=Z.encode(t);this.writer.write(e),this.writeU8(0)}writeId3V2TextFrame(t,e){let r=vt(e),a=1+(r?e.length:Z.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=vt(t),r="",n=4+r.length+1+t.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(e?0:3),this.writeAscii("und"),e?(this.writeIsoString(r),this.writeIsoString(t)):(this.writeUtf8String(r),this.writeUtf8String(t))}writeId3V2CommentFrame(t){let e=vt(t),r=e?t.length:Z.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=vt(t)&&vt(r),s=a?r.length:Z.encode(r).byteLength,o=1+t.length+1+1+s+1+n.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),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 Ie=class{constructor(t){this.mutex=new He;this.trackTimestampInfo=new WeakMap;this.output=t}onTrackClose(t){}validateTimestamp(t,e,r){let n=this.trackTimestampInfo.get(t);if(n){if(r&&(n.maxTimestampBeforeLastKeyPacket=n.maxTimestamp),n.maxTimestampBeforeLastKeyPacket!==null&&e<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 ${n.maxTimestampBeforeLastKeyPacket}s.`);n.maxTimestamp=Math.max(n.maxTimestamp,e)}else{if(!r)throw new Error("First packet must be a key packet.");n={maxTimestamp:e,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(t,n)}}};var rc=class extends Ie{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();this.writer=await this.output._getRootWriter(!0),Cr(this.output._metadataTags)||new gi(this.writer).writeId3V2Tag(this.output._metadataTags),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){Ce(n,e.source._codec);let s=n?.decoderConfig?.description;if(this.inputIsAdts=!s,!this.inputIsAdts){let o=Zt(Q(s)),c=Ts(o);this.header=c.header,this.headerBitstream=c.bitstream}}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;ws(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 xf=new Uint8Array([102,76,97,67]),Vh=38,Uh=34,ic=class extends Ie{constructor(e,r){super(e);this.metadataWritten=!1;this.blockSizes=[];this.frameSizes=[];this.sampleRate=null;this.channels=null;this.bitsPerSample=null;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(xf);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Ce({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.applyDecoderConfig(r.metadata.decoderConfig)),e()}applyDecoderConfig(e){b(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;let r=new H(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:u}){b(this.writer.getPos()===4);let l=!Cr(this.output._metadataTags),d=new H(new Uint8Array(4));d.writeBits(1,+!l),d.writeBits(7,0),d.writeBits(24,Uh),this.writer.write(d.bytes);let m=new H(new Uint8Array(18));if(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),u>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");m.writeBits(4,0),m.writeBits(32,u),this.writer.write(m.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let r=32+e.mimeType.length+(e.description?.length??0)+e.data.length,n=new Uint8Array(r),a=0,s=N(n);s.setUint32(a,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),a+=4,s.setUint32(a,e.mimeType.length),a+=4,n.set(Z.encode(e.mimeType),8),a+=e.mimeType.length,s.setUint32(a,e.description?.length??0),a+=4,n.set(Z.encode(e.description??""),a),a+=e.description?.length??0,a+=16,s.setUint32(a,e.data.length),a+=4,n.set(e.data,a),a+=e.data.length,b(a===r);let o=new H(new Uint8Array(4));o.writeBits(1,0),o.writeBits(7,6),o.writeBits(24,r),this.writer.write(o.bytes),this.writer.write(n)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(Vh+xf.byteLength),Cr(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let a of e)this.writePictureBlock(a);let r=ia(new Uint8Array(0),this.output._metadataTags,!1),n=new H(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&&(Ce(n,e.source._codec),b(n),b(n.decoderConfig),this.applyDecoderConfig(n.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let s=we.tempFromBytes(r.data);s.skip(2);let o=U(s,2),c=new H(o),u=po(c.readBits(4));if(u===null)throw new Error("Invalid FLAC frame: Invalid block size.");ho(s);let l=go(s,u);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(r.data.length));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=1/0,n=0,a=1/0,s=0,o=0;for(let c=0;c<this.blockSizes.length;c++)a=Math.min(a,this.frameSizes[c]),s=Math.max(s,this.frameSizes[c]),n=Math.max(n,this.blockSizes[c]),o+=this.blockSizes[c],c!==this.blockSizes.length-1&&(r=Math.min(r,this.blockSizes[c]));this.blockSizes.length===0&&(r=16,n=65535,a=0,s=0),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:o})}e()}};var ja=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,zh=/^WEBVTT(.|\n)*?\n{2}/,Hn=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,nc=class{constructor(t){this.preambleText=null;this.preambleEmitted=!1;this.options=t}parse(t){t=t.replaceAll(`\r
10
10
  `,`
11
11
  `).replaceAll("\r",`
12
12
  `),ja.lastIndex=0;let e;if(!this.preambleText){if(!zh.test(t))throw new Error("WebVTT preamble incorrect.");e=ja.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),ja.lastIndex=0)}for(;e=ja.exec(t);){let r=t.slice(0,e.index),n=e[1],a=e.index+e[0].length,s=t.indexOf(`
13
13
  `,a)+1,o=t.slice(a,s).trim(),c=t.indexOf(`
14
14
 
15
- `,a);c===-1&&(c=t.length);let u=ac(e[2]),d=ac(e[3])-u,m=t.slice(s,c).trim();t=t.slice(c).trimStart(),ja.lastIndex=0;let f={timestamp:u/1e3,duration:d/1e3,text:m,identifier:n,settings:o,notes:r},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,p)}}},Nh=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,ac=i=>{let t=Nh.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])},sc=i=>{let t=Math.floor(i/36e5),e=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),n=i%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var Hi=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}}},$=new Uint8Array(8),It=new DataView($.buffer),ke=i=>[(i%256+256)%256],K=i=>(It.setUint16(0,i,!1),[$[0],$[1]]),pl=i=>(It.setInt16(0,i,!1),[$[0],$[1]]),Ef=i=>(It.setUint32(0,i,!1),[$[1],$[2],$[3]]),R=i=>(It.setUint32(0,i,!1),[$[0],$[1],$[2],$[3]]),fr=i=>(It.setInt32(0,i,!1),[$[0],$[1],$[2],$[3]]),Lt=i=>(It.setUint32(0,Math.floor(i/2**32),!1),It.setUint32(4,i,!1),[$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7]]),Cf=i=>(It.setInt32(0,Math.floor(i/2**32),!1),It.setUint32(4,i,!1),[$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7]]),vf=i=>(It.setInt16(0,2**8*i,!1),[$[0],$[1]]),Pt=i=>(It.setInt32(0,2**16*i,!1),[$[0],$[1],$[2],$[3]]),dl=i=>(It.setInt32(0,2**30*i,!1),[$[0],$[1],$[2],$[3]]),ml=(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()},le=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,n)=>i.charCodeAt(n));return t&&e.push(0),e},_f=i=>[Pt(i[0]),Pt(i[1]),dl(i[2]),Pt(i[3]),Pt(i[4]),dl(i[5]),Pt(i[6]),Pt(i[7]),dl(i[8])],W=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),te=(i,t,e,r,n)=>W(i,[ke(t),Ef(e),r??[]],n),Rf=i=>i.isQuickTime?W("ftyp",[le("qt "),R(512),le("qt ")]):i.fragmented?i.cmaf?W("ftyp",[le("iso5"),R(512),le("iso5"),le("iso6"),le("mp41"),le("cmfc"),le("dash")]):W("ftyp",[le("iso5"),R(512),le("iso5"),le("iso6"),le("mp41")]):W("ftyp",[le("isom"),R(512),le("isom"),i.holdsAvc?le("avc1"):[],le("mp41")]),hl=()=>W("styp",[le("iso5"),R(0),le("iso5"),le("iso6"),le("mp41"),le("cmfc"),le("dash")]),gl=(i,t)=>{let e=Math.max(0,i.minWrittenTimestamp),r=Math.max(0,i.maxWrittenEndTimestamp-e);return Number.isFinite(r)||(r=0),te("sidx",1,0,[R(1),R(ct),Lt(de(e,ct)),Lt(0),K(0),K(1),R(t&2147483647),R(de(r,ct)),R(0)])},Xa=i=>({type:"mdat",largeSize:i}),Ff=i=>({type:"free",size:i}),qn=i=>W("moov",void 0,[Lh(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>Wh(t,i.creationTime)),i.isFragmented?Eg(i.trackDatas):null,Vg(i)]),Lh=(i,t)=>{let e=Math.max(0,...t.map(s=>Math.max(0,de(qi(s),ct)+de(s.startTimestampOffset??0,ct)))),r=Math.max(0,...t.map(s=>s.track.id))+1,n=!qt(i)||!qt(e),a=n?Lt:R;return te("mvhd",+n,0,[a(i),a(i),R(ct),a(e),Pt(1),vf(1),Array(10).fill(0),_f(Wr),Array(24).fill(0),R(r)])},Wh=(i,t)=>{let e=Lf(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset!==0;return W("trak",void 0,[Hh(i,t),r?qh(i):null,Kh(i,t),e.name!==void 0?W("udta",void 0,[W("name",[...Z.encode(e.name)])]):null])},Hh=(i,t)=>{let e=Math.max(0,de(qi(i),ct)+de(i.startTimestampOffset??0,ct)),r=!qt(t)||!qt(e),n=r?Lt:R,a;if(i.type==="video"&&i.track.metadata.transformationMatrix)a=i.track.metadata.transformationMatrix;else if(i.type==="video"){let{rotation:c,flip:u}=i.track.metadata,l=Ht(tn(c??0),us(u?-1:1,1));a=cs(l,i.info.width,i.info.height)}else a=Wr;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:ae(i);return te("tkhd",+r,s,[n(t),n(t),R(i.track.id),R(0),n(e),Array(8).fill(0),K(0),K(o),vf(i.type==="audio"?1:0),K(0),_f(a),Pt(i.type==="video"?i.info.width:0),Pt(i.type==="video"?i.info.height:0)])},qh=i=>{let t=i.startTimestampOffset;if(b(t!==null),t>0){let e=de(t,ct),r=de(qi(i),ct),n=!qt(e)||!qt(r),a=n?Lt:R,s=n?Cf:fr;return W("edts",void 0,[te("elst",n?1:0,0,[R(2),a(e),s(-1),Pt(1),a(r),s(0),Pt(1)])])}else{let e=de(-t,i.timescale),r=Math.max(0,de(qi(i),ct)+de(t,ct)),n=!Ul(e)||!qt(r),a=n?Lt:R,s=n?Cf:fr;return W("edts",void 0,[te("elst",n?1:0,0,[R(1),a(r),s(e),Pt(1)])])}},Kh=(i,t)=>W("mdia",void 0,[Gh(i,t),bl(!0,Qh[i.type],jh[i.type]),Xh(i)]),Gh=(i,t)=>{let e=de(qi(i),i.timescale),r=!qt(t)||!qt(e),n=r?Lt:R;return te("mdhd",+r,0,[n(t),n(t),R(i.timescale),n(e),K(Nf(i.track.metadata.languageCode??se)),K(0)])},Qh={video:"vide",audio:"soun",subtitle:"text"},jh={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},bl=(i,t,e,r="\0\0\0\0")=>te("hdlr",0,0,[i?le("mhlr"):R(0),le(t),le(r),R(0),R(0),le(e,!0)]),Xh=i=>W("minf",void 0,[Jh[i.type](),eg(),ig(i)]),$h=()=>te("vmhd",0,1,[K(0),K(0),K(0),K(0)]),Yh=()=>te("smhd",0,0,[K(0),K(0)]),Zh=()=>te("nmhd",0,0),Jh={video:$h,audio:Yh,subtitle:Zh},eg=()=>W("dinf",void 0,[tg()]),tg=()=>te("dref",0,0,[R(1)],[rg()]),rg=()=>te("url ",0,1),ig=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return W("stbl",void 0,[ng(i),wg(i),t?Pg(i):null,t?Ig(i):null,Ag(i),xg(i),Cg(i),Sg(i)])},ng=i=>{let t;if(i.type==="video")t=ag(Lg(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){let e=zf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime);b(e),t=dg(e,i)}else i.type==="subtitle"&&(t=kg(qg[i.track.source._codec],i));return b(t),te("stsd",0,0,[R(1)],[t])},ag=(i,t)=>W(i,[Array(6).fill(0),K(1),K(0),K(0),Array(12).fill(0),K(t.info.width),K(t.info.height),R(4718592),R(4718592),R(0),K(1),ke(Pr.length),le(Pr),Array(31-Pr.length).fill(0),K(t.info.hasAlphaChannel?32:24),pl(65535)],[Wg[t.track.source._codec]?.(t)??null,sg(t),ds(t.info.decoderConfig.colorSpace)?null:og(t),yl(t)]),yl=i=>i.avgBitrate===0&&i.maxBitrate===0?null:W("btrt",[R(0),R(i.maxBitrate),R(i.avgBitrate)]),sg=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:W("pasp",[R(i.info.pixelAspectRatio.num),R(i.info.pixelAspectRatio.den)]),og=i=>{let t=i.info.decoderConfig.colorSpace;return W("colr",[le(i.muxer.isQuickTime?"nclc":"nclx"),K(t?.primaries!=null?Tt[t.primaries]:2),K(t?.transfer!=null?wt[t.transfer]:2),K(t?.matrix!=null?St[t.matrix]:2),i.muxer.isQuickTime?[]:ke((t?.fullRange?1:0)<<7)])},cg=i=>i.info.decoderConfig&&W("avcC",[...Q(i.info.decoderConfig.description)]),ug=i=>i.info.decoderConfig&&W("hvcC",[...Q(i.info.decoderConfig.description)]),Pf=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=Number(e[3]),s=e[4]?Number(e[4]):1,o=e[8]?Number(e[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(s<<1)+o,u=e[5]?Number(e[5]):t.colorSpace?.primaries?Tt[t.colorSpace.primaries]:1,l=e[6]?Number(e[6]):t.colorSpace?.transfer?wt[t.colorSpace.transfer]:1,d=e[7]?Number(e[7]):t.colorSpace?.matrix?St[t.colorSpace.matrix]:1;return te("vpcC",1,0,[ke(r),ke(n),ke(c),ke(u),ke(l),ke(d),K(0)])},lg=i=>W("av1C",Us(i.info.decoderConfig.codec)),dg=(i,t)=>{let e=0,r,n=16,a=ne.includes(t.track.source._codec);if(a){let s=t.track.source._codec,{sampleSize:o}=Re(s);n=8*o,n>16&&(e=1)}if(t.muxer.isQuickTime&&(e=1),e===0)r=[Array(6).fill(0),K(1),K(e),K(0),R(0),K(t.info.numberOfChannels),K(n),K(0),K(0),K(t.info.sampleRate<2**16?t.info.sampleRate:0),K(0)];else{let s=a?0:-2;r=[Array(6).fill(0),K(1),K(e),K(0),R(0),K(t.info.numberOfChannels),K(Math.min(n,16)),pl(s),K(0),K(t.info.sampleRate<2**16?t.info.sampleRate:0),K(0),a?[R(1),R(n/8),R(t.info.numberOfChannels*n/8)]:[R(0),R(0),R(0)],R(2)]}return W(i,r,[Hg(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,yl(t)])},fl=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=[...ke(t),...ke(21),...Ef(0),...R(i.maxBitrate),...R(i.avgBitrate)];if(i.info.decoderConfig.description){let r=Q(i.info.decoderConfig.description);e=[...e,...ke(5),...ml(r.byteLength),...r]}return e=[...K(1),...ke(0),...ke(4),...ml(e.length),...e,...ke(6),...ke(1),...ke(2)],e=[...ke(3),...ml(e.length),...e],te("esds",0,0,e)},bi=i=>W("wave",void 0,[mg(i),fg(i),W("\0\0\0\0")]),mg=i=>W("frma",[le(zf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime))]),fg=i=>{let{littleEndian:t}=Re(i.track.source._codec);return W("enda",[K(+t)])},pg=i=>{let t=i.info.numberOfChannels,e=3840,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),u=Qr(c);t=u.outputChannelCount,e=u.preSkip,r=u.inputSampleRate,n=u.outputGain,a=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return W("dOps",[ke(0),ke(t),K(e),R(r),pl(n),ke(a),...s])},hg=i=>{let t=i.info.decoderConfig?.description;b(t);let e=Q(t);return te("dfLa",0,0,[...e.subarray(4)])},dr=i=>{let{littleEndian:t,sampleSize:e}=Re(i.track.source._codec),r=+t;return te("pcmC",0,0,[ke(r),ke(8*e)])},gg=i=>{b(i.info.primingPacket);let t=vs(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 H(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),W("dac3",[...e])},bg=i=>{b(i.info.primingPacket);let t=_s(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 H(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 W("dec3",[...n])},yg=i=>{b(i.info.primingPacket);let t=ca(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 W("ddts",[...Cd(t)])},kg=(i,t)=>W(i,[Array(6).fill(0),K(1)],[Kg[t.track.source._codec](t),yl(t)]),Tg=i=>W("vttC",[...Z.encode(i.info.config.description)]);var wg=i=>te("stts",0,0,[R(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[R(t.sampleCount),R(t.sampleDelta)])]),Sg=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return te("stss",0,0,[R(t.length),t.map(([e])=>R(e+1))])},Ag=i=>te("stsc",0,0,[R(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[R(t.firstChunk),R(t.samplesPerChunk),R(1)])]),xg=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:t}=Re(i.track.source._codec);return te("stsz",0,0,[R(t*i.info.numberOfChannels),R(i.samples.reduce((e,r)=>e+de(r.duration,i.timescale),0))])}return te("stsz",0,0,[R(0),R(i.samples.length),i.samples.map(t=>R(t.size))])},Cg=i=>i.finalizedChunks.length>0&&Y(i.finalizedChunks).offset>=2**32?te("co64",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>Lt(t.offset))]):te("stco",0,0,[R(i.finalizedChunks.length),i.finalizedChunks.map(t=>R(t.offset))]),Pg=i=>te("ctts",1,0,[R(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[R(t.sampleCount),fr(t.sampleCompositionTimeOffset)])]),Ig=i=>{let t=1/0,e=-1/0,r=1/0,n=-1/0;b(i.compositionTimeOffsetTable.length>0),b(i.samples.length>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:te("cslg",0,0,[fr(a),fr(t),fr(e),fr(r),fr(n)])},Eg=i=>W("mvex",void 0,i.map(vg)),vg=i=>te("trex",0,0,[R(i.track.id),R(1),R(0),R(0),R(0)]),kl=(i,t)=>W("moof",void 0,[_g(i),...t.map(Rg)]),_g=i=>te("mfhd",0,0,[R(i)]),Mf=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},Rg=i=>W("traf",void 0,[Fg(i),Mg(i),Bg(i)]),Fg=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:Mf(e)};return te("tfhd",0,t,[R(i.track.id),R(r.duration),R(r.size),R(r.flags)])},Mg=i=>(b(i.currentChunk),te("tfdt",1,0,[Lt(de(i.currentChunk.startTimestamp,i.timescale))])),Bg=i=>{b(i.currentChunk);let t=i.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(g=>g.size),r=i.currentChunk.samples.map(Mf),n=i.currentChunk.samples.map(g=>de(g.timestamp-g.decodeTimestamp,i.timescale)),a=new Set(t),s=new Set(e),o=new Set(r),c=new Set(n),u=o.size===2&&r[0]!==r[1],l=a.size>1,d=s.size>1,m=!u&&o.size>1,f=c.size>1||[...c].some(g=>g!==0),p=0;return p|=1,p|=4*+u,p|=256*+l,p|=512*+d,p|=1024*+m,p|=2048*+f,te("trun",1,p,[R(i.currentChunk.samples.length),R(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?R(r[0]):[],i.currentChunk.samples.map((g,h)=>[l?R(t[h]):[],d?R(e[h]):[],m?R(r[h]):[],f?fr(n[h]):[]])])},Bf=i=>W("mfra",void 0,[...i.map(Og),Dg()]),Og=i=>{let e=[];for(let r of i.finalizedChunks){let n=r.samples.findIndex(s=>s.type==="key");if(n===-1)continue;let a=r.samples[n];e.push([Lt(de(a.timestamp,i.timescale)),Lt(r.moofOffset),R(r.trafIndex+1),R(1),R(n+1)])}return te("tfra",1,0,[R(i.track.id),R(63),R(e.length),e])},Dg=()=>te("mfro",0,0,[R(0)]),Of=()=>W("vtte"),Df=(i,t,e,r,n)=>W("vttc",void 0,[n!==null?W("vsid",[fr(n)]):null,e!==null?W("iden",[...Z.encode(e)]):null,t!==null?W("ctim",[...Z.encode(sc(t))]):null,r!==null?W("sttg",[...Z.encode(r)]):null,W("payl",[...Z.encode(i)])]),Vf=i=>W("vtta",[...Z.encode(i)]),Vg=i=>{let t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){let n=zg(r);n&&t.push(n)}else if(e==="mdta"){let n=Ng(r);n&&t.push(n)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&Ug(t,i.output._metadataTags);return t.length===0?null:W("udta",void 0,t)},Ug=(i,t)=>{for(let{key:e,value:r}of _t(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"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:ae(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(W(e,Array.from(r))))}},mr=(i,t)=>{let e=Z.encode(t);return W(i,[K(e.length),K(Nf("und")),Array.from(e)])},If={"image/jpeg":13,"image/png":14,"image/bmp":27},Uf=(i,t)=>{let e=[];for(let{key:r,value:n}of _t(i))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:Nt(n)});break;case"description":e.push({key:t?"description":"\xA9des",value:Nt(n)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:Nt(n)});break;case"album":e.push({key:t?"album":"\xA9alb",value:Nt(n)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:Nt(n)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:Nt(n)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:Nt(n)});break;case"beatsPerMinute":t||e.push({key:"tmpo",value:W("data",[R(21),R(0),K(n)])});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:Nt(n)});break;case"date":e.push({key:t?"date":"\xA9day",value:Nt(n.toISOString().slice(0,10))});break;case"images":for(let a of n)a.kind==="coverFront"&&e.push({key:"covr",value:W("data",[R(If[a.mimeType]??0),R(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:Nt(a)})}else e.push({key:"trkn",value:W("data",[R(0),R(0),K(0),K(n),K(i.tracksTotal??0),K(0)])});break;case"discNumber":t||e.push({key:"disc",value:W("data",[R(0),R(0),K(0),K(n),K(i.discsTotal??0),K(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ae(r)}if(i.raw)for(let r in i.raw){let n=i.raw[r];n==null||!t&&r.length!==4||e.some(a=>a.key===r)||(typeof n=="string"?e.push({key:r,value:Nt(n)}):n instanceof Uint8Array?e.push({key:r,value:W("data",[R(0),R(0),Array.from(n)])}):n instanceof gt&&e.push({key:r,value:W("data",[R(If[n.mimeType]??0),R(0),Array.from(n.data)])}))}return e},zg=i=>{let t=Uf(i,!1);return t.length===0?null:te("meta",0,0,void 0,[bl(!1,"mdir","","appl"),W("ilst",void 0,t.map(e=>W(e.key,void 0,[e.value])))])},Ng=i=>{let t=Uf(i,!0);return t.length===0?null:W("meta",void 0,[bl(!1,"mdta",""),te("keys",0,0,[R(t.length)],t.map(e=>W("mdta",[...Z.encode(e.key)]))),W("ilst",void 0,t.map((e,r)=>{let n=String.fromCharCode(...R(r+1));return W(n,void 0,[e.value])}))])},Nt=i=>W("data",[R(1),R(0),...Z.encode(i)]),Lg=(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}},Wg={avc:cg,hevc:ug,vp8:Pf,vp9:Pf,av1:lg,prores:null},zf=(i,t,e)=>{switch(i){case"aac":return"mp4a";case"mp3":return"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}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"}},Hg=(i,t)=>{switch(i){case"aac":return fl;case"mp3":return fl;case"opus":return pg;case"vorbis":return fl;case"flac":return hg;case"ac3":return gg;case"eac3":return bg;case"dts":return yg}if(t)switch(i){case"pcm-s24":return bi;case"pcm-s24be":return bi;case"pcm-s32":return bi;case"pcm-s32be":return bi;case"pcm-f32":return bi;case"pcm-f32be":return bi;case"pcm-f64":return bi;case"pcm-f64be":return bi}else switch(i){case"pcm-s16":return dr;case"pcm-s16be":return dr;case"pcm-s24":return dr;case"pcm-s24be":return dr;case"pcm-s32":return dr;case"pcm-s32be":return dr;case"pcm-f32":return dr;case"pcm-f32be":return dr;case"pcm-f64":return dr;case"pcm-f64be":return dr}return null},qg={webvtt:"wvtt"},Kg={webvtt:Tg},Nf=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 pr=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.");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=0}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 Wf=Ol(Vu(),1);var Hf=typeof Wf<"u"?Wf:void 0,Me=class extends Je{constructor(){super(...arguments);this._writerAcquired=!1;this._monotonicity=null;this.onwrite=null}_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 $a(this,e)}},Tl=2**16,wl=2**32,yi=class extends Me{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(Tl,{maxByteLength:wl})}catch{this._buffer=new ArrayBuffer(Tl),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Tl);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let r=this._buffer.byteLength;for(;r<e;)r*=2;if(r!==this._buffer.byteLength){if(r>wl)throw new Error(`ArrayBuffer exceeded maximum size of ${wl} 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){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(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,r){return this._bytes.slice(e,r)}},Gg=2**24,Qg=2,Kn=class extends Me{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??Gg}_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){let n=this._chunks.findIndex(u=>u.start<=r&&r<u.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>Qg){for(let u=0;u<this._chunks.length-1;u++)this._chunks[u].shouldFlush=!0;this._tryToFlushChunks()}o.byteLength<e.byteLength&&this._writeDataIntoChunks(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&&jt()?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(u=>{this._writeError??=u}),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 _close(){return this._streamWriter?.close()}},oc=class extends Me{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new Kn(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()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},cc=class extends Me{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(!Hf.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 Hf.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 Kn(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 _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},ki=class extends Me{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}},$a=class extends Me{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 _close(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}},ut=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 ct=57600,jg=2082844800,Lf=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},qi=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},uc=class extends Ie{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new yi;this.auxWriter=new pr(this.auxTarget,!1);this.auxBoxWriter=new Hi(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.allTracksKnown=ee();this.creationTime=Math.floor(Date.now()/1e3)+jg;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 Gi,this.isCmaf=r instanceof Ki,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof Ki?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":n instanceof yi),this.boxWriter=new Hi(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof yi?"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 n=await this.output._getInitTarget(),a=new pr(n,!0);a.start(),this.initWriter=a,this.initBoxWriter=new Hi(a)}let r=this.output.tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(b(n),this.formatOptions.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(Rf({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:a,start:s}=n.writer.stopTrackingWrites();this.formatOptions.onFtyp(a,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output.tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(b(this.writer),b(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Xa(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let n of this.output.tracks)n.isVideoTrack()&&n.metadata.decoderConfig?this.getVideoTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig}):n.isAudioTrack()&&n.metadata.decoderConfig&&this.getAudioTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!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 Ks({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;nr(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=er(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=un(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=ir(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=pd(p),o=!0}let c=Xl(1/(e.metadata.frameRate??ct),1e6).den,u=s.displayAspectWidth,l=s.displayAspectHeight,d=u===void 0||l===void 0?{num:1,den:1}:Ar({num:u*s.codedHeight,den:l*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,compactlyCodedChunkTable:[],closed:!1,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(u=>u.track===e);if(a)return a;Ce(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 u=nt(we.tempFromBytes(r.data));if(!u)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 l=tt[u.samplingFrequencyIndex],d=Yt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=cn({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels: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.")}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ne.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ls(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,compactlyCodedChunkTable:[],closed:!1,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 u=[...Gr(o)].map(l=>o.subarray(l.offset,l.offset+l.length));if(u.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=Cs(u,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type);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 d=nt(we.tempFromBytes(o));if(!d)throw new Error("Expected ADTS frame, didn't get one.");let m=d.crcCheck===null?Ut:bt;o=o.subarray(m)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=r.timestamp,u=r.duration;if(s.info.requiresPcmTransformation){let m=Re(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(u=o.byteLength/m/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let f=c-s.info.expectedNextPcmPacketTimestamp;if(f<.01)c=s.info.expectedNextPcmPacketTimestamp;else{let p=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);c=s.info.expectedNextPcmPacketTimestamp+p}}s.info.expectedNextPcmPacketTimestamp=c+u}let l=this.createSampleForTrack(s,o,c,u,r.type);await this.registerSample(s,l)}finally{a()}}async padWithSilence(e,r,n){let a=de(n,e.timescale);if(n=a/e.timescale,a>0){let{sampleSize:s,silentValue:o}=Re(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,u=new Uint8Array(s*c).fill(o),l=this.createSampleForTrack(e,new Uint8Array(u.buffer),r,n,"key");await this.registerSample(e,l)}return n}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),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=new Set([]);for(let l of e.cueQueue)b(l.timestamp<=r),b(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let a=[...n].sort((l,d)=>l-d),s=a[0],o=a[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=Of();this.auxBoxWriter.writeBox(l);let d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),m=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,m),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let d=e.cueQueue[l];if(d.timestamp>=o)break;Hn.lastIndex=0;let m=Hn.test(d.text),f=d.timestamp+d.duration,p=e.cueToSourceId.get(d);if(p===void 0&&o<f&&(p=e.nextSourceId++,e.cueToSourceId.set(d,p)),d.notes){let h=Vf(d.notes);this.auxBoxWriter.writeBox(h)}let g=Df(d.text,m?s:null,d.identifier??null,d.settings??null,p??null);this.auxBoxWriter.writeBox(g),f===o&&e.cueQueue.splice(l--,1)}let c=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,c,s,o-s,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,n,a,s){return{timestamp:n,decodeTimestamp:n,duration:a,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:de(a,e.timescale)}}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=Y(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 u=de(s.decodeTimestamp,e.timescale,!1),l=Math.round(u-e.lastTimescaleUnits);if(b(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let d=Y(e.timeToSampleTable);if(b(d),d.sampleCount===1){d.sampleDelta=l;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),d=f)}else d.sampleDelta!==l&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:l}));d.sampleDelta===c?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let m=Y(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),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}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 less 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(o=>{if(e===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.closed});a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=a>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null,trafIndex: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){if(b(!this.isFragmented),b(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((n,a)=>n+de(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Y(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)b(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(b(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)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=qn(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 Hi(this.writer);let h=this.boxWriter.measureBox(hl()),y=this.boxWriter.measureBox(gl(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=kl(n,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+Mt,u=1/0;for(let p=0;p<r.length;p++){let g=r[p];b(g.currentChunk),b(g.startTimestampOffset!==null),g.currentChunk.offset=c,g.currentChunk.moofOffset=s,g.currentChunk.trafIndex=p,g.currentChunk.startTimestamp-=g.startTimestampOffset;for(let h of g.currentChunk.samples)c+=h.size,h.timestamp-=g.startTimestampOffset,h.decodeTimestamp-=g.startTimestampOffset;u=Math.min(u,g.currentChunk.startTimestamp)}let l=c-o,d=l>=2**32;if(d)for(let p of r)p.currentChunk.offset+=vr-Mt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let m=kl(n,r);if(this.boxWriter.writeBox(m),this.formatOptions.onMoof){let{data:p,start:g}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(p,g,u)}b(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=Xa(d);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(d?vr:Mt));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 of r)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,r)):e.sampleQueue.push(r)}async createFastStartReserveMdat(){b(this.writer),b(this.boxWriter),this.ensureOneEnabledTrack();let e=qn(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=Xa(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let s of a.sampleQueue)await this.addSampleToTrack(a,s);a.sampleQueue.length=0}}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}return e}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),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 finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart==="reserve"&&await this.createFastStartReserveMdat();for(let r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas){await this.finalizeCurrentChunk(r);let n=qi(r);if(n>0){let c=0;for(let u of r.samples)c+=u.size;r.avgBitrate=Math.round(8*c/n)}else r.avgBitrate=0;let a=0,s=0,o=0;for(let c=0;c<r.samples.length;c++){let u=r.samples[c];for(s+=u.size;u.decodeTimestamp-r.samples[a].decodeTimestamp>=1;)s-=r.samples[a].size,a++;o=Math.max(o,s)}if(r.maxBitrate=8*o,r.startTimestampOffset!==null)for(let c=0;c<r.samples.length;c++){let u=r.samples[c];u.timestamp-=r.startTimestampOffset,u.decodeTimestamp-=r.startTimestampOffset}}if(b(this.writer),b(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Xa(!1);let r;for(let a=0;a<2;a++){let s=qn(this),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let c=this.writer.getPos()+o+r;for(let u of this.finalizedChunks){u.offset=c;for(let{data:l}of u.samples)b(l),c+=l.byteLength,r+=l.byteLength}if(c<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let n=qn(this);if(this.boxWriter.writeBox(n),this.formatOptions.onMoov){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(a,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let a of this.finalizedChunks)for(let s of a.samples)b(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(a,s)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(hl()),this.boxWriter.writeBox(gl(this,r))}else{let r=this.writer.getPos(),n=Bf(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=qn(this);if(this.fastStart==="reserve"){b(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Ff(s))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);if(this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}};var Xg=-(2**15),$g=2**15-1,qf=6,Kf=5,Yg={video:1,audio:2,subtitle:17},lc=class extends Ie{constructor(e,r){super(e);this.trackDatas=[];this.allTracksKnown=ee();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.tagsElement=null;this.attachmentsElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.trackDatasInCurrentCluster=new Map;this.startTimestamp=1/0;this.endTimestamp=-1/0;this.warnedAboutTooNegativeTimestamp=!1;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new to(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});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 Ti?"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 yn(0)};this.segmentDuration=e;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:Pr},{id:22337,data:Pr},this.format._options.appendOnly?null:e]};this.segmentInfo=r}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=ze[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"));let a=0;if(r.type==="audio"&&r.track.source._codec==="opus"){a=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=Q(s),c=Qr(o);a=Math.round(1e9*(c.preSkip/Ft))}}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:Yg[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},{id:2274716,data:r.track.metadata.languageCode??se},{id:134,data:n},r.codecPrivate?{id:25506,data:Q(r.codecPrivate)}:null,a>0?{id:22203,data:a}:null,r.track.metadata.name!==void 0?{id:21358,data:new Vt(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:1e9/r}:null],s,o,c;if(n){s=Si(n);let g=Ht(tn(-s),n);o=Math.sign(g[0]),c=Math.sign(g[4]),c===-1&&(c=1,o=-o,s=yr(s+180))}else s=e.track.metadata.rotation??0,o=e.track.metadata.flip?-1:1,c=1;let u=s?yr(o===-1?s:-s):0,l=Math.round(Math.acos(o)*os),d=Math.round(Math.acos(c)*os),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,ds(f)?null:{id:21936,data:[{id:21937,data:f?.matrix!=null?St[f.matrix]:2},{id:21946,data:f?.transfer!=null?wt[f.transfer]:2},{id:21947,data:f?.primaries!=null?Tt[f.primaries]:2},{id:21945,data:f?.fullRange!=null?f.fullRange?2:1:0}]},u||l||d?{id:30320,data:[{id:30321,data:0},l?{id:30323,data:new ti(l)}:null,d?{id:30324,data:new ti(d)}:null,u?{id:30325,data:new ti((u+180)%360-180)}:null]}:null]};return a.push(p),a}audioSpecificTrackInfo(e){let r=ne.includes(e.track.source._codec)?Re(e.track.source._codec):null;return[{id:225,data:[{id:181,data:new ti(e.info.sampleRate)},{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 Vt(s)},typeof o=="string"?{id:17543,data:new Vt(o)}:{id:17541,data:o}]})},n=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of _t(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":break;default:ae(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")+(Zl(s.mimeType)??""));let c;for(;;){c=0n;for(let u=0;u<8;u++)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 Vt(s.description)}:null,{id:18030,data:new Vt(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 xr)||!/^\d+$/.test(s)||a.find(u=>u.mimeType===o.mimeType&&bs(u.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new Vt(o.description)}:null,{id:18030,data:new Vt(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:qf,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(!e.source._closed&&!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 no({isWebM:this.format instanceof Ti,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(l=>l.track===e);if(a)return a;nr(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:Ar({num:s,den:o}),u={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,closed:!1};return e.source._codec==="vp9"?u.codecPrivate=new Uint8Array(_d(u.info.decoderConfig.codec)):e.source._codec==="av1"?u.codecPrivate=new Uint8Array(Us(u.info.decoderConfig.codec)):e.source._codec==="prores"&&(u.codecPrivate=Z.encode(n.decoderConfig.codec)),this.trackDatas.push(u),this.trackDatas.sort((l,d)=>l.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Ce(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 u=nt(we.tempFromBytes(r.data));if(!u)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 l=tt[u.samplingFrequencyIndex],d=Yt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=cn({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels:d}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null,closed:!1};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ls(r),b(r),b(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Z.encode(r.config.description),closed:!1};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 u=r.timestamp,l=r.duration;e.metadata.frameRate!==void 0&&(u=Gt(u,e.metadata.frameRate),l=Gt(l,e.metadata.frameRate));let d=s.info.alphaMode?r.sideData.alpha??null:null,m=this.createInternalChunk(o,u,l,r.type,d);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,m),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 l=nt(we.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");let d=l.crcCheck===null?Ut:bt;o=o.subarray(d)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=this.createInternalChunk(o,r.timestamp,r.duration,r.type);s.chunkQueue.push(u),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);Hn.lastIndex=0,o=o.replace(Hn,m=>{let p=ac(m.slice(1,-1))-c;return`<${sc(p)}>`});let u=Z.encode(o),l=`${r.settings??""}
15
+ `,a);c===-1&&(c=t.length);let u=ac(e[2]),d=ac(e[3])-u,m=t.slice(s,c).trim();t=t.slice(c).trimStart(),ja.lastIndex=0;let f={timestamp:u/1e3,duration:d/1e3,text:m,identifier:n,settings:o,notes:r},p={};this.preambleEmitted||(p.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(f,p)}}},Nh=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,ac=i=>{let t=Nh.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])},sc=i=>{let t=Math.floor(i/36e5),e=Math.floor(i%(60*60*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),n=i%1e3;return t.toString().padStart(2,"0")+":"+e.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+n.toString().padStart(3,"0")};var Hi=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}}},$=new Uint8Array(8),It=new DataView($.buffer),ke=i=>[(i%256+256)%256],K=i=>(It.setUint16(0,i,!1),[$[0],$[1]]),pl=i=>(It.setInt16(0,i,!1),[$[0],$[1]]),Ef=i=>(It.setUint32(0,i,!1),[$[1],$[2],$[3]]),F=i=>(It.setUint32(0,i,!1),[$[0],$[1],$[2],$[3]]),fr=i=>(It.setInt32(0,i,!1),[$[0],$[1],$[2],$[3]]),Lt=i=>(It.setUint32(0,Math.floor(i/2**32),!1),It.setUint32(4,i,!1),[$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7]]),Cf=i=>(It.setInt32(0,Math.floor(i/2**32),!1),It.setUint32(4,i,!1),[$[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7]]),vf=i=>(It.setInt16(0,2**8*i,!1),[$[0],$[1]]),Pt=i=>(It.setInt32(0,2**16*i,!1),[$[0],$[1],$[2],$[3]]),dl=i=>(It.setInt32(0,2**30*i,!1),[$[0],$[1],$[2],$[3]]),ml=(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()},le=(i,t=!1)=>{let e=Array(i.length).fill(null).map((r,n)=>i.charCodeAt(n));return t&&e.push(0),e},_f=i=>[Pt(i[0]),Pt(i[1]),dl(i[2]),Pt(i[3]),Pt(i[4]),dl(i[5]),Pt(i[6]),Pt(i[7]),dl(i[8])],W=(i,t,e)=>({type:i,contents:t&&new Uint8Array(t.flat(10)),children:e}),te=(i,t,e,r,n)=>W(i,[ke(t),Ef(e),r??[]],n),Rf=i=>i.isQuickTime?W("ftyp",[le("qt "),F(512),le("qt ")]):i.fragmented?i.cmaf?W("ftyp",[le("iso5"),F(512),le("iso5"),le("iso6"),le("mp41"),le("cmfc"),le("dash")]):W("ftyp",[le("iso5"),F(512),le("iso5"),le("iso6"),le("mp41")]):W("ftyp",[le("isom"),F(512),le("isom"),i.holdsAvc?le("avc1"):[],le("mp41")]),hl=()=>W("styp",[le("iso5"),F(0),le("iso5"),le("iso6"),le("mp41"),le("cmfc"),le("dash")]),gl=(i,t)=>{let e=Math.max(0,i.minWrittenTimestamp),r=Math.max(0,i.maxWrittenEndTimestamp-e);return Number.isFinite(r)||(r=0),te("sidx",1,0,[F(1),F(ct),Lt(de(e,ct)),Lt(0),K(0),K(1),F(t&2147483647),F(de(r,ct)),F(0)])},Xa=i=>({type:"mdat",largeSize:i}),Ff=i=>({type:"free",size:i}),qn=i=>W("moov",void 0,[Lh(i.creationTime,i.trackDatas),...i.trackDatas.map(t=>Wh(t,i.creationTime)),i.isFragmented?Eg(i.trackDatas):null,Vg(i)]),Lh=(i,t)=>{let e=Math.max(0,...t.map(s=>Math.max(0,de(qi(s),ct)+de(s.startTimestampOffset??0,ct)))),r=Math.max(0,...t.map(s=>s.track.id))+1,n=!qt(i)||!qt(e),a=n?Lt:F;return te("mvhd",+n,0,[a(i),a(i),F(ct),a(e),Pt(1),vf(1),Array(10).fill(0),_f(Wr),Array(24).fill(0),F(r)])},Wh=(i,t)=>{let e=Lf(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset!==0;return W("trak",void 0,[Hh(i,t),r?qh(i):null,Kh(i,t),e.name!==void 0?W("udta",void 0,[W("name",[...Z.encode(e.name)])]):null])},Hh=(i,t)=>{let e=Math.max(0,de(qi(i),ct)+de(i.startTimestampOffset??0,ct)),r=!qt(t)||!qt(e),n=r?Lt:F,a;if(i.type==="video"&&i.track.metadata.transformationMatrix)a=i.track.metadata.transformationMatrix;else if(i.type==="video"){let{rotation:c,flip:u}=i.track.metadata,l=Ht(tn(c??0),us(u?-1:1,1));a=cs(l,i.info.width,i.info.height)}else a=Wr;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:ae(i);return te("tkhd",+r,s,[n(t),n(t),F(i.track.id),F(0),n(e),Array(8).fill(0),K(0),K(o),vf(i.type==="audio"?1:0),K(0),_f(a),Pt(i.type==="video"?i.info.width:0),Pt(i.type==="video"?i.info.height:0)])},qh=i=>{let t=i.startTimestampOffset;if(b(t!==null),t>0){let e=de(t,ct),r=de(qi(i),ct),n=!qt(e)||!qt(r),a=n?Lt:F,s=n?Cf:fr;return W("edts",void 0,[te("elst",n?1:0,0,[F(2),a(e),s(-1),Pt(1),a(r),s(0),Pt(1)])])}else{let e=de(-t,i.timescale),r=Math.max(0,de(qi(i),ct)+de(t,ct)),n=!Ul(e)||!qt(r),a=n?Lt:F,s=n?Cf:fr;return W("edts",void 0,[te("elst",n?1:0,0,[F(1),a(r),s(e),Pt(1)])])}},Kh=(i,t)=>W("mdia",void 0,[Gh(i,t),bl(!0,Qh[i.type],jh[i.type]),Xh(i)]),Gh=(i,t)=>{let e=de(qi(i),i.timescale),r=!qt(t)||!qt(e),n=r?Lt:F;return te("mdhd",+r,0,[n(t),n(t),F(i.timescale),n(e),K(Nf(i.track.metadata.languageCode??se)),K(0)])},Qh={video:"vide",audio:"soun",subtitle:"text"},jh={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},bl=(i,t,e,r="\0\0\0\0")=>te("hdlr",0,0,[i?le("mhlr"):F(0),le(t),le(r),F(0),F(0),le(e,!0)]),Xh=i=>W("minf",void 0,[Jh[i.type](),eg(),ig(i)]),$h=()=>te("vmhd",0,1,[K(0),K(0),K(0),K(0)]),Yh=()=>te("smhd",0,0,[K(0),K(0)]),Zh=()=>te("nmhd",0,0),Jh={video:$h,audio:Yh,subtitle:Zh},eg=()=>W("dinf",void 0,[tg()]),tg=()=>te("dref",0,0,[F(1)],[rg()]),rg=()=>te("url ",0,1),ig=i=>{let t=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return W("stbl",void 0,[ng(i),wg(i),t?Pg(i):null,t?Ig(i):null,Ag(i),xg(i),Cg(i),Sg(i)])},ng=i=>{let t;if(i.type==="video")t=ag(Lg(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){let e=zf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime);b(e),t=dg(e,i)}else i.type==="subtitle"&&(t=kg(qg[i.track.source._codec],i));return b(t),te("stsd",0,0,[F(1)],[t])},ag=(i,t)=>W(i,[Array(6).fill(0),K(1),K(0),K(0),Array(12).fill(0),K(t.info.width),K(t.info.height),F(4718592),F(4718592),F(0),K(1),ke(Pr.length),le(Pr),Array(31-Pr.length).fill(0),K(t.info.hasAlphaChannel?32:24),pl(65535)],[Wg[t.track.source._codec]?.(t)??null,sg(t),ds(t.info.decoderConfig.colorSpace)?null:og(t),yl(t)]),yl=i=>i.avgBitrate===0&&i.maxBitrate===0?null:W("btrt",[F(0),F(i.maxBitrate),F(i.avgBitrate)]),sg=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:W("pasp",[F(i.info.pixelAspectRatio.num),F(i.info.pixelAspectRatio.den)]),og=i=>{let t=i.info.decoderConfig.colorSpace;return W("colr",[le(i.muxer.isQuickTime?"nclc":"nclx"),K(t?.primaries!=null?Tt[t.primaries]:2),K(t?.transfer!=null?wt[t.transfer]:2),K(t?.matrix!=null?St[t.matrix]:2),i.muxer.isQuickTime?[]:ke((t?.fullRange?1:0)<<7)])},cg=i=>i.info.decoderConfig&&W("avcC",[...Q(i.info.decoderConfig.description)]),ug=i=>i.info.decoderConfig&&W("hvcC",[...Q(i.info.decoderConfig.description)]),Pf=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=Number(e[3]),s=e[4]?Number(e[4]):1,o=e[8]?Number(e[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(s<<1)+o,u=e[5]?Number(e[5]):t.colorSpace?.primaries?Tt[t.colorSpace.primaries]:1,l=e[6]?Number(e[6]):t.colorSpace?.transfer?wt[t.colorSpace.transfer]:1,d=e[7]?Number(e[7]):t.colorSpace?.matrix?St[t.colorSpace.matrix]:1;return te("vpcC",1,0,[ke(r),ke(n),ke(c),ke(u),ke(l),ke(d),K(0)])},lg=i=>W("av1C",Us(i.info.decoderConfig.codec)),dg=(i,t)=>{let e=0,r,n=16,a=ne.includes(t.track.source._codec);if(a){let s=t.track.source._codec,{sampleSize:o}=Re(s);n=8*o,n>16&&(e=1)}if(t.muxer.isQuickTime&&(e=1),e===0)r=[Array(6).fill(0),K(1),K(e),K(0),F(0),K(t.info.numberOfChannels),K(n),K(0),K(0),K(t.info.sampleRate<2**16?t.info.sampleRate:0),K(0)];else{let s=a?0:-2;r=[Array(6).fill(0),K(1),K(e),K(0),F(0),K(t.info.numberOfChannels),K(Math.min(n,16)),pl(s),K(0),K(t.info.sampleRate<2**16?t.info.sampleRate:0),K(0),a?[F(1),F(n/8),F(t.info.numberOfChannels*n/8)]:[F(0),F(0),F(0)],F(2)]}return W(i,r,[Hg(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null,yl(t)])},fl=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=[...ke(t),...ke(21),...Ef(0),...F(i.maxBitrate),...F(i.avgBitrate)];if(i.info.decoderConfig.description){let r=Q(i.info.decoderConfig.description);e=[...e,...ke(5),...ml(r.byteLength),...r]}return e=[...K(1),...ke(0),...ke(4),...ml(e.length),...e,...ke(6),...ke(1),...ke(2)],e=[...ke(3),...ml(e.length),...e],te("esds",0,0,e)},bi=i=>W("wave",void 0,[mg(i),fg(i),W("\0\0\0\0")]),mg=i=>W("frma",[le(zf(i.track.source._codec,i.info.decoderConfig.codec,i.muxer.isQuickTime))]),fg=i=>{let{littleEndian:t}=Re(i.track.source._codec);return W("enda",[K(+t)])},pg=i=>{let t=i.info.numberOfChannels,e=3840,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),u=Qr(c);t=u.outputChannelCount,e=u.preSkip,r=u.inputSampleRate,n=u.outputGain,a=u.channelMappingFamily,u.channelMappingTable&&(s=u.channelMappingTable)}return W("dOps",[ke(0),ke(t),K(e),F(r),pl(n),ke(a),...s])},hg=i=>{let t=i.info.decoderConfig?.description;b(t);let e=Q(t);return te("dfLa",0,0,[...e.subarray(4)])},dr=i=>{let{littleEndian:t,sampleSize:e}=Re(i.track.source._codec),r=+t;return te("pcmC",0,0,[ke(r),ke(8*e)])},gg=i=>{b(i.info.primingPacket);let t=vs(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 H(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),W("dac3",[...e])},bg=i=>{b(i.info.primingPacket);let t=_s(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 H(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 W("dec3",[...n])},yg=i=>{b(i.info.primingPacket);let t=ca(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 W("ddts",[...Cd(t)])},kg=(i,t)=>W(i,[Array(6).fill(0),K(1)],[Kg[t.track.source._codec](t),yl(t)]),Tg=i=>W("vttC",[...Z.encode(i.info.config.description)]);var wg=i=>te("stts",0,0,[F(i.timeToSampleTable.length),i.timeToSampleTable.map(t=>[F(t.sampleCount),F(t.sampleDelta)])]),Sg=i=>{if(i.samples.every(e=>e.type==="key"))return null;let t=[...i.samples.entries()].filter(([,e])=>e.type==="key");return te("stss",0,0,[F(t.length),t.map(([e])=>F(e+1))])},Ag=i=>te("stsc",0,0,[F(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(t=>[F(t.firstChunk),F(t.samplesPerChunk),F(1)])]),xg=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){let{sampleSize:t}=Re(i.track.source._codec);return te("stsz",0,0,[F(t*i.info.numberOfChannels),F(i.samples.reduce((e,r)=>e+de(r.duration,i.timescale),0))])}return te("stsz",0,0,[F(0),F(i.samples.length),i.samples.map(t=>F(t.size))])},Cg=i=>i.finalizedChunks.length>0&&Y(i.finalizedChunks).offset>=2**32?te("co64",0,0,[F(i.finalizedChunks.length),i.finalizedChunks.map(t=>Lt(t.offset))]):te("stco",0,0,[F(i.finalizedChunks.length),i.finalizedChunks.map(t=>F(t.offset))]),Pg=i=>te("ctts",1,0,[F(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(t=>[F(t.sampleCount),fr(t.sampleCompositionTimeOffset)])]),Ig=i=>{let t=1/0,e=-1/0,r=1/0,n=-1/0;b(i.compositionTimeOffsetTable.length>0),b(i.samples.length>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:te("cslg",0,0,[fr(a),fr(t),fr(e),fr(r),fr(n)])},Eg=i=>W("mvex",void 0,i.map(vg)),vg=i=>te("trex",0,0,[F(i.track.id),F(1),F(0),F(0),F(0)]),kl=(i,t)=>W("moof",void 0,[_g(i),...t.map(Rg)]),_g=i=>te("mfhd",0,0,[F(i)]),Mf=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},Rg=i=>W("traf",void 0,[Fg(i),Mg(i),Bg(i)]),Fg=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:Mf(e)};return te("tfhd",0,t,[F(i.track.id),F(r.duration),F(r.size),F(r.flags)])},Mg=i=>(b(i.currentChunk),te("tfdt",1,0,[Lt(de(i.currentChunk.startTimestamp,i.timescale))])),Bg=i=>{b(i.currentChunk);let t=i.currentChunk.samples.map(g=>g.timescaleUnitsToNextSample),e=i.currentChunk.samples.map(g=>g.size),r=i.currentChunk.samples.map(Mf),n=i.currentChunk.samples.map(g=>de(g.timestamp-g.decodeTimestamp,i.timescale)),a=new Set(t),s=new Set(e),o=new Set(r),c=new Set(n),u=o.size===2&&r[0]!==r[1],l=a.size>1,d=s.size>1,m=!u&&o.size>1,f=c.size>1||[...c].some(g=>g!==0),p=0;return p|=1,p|=4*+u,p|=256*+l,p|=512*+d,p|=1024*+m,p|=2048*+f,te("trun",1,p,[F(i.currentChunk.samples.length),F(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?F(r[0]):[],i.currentChunk.samples.map((g,h)=>[l?F(t[h]):[],d?F(e[h]):[],m?F(r[h]):[],f?fr(n[h]):[]])])},Bf=i=>W("mfra",void 0,[...i.map(Og),Dg()]),Og=i=>{let e=[];for(let r of i.finalizedChunks){let n=r.samples.findIndex(s=>s.type==="key");if(n===-1)continue;let a=r.samples[n];e.push([Lt(de(a.timestamp,i.timescale)),Lt(r.moofOffset),F(r.trafIndex+1),F(1),F(n+1)])}return te("tfra",1,0,[F(i.track.id),F(63),F(e.length),e])},Dg=()=>te("mfro",0,0,[F(0)]),Of=()=>W("vtte"),Df=(i,t,e,r,n)=>W("vttc",void 0,[n!==null?W("vsid",[fr(n)]):null,e!==null?W("iden",[...Z.encode(e)]):null,t!==null?W("ctim",[...Z.encode(sc(t))]):null,r!==null?W("sttg",[...Z.encode(r)]):null,W("payl",[...Z.encode(i)])]),Vf=i=>W("vtta",[...Z.encode(i)]),Vg=i=>{let t=[],e=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(e==="mdir"||e==="auto"&&!i.isQuickTime){let n=zg(r);n&&t.push(n)}else if(e==="mdta"){let n=Ng(r);n&&t.push(n)}else(e==="udta"||e==="auto"&&i.isQuickTime)&&Ug(t,i.output._metadataTags);return t.length===0?null:W("udta",void 0,t)},Ug=(i,t)=>{for(let{key:e,value:r}of _t(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"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:ae(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(W(e,Array.from(r))))}},mr=(i,t)=>{let e=Z.encode(t);return W(i,[K(e.length),K(Nf("und")),Array.from(e)])},If={"image/jpeg":13,"image/png":14,"image/bmp":27},Uf=(i,t)=>{let e=[];for(let{key:r,value:n}of _t(i))switch(r){case"title":e.push({key:t?"title":"\xA9nam",value:Nt(n)});break;case"description":e.push({key:t?"description":"\xA9des",value:Nt(n)});break;case"artist":e.push({key:t?"artist":"\xA9ART",value:Nt(n)});break;case"album":e.push({key:t?"album":"\xA9alb",value:Nt(n)});break;case"albumArtist":e.push({key:t?"album_artist":"aART",value:Nt(n)});break;case"comment":e.push({key:t?"comment":"\xA9cmt",value:Nt(n)});break;case"genre":e.push({key:t?"genre":"\xA9gen",value:Nt(n)});break;case"beatsPerMinute":t||e.push({key:"tmpo",value:W("data",[F(21),F(0),K(n)])});break;case"lyrics":e.push({key:t?"lyrics":"\xA9lyr",value:Nt(n)});break;case"date":e.push({key:t?"date":"\xA9day",value:Nt(n.toISOString().slice(0,10))});break;case"images":for(let a of n)a.kind==="coverFront"&&e.push({key:"covr",value:W("data",[F(If[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:Nt(a)})}else e.push({key:"trkn",value:W("data",[F(0),F(0),K(0),K(n),K(i.tracksTotal??0),K(0)])});break;case"discNumber":t||e.push({key:"disc",value:W("data",[F(0),F(0),K(0),K(n),K(i.discsTotal??0),K(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:ae(r)}if(i.raw)for(let r in i.raw){let n=i.raw[r];n==null||!t&&r.length!==4||e.some(a=>a.key===r)||(typeof n=="string"?e.push({key:r,value:Nt(n)}):n instanceof Uint8Array?e.push({key:r,value:W("data",[F(0),F(0),Array.from(n)])}):n instanceof gt&&e.push({key:r,value:W("data",[F(If[n.mimeType]??0),F(0),Array.from(n.data)])}))}return e},zg=i=>{let t=Uf(i,!1);return t.length===0?null:te("meta",0,0,void 0,[bl(!1,"mdir","","appl"),W("ilst",void 0,t.map(e=>W(e.key,void 0,[e.value])))])},Ng=i=>{let t=Uf(i,!0);return t.length===0?null:W("meta",void 0,[bl(!1,"mdta",""),te("keys",0,0,[F(t.length)],t.map(e=>W("mdta",[...Z.encode(e.key)]))),W("ilst",void 0,t.map((e,r)=>{let n=String.fromCharCode(...F(r+1));return W(n,void 0,[e.value])}))])},Nt=i=>W("data",[F(1),F(0),...Z.encode(i)]),Lg=(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}},Wg={avc:cg,hevc:ug,vp8:Pf,vp9:Pf,av1:lg,prores:null},zf=(i,t,e)=>{switch(i){case"aac":return"mp4a";case"mp3":return"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}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"}},Hg=(i,t)=>{switch(i){case"aac":return fl;case"mp3":return fl;case"opus":return pg;case"vorbis":return fl;case"flac":return hg;case"ac3":return gg;case"eac3":return bg;case"dts":return yg}if(t)switch(i){case"pcm-s24":return bi;case"pcm-s24be":return bi;case"pcm-s32":return bi;case"pcm-s32be":return bi;case"pcm-f32":return bi;case"pcm-f32be":return bi;case"pcm-f64":return bi;case"pcm-f64be":return bi}else switch(i){case"pcm-s16":return dr;case"pcm-s16be":return dr;case"pcm-s24":return dr;case"pcm-s24be":return dr;case"pcm-s32":return dr;case"pcm-s32be":return dr;case"pcm-f32":return dr;case"pcm-f32be":return dr;case"pcm-f64":return dr;case"pcm-f64be":return dr}return null},qg={webvtt:"wvtt"},Kg={webvtt:Tg},Nf=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 pr=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.");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=0}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 Wf=Ol(Vu(),1);var Hf=typeof Wf<"u"?Wf:void 0,Me=class extends Je{constructor(){super(...arguments);this._writerAcquired=!1;this._monotonicity=null;this.onwrite=null}_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 $a(this,e)}},Tl=2**16,wl=2**32,yi=class extends Me{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(Tl,{maxByteLength:wl})}catch{this._buffer=new ArrayBuffer(Tl),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Tl);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let r=this._buffer.byteLength;for(;r<e;)r*=2;if(r!==this._buffer.byteLength){if(r>wl)throw new Error(`ArrayBuffer exceeded maximum size of ${wl} 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){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(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,r){return this._bytes.slice(e,r)}},Gg=2**24,Qg=2,Kn=class extends Me{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??Gg}_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){let n=this._chunks.findIndex(u=>u.start<=r&&r<u.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>Qg){for(let u=0;u<this._chunks.length-1;u++)this._chunks[u].shouldFlush=!0;this._tryToFlushChunks()}o.byteLength<e.byteLength&&this._writeDataIntoChunks(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&&jt()?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(u=>{this._writeError??=u}),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 _close(){return this._streamWriter?.close()}},oc=class extends Me{constructor(e){super();this._writer=null;this._nextWritePos=0;this._writable=e,this._streamTarget=new Kn(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()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},cc=class extends Me{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(!Hf.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 Hf.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 Kn(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 _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},ki=class extends Me{_start(){}_write(t,e){this._dispatchWrite(e,e+t.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}},$a=class extends Me{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 _close(){}_setMonotonicity(t){super._setMonotonicity(t),this._baseTarget._setMonotonicity(t)}},ut=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 ct=57600,jg=2082844800,Lf=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},qi=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},uc=class extends Ie{constructor(e,r){super(e);this.writer=null;this.boxWriter=null;this.initWriter=null;this.initBoxWriter=null;this.auxTarget=new yi;this.auxWriter=new pr(this.auxTarget,!1);this.auxBoxWriter=new Hi(this.auxWriter);this.mdat=null;this.ftypSize=null;this.trackDatas=[];this.allTracksKnown=ee();this.creationTime=Math.floor(Date.now()/1e3)+jg;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 Gi,this.isCmaf=r instanceof Ki,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(r instanceof Ki?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(n=>this.formatOptions.fastStart!==void 0?this.formatOptions.fastStart==="fragmented":n instanceof yi),this.boxWriter=new Hi(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof yi?"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 n=await this.output._getInitTarget(),a=new pr(n,!0);a.start(),this.initWriter=a,this.initBoxWriter=new Hi(a)}let r=this.output.tracks.some(n=>n.isVideoTrack()&&n.source._codec==="avc");{let n=this.initBoxWriter??this.boxWriter;if(b(n),this.formatOptions.onFtyp&&n.writer.startTrackingWrites(),n.writeBox(Rf({isQuickTime:this.isQuickTime,holdsAvc:r,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:a,start:s}=n.writer.stopTrackingWrites();this.formatOptions.onFtyp(a,s)}this.ftypSize=n.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(let n of this.output.tracks)if(n.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(b(this.writer),b(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=Xa(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush();for(let n of this.output.tracks)n.isVideoTrack()&&n.metadata.decoderConfig?this.getVideoTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig}):n.isAudioTrack()&&n.metadata.decoderConfig&&this.getAudioTrackData(n,n.metadata.primingPacket??null,{decoderConfig:n.metadata.decoderConfig});e()}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!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 Ks({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;nr(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=er(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=un(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=ir(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=pd(p),o=!0}let c=Xl(1/(e.metadata.frameRate??ct),1e6).den,u=s.displayAspectWidth,l=s.displayAspectHeight,d=u===void 0||l===void 0?{num:1,den:1}:Ar({num:u*s.codedHeight,den:l*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,compactlyCodedChunkTable:[],closed:!1,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(u=>u.track===e);if(a)return a;Ce(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 u=nt(we.tempFromBytes(r.data));if(!u)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 l=tt[u.samplingFrequencyIndex],d=Yt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=cn({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels: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.")}let c={muxer:this,track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&ne.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,primingPacket:r},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ls(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,compactlyCodedChunkTable:[],closed:!1,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 u=[...Gr(o)].map(l=>o.subarray(l.offset,l.offset+l.length));if(u.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=Cs(u,4)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=this.createSampleForTrack(s,o,r.timestamp,r.duration,r.type);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 d=nt(we.tempFromBytes(o));if(!d)throw new Error("Expected ADTS frame, didn't get one.");let m=d.crcCheck===null?Ut:bt;o=o.subarray(m)}this.validateTimestamp(s.track,r.timestamp,r.type==="key");let c=r.timestamp,u=r.duration;if(s.info.requiresPcmTransformation){let m=Re(s.info.decoderConfig.codec).sampleSize*s.info.numberOfChannels;if(u=o.byteLength/m/s.info.sampleRate,s.info.expectedNextPcmPacketTimestamp!==null){let f=c-s.info.expectedNextPcmPacketTimestamp;if(f<.01)c=s.info.expectedNextPcmPacketTimestamp;else{let p=await this.padWithSilence(s,s.info.expectedNextPcmPacketTimestamp,f);c=s.info.expectedNextPcmPacketTimestamp+p}}s.info.expectedNextPcmPacketTimestamp=c+u}let l=this.createSampleForTrack(s,o,c,u,r.type);await this.registerSample(s,l)}finally{a()}}async padWithSilence(e,r,n){let a=de(n,e.timescale);if(n=a/e.timescale,a>0){let{sampleSize:s,silentValue:o}=Re(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,u=new Uint8Array(s*c).fill(o),l=this.createSampleForTrack(e,new Uint8Array(u.buffer),r,n,"key");await this.registerSample(e,l)}return n}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),e.source._codec==="webvtt"&&(s.cueQueue.push(r),await this.processWebVTTCues(s,r.timestamp))}finally{a()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);let n=new Set([]);for(let l of e.cueQueue)b(l.timestamp<=r),b(e.lastCueEndTimestamp<=l.timestamp+l.duration),n.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),n.add(l.timestamp+l.duration);let a=[...n].sort((l,d)=>l-d),s=a[0],o=a[1]??s;if(r<o)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let l=Of();this.auxBoxWriter.writeBox(l);let d=this.auxTarget._getSlice(0,this.auxWriter.getPos()),m=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,m),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let l=0;l<e.cueQueue.length;l++){let d=e.cueQueue[l];if(d.timestamp>=o)break;Hn.lastIndex=0;let m=Hn.test(d.text),f=d.timestamp+d.duration,p=e.cueToSourceId.get(d);if(p===void 0&&o<f&&(p=e.nextSourceId++,e.cueToSourceId.set(d,p)),d.notes){let h=Vf(d.notes);this.auxBoxWriter.writeBox(h)}let g=Df(d.text,m?s:null,d.identifier??null,d.settings??null,p??null);this.auxBoxWriter.writeBox(g),f===o&&e.cueQueue.splice(l--,1)}let c=this.auxTarget._getSlice(0,this.auxWriter.getPos()),u=this.createSampleForTrack(e,c,s,o-s,"key");await this.registerSample(e,u),e.lastCueEndTimestamp=o}}createSampleForTrack(e,r,n,a,s){return{timestamp:n,decodeTimestamp:n,duration:a,data:r,size:r.byteLength,type:s,timescaleUnitsToNextSample:de(a,e.timescale)}}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=Y(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 u=de(s.decodeTimestamp,e.timescale,!1),l=Math.round(u-e.lastTimescaleUnits);if(b(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let d=Y(e.timeToSampleTable);if(b(d),d.sampleCount===1){d.sampleDelta=l;let f=e.timeToSampleTable[e.timeToSampleTable.length-2];f&&f.sampleDelta===l&&(f.sampleCount++,e.timeToSampleTable.pop(),d=f)}else d.sampleDelta!==l&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:l}));d.sampleDelta===c?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:c});let m=Y(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),this.isFragmented?(e.sampleQueue.push(r),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,r):await this.addSampleToTrack(e,r)}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 less 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(o=>{if(e===o)return r.type==="key";let c=o.sampleQueue[0];return c?c.type==="key":o.closed});a>=this.minimumFragmentDuration&&s&&r.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=a>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null,trafIndex: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){if(b(!this.isFragmented),b(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce((n,a)=>n+de(a.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Y(e.compactlyCodedChunkTable).samplesPerChunk!==r)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let n of e.currentChunk.samples)b(n.data),this.writer.write(n.data),n.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(b(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let r=null,n=1/0;for(let s of this.trackDatas){if(!e&&s.sampleQueue.length===0&&!s.closed)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=qn(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 Hi(this.writer);let h=this.boxWriter.measureBox(hl()),y=this.boxWriter.measureBox(gl(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=kl(n,r),s=this.writer.getPos(),o=s+this.boxWriter.measureBox(a),c=o+Mt,u=1/0;for(let p=0;p<r.length;p++){let g=r[p];b(g.currentChunk),b(g.startTimestampOffset!==null),g.currentChunk.offset=c,g.currentChunk.moofOffset=s,g.currentChunk.trafIndex=p,g.currentChunk.startTimestamp-=g.startTimestampOffset;for(let h of g.currentChunk.samples)c+=h.size,h.timestamp-=g.startTimestampOffset,h.decodeTimestamp-=g.startTimestampOffset;u=Math.min(u,g.currentChunk.startTimestamp)}let l=c-o,d=l>=2**32;if(d)for(let p of r)p.currentChunk.offset+=vr-Mt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let m=kl(n,r);if(this.boxWriter.writeBox(m),this.formatOptions.onMoof){let{data:p,start:g}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(p,g,u)}b(this.writer.getPos()===o),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let f=Xa(d);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(d?vr:Mt));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 of r)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,r)):e.sampleQueue.push(r)}async createFastStartReserveMdat(){b(this.writer),b(this.boxWriter),this.ensureOneEnabledTrack();let e=qn(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=Xa(!0),this.boxWriter.writeBox(this.mdat);for(let a of this.trackDatas){for(let s of a.sampleQueue)await this.addSampleToTrack(a,s);a.sampleQueue.length=0}}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}return e}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,n.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),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 finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),!this.mdat&&this.fastStart==="reserve"&&await this.createFastStartReserveMdat();for(let r of this.trackDatas)r.closed=!0,r.type==="subtitle"&&r.track.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let r of this.trackDatas){await this.finalizeCurrentChunk(r);let n=qi(r);if(n>0){let c=0;for(let u of r.samples)c+=u.size;r.avgBitrate=Math.round(8*c/n)}else r.avgBitrate=0;let a=0,s=0,o=0;for(let c=0;c<r.samples.length;c++){let u=r.samples[c];for(s+=u.size;u.decodeTimestamp-r.samples[a].decodeTimestamp>=1;)s-=r.samples[a].size,a++;o=Math.max(o,s)}if(r.maxBitrate=8*o,r.startTimestampOffset!==null)for(let c=0;c<r.samples.length;c++){let u=r.samples[c];u.timestamp-=r.startTimestampOffset,u.decodeTimestamp-=r.startTimestampOffset}}if(b(this.writer),b(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Xa(!1);let r;for(let a=0;a<2;a++){let s=qn(this),o=this.boxWriter.measureBox(s);r=this.boxWriter.measureBox(this.mdat);let c=this.writer.getPos()+o+r;for(let u of this.finalizedChunks){u.offset=c;for(let{data:l}of u.samples)b(l),c+=l.byteLength,r+=l.byteLength}if(c<2**32)break;r>=2**32&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let n=qn(this);if(this.boxWriter.writeBox(n),this.formatOptions.onMoov){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(a,s)}this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=r,this.boxWriter.writeBox(this.mdat);for(let a of this.finalizedChunks)for(let s of a.samples)b(s.data),this.writer.write(s.data),s.data=null;if(this.formatOptions.onMdat){let{data:a,start:s}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(a,s)}}else if(this.isFragmented)if(this.isCmaf){let r=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(hl()),this.boxWriter.writeBox(gl(this,r))}else{let r=this.writer.getPos(),n=Bf(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=qn(this);if(this.fastStart==="reserve"){b(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);let s=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Ff(s))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(a);if(this.formatOptions.onMoov){let{data:s,start:o}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(s,o)}}e()}};var Xg=-(2**15),$g=2**15-1,qf=6,Kf=5,Yg={video:1,audio:2,subtitle:17},lc=class extends Ie{constructor(e,r){super(e);this.trackDatas=[];this.allTracksKnown=ee();this.segment=null;this.segmentInfo=null;this.seekHead=null;this.tracksElement=null;this.tagsElement=null;this.attachmentsElement=null;this.segmentDuration=null;this.cues=null;this.currentCluster=null;this.currentClusterStartMsTimestamp=null;this.currentClusterMaxMsTimestamp=null;this.trackDatasInCurrentCluster=new Map;this.startTimestamp=1/0;this.endTimestamp=-1/0;this.warnedAboutTooNegativeTimestamp=!1;this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new to(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});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 Ti?"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 yn(0)};this.segmentDuration=e;let r={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:Pr},{id:22337,data:Pr},this.format._options.appendOnly?null:e]};this.segmentInfo=r}createTracks(){let e={id:374648427,data:[]};this.tracksElement=e;for(let r of this.trackDatas){let n=ze[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"));let a=0;if(r.type==="audio"&&r.track.source._codec==="opus"){a=1e6*80;let s=r.info.decoderConfig.description;if(s){let o=Q(s),c=Qr(o);a=Math.round(1e9*(c.preSkip/Ft))}}e.data.push({id:174,data:[{id:215,data:r.track.id},{id:29637,data:r.track.id},{id:131,data:Yg[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},{id:2274716,data:r.track.metadata.languageCode??se},{id:134,data:n},r.codecPrivate?{id:25506,data:Q(r.codecPrivate)}:null,a>0?{id:22203,data:a}:null,r.track.metadata.name!==void 0?{id:21358,data:new Vt(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:1e9/r}:null],s,o,c;if(n){s=Si(n);let g=Ht(tn(-s),n);o=Math.sign(g[0]),c=Math.sign(g[4]),c===-1&&(c=1,o=-o,s=yr(s+180))}else s=e.track.metadata.rotation??0,o=e.track.metadata.flip?-1:1,c=1;let u=s?yr(o===-1?s:-s):0,l=Math.round(Math.acos(o)*os),d=Math.round(Math.acos(c)*os),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,ds(f)?null:{id:21936,data:[{id:21937,data:f?.matrix!=null?St[f.matrix]:2},{id:21946,data:f?.transfer!=null?wt[f.transfer]:2},{id:21947,data:f?.primaries!=null?Tt[f.primaries]:2},{id:21945,data:f?.fullRange!=null?f.fullRange?2:1:0}]},u||l||d?{id:30320,data:[{id:30321,data:0},l?{id:30323,data:new ti(l)}:null,d?{id:30324,data:new ti(d)}:null,u?{id:30325,data:new ti((u+180)%360-180)}:null]}:null]};return a.push(p),a}audioSpecificTrackInfo(e){let r=ne.includes(e.track.source._codec)?Re(e.track.source._codec):null;return[{id:225,data:[{id:181,data:new ti(e.info.sampleRate)},{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 Vt(s)},typeof o=="string"?{id:17543,data:new Vt(o)}:{id:17541,data:o}]})},n=this.output._metadataTags,a=new Set;for(let{key:s,value:o}of _t(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":break;default:ae(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")+(Zl(s.mimeType)??""));let c;for(;;){c=0n;for(let u=0;u<8;u++)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 Vt(s.description)}:null,{id:18030,data:new Vt(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 xr)||!/^\d+$/.test(s)||a.find(u=>u.mimeType===o.mimeType&&bs(u.data,o.data))||r.push({id:24999,data:[o.description!==void 0?{id:18046,data:new Vt(o.description)}:null,{id:18030,data:new Vt(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:qf,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(!e.source._closed&&!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 no({isWebM:this.format instanceof Ti,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(l=>l.track===e);if(a)return a;nr(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:Ar({num:s,den:o}),u={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,closed:!1};return e.source._codec==="vp9"?u.codecPrivate=new Uint8Array(_d(u.info.decoderConfig.codec)):e.source._codec==="av1"?u.codecPrivate=new Uint8Array(Us(u.info.decoderConfig.codec)):e.source._codec==="prores"&&(u.codecPrivate=Z.encode(n.decoderConfig.codec)),this.trackDatas.push(u),this.trackDatas.sort((l,d)=>l.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r,n){let a=this.trackDatas.find(u=>u.track===e);if(a)return a;Ce(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 u=nt(we.tempFromBytes(r.data));if(!u)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 l=tt[u.samplingFrequencyIndex],d=Yt[u.channelConfiguration];if(l===void 0||d===void 0)throw new Error("Invalid ADTS frame header.");s.description=cn({objectType:u.objectType,outputSampleRate:l,outputNumberOfChannels:d}),o=!0}let c={track:e,type:"audio",info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null,closed:!1};return this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getSubtitleTrackData(e,r){let n=this.trackDatas.find(s=>s.track===e);if(n)return n;Ls(r),b(r),b(r.config);let a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Z.encode(r.config.description),closed:!1};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 u=r.timestamp,l=r.duration;e.metadata.frameRate!==void 0&&(u=Gt(u,e.metadata.frameRate),l=Gt(l,e.metadata.frameRate));let d=s.info.alphaMode?r.sideData.alpha??null:null,m=this.createInternalChunk(o,u,l,r.type,d);e.source._codec==="vp9"&&this.fixVP9ColorSpace(s,m),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 l=nt(we.tempFromBytes(o));if(!l)throw new Error("Expected ADTS frame, didn't get one.");let d=l.crcCheck===null?Ut:bt;o=o.subarray(d)}let c=r.type==="key";this.validateTimestamp(s.track,r.timestamp,c);let u=this.createInternalChunk(o,r.timestamp,r.duration,r.type);s.chunkQueue.push(u),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);Hn.lastIndex=0,o=o.replace(Hn,m=>{let p=ac(m.slice(1,-1))-c;return`<${sc(p)}>`});let u=Z.encode(o),l=`${r.settings??""}
16
16
  ${r.identifier??""}
17
- ${r.notes??""}`,d=this.createInternalChunk(u,r.timestamp,r.duration,"key",l.trim()?Z.encode(l):null);s.chunkQueue.push(d),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&&!s.closed)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.writeBlock(r,a)}e||await this.writer.flush()}}fixVP9ColorSpace(e,r){if(r.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let n=new H(r.data);n.skipBits(2);let a=n.readBits(1),o=(n.readBits(1)<<1)+a;if(o===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;o>=2&&n.skipBits(1);let d={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];zl(r.data,n.pos,n.pos+3,d)}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let n=Math.round(1e3*r.timestamp),a=this.trackDatas.every(m=>{if(e===m)return r.type==="key";let f=m.chunkQueue[0];return f?f.type==="key":m.closed}),s=!1;if(!this.currentCluster)s=!0;else{b(this.currentClusterStartMsTimestamp!==null),b(this.currentClusterMaxMsTimestamp!==null);let m=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>$g}s&&this.createNewCluster(n);let o=n-this.currentClusterStartMsTimestamp;if(o<Xg){if(!this.warnedAboutTooNegativeTimestamp){let m=this.format instanceof Ti?"WebM":"Matroska";V._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${m}.`),this.warnedAboutTooNegativeTimestamp=!0}return}let c=new Uint8Array(4),u=new DataView(c.buffer);u.setUint8(0,128|e.track.id),u.setInt16(1,o,!1);let l=Math.round(1e3*r.duration);if(!!r.additions||e.type==="subtitle"){let m={id:160,data:[{id:161,data:[c,r.data]},r.type==="delta"?{id:251,data:new fa(e.lastWrittenMsTimestamp-n)}:null,r.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:r.additions}]}]}:null,l>0?{id:155,data:l}:null]};this.ebmlWriter.writeEBML(m)}else{u.setUint8(3,+(r.type==="key")<<7);let m={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(m)}this.startTimestamp=Math.min(this.startTimestamp,n),this.endTimestamp=Math.max(this.endTimestamp,n+l),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:Kf,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(b(this.currentCluster),!this.format._options.appendOnly){let a=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(a,Kf),this.writer.seek(s)}if(this.format._options.onCluster){b(this.currentClusterStartMsTimestamp!==null);let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(a);let n=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of n)b(this.cues),this.cues.data.push({id:187,data:[{id:179,data:Math.max(0,a)},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:e}]}))]})}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),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,qf);let n=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new yn(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)}e()}};var dc=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos(),r=255,n=224|t.mpegVersionId<<3|t.layer<<1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=155,c=-1,u=a*16*4+t.layer*16;for(let h=0;h<16;h++){let y=Ws[u+h];if(Hs(a,t.layer,1e3*y,t.sampleRate,s)>=o){c=h;break}}if(c===-1)throw new Error("No suitable bitrate found.");let l=c<<4|t.frequencyIndex<<2|s<<1,d=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]=l,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));let m=Yr(t.mpegVersionId,t.channel);this.writer.seek(e+m),this.writeU32($r);let f=0;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.writer.write(t.toc??new Uint8Array(100));let p=Ws[u+c],g=Hs(a,t.layer,1e3*p,t.sampleRate,s);this.writer.write(new Uint8Array(e+g-this.writer.getPos()))}};var mc=class extends Ie{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.xingFramePos=null;this.format=r,this.writeXingHeader=r._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new dc(this.writer),Cr(this.output._metadataTags)||new gi(this.writer).writeId3V2Tag(this.output._metadataTags),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.xingFrameData&&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=Zr(s,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");let c=Yr(o.mpegVersionId,o.channel);if(a.byteLength>=c+4){let u=a.getUint32(c,!1);if(u===$r||u===fn)return}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,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}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=Zr(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,frameCount:null,fileSize:null,toc:null}}else if(n.metadata.decoderConfig){let{sampleRate:s,numberOfChannels:o}=n.metadata.decoderConfig,c=[3,2,0],u=null,l=-1;for(let d=0;d<c.length;d++)if(l=ou.indexOf(s<<d),l!==-1){u=c[d];break}if(u===null)throw new Error(`${s} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:u,layer:1,frequencyIndex:l,sampleRate:s,channel:o===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,frameCount:null,fileSize:null,toc: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),this.frameCount++}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)),u=this.framePositions[c]-this.xingFramePos;s[o]=256*(u/a)}this.xingFrameData.toc=s}if(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 Zg=8192,fc=class extends Ie{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=ee();this.pageBytes=new Uint8Array(uo);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();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});e()}async getMimeType(){return await this.allTracksKnown.promise,co({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(o=>o.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));b(e.source._codec==="vorbis"||e.source._codec==="opus"),Ce(r,e.source._codec),b(r),b(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?Ft:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],startTimestampInSamples:null,currentTimestampInSamples:0,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(b(r.decoderConfig),e.track.source._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 h=0;for(;;){let y=n[a++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(h+=y,y<255)return h}},o=s(),c=s();if(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=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=ia(m,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!1},{data:d,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0});let g=N(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(g&15),1<<(g>>4)],modeBlockflags:Es(d).modeBlockflags}}else if(e.track.source._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=N(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=ia(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Qr(n).preSkip}}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);if(this.validateTimestamp(s.track,r.timestamp,r.type==="key"),s.startTimestampInSamples===null){let m=Math.round(r.timestamp*s.internalSampleRate),f=s.codecInfo.opusInfo?.preSkip??0;s.startTimestampInSamples=m>0?m+f:0,s.currentTimestampInSamples=s.startTimestampInSamples}let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=ya(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u;let l=r.duration>0?J(Math.round(r.duration*s.internalSampleRate),0,c):c,d=s.startTimestampInSamples>0&&s.audioPacketCount===1;s.audioPacketCount++,s.packetQueue.push({data:r.data,timestampInSamples:o,durationInSamples:c,trimmedDurationInSamples:l,forcePageFlush:d}),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!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&&!o.closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestampInSamples<n&&(r=o,n=o.packetQueue[0].timestampInSamples)}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+(n?r.trimmedDurationInSamples:r.durationInSamples);if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=r.timestampInSamples),this.format._options.maximumPageDuration!==void 0){let l=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&a-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,c+=l;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 u=r.data.subarray(o);e.currentPageData.push(u),e.currentPageSize+=u.length,e.currentGranulePosition=a,(e.currentPageSize>=Zg||r.forcePageFlush)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,ba,!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(u=>u===255)?-1:e.currentGranulePosition;Gl(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 u of e.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=dm(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:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(u,l,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);e()}};var Jg=0,$f=4096,Gf=256,eb=224,Qf=192,jf=new Uint8Array([9,240]),Xf=new Uint8Array([70,1]),pc=class extends Ie{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=N(this.packetBuffer);this.allTracksKnown=ee();this.videoTrackIndex=0;this.audioTrackIndex=0;this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,yo(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;nr(r,e.source._codec),b(r?.decoderConfig);let a=e.source._codec;b(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=Gf+this.trackDatas.length,c=eb+this.videoTrackIndex++,u={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;Ce(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,o;switch(a){case"aac":s=15,o=Qf+this.audioTrackIndex++;break;case"mp3":s=3,o=Qf+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break;case"dts":s=130,o=189;break}let c=Gf+this.trackDatas.length,u={track:e,pid:c,streamType:s,streamId:o,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!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(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=Q(s);a==="avc"?e.avcDecoderConfig=tr(o):e.hevcDecoderConfig=ln(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let s of Gr(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?Jt(o[0])===9:Rt(o[0])===35)||n.push(o)}let a=r==="avc"?jf:Xf;return n.unshift(a),ta(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of As(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(n==="avc"?Jt(l[0])===9:Rt(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="avc"){let u=e.avcDecoderConfig;for(let l of u.pictureParameterSets)o.unshift(l);for(let l of u.sequenceParameterSets)o.unshift(l)}else{let u=e.hevcDecoderConfig;for(let l of u.arrays)if(l.nalUnitType===34)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===33)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===32)for(let d of l.nalUnits)o.unshift(d)}let c=n==="avc"?jf:Xf;return o.unshift(c),ta(o)}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 u=n?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=Zt(Q(u)),d=Ts(l);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}}if(e.inputIsAdts)return r.data;b(e.adtsHeader),b(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;ws(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(!e.source._closed&&!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];s.decodeTimestamp=n[a],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&&!s.closed)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(Jg,Qi),this.writePsiSection($f,rb(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,u=Math.min(o,c),l;a?(l=this.payloadBuffer.subarray(0,1+u),l[0]=0,l.set(r.subarray(n,n+u),1)):l=r.subarray(n,n+u),this.writeTsPacket(e,a,null,l),n+=u,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 H(s.subarray(9));Pi(o,0,1,!1),s[3]=e.streamId;let u=e.track.type==="video"?0:Math.min(8+r.data.length,65535);o.setUint16(4,u,!1),o.setUint8(6,132),o.setUint8(7,n?192:128),o.setUint8(8,a);let l=Math.round(r.presentationTimestamp*9e4),d=Gc(l,8589934592);if(c.pos=0,c.writeBits(4,n?3:2),c.writeBits(3,Math.floor(d/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(d/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,d%2**15),c.writeBits(1,1),n){b(r.decodeTimestamp!==null);let g=Math.round(r.decodeTimestamp*9e4),h=Gc(g,8589934592);c.writeBits(4,1),c.writeBits(3,Math.floor(h/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(h/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,h%2**15),c.writeBits(1,1)}let m=s.length+r.data.length,f=0,p=!0;for(;f<m;){let g=p,h=m-f,y=p&&r.isKeyframe,k=p&&!e.firstPacketWritten,T=Math.max(0,184-h),w;y||k?w=Math.max(2,T):w=T;let S=null;if(w>0){let E=this.adaptationFieldBuffer;w===1?E[0]=0:(E[0]=w-1,E[1]=Number(k)<<7|Number(y)<<6,E.fill(255,2,w)),S=E.subarray(0,w)}let x=Math.min(184-w,h),C=this.payloadBuffer.subarray(0,x),I=0;if(f<s.length){let E=Math.min(s.length-f,x);C.set(s.subarray(f,f+E),0),I=E}let A=Math.max(0,f-s.length),P=A+(x-I);I<x&&C.set(r.data.subarray(A,P),I),this.writeTsPacket(e.pid,g,S,C),f+=x,p=!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 u=4;n&&(this.packetBuffer.set(n,u),u+=n.length),this.packetBuffer.set(a,u),u+=a.length,u<188&&this.packetBuffer.fill(255,u);let l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0,await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},tb=79764919,Yf=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^tb:t<<1;Yf[i]=t>>>0&4294967295}var Zf=i=>{let t=4294967295;for(let e=0;e<i.length;e++){let r=i[e];t=(t<<8^Yf[t>>>24^r])>>>0}return t},Qi=new Uint8Array(16);{let i=N(Qi);Qi[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),Qi[5]=193,Qi[6]=0,Qi[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|$f&8191,!1),i.setUint32(12,Zf(Qi.subarray(0,12)),!1)}var rb=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=aa.length:c.streamType===135&&(t+=sa.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)r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|aa.length,!1),a+=2,r.set(aa,a),a+=aa.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=Zf(r),o=new Uint8Array(r.length+4);return o.set(r,0),N(o).setUint32(r.length,s,!1),o};var hc=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(Z.encode(t))}};var gc=class extends Ie{constructor(e,r){super(e);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.riffSizePos=null;this.dataSizePos=null;this.ds64RiffSizePos=null;this.ds64DataSizePos=null;this.ds64SampleCountPos=null;this.format=r,this.isRf64=!!r._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new hc(this.writer);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Ce({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.writeHeader(r,r.metadata.decoderConfig),this.sampleRate=r.metadata.decoderConfig.sampleRate,this.headerWritten=!0),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||(Ce(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=Re(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,u=s.sampleSize*o;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!Cr(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ae(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:l,start:d}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,d)}}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,u)=>{if(!vt(u)){V._warn(`Didn't write tag '${c}' because '${u}' is not ISO 8859-1-compatible.`);return}let l=u.length+1,d=new Uint8Array(l);for(let m=0;m<u.length;m++)d[m]=u.charCodeAt(m);this.riffWriter.writeAscii(c),this.riffWriter.writeU32(l),this.writer.write(d),l&1&&this.writer.write(new Uint8Array(1)),n.add(c)};for(let{key:c,value:u}of _t(e))switch(c){case"title":a("INAM",u),n.add("INAM");break;case"artist":a("IART",u),n.add("IART");break;case"album":a("IPRD",u),n.add("IPRD");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${u}/${e.tracksTotal}`:u.toString();a("ITRK",l),n.add("ITRK")}break;case"genre":a("IGNR",u),n.add("IGNR");break;case"date":a("ICRD",u.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":a("ICMT",u),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"beatsPerMinute":case"description":case"lyrics":case"images":break;case"raw":break;default:ae(c)}if(e.raw)for(let c in e.raw){let u=e.raw[c];u==null||c.length!==4||n.has(c)||typeof u=="string"&&a(c,u)}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 gi(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.");let r=this.writer.getPos();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 bc=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 u=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+u,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=t.timestamp-this.startTime,s=a+t.duration,o=Math.floor((a-1/this.sourceSampleRate)*this.targetSampleRate)+1,c=Math.ceil(s*this.targetSampleRate);for(let u=o;u<c;u++){if(u<this.bufferStartFrame)continue;for(;u>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=u-this.bufferStartFrame;b(l<this.bufferCapacityInFrames);let f=(u/this.targetSampleRate-a)*this.sourceSampleRate,p=Math.floor(f),g=Math.ceil(f),h=f-p;for(let y=0;y<this.targetNumberOfChannels;y++){let k=0,T=0;p>=0&&p<t.numberOfFrames&&(k=this.channelMixer(n,p,y)),g>=0&&g<t.numberOfFrames&&(T=this.channelMixer(n,g,y));let w=k+h*(T-k),S=l*this.targetNumberOfChannels+y;this.outputBuffer[S]+=w}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}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 Ae({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:e});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 ji=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._closed=!1;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._closed)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),this._closed=!0,!(t.output.state==="finalizing"||t.output.state==="finalized")&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=(async()=>{await this._flushAndClose(t),this._closed=!0})()}},hr=class extends ji{constructor(t){if(super(),!ce.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${ce.join(", ")}.`);this._codec=t}},Cl=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Ur=class extends hr{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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(),Cl(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},Ya=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=-1;this.emittedEncoderPackets=0;this.chunkTimestampsAreShiftedByDuration=!1;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new Lr;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;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,s=a.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(o=!0,s==="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(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.flip!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||o&&s!=="passThrough"){let d=a.transform?.width,m=a.transform?.height,f=a.transform?.fit??"fill";o&&s!=="passThrough"&&(b(this.outputWidth),b(this.outputHeight),b(s!=="deny"),d=this.outputWidth,m=this.outputHeight,f=s);let p=await t.transform({width:d,height:m,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,flip:a.transform?.flip,fit:f,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),e&&t.close(),t=p,e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let l=a.transform?.frameRate;if(l!==void 0){let d=t.timestamp+t.duration,m=Qc(t.timestamp,l);if(this.frameRateLastSample!==null)if(m<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(m,r);t===n&&(t=t.clone(),e=!0),t.setTimestamp(m),t.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=m,this.frameRateLastEndTimestamp=d}await this.processAndEncode(t,r)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,n;if(r.transform?.process){let a=r.transform.process(t);if(_(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);let s=[];try{for(let o of a)o instanceof Ge?s.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?s.push(new Ge(o)):s.push(new Ge(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 Ge&&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},u={...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 l=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,u)).catch(m=>this.setError(m)).finally(()=>{this.customEncoderQueueSize--,l.close()});this.customEncoderQueueSize>=4&&await d}else{b(this.encoder);let l=a.toVideoFrame(),d=G(this.preciseTimings,l.timestamp,f=>f.microsecondTimestamp),m=d!==-1?this.preciseTimings[d]:null;if(m&&m.microsecondTimestamp===l.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:l.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(l,u)}finally{l.close()}}else{this.splitter||(this.splitter=new Pl);let{colorFrame:p,alphaFrame:g}=await this.splitter.split(l);this.alphaFrameQueue.push(g);try{this.encoder.encode(p,u)}finally{p.close()}}else try{this.encoder.encode(l,u)}finally{l.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 u=1;u<n;u++){var a=[];try{let l=dt(a,this.frameRateLastSample.clone());l.setTimestamp(this.frameRateLastTimestamp+u/r);l.setDuration(1/r);await this.processAndEncode(l,e)}catch(s){var o=s,c=!0}finally{mt(a,o,c)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let e=di(this.encodingConfig.quality,this.encodingConfig.bitrate);b(e!==void 0);let r=Zu({...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=Dn.find(l=>l.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(an("VideoEncoder"));let o=r[0].config,c=r.map(({config:u,quantizer:l})=>l!==null?`quantizer ${l}`:`${u.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=el(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 j))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.");Cl(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init()):(this.encoderConfig=s,this.encodingConfig.codec==="avc"&&Xt()&&(this.chunkTimestampsAreShiftedByDuration=await nb()),this.createWebCodecsEncoders()),b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let t=this.encoderConfig;b(t);let e=[],r=[],n=0,a=0,s=(c,u)=>{if(Yl(c)){this.encodersReclaimed=!0;return}c.stack=u,this.setError(c)},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(c,u)=>{if(!this.alphaEncoder){this.addPacket(c,null,u);return}let l=this.alphaFrameQueue.shift();b(l!==void 0),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),a++,l.close(),e.push({chunk:c,meta:u})):a===0?this.addPacket(c,null,u):(r.push(n+a),e.push({chunk:c,meta: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:(u,l)=>{a--;let d=e.shift();for(b(d!==void 0),this.addPacket(d.chunk,u,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)}},error:u=>s(u,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=j.fromEncodedChunk(t,n),s=this.encoderConfig;if(b(s),r?.decoderConfig&&(r.decoderConfig.codec=Xr({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?er(a.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?ir(a.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?dn(a.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?Mi(a.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&r.decoderConfig.description&&Xt())){let d=tr(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=un({...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=G(this.preciseTimings,o,d=>d.microsecondTimestamp),u=c!==-1?this.preciseTimings[c]:null,l=null;this.emittedEncoderPackets===0&&a.type==="delta"&&r?.decoderConfig&&(l=jr(this.encodingConfig.codec,r.decoderConfig,a.data)),(u&&u.microsecondTimestamp===o||l!==null)&&(a=a.clone({timestamp:u?.timestampIsValid?u.timestamp:void 0,duration:u?.durationIsValid?u.duration:void 0,type:l??void 0})),Cl(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=-1,this.createWebCodecsEncoders()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,r=Qc(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await Kr(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||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},ib=null,nb=()=>ib??=(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!1}finally{t.state!=="closed"&&t.close()}return i===500})(),Sl=null,Pl=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){if(!this.worker){if(!Sl){let n=new Blob([`(${ab.toString()})()`],{type:"application/javascript"});Sl=URL.createObjectURL(n)}this.worker=new Worker(Sl),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=ee();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()}},ab=()=>{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:u}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}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,u=o.visibleRect?.height??o.codedHeight,l=c*u,d=Math.ceil(c/2),m=Math.ceil(u/2),f=l+d*m*2,p=new Uint8Array(f);for(let k=0,T=3;k<l;k++,T+=4)p[k]=a[T];p.fill(128,l);let g=new VideoFrame(a,{format:s==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),h={format:"I420",codedWidth:c,codedHeight:u,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,u=o.visibleRect?.height??o.codedHeight,l=s.includes("P10"),d=s.includes("P12"),m=l||d?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(u/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=u):(f=c,p=u);let g=c*u,h=f*p,y=g*m,k=h*m,T=g*m,w=y+k*2,S=s.replace("A",""),x=Math.ceil(c/2),C=Math.ceil(u/2),I=x*C,A=I*m,P=T+2*A,E=new Uint8Array(P),v=w;E.set(a.subarray(v,v+T),0);let M=T,O=l?512:d?2048:128;m===1?E.fill(O,M):new Uint16Array(E.buffer,M,2*I).fill(O);let z=l?"I420P10":d?"I420P12":"I420",D=new VideoFrame(a.subarray(0,w),{format:S,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),q={format:z,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[E.buffer]},ie=new VideoFrame(E,q);return{colorFrame:D,alphaFrame:ie}}},Xi=class extends hr{constructor(t){$o(t),super(t.codec),this._encoder=new Ya(this,t)}add(t,e){if(!(t instanceof Ge))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},yc=class extends hr{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.");$o(e),super(e.codec),this._encoder=new Ya(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.");let n=new Ge(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},kc=class extends hr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if($o(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(typeof n.frameRate!="number"||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a 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=ee();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new Ya(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._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=0,s=!1,o=null,c=0,u=()=>{if(b(e!==null),!this._lastVideoFrame)return;b(n!==null),b(r!==null);let m=performance.now();for(;m-n>1e3/e;){n+=1e3/e;let f=r+a/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});d(p,m)}};e!==null&&(this._timerHandle=nd(u,4));let l=m=>{if(e===null)d(m);else{let f=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=m):(d(m.clone(),f),n=f,this._lastVideoFrame=m)}},d=(m,f=performance.now())=>{if(s){m.close();return}a++;let p=m.timestamp/1e6;if(this._paused){if(r!==null){if(o!==null&&this._options.timestampBase!=="unix"){let y=p-o;c-=y}o=p}m.close();return}if(r===null){r=p;let h,y=this._options.timestampBase??"synced-zero";if(y==="unix")h=Date.now()/1e3;else if(y==="zero")h=0;else{let k=this._connectedTrack.output;k._firstMediaStreamTimestamp===null?(k._firstMediaStreamTimestamp=f/1e3,h=0):h=f/1e3-k._firstMediaStreamTimestamp}c=h-r}if(o=p,this._encoder.getQueueSize()>=8){m.close();return}let g=new Ge(m,{timestamp:p+c});this._encoder.add(g,!0).catch(h=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(h),this._workerTrackId!==null&&xl({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let m=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});m.readable.pipeTo(f,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await ub())this._workerTrackId=ob++,xl({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{let p=f.data;p.type==="videoFrame"&&p.trackId===this._workerTrackId?l(p.videoFrame):p.type==="error"&&p.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(p.error)},Et.addEventListener("message",this._workerListener);else if(e!==null){let f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=new MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;let p=new VideoFrame(f,{timestamp:1e3*performance.now()});l(p),p.close()},{once:!0}),f.play().catch(p=>{s=!0,this._promiseWithResolvers.reject(p)})}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&&ad(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(b(this._workerListener),xl({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),Et.removeEventListener("message",this._workerListener),Et.removeEventListener("message",n),r())};Et.addEventListener("message",n)}))}finally{await this._encoder.flushAndClose(e)}}},gr=class extends ji{constructor(t){if(super(),!me.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${me.join(", ")}.`);this._codec=t}},zr=class extends gr{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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)}},Za=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.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.customEncoder=null;this.customEncoderCallSerializer=new Lr;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){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),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 r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new bc({targetNumberOfChannels:r.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:r.transform.sampleRate??t.sampleRate,onSample:async a=>{await this.processAndEncode(a,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&Ym(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(_(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(let a of n)if(!(a instanceof Ae))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,!0)}finally{for(let a of n)a instanceof Ae&&a.close()}}finally{e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(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=new Ae({data:new Float32Array(a*t.numberOfChannels),format:"f32-planar",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:a,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(s,!0)}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);let r=t.toAudioData();this.encoder.encode(r),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,o=2048,c=[];for(let g=0;g<n;g+=o){let h=Math.min(o,t.numberOfFrames-g),y=h*r*this.outputSampleSize,k=new ArrayBuffer(y),T=new DataView(k);c.push({frameCount:h,view:T})}let u=t.format==="s32"||t.format==="s32-planar",l=u?"s32-planar":"f32-planar",d=u?1/2147483648:1,m=t.allocationSize({planeIndex:0,format:l}),f=u?new Int32Array(m/4):new Float32Array(m/4);for(let g=0;g<r;g++){t.copyTo(f,{planeIndex:g,format:l});for(let h=0;h<c.length;h++){let{frameCount:y,view:k}=c[h];for(let T=0;T<y;T++)this.writeOutputValue(k,(T*r+g)*this.outputSampleSize,f[h*o+T]*d)}}e&&t.close();let p={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}};for(let g=0;g<c.length;g++){let{frameCount:h,view:y}=c[g],k=y.buffer,T=g*o,w=new j(new Uint8Array(k),"key",s+T/a,h/a);this.encodingConfig.onEncodedPacket?.(w,p),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,w,p)}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:e,sampleRate:r}=t,n=di(this.encodingConfig.quality,this.encodingConfig.bitrate),a=Ju({numberOfChannels:e,sampleRate:r,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(a),this.source._nominalBitrate=a.bitrate??null;let s=Vn.find(o=>o.supports(this.encodingConfig.codec,a));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof j))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.");this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else if(ne.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(an("AudioEncoder"));let o;try{o=(await AudioEncoder.isConfigSupported(a)).supported??!1}catch{o=!1}if(!o)throw new Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let c=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(u,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){if(l.decoderConfig.description&&l.decoderConfig.description.byteLength>0&&Q(l.decoderConfig.description)[0]===3){let{decoderSpecificInfo:f}=Xs(we.tempFromBytes(Q(l.decoderConfig.description)));l.decoderConfig.description=f??void 0}let m=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?m=!0:m=Zt(Q(l.decoderConfig.description)).objectType===0,m){let f=Number(Y(a.codec.split(".")));l.decoderConfig.description=cn({objectType:f,outputNumberOfChannels:l.decoderConfig.numberOfChannels,outputSampleRate:l.decoderConfig.sampleRate})}}let d=j.fromEncodedChunk(u);d=d.clone({timestamp:Gt(d.timestamp,a.sampleRate),duration:u.duration!=null?Gt(d.duration,a.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,l).catch(m=>{this.setError(m)})},error:u=>{u.stack=c,this.setError(u)}}),this.encoder.configure(a)}b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Re(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,J(Math.round(o*128)+128,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,J(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=J(Math.round(o*32768),-32768,32767);a.setUint8(s,hf(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=J(Math.round(o*32768),-32768,32767);a.setUint8(s,bf(c))}:b(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,J(Math.round(o*32768)+32768,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,J(Math.round(o*32768),-32768,32767),n):b(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>Pi(a,s,J(Math.round(o*8388608)+8388608,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Kl(a,s,J(Math.round(o*8388608),-8388608,8388607),n):b(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,J(Math.round(o*2147483648)+2147483648,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,J(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:ae(r),b(!1)}}async flushAndClose(t){try{t||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):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||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Gn=class extends gr{constructor(t){Yo(t),super(t.codec),this._encoder=new Za(this,t)}add(t){if(!(t instanceof Ae))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Tc=class extends gr{constructor(t,e={}){if(Yo(t),typeof e!="object"||!e)throw new TypeError("options must be an object.");if(e.startTimestamp!==void 0&&!Number.isFinite(e.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(t.codec),this._encoder=new Za(this,t),this._accumulatedTime=e.startTimestamp??0}async add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let e=Ae._fromAudioBuffer(t,this._accumulatedTime);this._accumulatedTime+=t.duration;for(let r of e)await this._encoder.add(r,!0)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},wc=class extends gr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Yo(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=ee();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new Za(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._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){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let l=c-n;a-=l}n=c}o.close();return}if(e===null){e=o.timestamp;let u,l=this._options.timestampBase??"synced-zero";if(l==="unix")u=Date.now()/1e3;else if(l==="zero")u=0;else{let d=this._connectedTrack.output;d._firstMediaStreamTimestamp===null?(d._firstMediaStreamTimestamp=performance.now()/1e3,u=0):u=performance.now()/1e3-d._firstMediaStreamTimestamp}a=u-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(u=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(u),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:u=>s(new Ae(u))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(u=>{u instanceof DOMException&&u.name==="AbortError"||this._promiseWithResolvers.reject(u)})}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 u=0;this._scriptProcessorNode.onaudioprocess=l=>{let d=Ae._fromAudioBuffer(l.inputBuffer,u);u+=l.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.suspend())}finally{await this._encoder.flushAndClose(e)}}},sb=()=>{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:ae(n)}})},ob=0,Et=null,cb=()=>{let i=new Blob([`(${sb.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(i);Et=new Worker(t)},Al=null,ub=async()=>Al!==null?Al:(Et||cb(),new Promise(i=>{b(Et);let t=e=>{let r=e.data;r.type==="support"&&(Al=r.supported,Et.removeEventListener("message",t),i(r.supported))};Et.addEventListener("message",t)})),xl=(i,t)=>{b(Et),t?Et.postMessage(i,t):Et.postMessage(i)},$i=class extends ji{constructor(t){if(super(),!Xe.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${Xe.join(", ")}.`);this._codec=t}},Sc=class extends $i{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new nc({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 Jf=i=>i==="opus"?"Opus":i,xc=class extends Ie{constructor(e,r){if(!(e._target instanceof ut))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];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.globalTargetDuration=this.targetSegmentDuration,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(),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,u=!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||(V._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){u||(V._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),u=!0);continue}let w=k.get(T.source._codec);w||k.set(T.source._codec,w=[]),w.push(T)}for(let[,T]of k){let w=T.map(C=>C.id).join("-");s.find(C=>C.key===w)||s.push({name:T[0].type+"-"+(s.length+1),key:w,tracks:T,needsEmit:!1,firstNoUri:!1});let x=a.get(y);x||a.set(y,x=[]),x.push(w)}}let l=o?"video":"audio",d=[],m=[],f=[];for(let y of this.output.tracks){let k=a.get(y);if(k){if(b(k.length>0),y.type!==l)continue;for(let T of k){let w=s.find(S=>S.key===T);if(b(w),k.length===1&&w.tracks.length===1){let S=a.get(w.tracks[0]);if(b(S!==void 0),S.length===1){let x=s.find(C=>C.key===S[0]);if(x.tracks.length===1){b(x.tracks[0]===y),d.push({tracks:[y,w.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[y],linkedGroup:w}),w.needsEmit=!0}}else y.type==="video"?m.push(y):y.type==="audio"&&f.push(y)}let p=({metadata:y})=>{let k="";return k+=`${y.languageCode??se}-`,k+=`${y.name??""}-`,k+=`${y.disposition?.default??!0}-`,k+=`${y.disposition?.primary??!1}-`,k+=`${y.disposition?.forced??!1}-`,k};if(m.length>0)if(new Set(m.map(p)).size>1){let k={key:m.map(T=>T.id).join("-"),name:"video-"+(s.length+1),tracks:m,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[m[0]],linkedGroup:k})}else for(let k of m)d.push({tracks:[k],linkedGroup:null});if(f.length>0)if(new Set(f.map(p)).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 g=y=>{let k=[],T=0,w=0,S=!1,x=null,C=-1/0;for(let I of y)I.isVideoTrack()?(T++,S||=(I.metadata.rotation??0)!==0||!!I.metadata.flip||!!I.metadata.transformationMatrix):I.isAudioTrack()&&w++,k.push(I.source._codec);for(let I of $t(this.format._options.segmentFormat)){let A=I.getSupportedCodecs(),P=I.getSupportedTrackCounts();if(k.some(v=>!A.includes(v))||T<P.video.min||T>P.video.max||w<P.audio.min||w>P.audio.max)continue;let E=0;S&&I.supportsVideoTransformationMetadata&&E++,E>C&&(x=I,C=E)}return b(x),x},h=async y=>{if(y.some(x=>this.playlists.some(C=>C.tracks.includes(x))))throw new Error("Internal error: track is already registered in a playlist.");let k=g(y),T=this.playlists.length+1,w=await this.getPlaylistPath({n:T,tracks:y,segmentFormat:k});lb(w);let S={id:this.playlists.length+1,path:w,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 He};return this.playlists.push(S),S};for(let y of s)if(y.needsEmit)for(let k=0;k<y.tracks.length;k++){let T=y.tracks[k],w=this.playlists.find(S=>S.tracks[0].id===T.id);w??=await h([T]),this.playlistDeclarations.push({playlist:w,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});e()}async getMimeType(){return or}allTracksAreKnown(e){for(let r of e.tracks)if(!r.source._closed&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0);let n=this.playlists.find(s=>s.tracks.includes(e));b(n);let a=await n.mutex.acquire();try{await this.advancePlaylist(n)}finally{a()}}getVideoTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;nr(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],closed:!1,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;Ce(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],closed:!1,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),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),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(s=>e.tracks.includes(s.track));if(e.currentSegmentStartTimestamp===null){r.every(s=>s.closed)&&await this.onPlaylistDone(e);return}let n=r.find(s=>s.info.type==="video"),a=r.find(s=>s.info.type==="audio");for(;;){let s=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,c=0;if(n&&(!n.closed||n.packets.length>0)){let x=n.packets.every(A=>A.timestamp<s),C=null,I=null;if(x){if(!n.closed)return}else for(let A=0;A<n.packets.length;A++){let P=n.packets[A];if(C!==null&&P.timestamp>s)break;A>0&&P.type==="key"&&(C=P,I=A)}if(I!==null){if(o=I,a){let A=a.packets.findIndex(P=>P.timestamp>=C.timestamp);if(A!==-1)c=A;else if(a.closed)c=a.packets.length;else return}}else{if(!n.closed)return;o=n.packets.length;let A=td(n.packets,E=>E.timestamp),P=n.packets[A];if(b(P),a)if(P.timestamp<s){let E=a.packets.findIndex(v=>v.timestamp>=s);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}else{let E=a.packets.findIndex(v=>v.timestamp>P.timestamp);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}}}else if(a&&(!a.closed||a.packets.length>0))if(a.packets.every(C=>C.timestamp<s))if(a.closed)c=a.packets.length;else return;else{let C=qr(a.packets,I=>I.timestamp<=s);c=Math.max(C,1)}if(o===0&&c===0){r.every(C=>C.closed)&&await this.onPlaylistDone(e);return}let u=null,l,d;b(this.output._target instanceof ut);let m=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let x={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Ac(e)};l=await this.getSegmentPath(x),ep(l),d=xe(xe(m.rootPath,e.path),l);let C=await this.output._getTarget({path:d,isRoot:!1,mimeType:e.segmentFormat.mimeType}),I=null;if(e.segmentFormat._isFragmentedIsobmff()){I={output:new br({format:e.segmentFormat,target:C}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},C.on("write",({end:E})=>{I.currentFileSize=Math.max(I.currentFileSize,E)});let A=I.output._muxer;A.minimumFragmentDuration=1/0;let P=A.formatOptions.onMoof;A.formatOptions.onMoof=(E,v,M)=>{I.firstMoofPosition=v,P?.(E,v,M),A.formatOptions.onMoof=P},n&&(I.videoSource=new Ur(n.track.source._codec),I.output.addVideoTrack(I.videoSource,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(I.audioSource=new zr(a.track.source._codec),I.output.addAudioTrack(I.audioSource,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await I.output.start()}else C._start();e.singleFile={target:C,path:l,nextOffset:0,info:x,fragmentedIsobmffOutput:I}}else l=e.singleFile.path,d=xe(xe(m.rootPath,e.path),l);else u={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Ac(e)},l=await this.getSegmentPath(u),ep(l),d=xe(xe(m.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,g=-1/0,h=null,y=null,k=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(h=e.singleFile.fragmentedIsobmffOutput.output,y=e.singleFile.fragmentedIsobmffOutput.videoSource,k=e.singleFile.fragmentedIsobmffOutput.audioSource):(h=new br({format:e.segmentFormat,target:new ut(d,async x=>{let C={...x,isRoot:!1};if(x.isRoot)if(e.singleFile){let I=e.singleFile.target.slice(e.singleFile.nextOffset);return I.on("write",({end:A})=>f=Math.max(f,A)),I}else{let I=await this.output._getTarget(C);return p=I,I.on("write",({end:A})=>f=Math.max(f,A)),I}return this.output._getTarget(C)}),initTarget:async()=>{if(e.initSegment)return new ki;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:C})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,C)}),x.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),x}else{let x=Ac(e),C=await this.getInitPath(x);db(C),e.initSegment={path:C,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let I=xe(xe(m.rootPath,e.path),C),A=await this.output._getTarget({path:I,isRoot:!1,mimeType:e.segmentFormat.mimeType});return A.on("write",({end:P})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,P)}),A.on("finalized",()=>{this.format._options.onInit?.(A,x)}),A}}}),n&&(y=new Ur(n.track.source._codec),h.addVideoTrack(y,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(k=new zr(a.track.source._codec),h.addAudioTrack(k,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await h.start()),n){b(y);let x={decoderConfig:n.info.decoderConfig};for(let C=0;C<o;C++){let I=n.packets[C];await y.add(I,x),g=Math.max(g,I.timestamp+I.duration)}}if(a){b(k);let x={decoderConfig:a.info.decoderConfig};for(let C=0;C<c;C++){let I=a.packets[C];await k.add(I,x),g=Math.max(g,I.timestamp+I.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),f=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await h.finalize()}catch(x){throw await h?.cancel(),x}u&&(b(p),this.format._options.onSegment?.(p,u)),o>0&&(b(n),n.packets.splice(0,o)),c>0&&(b(a),a.packets.splice(0,c));let T=1/0;n&&n.packets.length>0&&(T=n.packets[0].timestamp),a&&a.packets.length>0&&(T=Math.min(T,a.packets[0].timestamp));let w=T<1/0?T:g;b(Number.isFinite(w));let S=w-e.currentSegmentStartTimestamp;if(b(S>=0),e.writtenSegments.push({path:l,duration:S,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:u??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,S),e.currentSegmentStartTimestamp=w,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),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()}}}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)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let r=e.writtenSegments,n=0,a=0,s=0;for(let c=0;c<r.length;c++){s+=r[c].duration;let u=0,l=0;for(let d=c;d<r.length&&(u+=r[d].byteSize,l+=r[d].duration,l>=.5*this.globalTargetDuration&&l<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*u/l)),!(l>1.5*this.globalTargetDuration));d++);}if(n===0)for(let c of r){let u=c.duration||1;n=Math.max(n,8*c.byteSize/u)}for(let c of r)a+=8*c.byteSize;let o=a/(s||1);if(r.length===0)for(let c of e.tracks){let u=this.trackDatas.find(d=>d.track===c),l=c.source._nominalBitrate??c.metadata.bitrate??0;if(o+=c.source._nominalBitrate??c.metadata.averageBitrate??0,l===0){let d=new oe("medium");if(c.isVideoTrack()){let m=u?.info.decoderConfig;l=d._toVideoBitrate(c.source._codec,m?.codedWidth??1920,m?.codedHeight??1080)}else c.isAudioTrack()&&(l=d._toAudioBitrate(c.source._codec)??0)}n+=l}e.peakBitrate=n,e.averageBitrate=o}async writePlaylist(e){b(this.output._target instanceof ut);let r=this.output._target;this.updatePlaylistBitrates(e);let n=!1;for(let m of e.writtenSegments)n||=m.byteOffset!==null;let a=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,s=3;(a||n)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!a&&(s=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,c=xe(r.rootPath,e.path),u=`#EXTM3U
17
+ ${r.notes??""}`,d=this.createInternalChunk(u,r.timestamp,r.duration,"key",l.trim()?Z.encode(l):null);s.chunkQueue.push(d),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&&!s.closed)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.writeBlock(r,a)}e||await this.writer.flush()}}fixVP9ColorSpace(e,r){if(r.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let n=new H(r.data);n.skipBits(2);let a=n.readBits(1),o=(n.readBits(1)<<1)+a;if(o===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;o>=2&&n.skipBits(1);let d={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];zl(r.data,n.pos,n.pos+3,d)}createInternalChunk(e,r,n,a,s=null){return{data:e,type:a,timestamp:r,duration:n,additions:s}}writeBlock(e,r){this.segment||this.createSegment();let n=Math.round(1e3*r.timestamp),a=this.trackDatas.every(m=>{if(e===m)return r.type==="key";let f=m.chunkQueue[0];return f?f.type==="key":m.closed}),s=!1;if(!this.currentCluster)s=!0;else{b(this.currentClusterStartMsTimestamp!==null),b(this.currentClusterMaxMsTimestamp!==null);let m=n-this.currentClusterStartMsTimestamp;s=a&&n>this.currentClusterMaxMsTimestamp&&m>=1e3*(this.format._options.minimumClusterDuration??1)||m>$g}s&&this.createNewCluster(n);let o=n-this.currentClusterStartMsTimestamp;if(o<Xg){if(!this.warnedAboutTooNegativeTimestamp){let m=this.format instanceof Ti?"WebM":"Matroska";V._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${m}.`),this.warnedAboutTooNegativeTimestamp=!0}return}let c=new Uint8Array(4),u=new DataView(c.buffer);u.setUint8(0,128|e.track.id),u.setInt16(1,o,!1);let l=Math.round(1e3*r.duration);if(!!r.additions||e.type==="subtitle"){let m={id:160,data:[{id:161,data:[c,r.data]},r.type==="delta"?{id:251,data:new fa(e.lastWrittenMsTimestamp-n)}:null,r.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:r.additions}]}]}:null,l>0?{id:155,data:l}:null]};this.ebmlWriter.writeEBML(m)}else{u.setUint8(3,+(r.type==="key")<<7);let m={id:163,data:[c,r.data]};this.ebmlWriter.writeEBML(m)}this.startTimestamp=Math.min(this.startTimestamp,n),this.endTimestamp=Math.max(this.endTimestamp,n+l),e.lastWrittenMsTimestamp=n,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:n}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,n)}createNewCluster(e){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:Kf,data:[{id:231,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(b(this.currentCluster),!this.format._options.appendOnly){let a=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),s=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(a,Kf),this.writer.seek(s)}if(this.format._options.onCluster){b(this.currentClusterStartMsTimestamp!==null);let{data:a,start:s}=this.writer.stopTrackingWrites();this.format._options.onCluster(a,s,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(let[a,{firstMsTimestamp:s}]of this.trackDatasInCurrentCluster)r.has(s)||r.set(s,[]),r.get(s).push(a);let n=[...r.entries()].sort((a,s)=>a[0]-s[0]);for(let[a,s]of n)b(this.cues),this.cues.data.push({id:187,data:[{id:179,data:Math.max(0,a)},...s.map(o=>({id:183,data:[{id:247,data:o.track.id},{id:241,data:e}]}))]})}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),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,qf);let n=this.startTimestamp===1/0?0:this.endTimestamp;this.segmentDuration.data=new yn(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)}e()}};var dc=class{constructor(t){this.writer=t;this.helper=new Uint8Array(8);this.helperView=new DataView(this.helper.buffer)}writeU32(t){this.helperView.setUint32(0,t,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(t){let e=this.writer.getPos(),r=255,n=224|t.mpegVersionId<<3|t.layer<<1,a;t.mpegVersionId&2?a=t.mpegVersionId&1?0:1:a=1;let s=0,o=155,c=-1,u=a*16*4+t.layer*16;for(let h=0;h<16;h++){let y=Ws[u+h];if(Hs(a,t.layer,1e3*y,t.sampleRate,s)>=o){c=h;break}}if(c===-1)throw new Error("No suitable bitrate found.");let l=c<<4|t.frequencyIndex<<2|s<<1,d=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]=l,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));let m=Yr(t.mpegVersionId,t.channel);this.writer.seek(e+m),this.writeU32($r);let f=0;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.writer.write(t.toc??new Uint8Array(100));let p=Ws[u+c],g=Hs(a,t.layer,1e3*p,t.sampleRate,s);this.writer.write(new Uint8Array(e+g-this.writer.getPos()))}};var mc=class extends Ie{constructor(e,r){super(e);this.xingFrameData=null;this.frameCount=0;this.framePositions=[];this.xingFramePos=null;this.format=r,this.writeXingHeader=r._options.xingHeader!==!1}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!this.writeXingHeader),this.mp3Writer=new dc(this.writer),Cr(this.output._metadataTags)||new gi(this.writer).writeId3V2Tag(this.output._metadataTags),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.xingFrameData&&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=Zr(s,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");let c=Yr(o.mpegVersionId,o.channel);if(a.byteLength>=c+4){let u=a.getUint32(c,!1);if(u===$r||u===fn)return}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,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}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=Zr(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,frameCount:null,fileSize:null,toc:null}}else if(n.metadata.decoderConfig){let{sampleRate:s,numberOfChannels:o}=n.metadata.decoderConfig,c=[3,2,0],u=null,l=-1;for(let d=0;d<c.length;d++)if(l=ou.indexOf(s<<d),l!==-1){u=c[d];break}if(u===null)throw new Error(`${s} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:u,layer:1,frequencyIndex:l,sampleRate:s,channel:o===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,frameCount:null,fileSize:null,toc: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),this.frameCount++}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)),u=this.framePositions[c]-this.xingFramePos;s[o]=256*(u/a)}this.xingFrameData.toc=s}if(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 Zg=8192,fc=class extends Ie{constructor(e,r){super(e);this.trackDatas=[];this.bosPagesWritten=!1;this.allTracksKnown=ee();this.pageBytes=new Uint8Array(uo);this.pageView=new DataView(this.pageBytes.buffer);this.format=r}async start(){let e=await this.mutex.acquire();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});e()}async getMimeType(){return await this.allTracksKnown.promise,co({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(o=>o.track===e);if(n)return n;let a;do a=Math.floor(2**32*Math.random());while(this.trackDatas.some(o=>o.serialNumber===a));b(e.source._codec==="vorbis"||e.source._codec==="opus"),Ce(r,e.source._codec),b(r),b(r.decoderConfig);let s={track:e,serialNumber:a,internalSampleRate:e.source._codec==="opus"?Ft:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],startTimestampInSamples:null,currentTimestampInSamples:0,audioPacketCount:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(b(r.decoderConfig),e.track.source._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 h=0;for(;;){let y=n[a++];if(y===void 0)throw new TypeError("Vorbis decoder description is too short.");if(h+=y,y<255)return h}},o=s(),c=s();if(n.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");let l=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=ia(m,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!1},{data:d,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0});let g=N(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(g&15),1<<(g>>4)],modeBlockflags:Es(d).modeBlockflags}}else if(e.track.source._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=N(a);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);let o=ia(a,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0},{data:o,timestampInSamples:0,durationInSamples:0,trimmedDurationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Qr(n).preSkip}}}async addEncodedAudioPacket(e,r,n){let a=await this.mutex.acquire();try{let s=this.getTrackData(e,n);if(this.validateTimestamp(s.track,r.timestamp,r.type==="key"),s.startTimestampInSamples===null){let m=Math.round(r.timestamp*s.internalSampleRate),f=s.codecInfo.opusInfo?.preSkip??0;s.startTimestampInSamples=m>0?m+f:0,s.currentTimestampInSamples=s.startTimestampInSamples}let o=s.currentTimestampInSamples,{durationInSamples:c,vorbisBlockSize:u}=ya(r.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=c,s.vorbisLastBlocksize=u;let l=r.duration>0?J(Math.round(r.duration*s.internalSampleRate),0,c):c,d=s.startTimestampInSamples>0&&s.audioPacketCount===1;s.audioPacketCount++,s.packetQueue.push({data:r.data,timestampInSamples:o,durationInSamples:c,trimmedDurationInSamples:l,forcePageFlush:d}),await this.interleavePages()}finally{a()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!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&&!o.closed)break e;o.packetQueue.length>0&&o.packetQueue[0].timestampInSamples<n&&(r=o,n=o.packetQueue[0].timestampInSamples)}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+(n?r.trimmedDurationInSamples:r.durationInSamples);if(e.currentLacingValues.length===0&&(e.currentPageStartTimestampInSamples=r.timestampInSamples),this.format._options.maximumPageDuration!==void 0){let l=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&a-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=r.data.length,o=0,c=0;for(;;){e.currentLacingValues.length===0&&o>0&&(e.currentPageStartsWithFreshPacket=!1);let l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,c+=l;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 u=r.data.subarray(o);e.currentPageData.push(u),e.currentPageSize+=u.length,e.currentGranulePosition=a,(e.currentPageSize>=Zg||r.forcePageFlush)&&this.writePage(e,n)}writePage(e,r){this.pageView.setUint32(0,ba,!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(u=>u===255)?-1:e.currentGranulePosition;Gl(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 u of e.currentPageData)this.pageBytes.set(u,s),s+=u.length;let o=this.pageBytes.subarray(0,s),c=dm(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:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(u,l,e.track.source)}}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0;await this.interleavePages(!0);for(let r of this.trackDatas)r.currentLacingValues.length>0&&this.writePage(r,!0);e()}};var Jg=0,$f=4096,Gf=256,eb=224,Qf=192,jf=new Uint8Array([9,240]),Xf=new Uint8Array([70,1]),pc=class extends Ie{constructor(e,r){super(e);this.trackDatas=[];this.tablesWritten=!1;this.continuityCounters=new Map;this.packetBuffer=new Uint8Array(188);this.packetView=N(this.packetBuffer);this.allTracksKnown=ee();this.videoTrackIndex=0;this.audioTrackIndex=0;this.adaptationFieldBuffer=new Uint8Array(184);this.payloadBuffer=new Uint8Array(184);this.format=r}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,yo(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;nr(r,e.source._codec),b(r?.decoderConfig);let a=e.source._codec;b(a==="avc"||a==="hevc");let s=a==="avc"?27:36,o=Gf+this.trackDatas.length,c=eb+this.videoTrackIndex++,u={track:e,pid:o,streamType:s,streamId:c,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(u),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,r){let n=this.trackDatas.find(l=>l.track===e);if(n)return n;Ce(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,o;switch(a){case"aac":s=15,o=Qf+this.audioTrackIndex++;break;case"mp3":s=3,o=Qf+this.audioTrackIndex++;break;case"ac3":s=129,o=189;break;case"eac3":s=135,o=189;break;case"dts":s=130,o=189;break}let c=Gf+this.trackDatas.length,u={track:e,pid:c,streamType:s,streamId:o,codecString:r.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!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(e.inputIsAnnexB=!s,!e.inputIsAnnexB){let o=Q(s);a==="avc"?e.avcDecoderConfig=tr(o):e.hevcDecoderConfig=ln(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(r.data,a):this.prepareLengthPrefixedVideoPacket(e,r,a)}prepareAnnexBVideoPacket(e,r){let n=[];for(let s of Gr(e)){let o=e.subarray(s.offset,s.offset+s.length);(r==="avc"?Jt(o[0])===9:Rt(o[0])===35)||n.push(o)}let a=r==="avc"?jf:Xf;return n.unshift(a),ta(n)}prepareLengthPrefixedVideoPacket(e,r,n){let a=r.data,s=n==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,o=[];for(let u of As(a,s)){let l=a.subarray(u.offset,u.offset+u.length);(n==="avc"?Jt(l[0])===9:Rt(l[0])===35)||o.push(l)}if(r.type==="key")if(n==="avc"){let u=e.avcDecoderConfig;for(let l of u.pictureParameterSets)o.unshift(l);for(let l of u.sequenceParameterSets)o.unshift(l)}else{let u=e.hevcDecoderConfig;for(let l of u.arrays)if(l.nalUnitType===34)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===33)for(let d of l.nalUnits)o.unshift(d);for(let l of u.arrays)if(l.nalUnitType===32)for(let d of l.nalUnits)o.unshift(d)}let c=n==="avc"?jf:Xf;return o.unshift(c),ta(o)}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 u=n?.decoderConfig?.description;if(e.inputIsAdts=!u,!e.inputIsAdts){let l=Zt(Q(u)),d=Ts(l);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}}if(e.inputIsAdts)return r.data;b(e.adtsHeader),b(e.adtsHeaderBitstream);let s=e.adtsHeader,o=r.data.byteLength+s.byteLength;ws(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(!e.source._closed&&!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];s.decodeTimestamp=n[a],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&&!s.closed)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(Jg,Qi),this.writePsiSection($f,rb(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,u=Math.min(o,c),l;a?(l=this.payloadBuffer.subarray(0,1+u),l[0]=0,l.set(r.subarray(n,n+u),1)):l=r.subarray(n,n+u),this.writeTsPacket(e,a,null,l),n+=u,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 H(s.subarray(9));Pi(o,0,1,!1),s[3]=e.streamId;let u=e.track.type==="video"?0:Math.min(8+r.data.length,65535);o.setUint16(4,u,!1),o.setUint8(6,132),o.setUint8(7,n?192:128),o.setUint8(8,a);let l=Math.round(r.presentationTimestamp*9e4),d=Gc(l,8589934592);if(c.pos=0,c.writeBits(4,n?3:2),c.writeBits(3,Math.floor(d/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(d/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,d%2**15),c.writeBits(1,1),n){b(r.decodeTimestamp!==null);let g=Math.round(r.decodeTimestamp*9e4),h=Gc(g,8589934592);c.writeBits(4,1),c.writeBits(3,Math.floor(h/2**30)),c.writeBits(1,1),c.writeBits(15,Math.floor(h/2**15)%2**15),c.writeBits(1,1),c.writeBits(15,h%2**15),c.writeBits(1,1)}let m=s.length+r.data.length,f=0,p=!0;for(;f<m;){let g=p,h=m-f,y=p&&r.isKeyframe,k=p&&!e.firstPacketWritten,w=Math.max(0,184-h),T;y||k?T=Math.max(2,w):T=w;let S=null;if(T>0){let E=this.adaptationFieldBuffer;T===1?E[0]=0:(E[0]=T-1,E[1]=Number(k)<<7|Number(y)<<6,E.fill(255,2,T)),S=E.subarray(0,T)}let x=Math.min(184-T,h),C=this.payloadBuffer.subarray(0,x),P=0;if(f<s.length){let E=Math.min(s.length-f,x);C.set(s.subarray(f,f+E),0),P=E}let A=Math.max(0,f-s.length),I=A+(x-P);P<x&&C.set(r.data.subarray(A,I),P),this.writeTsPacket(e.pid,g,S,C),f+=x,p=!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 u=4;n&&(this.packetBuffer.set(n,u),u+=n.length),this.packetBuffer.set(a,u),u+=a.length,u<188&&this.packetBuffer.fill(255,u);let l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){let r=await this.mutex.acquire(),n=this.trackDatas.find(a=>a.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),r()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let r of this.trackDatas)r.closed=!0,await this.flushTimestampQueue(r,!1);await this.interleavePackets(!0),e()}},tb=79764919,Yf=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^tb:t<<1;Yf[i]=t>>>0&4294967295}var Zf=i=>{let t=4294967295;for(let e=0;e<i.length;e++){let r=i[e];t=(t<<8^Yf[t>>>24^r])>>>0}return t},Qi=new Uint8Array(16);{let i=N(Qi);Qi[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),Qi[5]=193,Qi[6]=0,Qi[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|$f&8191,!1),i.setUint32(12,Zf(Qi.subarray(0,12)),!1)}var rb=i=>{let t=0;for(let c of i)t+=5,c.streamType===129?t+=aa.length:c.streamType===135&&(t+=sa.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)r[a++]=c.streamType,n.setUint16(a,57344|c.pid&8191,!1),a+=2,c.streamType===129?(n.setUint16(a,61440|aa.length,!1),a+=2,r.set(aa,a),a+=aa.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=Zf(r),o=new Uint8Array(r.length+4);return o.set(r,0),N(o).setUint32(r.length,s,!1),o};var hc=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(Z.encode(t))}};var gc=class extends Ie{constructor(e,r){super(e);this.headerWritten=!1;this.dataSize=0;this.sampleRate=null;this.sampleCount=0;this.riffSizePos=null;this.dataSizePos=null;this.ds64RiffSizePos=null;this.ds64DataSizePos=null;this.ds64SampleCountPos=null;this.format=r,this.isRf64=!!r._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new hc(this.writer);let r=this.output.tracks[0];b(r?.isAudioTrack()),r.metadata.decoderConfig&&(Ce({decoderConfig:r.metadata.decoderConfig},r.source._codec),this.writeHeader(r,r.metadata.decoderConfig),this.sampleRate=r.metadata.decoderConfig.sampleRate,this.headerWritten=!0),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||(Ce(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=Re(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,u=s.sampleSize*o;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(o),this.riffWriter.writeU32(c),this.riffWriter.writeU32(c*u),this.riffWriter.writeU16(u),this.riffWriter.writeU16(8*s.sampleSize),!Cr(this.output._metadataTags)){let l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):ae(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:l,start:d}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,d)}}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,u)=>{if(!vt(u)){V._warn(`Didn't write tag '${c}' because '${u}' is not ISO 8859-1-compatible.`);return}let l=u.length+1,d=new Uint8Array(l);for(let m=0;m<u.length;m++)d[m]=u.charCodeAt(m);this.riffWriter.writeAscii(c),this.riffWriter.writeU32(l),this.writer.write(d),l&1&&this.writer.write(new Uint8Array(1)),n.add(c)};for(let{key:c,value:u}of _t(e))switch(c){case"title":a("INAM",u),n.add("INAM");break;case"artist":a("IART",u),n.add("IART");break;case"album":a("IPRD",u),n.add("IPRD");break;case"trackNumber":{let l=e.tracksTotal!==void 0?`${u}/${e.tracksTotal}`:u.toString();a("ITRK",l),n.add("ITRK")}break;case"genre":a("IGNR",u),n.add("IGNR");break;case"date":a("ICRD",u.toISOString().slice(0,10)),n.add("ICRD");break;case"comment":a("ICMT",u),n.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"beatsPerMinute":case"description":case"lyrics":case"images":break;case"raw":break;default:ae(c)}if(e.raw)for(let c in e.raw){let u=e.raw[c];u==null||c.length!==4||n.has(c)||typeof u=="string"&&a(c,u)}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 gi(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.");let r=this.writer.getPos();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 bc=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 u=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+u,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=t.timestamp-this.startTime,s=a+t.duration,o=Math.floor((a-1/this.sourceSampleRate)*this.targetSampleRate)+1,c=Math.ceil(s*this.targetSampleRate);for(let u=o;u<c;u++){if(u<this.bufferStartFrame)continue;for(;u>=this.bufferStartFrame+this.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let l=u-this.bufferStartFrame;b(l<this.bufferCapacityInFrames);let f=(u/this.targetSampleRate-a)*this.sourceSampleRate,p=Math.floor(f),g=Math.ceil(f),h=f-p;for(let y=0;y<this.targetNumberOfChannels;y++){let k=0,w=0;p>=0&&p<t.numberOfFrames&&(k=this.channelMixer(n,p,y)),g>=0&&g<t.numberOfFrames&&(w=this.channelMixer(n,g,y));let T=k+h*(w-k),S=l*this.targetNumberOfChannels+y;this.outputBuffer[S]+=T}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}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 Ae({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:e});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 ji=class{constructor(){this._connectedTrack=null;this._closingPromise=null;this._closed=!1;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._closed)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),this._closed=!0,!(t.output.state==="finalizing"||t.output.state==="finalized")&&t.output._muxer.onTrackClose(t)})()}async _flushOrWaitForOngoingClose(t){return this._closingPromise??=(async()=>{await this._flushAndClose(t),this._closed=!0})()}},hr=class extends ji{constructor(t){if(super(),!ce.includes(t))throw new TypeError(`Invalid video codec '${t}'. Must be one of: ${ce.join(", ")}.`);this._codec=t}},Cl=(i,t)=>{if(i.metadata.hasOnlyKeyPackets&&t.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Ur=class extends hr{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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(),Cl(this._connectedTrack,t),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,t,e)}},Ya=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=-1;this.emittedEncoderPackets=0;this.chunkTimestampsAreShiftedByDuration=!1;this.codedWidth=null;this.codedHeight=null;this.outputWidth=null;this.outputHeight=null;this.frameRateLastSample=null;this.frameRateLastTimestamp=null;this.frameRateLastEndTimestamp=null;this.preciseTimings=[];this.customEncoder=null;this.customEncoderCallSerializer=new Lr;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;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,s=a.sizeChangeBehavior??"deny",o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((t.codedWidth!==this.codedWidth||t.codedHeight!==this.codedHeight)&&(o=!0,s==="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(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.flip!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||o&&s!=="passThrough"){let d=a.transform?.width,m=a.transform?.height,f=a.transform?.fit??"fill";o&&s!=="passThrough"&&(b(this.outputWidth),b(this.outputHeight),b(s!=="deny"),d=this.outputWidth,m=this.outputHeight,f=s);let p=await t.transform({width:d,height:m,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,flip:a.transform?.flip,fit:f,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),e&&t.close(),t=p,e=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=t.codedWidth,this.outputHeight=t.codedHeight);let l=a.transform?.frameRate;if(l!==void 0){let d=t.timestamp+t.duration,m=Qc(t.timestamp,l);if(this.frameRateLastSample!==null)if(m<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=t.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(m,r);t===n&&(t=t.clone(),e=!0),t.setTimestamp(m),t.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=t.clone(),this.frameRateLastTimestamp=m,this.frameRateLastEndTimestamp=d}await this.processAndEncode(t,r)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig,n;if(r.transform?.process){let a=r.transform.process(t);if(_(a)&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);let s=[];try{for(let o of a)o instanceof Ge?s.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?s.push(new Ge(o)):s.push(new Ge(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 Ge&&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},u={...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 l=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,u)).catch(m=>this.setError(m)).finally(()=>{this.customEncoderQueueSize--,l.close()});this.customEncoderQueueSize>=4&&await d}else{b(this.encoder);let l=a.toVideoFrame(),d=G(this.preciseTimings,l.timestamp,f=>f.microsecondTimestamp),m=d!==-1?this.preciseTimings[d]:null;if(m&&m.microsecondTimestamp===l.timestamp?(m.timestamp!==a.timestamp&&(m.timestampIsValid=!1),m.duration!==a.duration&&(m.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:l.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(l,u)}finally{l.close()}}else{this.splitter||(this.splitter=new Pl);let{colorFrame:p,alphaFrame:g}=await this.splitter.split(l);this.alphaFrameQueue.push(g);try{this.encoder.encode(p,u)}finally{p.close()}}else try{this.encoder.encode(l,u)}finally{l.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 u=1;u<n;u++){var a=[];try{let l=dt(a,this.frameRateLastSample.clone());l.setTimestamp(this.frameRateLastTimestamp+u/r);l.setDuration(1/r);await this.processAndEncode(l,e)}catch(s){var o=s,c=!0}finally{mt(a,o,c)}}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let e=di(this.encodingConfig.quality,this.encodingConfig.bitrate);b(e!==void 0);let r=Zu({...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=Dn.find(l=>l.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(an("VideoEncoder"));let o=r[0].config,c=r.map(({config:u,quantizer:l})=>l!==null?`quantizer ${l}`:`${u.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=el(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 j))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.");Cl(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init()):(this.encoderConfig=s,this.encodingConfig.codec==="avc"&&Xt()&&(this.chunkTimestampsAreShiftedByDuration=await nb()),this.createWebCodecsEncoders()),b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}createWebCodecsEncoders(){let t=this.encoderConfig;b(t);let e=[],r=[],n=0,a=0,s=(c,u)=>{if(Yl(c)){this.encodersReclaimed=!0;return}c.stack=u,this.setError(c)},o=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(c,u)=>{if(!this.alphaEncoder){this.addPacket(c,null,u);return}let l=this.alphaFrameQueue.shift();b(l!==void 0),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:c.type==="key"}),a++,l.close(),e.push({chunk:c,meta:u})):a===0?this.addPacket(c,null,u):(r.push(n+a),e.push({chunk:c,meta: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:(u,l)=>{a--;let d=e.shift();for(b(d!==void 0),this.addPacket(d.chunk,u,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)}},error:u=>s(u,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=j.fromEncodedChunk(t,n),s=this.encoderConfig;if(b(s),r?.decoderConfig&&(r.decoderConfig.codec=Xr({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?er(a.data):null,hevcCodecInfo:this.encodingConfig.codec==="hevc"&&!r.decoderConfig.description?ir(a.data):null,vp9CodecInfo:this.encodingConfig.codec==="vp9"?dn(a.data):null,av1CodecInfo:this.encodingConfig.codec==="av1"?Mi(a.data):null,proresFormat:null}),this.encodingConfig.codec==="avc"&&r.decoderConfig.description&&Xt())){let d=tr(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=un({...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=G(this.preciseTimings,o,d=>d.microsecondTimestamp),u=c!==-1?this.preciseTimings[c]:null,l=null;this.emittedEncoderPackets===0&&a.type==="delta"&&r?.decoderConfig&&(l=jr(this.encodingConfig.codec,r.decoderConfig,a.data)),(u&&u.microsecondTimestamp===o||l!==null)&&(a=a.clone({timestamp:u?.timestampIsValid?u.timestamp:void 0,duration:u?.durationIsValid?u.duration:void 0,type:l??void 0})),Cl(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=-1,this.createWebCodecsEncoders()}async flushAndClose(t){try{if(!t&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,r=Qc(this.frameRateLastEndTimestamp,e);await this.padFrameRate(r)}this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&!this.encodersReclaimed&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await Kr(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||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},ib=null,nb=()=>ib??=(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!1}finally{t.state!=="closed"&&t.close()}return i===500})(),Sl=null,Pl=class{constructor(){this.worker=null;this.pendingRequests=new Map;this.nextRequestId=0}split(t){if(!this.worker){if(!Sl){let n=new Blob([`(${ab.toString()})()`],{type:"application/javascript"});Sl=URL.createObjectURL(n)}this.worker=new Worker(Sl),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=ee();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()}},ab=()=>{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:u}=await e(o);self.postMessage({id:s,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}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,u=o.visibleRect?.height??o.codedHeight,l=c*u,d=Math.ceil(c/2),m=Math.ceil(u/2),f=l+d*m*2,p=new Uint8Array(f);for(let k=0,w=3;k<l;k++,w+=4)p[k]=a[w];p.fill(128,l);let g=new VideoFrame(a,{format:s==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),h={format:"I420",codedWidth:c,codedHeight:u,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,u=o.visibleRect?.height??o.codedHeight,l=s.includes("P10"),d=s.includes("P12"),m=l||d?2:1,f,p;s.startsWith("I420")?(f=Math.ceil(c/2),p=Math.ceil(u/2)):s.startsWith("I422")?(f=Math.ceil(c/2),p=u):(f=c,p=u);let g=c*u,h=f*p,y=g*m,k=h*m,w=g*m,T=y+k*2,S=s.replace("A",""),x=Math.ceil(c/2),C=Math.ceil(u/2),P=x*C,A=P*m,I=w+2*A,E=new Uint8Array(I),v=T;E.set(a.subarray(v,v+w),0);let R=w,B=l?512:d?2048:128;m===1?E.fill(B,R):new Uint16Array(E.buffer,R,2*P).fill(B);let z=l?"I420P10":d?"I420P12":"I420",D=new VideoFrame(a.subarray(0,T),{format:S,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0}),q={format:z,codedWidth:c,codedHeight:u,timestamp:o.timestamp,duration:o.duration??void 0,colorSpace:{fullRange:!0,matrix:"bt709",primaries:"bt709",transfer:"bt709"},transfer:[E.buffer]},ie=new VideoFrame(E,q);return{colorFrame:D,alphaFrame:ie}}},Xi=class extends hr{constructor(t){$o(t),super(t.codec),this._encoder=new Ya(this,t)}add(t,e){if(!(t instanceof Ge))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(t,!1,e)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},yc=class extends hr{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.");$o(e),super(e.codec),this._encoder=new Ya(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.");let n=new Ge(this._canvas,{timestamp:t,duration:e});return this._encoder.add(n,!0,r)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},kc=class extends hr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if($o(r),typeof n!="object"||!n)throw new TypeError("options must be an object.");if(n.frameRate!=null&&(typeof n.frameRate!="number"||n.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a 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=ee();this._errorPromiseAccessed=!1;this._paused=!1;this._lastVideoFrame=null;this._timerHandle=null;this._videoElement=null;this._options=n,this._encoder=new Ya(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._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=0,s=!1,o=null,c=0,u=()=>{if(b(e!==null),!this._lastVideoFrame)return;b(n!==null),b(r!==null);let m=performance.now();for(;m-n>1e3/e;){n+=1e3/e;let f=r+a/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});d(p,m)}};e!==null&&(this._timerHandle=nd(u,4));let l=m=>{if(e===null)d(m);else{let f=performance.now();this._lastVideoFrame?(u(),this._lastVideoFrame?.close(),this._lastVideoFrame=m):(d(m.clone(),f),n=f,this._lastVideoFrame=m)}},d=(m,f=performance.now())=>{if(s){m.close();return}a++;let p=m.timestamp/1e6;if(this._paused){if(r!==null){if(o!==null&&this._options.timestampBase!=="unix"){let y=p-o;c-=y}o=p}m.close();return}if(r===null){r=p;let h,y=this._options.timestampBase??"synced-zero";if(y==="unix")h=Date.now()/1e3;else if(y==="zero")h=0;else{let k=this._connectedTrack.output;k._firstMediaStreamTimestamp===null?(k._firstMediaStreamTimestamp=f/1e3,h=0):h=f/1e3-k._firstMediaStreamTimestamp}c=h-r}if(o=p,this._encoder.getQueueSize()>=8){m.close();return}let g=new Ge(m,{timestamp:p+c});this._encoder.add(g,!0).catch(h=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(h),this._workerTrackId!==null&&xl({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let m=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});m.readable.pipeTo(f,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await ub())this._workerTrackId=ob++,xl({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{let p=f.data;p.type==="videoFrame"&&p.trackId===this._workerTrackId?l(p.videoFrame):p.type==="error"&&p.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(p.error)},Et.addEventListener("message",this._workerListener);else if(e!==null){let f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=new MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;let p=new VideoFrame(f,{timestamp:1e3*performance.now()});l(p),p.close()},{once:!0}),f.play().catch(p=>{s=!0,this._promiseWithResolvers.reject(p)})}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&&ad(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(b(this._workerListener),xl({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),Et.removeEventListener("message",this._workerListener),Et.removeEventListener("message",n),r())};Et.addEventListener("message",n)}))}finally{await this._encoder.flushAndClose(e)}}},gr=class extends ji{constructor(t){if(super(),!me.includes(t))throw new TypeError(`Invalid audio codec '${t}'. Must be one of: ${me.join(", ")}.`);this._codec=t}},zr=class extends gr{constructor(t){super(t)}add(t,e){if(!(t instanceof j))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)}},Za=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.isPcmEncoder=!1;this.outputSampleSize=null;this.writeOutputValue=null;this.customEncoder=null;this.customEncoderCallSerializer=new Lr;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){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),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 r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new bc({targetNumberOfChannels:r.transform.numberOfChannels??t.numberOfChannels,targetSampleRate:r.transform.sampleRate??t.sampleRate,onSample:async a=>{await this.processAndEncode(a,!0)}})),await this.resampler.add(t)):await this.processAndEncode(t,e)}finally{e&&t.close()}}async processAndEncode(t,e){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&Ym(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(_(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(let a of n)if(!(a instanceof Ae))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,!0)}finally{for(let a of n)a instanceof Ae&&a.close()}}finally{e&&t.close()}else await this.encodeSample(t,e)}async encodeSample(t,e){try{if(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=new Ae({data:new Float32Array(a*t.numberOfChannels),format:"f32-planar",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,numberOfFrames:a,timestamp:this.lastEndSampleIndex/t.sampleRate});await this.encodeSample(s,!0)}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);let r=t.toAudioData();this.encoder.encode(r),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,o=2048,c=[];for(let g=0;g<n;g+=o){let h=Math.min(o,t.numberOfFrames-g),y=h*r*this.outputSampleSize,k=new ArrayBuffer(y),w=new DataView(k);c.push({frameCount:h,view:w})}let u=t.format==="s32"||t.format==="s32-planar",l=u?"s32-planar":"f32-planar",d=u?1/2147483648:1,m=t.allocationSize({planeIndex:0,format:l}),f=u?new Int32Array(m/4):new Float32Array(m/4);for(let g=0;g<r;g++){t.copyTo(f,{planeIndex:g,format:l});for(let h=0;h<c.length;h++){let{frameCount:y,view:k}=c[h];for(let w=0;w<y;w++)this.writeOutputValue(k,(w*r+g)*this.outputSampleSize,f[h*o+w]*d)}}e&&t.close();let p={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}};for(let g=0;g<c.length;g++){let{frameCount:h,view:y}=c[g],k=y.buffer,w=g*o,T=new j(new Uint8Array(k),"key",s+w/a,h/a);this.encodingConfig.onEncodedPacket?.(T,p),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,T,p)}}ensureEncoder(t){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:e,sampleRate:r}=t,n=di(this.encodingConfig.quality,this.encodingConfig.bitrate),a=Ju({numberOfChannels:e,sampleRate:r,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(a),this.source._nominalBitrate=a.bitrate??null;let s=Vn.find(o=>o.supports(this.encodingConfig.codec,a));if(s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof j))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.");this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,o,c).catch(u=>{this.setError(u)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else if(ne.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(an("AudioEncoder"));let o;try{o=(await AudioEncoder.isConfigSupported(a)).supported??!1}catch{o=!1}if(!o)throw new Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);let c=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(u,l)=>{if(this.encodingConfig.codec==="aac"&&l?.decoderConfig){if(l.decoderConfig.description&&l.decoderConfig.description.byteLength>0&&Q(l.decoderConfig.description)[0]===3){let{decoderSpecificInfo:f}=Xs(we.tempFromBytes(Q(l.decoderConfig.description)));l.decoderConfig.description=f??void 0}let m=!1;if(!l.decoderConfig.description||l.decoderConfig.description.byteLength<2?m=!0:m=Zt(Q(l.decoderConfig.description)).objectType===0,m){let f=Number(Y(a.codec.split(".")));l.decoderConfig.description=cn({objectType:f,outputNumberOfChannels:l.decoderConfig.numberOfChannels,outputSampleRate:l.decoderConfig.sampleRate})}}let d=j.fromEncodedChunk(u);d=d.clone({timestamp:Gt(d.timestamp,a.sampleRate),duration:u.duration!=null?Gt(d.duration,a.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,l),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,l).catch(m=>{this.setError(m)})},error:u=>{u.stack=c,this.setError(u)}}),this.encoder.configure(a)}b(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let t=this.encodingConfig.codec,{dataType:e,sampleSize:r,littleEndian:n}=Re(t);switch(this.outputSampleSize=r,r){case 1:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint8(s,J(Math.round(o*128)+128,0,255)):e==="signed"?this.writeOutputValue=(a,s,o)=>{a.setInt8(s,J(Math.round(o*128),-128,127))}:e==="ulaw"?this.writeOutputValue=(a,s,o)=>{let c=J(Math.round(o*32768),-32768,32767);a.setUint8(s,hf(c))}:e==="alaw"?this.writeOutputValue=(a,s,o)=>{let c=J(Math.round(o*32768),-32768,32767);a.setUint8(s,bf(c))}:b(!1);break;case 2:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint16(s,J(Math.round(o*32768)+32768,0,65535),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt16(s,J(Math.round(o*32768),-32768,32767),n):b(!1);break;case 3:e==="unsigned"?this.writeOutputValue=(a,s,o)=>Pi(a,s,J(Math.round(o*8388608)+8388608,0,16777215),n):e==="signed"?this.writeOutputValue=(a,s,o)=>Kl(a,s,J(Math.round(o*8388608),-8388608,8388607),n):b(!1);break;case 4:e==="unsigned"?this.writeOutputValue=(a,s,o)=>a.setUint32(s,J(Math.round(o*2147483648)+2147483648,0,4294967295),n):e==="signed"?this.writeOutputValue=(a,s,o)=>a.setInt32(s,J(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:ae(r),b(!1)}}async flushAndClose(t){try{t||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,t||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):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||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}},Gn=class extends gr{constructor(t){Yo(t),super(t.codec),this._encoder=new Za(this,t)}add(t){if(!(t instanceof Ae))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(t,!1)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},Tc=class extends gr{constructor(t,e={}){if(Yo(t),typeof e!="object"||!e)throw new TypeError("options must be an object.");if(e.startTimestamp!==void 0&&!Number.isFinite(e.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(t.codec),this._encoder=new Za(this,t),this._accumulatedTime=e.startTimestamp??0}async add(t){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");let e=Ae._fromAudioBuffer(t,this._accumulatedTime);this._accumulatedTime+=t.duration;for(let r of e)await this._encoder.add(r,!0)}_flushAndClose(t){return this._encoder.flushAndClose(t)}},wc=class extends gr{constructor(e,r,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Yo(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=ee();this._errorPromiseAccessed=!1;this._paused=!1;this._options=n,this._encoder=new Za(this,r),this._track=e}get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}async _start(){this._errorPromiseAccessed||V._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){o.close();return}let c=o.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!=="unix"){let l=c-n;a-=l}n=c}o.close();return}if(e===null){e=o.timestamp;let u,l=this._options.timestampBase??"synced-zero";if(l==="unix")u=Date.now()/1e3;else if(l==="zero")u=0;else{let d=this._connectedTrack.output;d._firstMediaStreamTimestamp===null?(d._firstMediaStreamTimestamp=performance.now()/1e3,u=0):u=performance.now()/1e3-d._firstMediaStreamTimestamp}a=u-e}if(n=c,this._encoder.getQueueSize()>=8){o.close();return}o.setTimestamp(c+a),this._encoder.add(o,!0).catch(u=>{r=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(u),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let o=new MediaStreamTrackProcessor({track:this._track}),c=new WritableStream({write:u=>s(new Ae(u))});o.readable.pipeTo(c,{signal:this._abortController.signal}).catch(u=>{u instanceof DOMException&&u.name==="AbortError"||this._promiseWithResolvers.reject(u)})}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 u=0;this._scriptProcessorNode.onaudioprocess=l=>{let d=Ae._fromAudioBuffer(l.inputBuffer,u);u+=l.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.suspend())}finally{await this._encoder.flushAndClose(e)}}},sb=()=>{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:ae(n)}})},ob=0,Et=null,cb=()=>{let i=new Blob([`(${sb.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(i);Et=new Worker(t)},Al=null,ub=async()=>Al!==null?Al:(Et||cb(),new Promise(i=>{b(Et);let t=e=>{let r=e.data;r.type==="support"&&(Al=r.supported,Et.removeEventListener("message",t),i(r.supported))};Et.addEventListener("message",t)})),xl=(i,t)=>{b(Et),t?Et.postMessage(i,t):Et.postMessage(i)},$i=class extends ji{constructor(t){if(super(),!Xe.includes(t))throw new TypeError(`Invalid subtitle codec '${t}'. Must be one of: ${Xe.join(", ")}.`);this._codec=t}},Sc=class extends $i{constructor(e){super(e);this._error=null;this._errorSet=!1;this._lastMuxerPromise=Promise.resolve();this._parser=new nc({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 Jf=i=>i==="opus"?"Opus":i,xc=class extends Ie{constructor(e,r){if(!(e._target instanceof ut))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e);this.trackDatas=[];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.globalTargetDuration=this.targetSegmentDuration,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(),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,u=!1;for(let y of this.output.tracks){y.type==="video"&&(o=!0);let k=new Map;for(let w of this.output.tracks){if(y===w||!y.canBePairedWith(w))continue;if(y.type===w.type){c||(V._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||w.isVideoTrack()&&w.metadata.hasOnlyKeyPackets){u||(V._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),u=!0);continue}let T=k.get(w.source._codec);T||k.set(w.source._codec,T=[]),T.push(w)}for(let[,w]of k){let T=w.map(C=>C.id).join("-");s.find(C=>C.key===T)||s.push({name:w[0].type+"-"+(s.length+1),key:T,tracks:w,needsEmit:!1,firstNoUri:!1});let x=a.get(y);x||a.set(y,x=[]),x.push(T)}}let l=o?"video":"audio",d=[],m=[],f=[];for(let y of this.output.tracks){let k=a.get(y);if(k){if(b(k.length>0),y.type!==l)continue;for(let w of k){let T=s.find(S=>S.key===w);if(b(T),k.length===1&&T.tracks.length===1){let S=a.get(T.tracks[0]);if(b(S!==void 0),S.length===1){let x=s.find(C=>C.key===S[0]);if(x.tracks.length===1){b(x.tracks[0]===y),d.push({tracks:[y,T.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[y],linkedGroup:T}),T.needsEmit=!0}}else y.type==="video"?m.push(y):y.type==="audio"&&f.push(y)}let p=({metadata:y})=>{let k="";return k+=`${y.languageCode??se}-`,k+=`${y.name??""}-`,k+=`${y.disposition?.default??!0}-`,k+=`${y.disposition?.primary??!1}-`,k+=`${y.disposition?.forced??!1}-`,k};if(m.length>0)if(new Set(m.map(p)).size>1){let k={key:m.map(w=>w.id).join("-"),name:"video-"+(s.length+1),tracks:m,needsEmit:!0,firstNoUri:!0};s.push(k),d.push({tracks:[m[0]],linkedGroup:k})}else for(let k of m)d.push({tracks:[k],linkedGroup:null});if(f.length>0)if(new Set(f.map(p)).size>1){let k={key:f.map(w=>w.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 g=y=>{let k=[],w=0,T=0,S=!1,x=null,C=-1/0;for(let P of y)P.isVideoTrack()?(w++,S||=(P.metadata.rotation??0)!==0||!!P.metadata.flip||!!P.metadata.transformationMatrix):P.isAudioTrack()&&T++,k.push(P.source._codec);for(let P of $t(this.format._options.segmentFormat)){let A=P.getSupportedCodecs(),I=P.getSupportedTrackCounts();if(k.some(v=>!A.includes(v))||w<I.video.min||w>I.video.max||T<I.audio.min||T>I.audio.max)continue;let E=0;S&&P.supportsVideoTransformationMetadata&&E++,E>C&&(x=P,C=E)}return b(x),x},h=async y=>{if(y.some(x=>this.playlists.some(C=>C.tracks.includes(x))))throw new Error("Internal error: track is already registered in a playlist.");let k=g(y),w=this.playlists.length+1,T=await this.getPlaylistPath({n:w,tracks:y,segmentFormat:k});lb(T);let S={id:this.playlists.length+1,path:T,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 He};return this.playlists.push(S),S};for(let y of s)if(y.needsEmit)for(let k=0;k<y.tracks.length;k++){let w=y.tracks[k],T=this.playlists.find(S=>S.tracks[0].id===w.id);T??=await h([w]),this.playlistDeclarations.push({playlist:T,groupId:y.name,noUri:y.firstNoUri&&k===0,references:[]})}for(let y of d){let k=this.playlists.find(w=>w.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(w=>w.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});e()}async getMimeType(){return or}allTracksAreKnown(e){for(let r of e.tracks)if(!r.source._closed&&!this.trackDatas.some(n=>n.track===r))return!1;return!0}async onTrackClose(e){let r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0);let n=this.playlists.find(s=>s.tracks.includes(e));b(n);let a=await n.mutex.acquire();try{await this.advancePlaylist(n)}finally{a()}}getVideoTrackData(e,r,n){let a=this.trackDatas.find(o=>o.track===e);if(a)return a;nr(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],closed:!1,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;Ce(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],closed:!1,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),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),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(s=>e.tracks.includes(s.track));if(e.currentSegmentStartTimestamp===null){r.every(s=>s.closed)&&await this.onPlaylistDone(e);return}let n=r.find(s=>s.info.type==="video"),a=r.find(s=>s.info.type==="audio");for(;;){let s=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,c=0;if(n&&(!n.closed||n.packets.length>0)){let x=n.packets.every(A=>A.timestamp<s),C=null,P=null;if(x){if(!n.closed)return}else for(let A=0;A<n.packets.length;A++){let I=n.packets[A];if(C!==null&&I.timestamp>s)break;A>0&&I.type==="key"&&(C=I,P=A)}if(P!==null){if(o=P,a){let A=a.packets.findIndex(I=>I.timestamp>=C.timestamp);if(A!==-1)c=A;else if(a.closed)c=a.packets.length;else return}}else{if(!n.closed)return;o=n.packets.length;let A=td(n.packets,E=>E.timestamp),I=n.packets[A];if(b(I),a)if(I.timestamp<s){let E=a.packets.findIndex(v=>v.timestamp>=s);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}else{let E=a.packets.findIndex(v=>v.timestamp>I.timestamp);if(E!==-1)c=E;else if(a.closed)c=a.packets.length;else return}}}else if(a&&(!a.closed||a.packets.length>0))if(a.packets.every(C=>C.timestamp<s))if(a.closed)c=a.packets.length;else return;else{let C=qr(a.packets,P=>P.timestamp<=s);c=Math.max(C,1)}if(o===0&&c===0){r.every(C=>C.closed)&&await this.onPlaylistDone(e);return}let u=null,l,d;b(this.output._target instanceof ut);let m=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let x={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Ac(e)};l=await this.getSegmentPath(x),ep(l),d=xe(xe(m.rootPath,e.path),l);let C=await this.output._getTarget({path:d,isRoot:!1,mimeType:e.segmentFormat.mimeType}),P=null;if(e.segmentFormat._isFragmentedIsobmff()){P={output:new br({format:e.segmentFormat,target:C}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},C.on("write",({end:E})=>{P.currentFileSize=Math.max(P.currentFileSize,E)});let A=P.output._muxer;A.minimumFragmentDuration=1/0;let I=A.formatOptions.onMoof;A.formatOptions.onMoof=(E,v,R)=>{P.firstMoofPosition=v,I?.(E,v,R),A.formatOptions.onMoof=I},n&&(P.videoSource=new Ur(n.track.source._codec),P.output.addVideoTrack(P.videoSource,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(P.audioSource=new zr(a.track.source._codec),P.output.addAudioTrack(P.audioSource,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await P.output.start()}else C._start();e.singleFile={target:C,path:l,nextOffset:0,info:x,fragmentedIsobmffOutput:P}}else l=e.singleFile.path,d=xe(xe(m.rootPath,e.path),l);else u={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Ac(e)},l=await this.getSegmentPath(u),ep(l),d=xe(xe(m.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,g=-1/0,h=null,y=null,k=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(h=e.singleFile.fragmentedIsobmffOutput.output,y=e.singleFile.fragmentedIsobmffOutput.videoSource,k=e.singleFile.fragmentedIsobmffOutput.audioSource):(h=new br({format:e.segmentFormat,target:new ut(d,async x=>{let C={...x,isRoot:!1};if(x.isRoot)if(e.singleFile){let P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:A})=>f=Math.max(f,A)),P}else{let P=await this.output._getTarget(C);return p=P,P.on("write",({end:A})=>f=Math.max(f,A)),P}return this.output._getTarget(C)}),initTarget:async()=>{if(e.initSegment)return new ki;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:C})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,C)}),x.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),x}else{let x=Ac(e),C=await this.getInitPath(x);db(C),e.initSegment={path:C,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let P=xe(xe(m.rootPath,e.path),C),A=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return A.on("write",({end:I})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,I)}),A.on("finalized",()=>{this.format._options.onInit?.(A,x)}),A}}}),n&&(y=new Ur(n.track.source._codec),h.addVideoTrack(y,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),a&&(k=new zr(a.track.source._codec),h.addAudioTrack(k,{...a.track.metadata,decoderConfig:a.info.decoderConfig,primingPacket:a.info.primingPacket??void 0})),await h.start()),n){b(y);let x={decoderConfig:n.info.decoderConfig};for(let C=0;C<o;C++){let P=n.packets[C];await y.add(P,x),g=Math.max(g,P.timestamp+P.duration)}}if(a){b(k);let x={decoderConfig:a.info.decoderConfig};for(let C=0;C<c;C++){let P=a.packets[C];await k.add(P,x),g=Math.max(g,P.timestamp+P.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),f=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await h.finalize()}catch(x){throw await h?.cancel(),x}u&&(b(p),this.format._options.onSegment?.(p,u)),o>0&&(b(n),n.packets.splice(0,o)),c>0&&(b(a),a.packets.splice(0,c));let w=1/0;n&&n.packets.length>0&&(w=n.packets[0].timestamp),a&&a.packets.length>0&&(w=Math.min(w,a.packets[0].timestamp));let T=w<1/0?w:g;b(Number.isFinite(T));let S=T-e.currentSegmentStartTimestamp;if(b(S>=0),e.writtenSegments.push({path:l,duration:S,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:u??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,S),e.currentSegmentStartTimestamp=T,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),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()}}}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)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let r=e.writtenSegments,n=0,a=0,s=0;for(let c=0;c<r.length;c++){s+=r[c].duration;let u=0,l=0;for(let d=c;d<r.length&&(u+=r[d].byteSize,l+=r[d].duration,l>=.5*this.globalTargetDuration&&l<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*u/l)),!(l>1.5*this.globalTargetDuration));d++);}if(n===0)for(let c of r){let u=c.duration||1;n=Math.max(n,8*c.byteSize/u)}for(let c of r)a+=8*c.byteSize;let o=a/(s||1);if(r.length===0)for(let c of e.tracks){let u=this.trackDatas.find(d=>d.track===c),l=c.source._nominalBitrate??c.metadata.bitrate??0;if(o+=c.source._nominalBitrate??c.metadata.averageBitrate??0,l===0){let d=new oe("medium");if(c.isVideoTrack()){let m=u?.info.decoderConfig;l=d._toVideoBitrate(c.source._codec,m?.codedWidth??1920,m?.codedHeight??1080)}else c.isAudioTrack()&&(l=d._toAudioBitrate(c.source._codec)??0)}n+=l}e.peakBitrate=n,e.averageBitrate=o}async writePlaylist(e){b(this.output._target instanceof ut);let r=this.output._target;this.updatePlaylistBitrates(e);let n=!1;for(let m of e.writtenSegments)n||=m.byteOffset!==null;let a=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,s=3;(a||n)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!a&&(s=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,c=xe(r.rootPath,e.path),u=`#EXTM3U
18
18
  #EXT-X-VERSION:${s}
19
19
  `+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
20
20
  `)+`#EXT-X-TARGETDURATION:${Math.ceil(o)}
@@ -30,12 +30,12 @@ ${r.notes??""}`,d=this.createInternalChunk(u,r.timestamp,r.duration,"key",l.trim
30
30
  `).join("")+(e.done?(e.writtenSegments.length>0?`
31
31
  `:"")+`#EXT-X-ENDLIST
32
32
  `:"");this.format._options.onPlaylist?.(u,Ac(e));let l=await this.output._getTarget({path:c,isRoot:!1,mimeType:or}),d=new pr(l,!0);d.start(),d.write(Z.encode(u)),await d.flush(),await d.finalize()}async writeMasterPlaylist(){b(this.output._target instanceof ut);let e=this.output._target,r=`#EXTM3U
33
- `,n=!1,a=null,s=0,o=!1;for(let u of this.playlistDeclarations)if(u.groupId===null){let l=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,d=[];for(let y of u.playlist.tracks){let T=this.trackDatas.find(w=>w.track===y)?.info.decoderConfig.codec??y.source._codec;d.push(Jf(T))}let m=0,f=0;if(u.references.length>0){let k=u.references[0].playlist.tracks[0],w=this.trackDatas.find(S=>S.track===k)?.info.decoderConfig.codec??k.source._codec;d.push(Jf(w));for(let S of u.references)b(S.playlist.peakBitrate!==null),m=Math.max(m,S.playlist.peakBitrate),f=Math.max(f,S.playlist.averageBitrate??0)}b(u.playlist.peakBitrate!==null);let p=u.playlist.peakBitrate+m,g=(u.playlist.averageBitrate??0)+f;n||(r+=`
34
- `,n=!0),l?r+="#EXT-X-I-FRAME-STREAM-INF:":r+="#EXT-X-STREAM-INF:",r+=`BANDWIDTH=${Math.ceil(p)}`,g>0&&(r+=`,AVERAGE-BANDWIDTH=${Math.ceil(g)}`),r+=`,CODECS="${d.join(",")}"`;let h=u.playlist.tracks.find(y=>y.isVideoTrack());if(h?.isVideoTrack()){let k=this.trackDatas.find(T=>T.track===h)?.info.decoderConfig;if(k){let T=k.displayAspectWidth??k.codedWidth,w=k.displayAspectHeight??k.codedHeight;T!==void 0&&w!==void 0&&(h.metadata.rotation!==void 0&&h.metadata.rotation%180===90&&([T,w]=[w,T]),r+=`,RESOLUTION=${T}x${w}`)}!l&&h.metadata.frameRate!==void 0&&(r+=`,FRAME-RATE=${+h.metadata.frameRate.toFixed(3)}`)}if(!l){let y=new Map;for(let k of u.references){b(k.groupId!==null);let T=k.playlist.tracks[0].type;y.set(T,k.groupId)}for(let[k,T]of y)r+=`,${k.toUpperCase()}="${T}"`}l?(r+=`,URI="${u.playlist.path}"`,r+=`
33
+ `,n=!1,a=null,s=0,o=!1;for(let u of this.playlistDeclarations)if(u.groupId===null){let l=u.playlist.tracks[0].isVideoTrack()&&u.playlist.tracks[0].metadata.hasOnlyKeyPackets,d=[];for(let y of u.playlist.tracks){let w=this.trackDatas.find(T=>T.track===y)?.info.decoderConfig.codec??y.source._codec;d.push(Jf(w))}let m=0,f=0;if(u.references.length>0){let k=u.references[0].playlist.tracks[0],T=this.trackDatas.find(S=>S.track===k)?.info.decoderConfig.codec??k.source._codec;d.push(Jf(T));for(let S of u.references)b(S.playlist.peakBitrate!==null),m=Math.max(m,S.playlist.peakBitrate),f=Math.max(f,S.playlist.averageBitrate??0)}b(u.playlist.peakBitrate!==null);let p=u.playlist.peakBitrate+m,g=(u.playlist.averageBitrate??0)+f;n||(r+=`
34
+ `,n=!0),l?r+="#EXT-X-I-FRAME-STREAM-INF:":r+="#EXT-X-STREAM-INF:",r+=`BANDWIDTH=${Math.ceil(p)}`,g>0&&(r+=`,AVERAGE-BANDWIDTH=${Math.ceil(g)}`),r+=`,CODECS="${d.join(",")}"`;let h=u.playlist.tracks.find(y=>y.isVideoTrack());if(h?.isVideoTrack()){let k=this.trackDatas.find(w=>w.track===h)?.info.decoderConfig;if(k){let w=k.displayAspectWidth??k.codedWidth,T=k.displayAspectHeight??k.codedHeight;w!==void 0&&T!==void 0&&(h.metadata.rotation!==void 0&&h.metadata.rotation%180===90&&([w,T]=[T,w]),r+=`,RESOLUTION=${w}x${T}`)}!l&&h.metadata.frameRate!==void 0&&(r+=`,FRAME-RATE=${+h.metadata.frameRate.toFixed(3)}`)}if(!l){let y=new Map;for(let k of u.references){b(k.groupId!==null);let w=k.playlist.tracks[0].type;y.set(w,k.groupId)}for(let[k,w]of y)r+=`,${k.toUpperCase()}="${w}"`}l?(r+=`,URI="${u.playlist.path}"`,r+=`
35
35
  `):(r+=`
36
36
  `,r+=`${u.playlist.path}
37
37
  `)}else{b(u.playlist.tracks.length===1);let l=u.playlist.tracks[0],d=l.type,m=l.metadata.name??null,f=l.metadata.languageCode,p=l.metadata.disposition;(a===null||u.groupId!==a)&&(s=0,r+=`
38
- `,o=!1),a=u.groupId,s++,r+=`#EXT-X-MEDIA:TYPE=${d.toUpperCase()},GROUP-ID="${u.groupId}"`,m!==null&&/[\n\r"]/.test(m)&&(V._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),m=null),m??=`${f??u.groupId}-${s}`,r+=`,NAME="${m}"`,f!==void 0&&(r+=`,LANGUAGE="${f}"`);let g=p?.primary??!1,h=p?.default??!0,y=p?.forced??!1;if(g&&!o&&(r+=",DEFAULT=YES",o=!0),(g||h)&&(r+=",AUTOSELECT=YES"),y&&(r+=",FORCED=YES"),d==="audio"){let T=this.trackDatas.find(w=>w.track===l)?.info.decoderConfig;T&&(r+=`,CHANNELS="${T.numberOfChannels}"`)}u.noUri||(r+=`,URI="${u.playlist.path}"`),r+=`
38
+ `,o=!1),a=u.groupId,s++,r+=`#EXT-X-MEDIA:TYPE=${d.toUpperCase()},GROUP-ID="${u.groupId}"`,m!==null&&/[\n\r"]/.test(m)&&(V._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),m=null),m??=`${f??u.groupId}-${s}`,r+=`,NAME="${m}"`,f!==void 0&&(r+=`,LANGUAGE="${f}"`);let g=p?.primary??!1,h=p?.default??!0,y=p?.forced??!1;if(g&&!o&&(r+=",DEFAULT=YES",o=!0),(g||h)&&(r+=",AUTOSELECT=YES"),y&&(r+=",FORCED=YES"),d==="audio"){let w=this.trackDatas.find(T=>T.track===l)?.info.decoderConfig;w&&(r+=`,CHANNELS="${w.numberOfChannels}"`)}u.noUri||(r+=`,URI="${u.playlist.path}"`),r+=`
39
39
  `}this.format._options.onMaster?.(r);let c=await this.mutex.acquire();try{let u;if(this.numWrittenMasterPlaylists===0)u=await this.output._getRootWriter(!0);else{let l=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:or});u=new pr(l,!0),u.start()}u.write(Z.encode(r)),await u.flush(),await u.finalize(),this.numWrittenMasterPlaylists++}finally{c()}}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.trackDatas)r.closed=!0;await Promise.all(this.playlists.map(r=>r.done?Promise.resolve():this.advancePlaylist(r))),this.isLive||await this.writeMasterPlaylist()}},lb=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.")},ep=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.")},db=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.")},Ac=i=>({n:i.id,tracks:i.tracks,segmentFormat:i.segmentFormat});var Le=class{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(t=>ce.includes(t))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(t=>me.includes(t))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(t=>Xe.includes(t))}_codecUnsupportedHint(t){return""}_isFragmentedIsobmff(){return!1}},Yi=class extends Le{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&&(!ve(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"}_createMuxer(t){return new uc(t,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}},Zi=class extends Yi{constructor(t){super(t)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ce,...At,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Xe]}_codecUnsupportedHint(t){return new Gi().getSupportedCodecs().includes(t)?" Switching to MOV will grant support for this codec.":""}},Ki=class extends Yi{constructor(t){super(t)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ce,...At,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Xe]}},Gi=class extends Yi{constructor(t){super(t)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ce,...me]}_codecUnsupportedHint(t){return new Zi().getSupportedCodecs().includes(t)?" Switching to MP4 will grant support for this codec.":""}},Qn=class extends Le{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&&(!ve(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.onHeader, 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 lc(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[...ce,...At,...ne.filter(t=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(t)),...Xe]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},Ti=class extends Qn{constructor(t){super(t)}getSupportedCodecs(){return[...ce.filter(t=>["vp8","vp9","av1"].includes(t)),...me.filter(t=>["opus","vorbis"].includes(t)),...Xe]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(t){return new Qn().getSupportedCodecs().includes(t)?" Switching to MKV will grant support for this codec.":""}},Cc=class extends Le{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 mc(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}},Pc=class extends Le{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");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 gc(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[...ne.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}},Ic=class extends Le{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maximumPageDuration!==void 0&&(!ve(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 fc(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[...me.filter(t=>["vorbis","opus"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"none"}},Ec=class extends Le{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 rc(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}},vc=class extends Le{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.");super(),this._options=t}_createMuxer(t){return new ic(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}},_c=class extends Le{constructor(t={}){if(!t||typeof t!="object")throw new TypeError("options must be an object.");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 pc(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[...ce.filter(t=>["avc","hevc"].includes(t)),...me.filter(t=>["aac","mp3","ac3","eac3","dts"].includes(t))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}},Rc=class extends Le{constructor(t){if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!(t.segmentFormat instanceof Le)&&(!Array.isArray(t.segmentFormat)||t.segmentFormat.length===0||!t.segmentFormat.every(e=>e instanceof Le)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(t.targetDuration!==void 0&&(typeof t.targetDuration!="number"||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.maxLiveSegmentCount!==void 0&&(typeof t.maxLiveSegmentCount!="number"||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.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 xc(t,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return or}getSupportedCodecs(){return[...new Set($t(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()))]}getSupportedTrackCounts(){let t=!1,e=!1,r=!1;for(let n of $t(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 $t(this._options.segmentFormat).some(t=>t.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){let t=$t(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" Using different segment formats may grant support for this codec."}};var Fc=["video","audio","subtitle"],Ji=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=$t(this.metadata.group),r=$t(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}},Ja=class extends Ji{constructor(t,e,r,n){super(t,e,"video",r,n)}},es=class extends Ji{constructor(t,e,r,n){super(t,e,"audio",r,n)}},ts=class extends Ji{constructor(t,e,r,n){super(t,e,"subtitle",r,n)}},lt=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)}},Il=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!Sr(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&&sd(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 lt)&&(!Array.isArray(i.group)||i.group.some(t=>!(t instanceof lt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},br=class extends Je{constructor(e){super();this.state="pending";this.defaultTrackGroup=new lt;this.tracks=[];this._onFinalize=null;this._unfinalizedTargets=new Set;this._rootWriterPromise=null;this._startPromise=null;this._cancelPromise=null;this._finalizePromise=null;this._mutex=new He;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 Le))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Me||e.target instanceof ut))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Me&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Me)&&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 Me&&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))throw new TypeError(e);return r}_getTargetValidated(e){b(this._target instanceof ut);let r=this._target.getTarget(e),n=a=>{if(!(a instanceof Me))throw new TypeError("getTarget must return a Target.");return a};return _(r)?r.then(n):n(r)}async _getTarget(e){b(this._target instanceof ut);let r=await this._getTargetValidated(e);return this._emit("target",{target:r,request:e,isRoot:e.isRoot}),this.state==="canceled"?await r._close():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 Me)return this._initTarget;let e=await this._initTarget();return this.state==="canceled"?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 Me)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.state==="canceled"?a._close():this._rememberTarget(a),this._emit("target",{target:a,request:e,isRoot:!0}),this._rootTarget=a,a);return _(r)?this._rootTargetPromise=r.then(n):n(r)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let r=await this._getRootTarget(),n=new pr(r,typeof e=="boolean"?e:e(r));return n.start(),n})()}addVideoTrack(e,r={}){if(!(e instanceof hr))throw new TypeError("source must be a VideoSource.");if(Il(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&&nr({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof j))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 Ja(this.tracks.length+1,this,e,n))}addAudioTrack(e,r={}){if(!(e instanceof gr))throw new TypeError("source must be an AudioSource.");if(Il(r),r.decoderConfig!==void 0&&Ce({decoderConfig:r.decoderConfig},e._codec),r.primingPacket!==void 0){if(!(r.primingPacket instanceof j))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 es(this.tracks.length+1,this,e,n))}addSubtitleTrack(e,r={}){if(!(e instanceof $i))throw new TypeError("source must be a SubtitleSource.");Il(r);let n={...r};return n.group??=this.defaultTrackGroup,this._addTrack(new ts(this.tracks.length+1,this,e,n))}setMetadataTags(e){if(Zn(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} tracks${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 Fc){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 Fc){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.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(V._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let n=this._mutex.acquire();try{await this._muxer.start();let a=this.tracks.map(s=>s.source._start());await Promise.all(a)}finally{(await n)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&V._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let r=this.tracks.map(n=>n.source._flushOrWaitForOngoingClose(!0));await Promise.all(r),await Promise.all([...this._unfinalizedTargets].map(n=>n._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(V._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{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",r}finally{await Promise.all([...this._unfinalizedTargets].map(r=>r._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}};var Mc=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&&!ce.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${ce.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof oe))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 oe)&&(!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&&li(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 lt||Array.isArray(i.group)&&i.group.every(e=>e instanceof lt)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},Bc=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&&!me.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${me.join(", ")}.`);let t=i?.bitrate;if(i?.quality!==void 0&&!(i.quality instanceof oe))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 oe)&&(!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 lt||Array.isArray(i.group)&&i.group.every(e=>e instanceof lt)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},El=2,vl=48e3,Oc=class i{constructor(t){this._state="idle";this._timestampOffset=0;this._timestampOffsetAdjusted=!1;this._copyTimestampPossible=new Map;this._copyStartPackets=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 _l(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 oi))throw new TypeError("options.input must be an Input.");if(!(t.output instanceof br))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&&(!ve(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&&(!ve(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)Mc(r);else Mc(t.video);if(t.audio!==void 0&&typeof t.audio!="function")if(Array.isArray(t.audio))for(let r of t.audio)Bc(r);else Bc(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&&!ve(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"&&Zn(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 u=await this.input.getPrimaryVideoTrack(),l=await this.input.getPrimaryAudioTrack();e=[u,l].filter(d=>d!==null)}else ae(r),b(!1);let n=this.output.format.getSupportedTrackCounts(),a=1,s=1,o=[],c=[];for(let u of e){let l;if(u.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){let f=await this._options.video(u,a)??{};if(Array.isArray(f))for(let p of f)Mc(p);else Mc(f);l=Array.isArray(f)?f:[f],a++}else l=Array.isArray(this._options.video)?this._options.video:[this._options.video];else l=[{}];else if(u.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){let f=await this._options.audio(u,s)??{};if(Array.isArray(f))for(let p of f)Bc(p);else Bc(f);l=Array.isArray(f)?f:[f],s++}else l=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else l=[{}];else b(!1);let d=l.filter(f=>f.discard);for(let f of d)this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:f});if(l.length===d.length){l.length===0&&this.discardedTracks.push({track:u,reason:"discarded_by_user",trackOptions:{}});continue}let m=l.filter(f=>!f.discard);o.push(u),c.push(m)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let u=0;u<o.length;u++){let l=o[u],d=c[u];for(let m of d){if(this.output.tracks.length===n.total.max){this.discardedTracks.push({track:l,reason:"max_track_count_reached",trackOptions:m});continue}if(this.output.tracks.reduce((g,h)=>g+(h.type===l.type?1:0),0)===n[l.type].max){this.discardedTracks.push({track:l,reason:"max_track_count_of_type_reached",trackOptions:m});continue}let p=this._nextOutputTrackId++;l.isVideoTrack()?await this._processVideoTrack(l,m,p):l.isAudioTrack()?await this._processAudioTrack(l,m,p):b(!1)}}for(let u=0;u<this.utilizedTracks.length-1;u++)for(let l=u+1;l<this.utilizedTracks.length;l++){let d=this.utilizedTracks[u],m=this.utilizedTracks[l],f=this._outputOwnTrackGroups[u],p=this._outputOwnTrackGroups[l];b(f!==void 0),b(p!==void 0),f&&p&&d.canBePairedWith(m)&&f.pairWith(p)}if(!this._composable){let u=await this.input.getMetadataTags(),l;if(this._options.tags){let f=typeof this._options.tags=="function"?await this._options.tags(u):this._options.tags;Zn(f),l=f}else l=u;let d=t.mimeType===this.output.format.mimeType;u.raw===l.raw&&!d&&delete l.raw,this.output.setMetadataTags(l)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let u=[],l=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");l.length>0&&u.push("Some tracks had to be discarded from the conversion:",l),this.isValid||(u.length>0&&u.push(`
40
40
 
41
41
  `),u.push(this._getInvalidityExplanation().join(""))),u.length>0&&V._warn(...u)}}_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=this.discardedTracks.flatMap(a=>{if(a.reason==="discarded_by_user")return[];let s;return a.track.type==="video"?s=this.output.format.getSupportedVideoCodecs():a.track.type==="audio"?s=this.output.format.getSupportedAudioCodecs():s=this.output.format.getSupportedSubtitleCodecs(),s.filter(o=>!a.trackOptions.codec||o===a.trackOptions.codec)}),n=[...new Set(r)];n.length===1?t.push(`
@@ -46,6 +46,6 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
46
46
  The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes("flac")&&t.push(`
47
47
  The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else t.push(`
48
48
  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.
49
- `+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 jn;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=ee());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(async o=>await o.isLive()?1/0:await o.getDurationFromMetadata()??await o.computeDuration()),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()}try{await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){throw this._state!=="canceled"&&this.cancel(),n}finally{t.pauseSignal?.removeEventListener("abort",e)}if(this._state==="canceled")throw new jn;let r=this._trackPumps.every(n=>n.done);this._state=r?"done":"idle",r&&(this._composable||await this.output.finalize(),this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime))}async cancel(){if(this._state!=="done"){if(this._state==="canceled"){V._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}let a,s=await t.getRotation(),o=await t.getFlip(),{rotation:c,flip:u}=ls(s,o,e.rotate??0,e.flip??!1),l=c,d=u,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=Bn(k,h,y));let[T,w]=k?[k.width,k.height]:[h,y],S=T,x=w,C=S/x;e.width!==void 0&&e.height===void 0?(S=_i(e.width),x=_i(Math.round(S/C))):e.width===void 0&&e.height!==void 0?(x=_i(e.height),S=_i(Math.round(x*C))):e.width!==void 0&&e.height!==void 0&&(S=_i(e.width),x=_i(e.height));let I=this.output.format.getSupportedVideoCodecs(),A=e.alpha??"discard",P=!this._copyMode||!!e.forceTranscode||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.quality!==void 0||e.bitrate!==void 0||!I.includes(n)||e.codec&&e.codec!==n||S!==T||x!==w||c!==0&&!f||u&&!f||!!k,E=null;if(!P){let Qe=new st(t),Be=await Qe.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await Qe.getFirstKeyPacket({verifyKeyPackets:!0});if(Be&&Be.timestamp<this._startTimestamp&&Be.timestamp+Be.duration<=this._startTimestamp&&this._copyBoundaryPolicy==="shrink"&&(Be=await Qe.getNextKeyPacket(Be,{verifyKeyPackets:!0})),E=Be,Be){let We=this._copyBoundaryPolicy==="shrink"?Math.max(Be.timestamp,this._startTimestamp):Be.timestamp;if((this._copyBoundaryPolicy==="shrink"?We-this._startTimestamp:Math.max(this._startTimestamp-We,0))>this._copyBoundaryTolerance)P=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&We<this._startTimestamp){let Oe=Math.min(this._startTimestamp-We,this._copyTimestampShiftTolerance);We+Oe>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+Oe):P=!0}}else if(this._timestampOffsetAdjusted)We+this._timestampOffset===0||(P=!0);else{let Oe=J(this._startTimestamp-We,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);We+Oe===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+Oe,this._timestampOffsetAdjusted=!0):P=!0}}}if(P&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(P){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(I=I.filter(pe=>pe===e.codec));let Be=di(e.quality,e.bitrate)??new oe("high"),We=await Zo(I,{width:e.process&&e.processedWidth?e.processedWidth:S,height:e.process&&e.processedHeight?e.processedHeight:x,quality:Be});if(!We){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let re={codec:We,quality:Be,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:A,hardwareAcceleration:e.hardwareAcceleration,transform:{}};b(re.transform);let Oe=S!==T||x!==w||c!==0&&(!f||e.process!==void 0)||u&&(!f||e.process!==void 0)||!!k||p!==await t.getCodedWidth()||g!==await t.getCodedHeight();if(!Oe){var be=[];try{let pe=new br({format:new Zi,target:new ki});let Ve=new Xi(re);pe.addVideoTrack(Ve);await pe.start();let Nr=new mi(t);let je=dt(be,await Nr.getSample(await t.getFirstTimestamp()));if(je)try{await Ve.add(je),je.close(),await pe.finalize()}catch(en){V._warn("An error occurred when probing encoder support. Falling back to rerender path.",en),pe.cancel(),Oe=!0,re.transform.force=!0}else await pe.cancel()}catch(Te){var Wt=Te,yt=!0}finally{mt(be,Wt,yt)}}e.frameRate&&(re.transform.frameRate=e.frameRate),e.process&&(re.transform.process=e.process),Oe&&(l=0,d=!1,m=null,re.transform.width=S,re.transform.height=x,re.transform.fit=e.fit??"fill",re.transform.rotate=e.rotate,re.transform.flip=e.flip,re.transform.crop=k,re.transform.alpha=A);let De=null;re.onEncodedSample=pe=>{De=pe.timestamp};let Ee=new Xi(re);a=Ee,this._registerTrackPump(async pe=>{let Ve=new mi(t);for await(var Nr of Ve.samples(this._startTimestamp,this._endTimestamp)){var je=[];try{let kt=dt(je,Nr);if(this._state==="canceled")break;let wi=Math.max(this._startTimestamp,kt.timestamp),Rl=Math.min(this._endTimestamp,kt.timestamp+kt.duration);wi>=Rl||(kt.setTimestamp(wi+this._timestampOffset),kt.setDuration(Rl-wi),this._updateProgress(r,kt.timestamp+kt.duration),await Ee.add(kt),kt.close(),De!==null&&(this._synchronizer.shouldWait(r,De)&&await this._synchronizer.wait(De),await this._checkpoint(pe,De)))}catch(en){var rs=en,Dc=!0}finally{mt(je,rs,Dc)}}Ee.close(),this._closeTrack(r)})}else{let Qe=new Ur(n);a=Qe,this._registerTrackPump(async Be=>{let We=new st(t),Oe={decoderConfig:await t.getDecoderConfig()??void 0},De=null;if(E)for await(let Ee of We.packets(E,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(Ee.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let en=Ee,rs=!1,Dc=6;for(let kt=0;kt<Dc;kt++){let wi=await We.getNextPacket(en,{metadataOnly:!0});if(!wi)break;if(wi.timestamp<this._endTimestamp){rs=!0;break}en=wi}if(!rs)break}}let pe=Ee.timestamp,Ve=Ee.timestamp+Ee.duration;this._copyBoundaryPolicy==="shrink"&&(pe=Math.max(pe,this._startTimestamp),Ve=Math.min(Ve,this._endTimestamp),Ve=Math.max(Ve,pe)),pe+=this._timestampOffset,Ve+=this._timestampOffset;let Nr=Ee.type;Nr==="key"&&De!==null&&pe<De&&(Nr="delta"),De=Math.max(De??-1/0,pe);let je=Ee.clone({timestamp:pe,duration:Ve-pe,sideData:A==="discard"?{}:Ee.sideData,type:Nr});this._updateProgress(r,je.timestamp+je.duration),await Qe.add(je,Oe),this._synchronizer.shouldWait(r,je.timestamp)&&await this._synchronizer.wait(je.timestamp),await this._checkpoint(Be,je.timestamp)}Qe.close(),this._closeTrack(r)})}let v=null;!e.group&&!this._composable&&(v=new lt);let M=await t.getLanguageCode(),O=await t.getName(),z=await t.getDisposition(),D=P?null:await t.getBitrate(),q=P?null:await t.getAverageBitrate(),ie=A==="keep"&&await t.canBeTransparent();this.output.addVideoTrack(a,{frameRate:e.frameRate,languageCode:Sr(M)?M:void 0,name:O??void 0,disposition:z,rotation:l,flip:d,transformationMatrix:m??void 0,canBeTransparent:ie,group:v??e.group,bitrate:D??void 0,averageBitrate:q??void 0}),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}let a,s=await t.getNumberOfChannels(),o=await t.getSampleRate(),c=e.numberOfChannels??s,u=e.sampleRate??o,l=this.output.format.getSupportedAudioCodecs(),d=!this._copyMode||!!e.forceTranscode||!!e.quality||!!e.bitrate||c!==s||u!==o||!l.includes(n)||!!e.codec&&e.codec!==n||e.process!==void 0||e.sampleFormat!==void 0,m=null;if(!d){let T=new st(t),w=await T.getKeyPacket(this._startTimestamp)??await T.getFirstKeyPacket();w&&(this._copyBoundaryPolicy==="shrink"&&w.timestamp<this._startTimestamp||this._copyBoundaryPolicy==="expand"&&w.timestamp+w.duration<=this._startTimestamp)&&(w=await T.getNextKeyPacket(w));let S=At.includes(n)&&n!=="flac";if(w&&this._copyBoundaryPolicy==="expand"&&S){let x=await T.getKeyPacket(w.timestamp-1/await t.getTimeResolution());x&&(w=x)}if(m=w,w)if((this._copyBoundaryPolicy==="shrink"?Math.max(w.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-w.timestamp,0))>this._copyBoundaryTolerance)d=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&w.timestamp<this._startTimestamp){let C=Math.min(this._startTimestamp-w.timestamp,this._copyTimestampShiftTolerance);w.timestamp+C>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+C):d=!0}}else if(this._timestampOffsetAdjusted)w.timestamp+this._timestampOffset===0||(d=!0);else{let C=J(this._startTimestamp-w.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);w.timestamp+C===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+C,this._timestampOffsetAdjusted=!0):d=!0}}if(d&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(d){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}let w=null;e.codec&&(l=l.filter(P=>P===e.codec));let S=di(e.quality,e.bitrate)??new oe("high"),x=await On(l,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:c,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:u,quality:S});if(!x.some(P=>At.includes(P))&&l.some(P=>At.includes(P))&&(c!==El||u!==vl)){let E=(await On(l,{numberOfChannels:El,sampleRate:vl,quality:S})).find(v=>At.includes(v));E&&(w=E,c=El,u=vl)}else w=x[0]??null;if(w===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let C={codec:w,quality:S,transform:{sampleFormat:e.sampleFormat,process:e.process}};b(C.transform),c!==s&&(C.transform.numberOfChannels=c),u!==o&&(C.transform.sampleRate=u);let I=null;C.onEncodedSample=P=>{I=P.timestamp};let A=new Gn(C);a=A,this._registerTrackPump(async P=>{let E=null,v=new Wi(t);for await(var Wt of v.samples(this._startTimestamp,this._endTimestamp)){var yt=[];try{let re=dt(yt,Wt);var q=[];try{if(this._state==="canceled")break;let Oe=0;let De=re.numberOfFrames;re.timestamp<this._startTimestamp&&(Oe=Math.round((this._startTimestamp-re.timestamp)*re.sampleRate));re.timestamp+re.duration>this._endTimestamp&&(De=Math.round((this._endTimestamp-re.timestamp)*re.sampleRate));if(Oe>=De){re.close();continue}let Ee;if(Oe>0||De<re.numberOfFrames){let Ve=re.trim(Oe,De);if(re.close(),Ee=Ve,Ve.numberOfFrames===0){Ve.close();continue}}else Ee=re;let pe=dt(q,Ee);pe.setTimestamp(pe.timestamp+this._timestampOffset);E===null&&(E=this.output.format.supportsTimestampedMediaData?0:Math.round(pe.timestamp*o));if(E>0){var M=[];try{let Ve=cr(re.format);let Nr=new Uint8Array(Ve*E*s);(re.format==="u8"||re.format==="u8-planar")&&Nr.fill(2**7);let je=dt(M,new Ae({data:Nr,format:re.format,numberOfChannels:s,sampleRate:o,timestamp:0}));await this._registerAudioSample(P,je,A,r,()=>I);E=0}catch(O){var z=O,D=!0}finally{mt(M,z,D)}}await this._registerAudioSample(P,pe,A,r,()=>I)}catch(ie){var be=ie,Te=!0}finally{mt(q,be,Te)}}catch(Qe){var Be=Qe,We=!0}finally{mt(yt,Be,We)}}A.close(),this._closeTrack(r)})}else{let T=new zr(n);a=T,this._registerTrackPump(async w=>{let S=new st(t),C={decoderConfig:await t.getDecoderConfig()??void 0},I=null;if(m)for await(let A of S.packets(m)){if(this._state==="canceled"||A.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&A.timestamp+A.duration>this._endTimestamp)break;let P=A.timestamp+this._timestampOffset;if(I!==null&&P<I)continue;I=P;let E=A.clone({timestamp:P,duration:A.duration});this._updateProgress(r,E.timestamp+E.duration),await T.add(E,C),this._synchronizer.shouldWait(r,E.timestamp)&&await this._synchronizer.wait(E.timestamp),await this._checkpoint(w,E.timestamp)}T.close(),this._closeTrack(r)})}let f=null;!e.group&&!this._composable&&(f=new lt);let p=await t.getLanguageCode(),g=await t.getName(),h=await t.getDisposition(),y=d?null:await t.getBitrate(),k=d?null:await t.getAverageBitrate();this.output.addAudioTrack(a,{languageCode:Sr(p)?p:void 0,name:g??void 0,disposition:h,group:f??e.group,bitrate:y??void 0,averageBitrate:k??void 0}),this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(f)}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:ee(),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}=ee();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=J(t/this._totalDuration,0,1);this._lastProcessedTime=t,e!==this._lastProgress&&(this._lastProgress=e,this.onProgress?.(e,t))}},jn=class extends Error{constructor(t="Conversion has been canceled."){super(t),this.name="ConversionCanceledError"}},tp=1,_l=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>tp}wait(t){let{promise:e,resolve:r}=ee();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<tp&&(r.resolve(),this.resolvers.splice(e,1),e--)}return t}};var rp=Symbol.for("mediabunny loaded");globalThis[rp]&&V._error(`[WARNING]
49
+ `+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 jn;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=ee());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(async o=>await o.isLive()?1/0:await o.getDurationFromMetadata()??await o.computeDuration()),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()}try{await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){throw this._state!=="canceled"&&this.cancel(),n}finally{t.pauseSignal?.removeEventListener("abort",e)}if(this._state==="canceled")throw new jn;let r=this._trackPumps.every(n=>n.done);this._state=r?"done":"idle",r&&(this._composable||await this.output.finalize(),this._computeProgress&&this.onProgress?.(1,this._lastProcessedTime))}async cancel(){if(this._state!=="done"){if(this._state==="canceled"){V._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}let a,s=await t.getRotation(),o=await t.getFlip(),{rotation:c,flip:u}=ls(s,o,e.rotate??0,e.flip??!1),l=c,d=u,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=Bn(k,h,y));let[w,T]=k?[k.width,k.height]:[h,y],S=w,x=T,C=S/x;e.width!==void 0&&e.height===void 0?(S=_i(e.width),x=_i(Math.round(S/C))):e.width===void 0&&e.height!==void 0?(x=_i(e.height),S=_i(Math.round(x*C))):e.width!==void 0&&e.height!==void 0&&(S=_i(e.width),x=_i(e.height));let P=this.output.format.getSupportedVideoCodecs(),A=e.alpha??"discard",I=!this._copyMode||!!e.forceTranscode||!!e.frameRate||e.keyFrameInterval!==void 0||e.process!==void 0||e.quality!==void 0||e.bitrate!==void 0||!P.includes(n)||e.codec&&e.codec!==n||S!==w||x!==T||c!==0&&!f||u&&!f||!!k,E=null;if(!I){let Qe=new st(t),Be=await Qe.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await Qe.getFirstKeyPacket({verifyKeyPackets:!0});if(Be&&Be.timestamp<this._startTimestamp&&Be.timestamp+Be.duration<=this._startTimestamp&&this._copyBoundaryPolicy==="shrink"&&(Be=await Qe.getNextKeyPacket(Be,{verifyKeyPackets:!0})),E=Be,Be){let We=this._copyBoundaryPolicy==="shrink"?Math.max(Be.timestamp,this._startTimestamp):Be.timestamp;if((this._copyBoundaryPolicy==="shrink"?We-this._startTimestamp:Math.max(this._startTimestamp-We,0))>this._copyBoundaryTolerance)I=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&We<this._startTimestamp){let Oe=Math.min(this._startTimestamp-We,this._copyTimestampShiftTolerance);We+Oe>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+Oe):I=!0}}else if(this._timestampOffsetAdjusted)We+this._timestampOffset===0||(I=!0);else{let Oe=J(this._startTimestamp-We,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);We+Oe===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+Oe,this._timestampOffsetAdjusted=!0):I=!0}}}if(I&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(I){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}e.codec&&(P=P.filter(pe=>pe===e.codec));let Be=di(e.quality,e.bitrate)??new oe("high"),We=await Zo(P,{width:e.process&&e.processedWidth?e.processedWidth:S,height:e.process&&e.processedHeight?e.processedHeight:x,quality:Be});if(!We){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let re={codec:We,quality:Be,keyFrameInterval:e.keyFrameInterval,sizeChangeBehavior:e.fit??"passThrough",alpha:A,hardwareAcceleration:e.hardwareAcceleration,transform:{}};b(re.transform);let Oe=S!==w||x!==T||c!==0&&(!f||e.process!==void 0)||u&&(!f||e.process!==void 0)||!!k||p!==await t.getCodedWidth()||g!==await t.getCodedHeight();if(!Oe){var be=[];try{let pe=new br({format:new Zi,target:new ki});let Ve=new Xi(re);pe.addVideoTrack(Ve);await pe.start();let Nr=new mi(t);let je=dt(be,await Nr.getSample(await t.getFirstTimestamp()));if(je)try{await Ve.add(je),je.close(),await pe.finalize()}catch(en){V._warn("An error occurred when probing encoder support. Falling back to rerender path.",en),pe.cancel(),Oe=!0,re.transform.force=!0}else await pe.cancel()}catch(Te){var Wt=Te,yt=!0}finally{mt(be,Wt,yt)}}e.frameRate&&(re.transform.frameRate=e.frameRate),e.process&&(re.transform.process=e.process),Oe&&(l=0,d=!1,m=null,re.transform.width=S,re.transform.height=x,re.transform.fit=e.fit??"fill",re.transform.rotate=e.rotate,re.transform.flip=e.flip,re.transform.crop=k,re.transform.alpha=A);let De=null;re.onEncodedSample=pe=>{De=pe.timestamp};let Ee=new Xi(re);a=Ee,this._registerTrackPump(async pe=>{let Ve=new mi(t);for await(var Nr of Ve.samples(this._startTimestamp,this._endTimestamp)){var je=[];try{let kt=dt(je,Nr);if(this._state==="canceled")break;let wi=Math.max(this._startTimestamp,kt.timestamp),Rl=Math.min(this._endTimestamp,kt.timestamp+kt.duration);wi>=Rl||(kt.setTimestamp(wi+this._timestampOffset),kt.setDuration(Rl-wi),this._updateProgress(r,kt.timestamp+kt.duration),await Ee.add(kt),kt.close(),De!==null&&(this._synchronizer.shouldWait(r,De)&&await this._synchronizer.wait(De),await this._checkpoint(pe,De)))}catch(en){var rs=en,Dc=!0}finally{mt(je,rs,Dc)}}Ee.close(),this._closeTrack(r)})}else{let Qe=new Ur(n);a=Qe,this._registerTrackPump(async Be=>{let We=new st(t),Oe={decoderConfig:await t.getDecoderConfig()??void 0},De=null;if(E)for await(let Ee of We.packets(E,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(Ee.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let en=Ee,rs=!1,Dc=6;for(let kt=0;kt<Dc;kt++){let wi=await We.getNextPacket(en,{metadataOnly:!0});if(!wi)break;if(wi.timestamp<this._endTimestamp){rs=!0;break}en=wi}if(!rs)break}}let pe=Ee.timestamp,Ve=Ee.timestamp+Ee.duration;this._copyBoundaryPolicy==="shrink"&&(pe=Math.max(pe,this._startTimestamp),Ve=Math.min(Ve,this._endTimestamp),Ve=Math.max(Ve,pe)),pe+=this._timestampOffset,Ve+=this._timestampOffset;let Nr=Ee.type;Nr==="key"&&De!==null&&pe<De&&(Nr="delta"),De=Math.max(De??-1/0,pe);let je=Ee.clone({timestamp:pe,duration:Ve-pe,sideData:A==="discard"?{}:Ee.sideData,type:Nr});this._updateProgress(r,je.timestamp+je.duration),await Qe.add(je,Oe),this._synchronizer.shouldWait(r,je.timestamp)&&await this._synchronizer.wait(je.timestamp),await this._checkpoint(Be,je.timestamp)}Qe.close(),this._closeTrack(r)})}let v=null;!e.group&&!this._composable&&(v=new lt);let R=await t.getLanguageCode(),B=await t.getName(),z=await t.getDisposition(),D=I?null:await t.getBitrate(),q=I?null:await t.getAverageBitrate(),ie=A==="keep"&&await t.canBeTransparent();this.output.addVideoTrack(a,{frameRate:e.frameRate,languageCode:Sr(R)?R:void 0,name:B??void 0,disposition:z,rotation:l,flip:d,transformationMatrix:m??void 0,canBeTransparent:ie,group:v??e.group,bitrate:D??void 0,averageBitrate:q??void 0}),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}let a,s=await t.getNumberOfChannels(),o=await t.getSampleRate(),c=e.numberOfChannels??s,u=e.sampleRate??o,l=this.output.format.getSupportedAudioCodecs(),d=!this._copyMode||!!e.forceTranscode||!!e.quality||!!e.bitrate||c!==s||u!==o||!l.includes(n)||!!e.codec&&e.codec!==n||e.process!==void 0||e.sampleFormat!==void 0,m=null;if(!d){let w=new st(t),T=await w.getKeyPacket(this._startTimestamp)??await w.getFirstKeyPacket();T&&(this._copyBoundaryPolicy==="shrink"&&T.timestamp<this._startTimestamp||this._copyBoundaryPolicy==="expand"&&T.timestamp+T.duration<=this._startTimestamp)&&(T=await w.getNextKeyPacket(T));let S=At.includes(n)&&n!=="flac";if(T&&this._copyBoundaryPolicy==="expand"&&S){let x=await w.getKeyPacket(T.timestamp-1/await t.getTimeResolution());x&&(T=x)}if(m=T,T)if((this._copyBoundaryPolicy==="shrink"?Math.max(T.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-T.timestamp,0))>this._copyBoundaryTolerance)d=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&T.timestamp<this._startTimestamp){let C=Math.min(this._startTimestamp-T.timestamp,this._copyTimestampShiftTolerance);T.timestamp+C>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+C):d=!0}}else if(this._timestampOffsetAdjusted)T.timestamp+this._timestampOffset===0||(d=!0);else{let C=J(this._startTimestamp-T.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);T.timestamp+C===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+C,this._timestampOffsetAdjusted=!0):d=!0}}if(d&&this._copyMode==="forced"){this.discardedTracks.push({track:t,reason:"cannot_copy",trackOptions:e});return}if(d){if(!await t.canDecode()){this.discardedTracks.push({track:t,reason:"undecodable_source_codec",trackOptions:e});return}let T=null;e.codec&&(l=l.filter(I=>I===e.codec));let S=di(e.quality,e.bitrate)??new oe("high"),x=await On(l,{numberOfChannels:e.process&&e.processedNumberOfChannels?e.processedNumberOfChannels:c,sampleRate:e.process&&e.processedSampleRate?e.processedSampleRate:u,quality:S});if(!x.some(I=>At.includes(I))&&l.some(I=>At.includes(I))&&(c!==El||u!==vl)){let E=(await On(l,{numberOfChannels:El,sampleRate:vl,quality:S})).find(v=>At.includes(v));E&&(T=E,c=El,u=vl)}else T=x[0]??null;if(T===null){this.discardedTracks.push({track:t,reason:"no_encodable_target_codec",trackOptions:e});return}let C={codec:T,quality:S,transform:{sampleFormat:e.sampleFormat,process:e.process}};b(C.transform),c!==s&&(C.transform.numberOfChannels=c),u!==o&&(C.transform.sampleRate=u);let P=null;C.onEncodedSample=I=>{P=I.timestamp};let A=new Gn(C);a=A,this._registerTrackPump(async I=>{let E=null,v=new Wi(t);for await(var Wt of v.samples(this._startTimestamp,this._endTimestamp)){var yt=[];try{let re=dt(yt,Wt);var q=[];try{if(this._state==="canceled")break;let Oe=0;let De=re.numberOfFrames;re.timestamp<this._startTimestamp&&(Oe=Math.round((this._startTimestamp-re.timestamp)*re.sampleRate));re.timestamp+re.duration>this._endTimestamp&&(De=Math.round((this._endTimestamp-re.timestamp)*re.sampleRate));if(Oe>=De){re.close();continue}let Ee;if(Oe>0||De<re.numberOfFrames){let Ve=re.trim(Oe,De);if(re.close(),Ee=Ve,Ve.numberOfFrames===0){Ve.close();continue}}else Ee=re;let pe=dt(q,Ee);pe.setTimestamp(pe.timestamp+this._timestampOffset);E===null&&(E=this.output.format.supportsTimestampedMediaData?0:Math.round(pe.timestamp*o));if(E>0){var R=[];try{let Ve=cr(re.format);let Nr=new Uint8Array(Ve*E*s);(re.format==="u8"||re.format==="u8-planar")&&Nr.fill(2**7);let je=dt(R,new Ae({data:Nr,format:re.format,numberOfChannels:s,sampleRate:o,timestamp:0}));await this._registerAudioSample(I,je,A,r,()=>P);E=0}catch(B){var z=B,D=!0}finally{mt(R,z,D)}}await this._registerAudioSample(I,pe,A,r,()=>P)}catch(ie){var be=ie,Te=!0}finally{mt(q,be,Te)}}catch(Qe){var Be=Qe,We=!0}finally{mt(yt,Be,We)}}A.close(),this._closeTrack(r)})}else{let w=new zr(n);a=w,this._registerTrackPump(async T=>{let S=new st(t),C={decoderConfig:await t.getDecoderConfig()??void 0},P=null;if(m)for await(let A of S.packets(m)){if(this._state==="canceled"||A.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&A.timestamp+A.duration>this._endTimestamp)break;let I=A.timestamp+this._timestampOffset;if(P!==null&&I<P)continue;P=I;let E=A.clone({timestamp:I,duration:A.duration});this._updateProgress(r,E.timestamp+E.duration),await w.add(E,C),this._synchronizer.shouldWait(r,E.timestamp)&&await this._synchronizer.wait(E.timestamp),await this._checkpoint(T,E.timestamp)}w.close(),this._closeTrack(r)})}let f=null;!e.group&&!this._composable&&(f=new lt);let p=await t.getLanguageCode(),g=await t.getName(),h=await t.getDisposition(),y=d?null:await t.getBitrate(),k=d?null:await t.getAverageBitrate();this.output.addAudioTrack(a,{languageCode:Sr(p)?p:void 0,name:g??void 0,disposition:h,group:f??e.group,bitrate:y??void 0,averageBitrate:k??void 0}),this.utilizedTracks.push(t),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(f)}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:ee(),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}=ee();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=J(t/this._totalDuration,0,1);this._lastProcessedTime=t,e!==this._lastProgress&&(this._lastProgress=e,this.onProgress?.(e,t))}},jn=class extends Error{constructor(t="Conversion has been canceled."){super(t),this.name="ConversionCanceledError"}},tp=1,_l=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>tp}wait(t){let{promise:e,resolve:r}=ee();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<tp&&(r.resolve(),this.resolvers.splice(e,1),e--)}return t}};var rp=Symbol.for("mediabunny loaded");globalThis[rp]&&V._error(`[WARNING]
50
50
  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[rp]=!0;return lp(mb);})();
51
51
  if (typeof module === "object" && typeof module.exports === "object") Object.assign(module.exports, Mediabunny)