@volter/game-editor 0.5.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 (653) hide show
  1. package/BUNDLED_NOTICES +11228 -0
  2. package/LICENSE +686 -0
  3. package/LICENSE-BLENDER +1409 -0
  4. package/LICENSE-MCP +21 -0
  5. package/NOTICE +21 -0
  6. package/catalog/entries/audio.json +14 -0
  7. package/catalog/entries/bake.json +36 -0
  8. package/catalog/entries/blender.json +17 -0
  9. package/catalog/entries/react-root.json +24 -0
  10. package/catalog/entries/reflections.json +29 -0
  11. package/catalog/entries/static-batch.json +25 -0
  12. package/catalog/project-source/LICENSE +37 -0
  13. package/catalog/project-source/src/contributions/bake.kind.ts +40 -0
  14. package/catalog/project-source/src/contributions/builder-document.tsx +65 -0
  15. package/catalog/project-source/src/contributions/builder-state.ts +27 -0
  16. package/catalog/project-source/src/contributions/builder-ui.tsx +61 -0
  17. package/catalog/project-source/src/contributions/module-source.ts +502 -0
  18. package/catalog/project-source/src/contributions/pages.finder.ts +61 -0
  19. package/catalog/project-source/src/lib/audio/sfx.ts +255 -0
  20. package/catalog/project-source/src/lib/bake/asset-seed.ts +128 -0
  21. package/catalog/project-source/src/lib/bake/bake-schema.ts +65 -0
  22. package/catalog/project-source/src/lib/bake/clip-layering.ts +203 -0
  23. package/catalog/project-source/src/lib/bake/gltf-bake.ts +657 -0
  24. package/catalog/project-source/src/lib/bake/mesh-slice.ts +157 -0
  25. package/catalog/project-source/src/lib/bake/node-image.ts +463 -0
  26. package/catalog/project-source/src/lib/bake/object3d-bake.ts +121 -0
  27. package/catalog/project-source/src/lib/bake/object3d-lifecycle.ts +15 -0
  28. package/catalog/project-source/src/lib/bake/object3d-source.ts +8 -0
  29. package/catalog/project-source/src/lib/bake/params.ts +75 -0
  30. package/catalog/project-source/src/lib/bake/rest-relative-animation.ts +217 -0
  31. package/catalog/project-source/src/lib/bake/use-model.ts +95 -0
  32. package/catalog/project-source/src/lib/react-root/index.ts +20 -0
  33. package/catalog/project-source/src/lib/react-root/react-root-adapter.tsx +57 -0
  34. package/catalog/project-source/src/lib/reflections/ReflectionProbe.tsx +201 -0
  35. package/catalog/project-source/src/lib/reflections/index.ts +19 -0
  36. package/catalog/project-source/src/lib/reflections/probe-controller.ts +75 -0
  37. package/catalog/project-source/src/lib/reflections/reflection-probe-registry.ts +402 -0
  38. package/catalog/project-source/src/lib/reflections/volume-reflection-material.ts +416 -0
  39. package/catalog/project-source/src/lib/static-batch/Frozen.tsx +91 -0
  40. package/catalog/project-source/src/lib/static-batch/freeze.ts +579 -0
  41. package/catalog/project-source/src/lib/static-batch/index.ts +44 -0
  42. package/catalog/project-source/src/lib/static-batch/mutation-watch.ts +149 -0
  43. package/catalog/project-source/src/lib/static-batch/shadow-cache.ts +171 -0
  44. package/catalog/project-source/src/tools/bake-module.tool.ts +139 -0
  45. package/catalog/project-source/src/tools/bake-preview.tool.ts +475 -0
  46. package/dist/.vite/manifest.json +8304 -0
  47. package/dist/assets/AssetBudgetPanel-J9--TZPU.js +23 -0
  48. package/dist/assets/AudioViewer-CR7333fe.js +1 -0
  49. package/dist/assets/BVHLoader-6bQIXhMX.js +1 -0
  50. package/dist/assets/BufferGeometryUtils-Nz37EVXf.js +1 -0
  51. package/dist/assets/CCDIKSolver-CD7vLpsK.js +1 -0
  52. package/dist/assets/CSS3DRenderer-CL7ABLVK.js +1 -0
  53. package/dist/assets/CanvasSceneViewport-Bpi6gVTC.js +1 -0
  54. package/dist/assets/ColladaLoader-aVOPIsCh.js +3 -0
  55. package/dist/assets/ColorInput-DQBNrW-K.js +1 -0
  56. package/dist/assets/ConvexGeometry-CAzXlPVG.js +1 -0
  57. package/dist/assets/ConvexHull-BINCESFp.js +1 -0
  58. package/dist/assets/CopyShader-BzTUYzf6.js +24 -0
  59. package/dist/assets/DecalGeometry-160KRdfg.js +1 -0
  60. package/dist/assets/EXRLoader-Cdans_oJ.js +1 -0
  61. package/dist/assets/EffectComposer-DQxfsXBZ.js +1 -0
  62. package/dist/assets/EntityModelDocument-Ccvw66N9.js +1 -0
  63. package/dist/assets/EnvironmentAssetDocument-Dg-Qq6O6.js +1 -0
  64. package/dist/assets/FBXLoader-B4MoUtAn.js +1 -0
  65. package/dist/assets/Fbo-Dz-Soul3.js +1 -0
  66. package/dist/assets/FontLoader-CvGoVI5a.js +2 -0
  67. package/dist/assets/GLTFExporter-HgrCle4L.js +1 -0
  68. package/dist/assets/GameplaySessionTimeline-B52W3FVZ.js +1 -0
  69. package/dist/assets/Gltf-UHVWKz65.js +2 -0
  70. package/dist/assets/HDRLoader-THU88oVD.js +5 -0
  71. package/dist/assets/ImageViewer-Tn7s_MnW.js +1 -0
  72. package/dist/assets/InspectorCanvasPreview-CEr_Kxna.js +1 -0
  73. package/dist/assets/InspectorObjectPreview-CVejvLRg.js +1 -0
  74. package/dist/assets/JsonAssetDocument-C7VGcLhu.js +3 -0
  75. package/dist/assets/LineSegments2-CsOpKSiM.js +370 -0
  76. package/dist/assets/MTLLoader-_Xzd4_0p.js +2 -0
  77. package/dist/assets/MarchingCubes-Bsp4wrzd.js +1 -0
  78. package/dist/assets/MeshBVH-BiDHDcu-.js +1 -0
  79. package/dist/assets/ModelAssetDocument-F5GACirk.js +1 -0
  80. package/dist/assets/NonThreeAuthoringBootstrap-C3woOMxX.js +1 -0
  81. package/dist/assets/OBJLoader-BhIC6Hwo.js +5 -0
  82. package/dist/assets/Object3DDocumentViewport-DB7T0NTl.js +2 -0
  83. package/dist/assets/Object3DPreview-DL8oi7Xs.js +2 -0
  84. package/dist/assets/OnlineAssetDetail-C6z9RvYK.js +2 -0
  85. package/dist/assets/OrbitControls-CM3bPray.js +1 -0
  86. package/dist/assets/OrbitControls-DLpayAaK.js +1 -0
  87. package/dist/assets/OrthographicCamera-bQozawrh.js +1 -0
  88. package/dist/assets/PLYLoader-DYQqs5Ik.js +2 -0
  89. package/dist/assets/PerspectiveCamera-CQ2lh01o.js +1 -0
  90. package/dist/assets/PlayBar-BR-Vg3Jb.js +2 -0
  91. package/dist/assets/RGBELoader-BgBcQv8j.js +1 -0
  92. package/dist/assets/RectAreaLightUniformsLib-CMMoWfll.js +1 -0
  93. package/dist/assets/RenderPass-DPrn-Uky.js +1 -0
  94. package/dist/assets/ResolutionPicker-C67vs1F3.js +1 -0
  95. package/dist/assets/RootSelectionOverlay-BZPlxmXU.js +1 -0
  96. package/dist/assets/RoundedBox-BDGBg6QZ.js +1 -0
  97. package/dist/assets/RoundedBoxGeometry-CyUuYPfW.js +1 -0
  98. package/dist/assets/STLLoader-Dyv3lsxY.js +1 -0
  99. package/dist/assets/SelectionBox-D_75KrNW.js +1 -0
  100. package/dist/assets/ShaderPass-QYRpPuFJ.js +1 -0
  101. package/dist/assets/ShadowEditor-DkImwu1Y.js +1 -0
  102. package/dist/assets/SimplifyModifier-C8ayvRzd.js +1 -0
  103. package/dist/assets/SkeletonUtils-Cps8GOC6.js +1 -0
  104. package/dist/assets/Sky-CQKCgYDs.js +154 -0
  105. package/dist/assets/SourceAssetViewer-2SWQoUut.js +12 -0
  106. package/dist/assets/StageHost-BN-IoTef.js +2 -0
  107. package/dist/assets/StoryPreviewMount-DjyxRCXu.js +1 -0
  108. package/dist/assets/TDSLoader-D_T8XJ81.js +1 -0
  109. package/dist/assets/TextGeometry-DOWAEUV0.js +1 -0
  110. package/dist/assets/ThreeBoardDocument-CVncZyIq.js +2 -0
  111. package/dist/assets/ThreeIsolationSceneContent-C8C8whSF.js +1 -0
  112. package/dist/assets/ToolObject3DPreview-BRoDWe4Q.js +1 -0
  113. package/dist/assets/TrackballControls-DfznuQTh.js +1 -0
  114. package/dist/assets/TransientHint-BB1fwrvK.js +1 -0
  115. package/dist/assets/UnrealBloomPass-CR-cS_K5.js +83 -0
  116. package/dist/assets/VideoViewer-C6kocgIU.js +1 -0
  117. package/dist/assets/_commonjsHelpers-D6-XlEtG.js +1 -0
  118. package/dist/assets/active-ingest-CT6jSGhr.js +3 -0
  119. package/dist/assets/adapter-surface-Y37Nzcyw.js +1 -0
  120. package/dist/assets/after-paint-CB4bz1-e.js +1 -0
  121. package/dist/assets/agx-base-srgb-BjWZJgrZ.lut +0 -0
  122. package/dist/assets/agx-look-medium-high-contrast-D5F_ob1L.lut +0 -0
  123. package/dist/assets/agx-look-punchy-dxsnycNs.lut +0 -0
  124. package/dist/assets/animation-clock-CnjZqfJp.js +1 -0
  125. package/dist/assets/asset-budget-asset.menu-Di3KiQCd.js +1 -0
  126. package/dist/assets/asset-budget.action-DCzzcuTh.js +1 -0
  127. package/dist/assets/asset-budget.document-BWU8wnVW.js +1 -0
  128. package/dist/assets/asset-budget.menu-BGZpT_31.js +1 -0
  129. package/dist/assets/asset-editor-persistence-BBaONOJt.js +1 -0
  130. package/dist/assets/asset-loaders-BOy5Ss8k.js +2 -0
  131. package/dist/assets/asset-parse-error-BHMwBRU3.js +3 -0
  132. package/dist/assets/assets-BuSoGjBX.js +1 -0
  133. package/dist/assets/audio-meter-CyiToeUW.js +1 -0
  134. package/dist/assets/audio-unlock.service-CfUgUQVy.js +1 -0
  135. package/dist/assets/audio.utility-C6K6jem8.js +1 -0
  136. package/dist/assets/authoring-CgcOFhGS.js +1 -0
  137. package/dist/assets/autoplay.service-BZBGNSvt.js +1 -0
  138. package/dist/assets/axe-LkjAB6Lv.js +30 -0
  139. package/dist/assets/babylon-authoring-adapter-CL02gWDn.js +1 -0
  140. package/dist/assets/binding-Bmxqznjk.js +1 -0
  141. package/dist/assets/binding-identity-DcTpbvyg.js +1 -0
  142. package/dist/assets/binding-resolver-Dsh-6Vor.js +2 -0
  143. package/dist/assets/blender-emscripten-engine-9ZIRYNhe.js +2 -0
  144. package/dist/assets/blender-node-editor.document-iIDkB9sI.js +1 -0
  145. package/dist/assets/blender-properties-tab-C5CyPydi.js +3 -0
  146. package/dist/assets/blender-runtime-host-BpBwGv7r.js +4 -0
  147. package/dist/assets/blender-runtime-skin-DyQ9B6CR.js +7140 -0
  148. package/dist/assets/blender-runtime.document-lIYhhPtv.js +8 -0
  149. package/dist/assets/blender-timeline.document-77fx96N7.js +1 -0
  150. package/dist/assets/blender-uv-editor.document-fsT7B4gV.js +1 -0
  151. package/dist/assets/blender-version.status-o6dBm3n6.js +1 -0
  152. package/dist/assets/blender-wali-engine-wTOcrOMC.js +2 -0
  153. package/dist/assets/blender.command-BtJeWk-A.js +1 -0
  154. package/dist/assets/blender.keymap-GAQgeklK.js +1 -0
  155. package/dist/assets/blender.status-ujwGU6dU.js +1 -0
  156. package/dist/assets/blender.style-Dcem5f_T.js +1 -0
  157. package/dist/assets/board-guides-DziKSTss.js +1 -0
  158. package/dist/assets/body-marks-h_xDxiDE.js +1 -0
  159. package/dist/assets/bridge.command-o5gDNEwa.js +3 -0
  160. package/dist/assets/browserAll-DeWblVez.js +1 -0
  161. package/dist/assets/build-profiles.document-kW8iw8Xj.js +2 -0
  162. package/dist/assets/build-progress.status-BNRLytg2.js +1 -0
  163. package/dist/assets/build-session-C_sg3CEn.js +9 -0
  164. package/dist/assets/build.action-lYjTLb7K.js +1 -0
  165. package/dist/assets/build.command-DIGgUPU_.js +1 -0
  166. package/dist/assets/build.header-CKajx5U3.js +1 -0
  167. package/dist/assets/build.menu-BdU0QXny.js +1 -0
  168. package/dist/assets/build.service-CbBAyeu3.js +1 -0
  169. package/dist/assets/bus-mixer-CGfWDP3C.js +1 -0
  170. package/dist/assets/camera-KEsKvOL7.js +1 -0
  171. package/dist/assets/camera-runtime.inspector-B7unX4g1.js +1 -0
  172. package/dist/assets/canvas-entry-runtime-SfBxaR9M.js +2 -0
  173. package/dist/assets/capability-coverage-Czas4C18.js +7 -0
  174. package/dist/assets/chrome-trace-YZHMz60-.js +1 -0
  175. package/dist/assets/client-DNXj_opT.js +25 -0
  176. package/dist/assets/clip-planes-CnAI6DZn.js +1 -0
  177. package/dist/assets/collaboration-presence-DLoZ7EA3.js +1 -0
  178. package/dist/assets/collider-Bw0mXlsW.js +1 -0
  179. package/dist/assets/collider-dimensions-9xoFADXN.js +1 -0
  180. package/dist/assets/collision-system-DpNUJRJ3.js +1 -0
  181. package/dist/assets/command-results-CUQD49AB.js +1 -0
  182. package/dist/assets/component-board-registry-DrIa2csL.js +1 -0
  183. package/dist/assets/component-board.service-DCwcUssB.js +2 -0
  184. package/dist/assets/component-board.service-DidCyM4O.js +2 -0
  185. package/dist/assets/component-verbs.command-7xzfjGMZ.js +1 -0
  186. package/dist/assets/component-verbs.service-Bv9jId3q.js +1 -0
  187. package/dist/assets/config-CEZk921y.js +6 -0
  188. package/dist/assets/configurations-DTBMdaTL.js +1 -0
  189. package/dist/assets/connection.status-BifnQdOs.js +1 -0
  190. package/dist/assets/console-bridge-CHcb-xk5.js +1 -0
  191. package/dist/assets/constraint-De8f1Uiq.js +1 -0
  192. package/dist/assets/constraints.inspector-B9U9Yj-u.js +1 -0
  193. package/dist/assets/countdown-timer-CUm74dom.js +1 -0
  194. package/dist/assets/coverage.service-VTX5Mcsx.js +3 -0
  195. package/dist/assets/crash-null-boundary-v3a0uEgw.js +1 -0
  196. package/dist/assets/create-runtime-CVCc1BDx.js +1 -0
  197. package/dist/assets/curve-7Q79VgU4.js +1 -0
  198. package/dist/assets/data-asset-4hjS642k.js +5 -0
  199. package/dist/assets/data-check-core-CQEjuFyt.js +1 -0
  200. package/dist/assets/data-ref-CQI28C0D.js +1 -0
  201. package/dist/assets/debug-bridge-CCohG-d-.js +1 -0
  202. package/dist/assets/debug-registry-Dgvitx8M.js +1 -0
  203. package/dist/assets/defaults-DKiBJCPN.js +1 -0
  204. package/dist/assets/deferred-commands-CEMmvL47.js +1 -0
  205. package/dist/assets/deferred-ingest-play-DCJi_Pgu.js +2 -0
  206. package/dist/assets/design-time-layers-wYgOTgni.js +1 -0
  207. package/dist/assets/design-time-mount-registry-DUpXCg1U.js +1 -0
  208. package/dist/assets/design-time-mount.service-BzY21e1F.js +2 -0
  209. package/dist/assets/design-time-react-mount-DM9WLrF2.js +1 -0
  210. package/dist/assets/dev-build-gDYrq68M.js +1 -0
  211. package/dist/assets/directional-shadow-fit-BVkOKAv2.js +1 -0
  212. package/dist/assets/document-preview-three-Kbg2GCLm.js +1 -0
  213. package/dist/assets/dom-authoring-adapter-CY8C7f4T.js +1 -0
  214. package/dist/assets/draco3d-BBUTcNkz.js +1 -0
  215. package/dist/assets/draco_decoder-DsQ12WqX.wasm +0 -0
  216. package/dist/assets/draco_encoder-2Tcju8Ns.wasm +0 -0
  217. package/dist/assets/edit-mode-audio.service-Bzetwd5B.js +1 -0
  218. package/dist/assets/edit-mode-authoring-B47TfLqu.js +1 -0
  219. package/dist/assets/edit-mode-networking.service-YCX6RRb_.js +1 -0
  220. package/dist/assets/editor-api-BoJIcyZG.js +1 -0
  221. package/dist/assets/editor-port-C_FeBdeV.js +1 -0
  222. package/dist/assets/editor-presentation-activity-C7SNSmTd.js +1 -0
  223. package/dist/assets/entry-adjudication-Cq8Yeb74.js +1 -0
  224. package/dist/assets/environment-capture-7himRh2L.js +1 -0
  225. package/dist/assets/esbuild-BHljloGq.wasm +0 -0
  226. package/dist/assets/events-156d8d12.esm-ErOhDXXB.js +36 -0
  227. package/dist/assets/extend-B-eOccUm.js +36 -0
  228. package/dist/assets/extends-CF3RwP-h.js +1 -0
  229. package/dist/assets/eyedropper-session-bjPXnfeX.js +1 -0
  230. package/dist/assets/fflate.module-DPuTF8aG.js +6 -0
  231. package/dist/assets/filmic-srgb-Ct35FIH6.lut +0 -0
  232. package/dist/assets/first-party-audio-system-DxnGJOER.js +1 -0
  233. package/dist/assets/first-party-navigation-system-CL5Bquub.js +1 -0
  234. package/dist/assets/fork-menu-BoVyw2Wu.js +1 -0
  235. package/dist/assets/frame-debugger-store-D1Mf_5up.js +1 -0
  236. package/dist/assets/frame-delta-D2nsw_Ht.js +1 -0
  237. package/dist/assets/frame-pacing-D5acoOzO.js +1 -0
  238. package/dist/assets/frame-selector-cache-cCeUbcjG.js +1 -0
  239. package/dist/assets/game-DHOZVb-7.js +1 -0
  240. package/dist/assets/game-contract-seams-a5YXejOu.js +1 -0
  241. package/dist/assets/game-css-scope-transform-Eng4wS8E.js +33 -0
  242. package/dist/assets/game-document.service-DbRfx2V0.js +1 -0
  243. package/dist/assets/game-eval.command-D-7Dxbj_.js +2 -0
  244. package/dist/assets/game-input-seams-CIQdetRw.js +1 -0
  245. package/dist/assets/game-loop-CZvXlY00.js +1 -0
  246. package/dist/assets/game-module-access-B2mFxv-i.js +1 -0
  247. package/dist/assets/game.layout-CBASrvQu.js +1 -0
  248. package/dist/assets/gameplay-export-BoKXm51x.js +1 -0
  249. package/dist/assets/gameplay-replay-e5umMlXv.js +1 -0
  250. package/dist/assets/gameplay-rng-trap-CTNhm-UW.js +3 -0
  251. package/dist/assets/gameplay.command-DxcVYX6F.js +1 -0
  252. package/dist/assets/generation-DhwCUHPf.css +1 -0
  253. package/dist/assets/generation-jobs-BQrXbGp_.js +1 -0
  254. package/dist/assets/generation.service-CDIgObuw.js +1 -0
  255. package/dist/assets/generations-DzUogZsM.js +1 -0
  256. package/dist/assets/generations.status-CgOUBCum.js +1 -0
  257. package/dist/assets/hierarchy-marks-BLPfSIym.js +1 -0
  258. package/dist/assets/host-pointer-DbGSCjE9.js +1 -0
  259. package/dist/assets/hosted-asset-materialization-CiIvWkGU.js +2 -0
  260. package/dist/assets/ibl-override-material-BlmCxFKq.js +6 -0
  261. package/dist/assets/index-96FBF1Oj.js +1 -0
  262. package/dist/assets/index-BAWkB0dv.js +1 -0
  263. package/dist/assets/index-BDnS2b6S.js +1 -0
  264. package/dist/assets/index-BHp07vN0.js +2 -0
  265. package/dist/assets/index-BMxv2MNV.js +1 -0
  266. package/dist/assets/index-BP6wv2A0.js +5 -0
  267. package/dist/assets/index-BcCBqgM_.js +952 -0
  268. package/dist/assets/index-Bge9JUr6.js +1 -0
  269. package/dist/assets/index-BjTCPEQ7.js +134 -0
  270. package/dist/assets/index-BncK9THk.js +1 -0
  271. package/dist/assets/index-CJbYy-CF.js +3 -0
  272. package/dist/assets/index-CVCb_ImQ.js +1 -0
  273. package/dist/assets/index-CZd9o7Lu.js +1 -0
  274. package/dist/assets/index-CanA16PU.js +2 -0
  275. package/dist/assets/index-CinJrH5C.js +9 -0
  276. package/dist/assets/index-CtzuWnCS.js +1 -0
  277. package/dist/assets/index-D2fNXpHa.css +1 -0
  278. package/dist/assets/index-DUpHH6JR.js +3120 -0
  279. package/dist/assets/index-DUqP1RMl.js +1 -0
  280. package/dist/assets/index-D_NuPfjr.js +9 -0
  281. package/dist/assets/index-Da9JhEvW.js +25 -0
  282. package/dist/assets/index-DgapqSPi.js +7 -0
  283. package/dist/assets/index-FUuS4qwW.js +562 -0
  284. package/dist/assets/index-GIL7oGEO.js +4894 -0
  285. package/dist/assets/index-IEjydI9d.js +1 -0
  286. package/dist/assets/index-OrYXPk3Z.js +487 -0
  287. package/dist/assets/index-V1R-e5Bd.js +1 -0
  288. package/dist/assets/index-bQE2NA0D.js +1 -0
  289. package/dist/assets/index-gHZae-lw.js +13 -0
  290. package/dist/assets/index-mjWQmGhM.js +1 -0
  291. package/dist/assets/index-nmcBqr7Y.js +1 -0
  292. package/dist/assets/inference-diagnostics-Dhmtfbq_.js +1 -0
  293. package/dist/assets/ingest-BbYMC2vQ.js +1 -0
  294. package/dist/assets/ingest-boot-viewport-D5rI_Kk_.js +1 -0
  295. package/dist/assets/ingest-siblings-Bop2kqVl.js +1 -0
  296. package/dist/assets/ingest-source-persistence-C_6Hiyra.js +1 -0
  297. package/dist/assets/ingest.service-BTDnQfM1.js +1 -0
  298. package/dist/assets/input-manager-DH_hGW6d.js +1 -0
  299. package/dist/assets/input-router-BNQvtIqw.js +1 -0
  300. package/dist/assets/inspect-BZfi3mmo.js +1 -0
  301. package/dist/assets/inspection-CObLhnrs.js +1 -0
  302. package/dist/assets/instance-fork-actions-D3sRzS3K.js +1 -0
  303. package/dist/assets/instances.command-D6UkZNO8.js +1 -0
  304. package/dist/assets/instruments-CKR02Y8I.js +1 -0
  305. package/dist/assets/json-history-resource-BbxllWfV.js +1 -0
  306. package/dist/assets/jsx-runtime-DPjLkJKQ.js +9 -0
  307. package/dist/assets/light-D-_wsKTq.js +1 -0
  308. package/dist/assets/light-camera-factory-CWbbe9gI.js +1 -0
  309. package/dist/assets/lil-gui.module.min-BF55BEwA.js +10 -0
  310. package/dist/assets/live-behaviors-Bxq49Maz.js +1 -0
  311. package/dist/assets/live-gesture-lock-DJbrjOqf.js +1 -0
  312. package/dist/assets/loader-CaF_I7Yt.js +1 -0
  313. package/dist/assets/logger-Dqis-7W1.js +1 -0
  314. package/dist/assets/loop-gate-report-N52EWFGD.js +1 -0
  315. package/dist/assets/matcap-texture-CVfalpWT.js +1 -0
  316. package/dist/assets/material-CpAdjDxn.js +1 -0
  317. package/dist/assets/material-factory-Bz6h__6g.js +1 -0
  318. package/dist/assets/mesh-B3WPtNKO.js +1 -0
  319. package/dist/assets/mesh-shadow-CZnXrw_l.js +1 -0
  320. package/dist/assets/mikktspace.module-DO88SLib.js +1 -0
  321. package/dist/assets/model-asset-sections-CFvvihfx.css +1 -0
  322. package/dist/assets/model-asset-sections.service-CHhFS3ZX.js +1 -0
  323. package/dist/assets/model.layout-BJUEQYUI.js +1 -0
  324. package/dist/assets/models.finder-G2jQgIRu.js +1 -0
  325. package/dist/assets/module-mode-DVBLT9d-.js +2 -0
  326. package/dist/assets/mount-canvas-ingest-root-DDuAWf_C.js +2 -0
  327. package/dist/assets/mount-dom-ingest-root-D_EiBgpn.js +2 -0
  328. package/dist/assets/mount-game-6t9cKNo4.js +1 -0
  329. package/dist/assets/mount-ingest-root-glv2SSWf.js +2 -0
  330. package/dist/assets/mount-manifest-CGVxhmAw.js +1 -0
  331. package/dist/assets/mount-readiness-Ds0HvvLH.js +4 -0
  332. package/dist/assets/mount-three-ingest-root-hrUt9VVU.js +1 -0
  333. package/dist/assets/mounted-authoring-Dmg5xmhP.js +1 -0
  334. package/dist/assets/mounted-story-viewport-source-DjP6RA9U.js +1 -0
  335. package/dist/assets/native-debug-module-CWicoSGD.js +1 -0
  336. package/dist/assets/native-entry-surface-BE8LJNdu.js +1 -0
  337. package/dist/assets/navigation-CIiCx-SM.js +1 -0
  338. package/dist/assets/navmesh-workflow-store-Cmnm57TB.js +1 -0
  339. package/dist/assets/navmesh.menu-CAKiH8PW.js +1 -0
  340. package/dist/assets/navmesh.service-jgDWlgj1.js +1 -0
  341. package/dist/assets/network.utility-CEu5nHf7.js +1 -0
  342. package/dist/assets/object-marks-DwvIEBOK.js +1 -0
  343. package/dist/assets/object3d-authoring-subject-CH5sI2oP.js +1 -0
  344. package/dist/assets/output-DK8waum9.js +195 -0
  345. package/dist/assets/particles-Y626p22p.js +1 -0
  346. package/dist/assets/particles-factory-DnLOHXT8.js +1 -0
  347. package/dist/assets/pasteboard-materialize-BqSS4QzV.js +20 -0
  348. package/dist/assets/pasteboard.action-DU3UHtJG.js +2 -0
  349. package/dist/assets/performance-profiler-D_Jey87L.js +1 -0
  350. package/dist/assets/physics-registry-B2Jkp8e6.js +1 -0
  351. package/dist/assets/physics-registry-CUB9cT9p.js +1 -0
  352. package/dist/assets/pixi-authoring-adapter-CjibysC3.js +1 -0
  353. package/dist/assets/pixi-live-write-target-DuWydlWb.js +1 -0
  354. package/dist/assets/pixi-primitive-DlWbUPN9.js +1 -0
  355. package/dist/assets/pixi-react-root-factory-DYsznYRQ.js +1 -0
  356. package/dist/assets/pixi-story-model-DNkfnWUV.js +1 -0
  357. package/dist/assets/pixi-transform-channels-VjdohT11.js +1 -0
  358. package/dist/assets/play-mode-BFU2PCkG.js +22 -0
  359. package/dist/assets/play.command-BpqqLqkq.js +2 -0
  360. package/dist/assets/playtest-BXIL1JEF.js +1 -0
  361. package/dist/assets/pose-guard-6Osb2cFu.js +1 -0
  362. package/dist/assets/presentation-BPP5pXeQ.js +1 -0
  363. package/dist/assets/product-DFhyARJj.js +1 -0
  364. package/dist/assets/profiler.action-CaXJDp3t.js +1 -0
  365. package/dist/assets/profiler.menu-BIMF6Bi4.js +1 -0
  366. package/dist/assets/profiler.utility-BExw9wBO.js +1 -0
  367. package/dist/assets/project-authoring-session-Bnt6icLr.js +2 -0
  368. package/dist/assets/project-provenance-BoP3nrle.js +1 -0
  369. package/dist/assets/prompt-labels-DSMdM2_B.js +1 -0
  370. package/dist/assets/properties-bone-constraints.inspector-ByT6p7S-.js +1 -0
  371. package/dist/assets/properties-bone.inspector-z4qJwKO5.js +1 -0
  372. package/dist/assets/properties-collection.inspector-D0_3ijWU.js +1 -0
  373. package/dist/assets/properties-constraints.inspector-CESzjuls.js +1 -0
  374. package/dist/assets/properties-data.inspector-hG8Wgyzb.js +1 -0
  375. package/dist/assets/properties-material.inspector-CzY0JCQ6.js +1 -0
  376. package/dist/assets/properties-modifiers.inspector-3dDhwf7g.js +1 -0
  377. package/dist/assets/properties-object.inspector-CiarfxkT.js +1 -0
  378. package/dist/assets/properties-output.inspector-DKJxmKSD.js +1 -0
  379. package/dist/assets/properties-particles.inspector-CCEdYWGm.js +1 -0
  380. package/dist/assets/properties-physics.inspector-B2c0KUyA.js +1 -0
  381. package/dist/assets/properties-render.inspector-Bcm0HLRW.js +1 -0
  382. package/dist/assets/properties-scene.inspector-PIM_eTb_.js +1 -0
  383. package/dist/assets/properties-texture.inspector-CgFlnyr8.js +1 -0
  384. package/dist/assets/properties-view-layer.inspector-DGjF_Aqo.js +1 -0
  385. package/dist/assets/properties-world.inspector-CrMvaRvB.js +1 -0
  386. package/dist/assets/r3f-design-session-D-4yyDO9.js +2 -0
  387. package/dist/assets/r3f-physics-binding-BBo8oma9.js +1 -0
  388. package/dist/assets/r3f-root-factory-z9llD1OU.js +1 -0
  389. package/dist/assets/r3f-source-authoring-adapter-w6Bc60K-.js +13 -0
  390. package/dist/assets/rapier-physics-adapter-CaZqWLu0.js +1 -0
  391. package/dist/assets/rapier-physics-bridge-CMoeVo3Y.js +1 -0
  392. package/dist/assets/react-18-By2b4xR9.js +1 -0
  393. package/dist/assets/react-inspector.service-B_neRnSK.js +1 -0
  394. package/dist/assets/react-root-CEz5NTck.js +1 -0
  395. package/dist/assets/react-story-board-BDDwiE2H.js +1 -0
  396. package/dist/assets/react-three-fiber.esm-CycrbDlA.js +1 -0
  397. package/dist/assets/react-three-rapier.esm-CEfKpvxT.js +1 -0
  398. package/dist/assets/react-world-authoring-adapter-DmrwM3py.js +1 -0
  399. package/dist/assets/realm-services-CobQsq_X.js +1 -0
  400. package/dist/assets/rebind-controller-Dtq19Vb3.js +1 -0
  401. package/dist/assets/recast-navigation.wasm-compat-Dsoa_MD-.js +1 -0
  402. package/dist/assets/reflection-probe-Don-M3Fj.js +1 -0
  403. package/dist/assets/reflection-probe-capture.inspector-CmFUoJCx.js +1 -0
  404. package/dist/assets/register-render-vitals-BiZk29b2.js +1 -0
  405. package/dist/assets/registry-02YZjMNp.js +1 -0
  406. package/dist/assets/relative-path-guard-GiM7Lsz8.js +1 -0
  407. package/dist/assets/render-audio-control-vMRlePWb.js +1 -0
  408. package/dist/assets/render-batch-system-0vq7p0VC.js +1 -0
  409. package/dist/assets/render-census-BrQX_CXv.js +1 -0
  410. package/dist/assets/render-control-Df3yTiyr.js +1 -0
  411. package/dist/assets/render-env-D2IV2x5k.js +1 -0
  412. package/dist/assets/render-features-CPQ_e568.js +1 -0
  413. package/dist/assets/render-seed-DF4JHy7P.js +1 -0
  414. package/dist/assets/render-settings-Bw4W9SYF.js +1 -0
  415. package/dist/assets/render-vitals-BZ5HtvMi.js +1 -0
  416. package/dist/assets/renderer-config-BqG4O8i9.js +1 -0
  417. package/dist/assets/resolve-three-SZE_WWUM.js +702 -0
  418. package/dist/assets/root-seam-contract-Z0VWX3Bk.js +1 -0
  419. package/dist/assets/rrweb-Cd2ifIRP.js +142 -0
  420. package/dist/assets/run-ticks-settled-C4ksViyA.js +1 -0
  421. package/dist/assets/runtime-inspection-l2iFQSsg.js +1 -0
  422. package/dist/assets/scene-capture-BQKzU0NT.js +1 -0
  423. package/dist/assets/scene-capture-CGYF-Viw.js +1 -0
  424. package/dist/assets/scene-document.service-qkDjUrlP.js +2 -0
  425. package/dist/assets/scene-framing-Cat0GtyJ.js +1 -0
  426. package/dist/assets/scene-index-B6BZOHMk.js +1 -0
  427. package/dist/assets/scene-query-C7_N-TpI.js +1 -0
  428. package/dist/assets/schema-kl9-2B_J.js +1 -0
  429. package/dist/assets/sculpt.layout-zJF55yCR.js +1 -0
  430. package/dist/assets/seeded-random-i3mtgBKZ.js +1 -0
  431. package/dist/assets/session-CZ5JPg-z.js +4877 -0
  432. package/dist/assets/setup-audio-S8GQF91f.js +1 -0
  433. package/dist/assets/setup-particles-GCXlnkj_.js +1 -0
  434. package/dist/assets/setup-physics-BeZ7-LKD.js +1 -0
  435. package/dist/assets/setup-renderer-DVXaSGin.js +1587 -0
  436. package/dist/assets/shading.layout-DULYZV6M.js +1 -0
  437. package/dist/assets/sim-clock-CLflx7kg.js +1 -0
  438. package/dist/assets/sky-precompute-worker-ChN7J87v.js +1 -0
  439. package/dist/assets/soft-particle-depth-DGvfQDi1.js +1 -0
  440. package/dist/assets/source-object3d-authoring-adapter-B-L6Ha6f.js +1 -0
  441. package/dist/assets/source-persistence-backend-C-aR-B_Y.js +1 -0
  442. package/dist/assets/spark-renderer-lifecycle-ynWESJcv.js +1 -0
  443. package/dist/assets/spark.module-4pXQoz5d.js +12120 -0
  444. package/dist/assets/stage-invalidation-DBg3C3Ta.js +1 -0
  445. package/dist/assets/stage-keyboard-n-5kKH-m.js +1 -0
  446. package/dist/assets/stage-overlay-set-B9zp2sLB.js +1 -0
  447. package/dist/assets/stage-presence-markers-DiGI6A45.js +1 -0
  448. package/dist/assets/standard-viewport-dressing-CzjAe_0A.js +7 -0
  449. package/dist/assets/state-bridge-DLP1jLRW.js +1 -0
  450. package/dist/assets/state-watch.action-BOvQR2qt.js +1 -0
  451. package/dist/assets/state-watch.menu-CNLvDeeY.js +1 -0
  452. package/dist/assets/state-watch.utility-Bg1tTTQU.js +1 -0
  453. package/dist/assets/static-batch-advisor-B13QEH7d.js +1 -0
  454. package/dist/assets/stats.module-BL02l9NC.js +1 -0
  455. package/dist/assets/story-arg-descriptors-Ek86ExX7.js +1 -0
  456. package/dist/assets/story-capture-_gC8dXV-.js +1 -0
  457. package/dist/assets/story-documents--TDLaPeL.js +3 -0
  458. package/dist/assets/story-documents.service-BiS_YbNQ.js +1 -0
  459. package/dist/assets/story-documents.service-CxOPYJ2j.js +1 -0
  460. package/dist/assets/story-media-presence-BHzk2IV5.js +1 -0
  461. package/dist/assets/story-mount-turn-DFRTj5hi.js +1 -0
  462. package/dist/assets/story-pixi-preview-BUrOJZXS.js +1 -0
  463. package/dist/assets/story-presentation-j2AVN-mK.js +1 -0
  464. package/dist/assets/story-three-preview-BHEDZzcl.js +2 -0
  465. package/dist/assets/structural-ids-Dc-7rEwi.js +1 -0
  466. package/dist/assets/structural-signature-0w-i_ats.js +1 -0
  467. package/dist/assets/surface-content-Dg9Kkazf.js +1 -0
  468. package/dist/assets/surface-state-DaxyruCj.js +3 -0
  469. package/dist/assets/system-adapters-rIC8FSGP.js +1 -0
  470. package/dist/assets/system-runner-DkOjxEBt.js +1 -0
  471. package/dist/assets/system-slot-E2mEdiih.js +1 -0
  472. package/dist/assets/team-playtest.service-DqOinFVA.js +1 -0
  473. package/dist/assets/texture.layout-DASpHVht.js +1 -0
  474. package/dist/assets/three-CDSueJyJ.js +1 -0
  475. package/dist/assets/three-authoring-adapter-CmSQ3Vui.js +1 -0
  476. package/dist/assets/three-authoring.service-iuHLwtf1.js +2 -0
  477. package/dist/assets/three-ingest-runtime-QzDYk6tU.js +1 -0
  478. package/dist/assets/three-projection-core-BmKMZ-nf.js +1 -0
  479. package/dist/assets/three-viewport-presentation-QBQpSdMh.js +1 -0
  480. package/dist/assets/three.module-D396a9Mn.js +3840 -0
  481. package/dist/assets/three.quarks.esm-B1C61jGo.js +1039 -0
  482. package/dist/assets/tools-B_NJsk05.js +1 -0
  483. package/dist/assets/transform-writer-BhBBTx33.js +1 -0
  484. package/dist/assets/transport.header-B-6HQlU2.js +1 -0
  485. package/dist/assets/trigger-volume-BNK2XzPL.js +1 -0
  486. package/dist/assets/tuples-CIQ4Bn1U.js +1 -0
  487. package/dist/assets/tween.module-DciWpAG6.js +1 -0
  488. package/dist/assets/ui-board-document-Bwtt--xp.js +2 -0
  489. package/dist/assets/unexported-game-trap-Dm1JYKHy.js +2 -0
  490. package/dist/assets/unmanaged-root-detector-B8CpbkSN.js +2 -0
  491. package/dist/assets/upstream-pin-BdgRH6ID.js +1 -0
  492. package/dist/assets/use-data-Dzq-MytE.js +1 -0
  493. package/dist/assets/use-live-actor-state-DErbWQWF.js +1 -0
  494. package/dist/assets/use-selection-DbR73-xd.js +1 -0
  495. package/dist/assets/user-data-BB2Of6Ht.js +1 -0
  496. package/dist/assets/utility-view-state-BHypxA33.js +1 -0
  497. package/dist/assets/uv-editing.layout-BEKHxmHw.js +1 -0
  498. package/dist/assets/vgai-shared-fontawesome-CU65D4Ij.js +1 -0
  499. package/dist/assets/vgai-shared-jsx-dev-runtime-DFDKL7fx.js +1 -0
  500. package/dist/assets/vgai-shared-jsx-runtime-DIqBpTut.js +1 -0
  501. package/dist/assets/vgai-shared-react-BT7rMc2H.js +1 -0
  502. package/dist/assets/vgai-shared-react-dom-DFajMqMT.js +1 -0
  503. package/dist/assets/vgai-shared-react-dom-client-S0ozfl6_.js +1 -0
  504. package/dist/assets/vgai-shared-three-Bc5PvpLM.js +1 -0
  505. package/dist/assets/viewport-pick-context-DkawXbEi.js +1 -0
  506. package/dist/assets/viewport-root-presentation-CWsE56K6.js +1 -0
  507. package/dist/assets/viewport-shading-BuA88e_A.js +1 -0
  508. package/dist/assets/viewport-shading-boundary-B_-_gABg.js +82 -0
  509. package/dist/assets/viewport-surface-status-B3om4Kcf.js +1 -0
  510. package/dist/assets/vision_bundle-DX0dWqEa.js +15 -0
  511. package/dist/assets/voxel-surface-DtcsSWRL.js +1 -0
  512. package/dist/assets/wav-encode-D31zWF6O.js +1 -0
  513. package/dist/assets/webgl-frame-capture-FlF9zQmW.js +1 -0
  514. package/dist/assets/webgl-gpu-timer-D3YX7RaD.js +1 -0
  515. package/dist/assets/webworkerAll-CM2o_dnz.js +1 -0
  516. package/dist/assets/worker-UrMcrc5_.js +2 -0
  517. package/dist/assets/world-documents-147tiFZe.js +1 -0
  518. package/dist/assets/world-root-stage-binding-vwTrtBz6.js +1 -0
  519. package/dist/assets/world-state-BWG-IcOd.js +1 -0
  520. package/dist/assets/writer-B-KovzkA.js +5 -0
  521. package/dist/assets/xstate-animation-binding-Brd0NST6.js +1 -0
  522. package/dist/assets/xstate-animation-meta-Q3u9zh_m.js +1 -0
  523. package/dist/assets/xstate-behavior.action-B8UluFBK.js +1 -0
  524. package/dist/assets/xstate-behavior.document-CKAsE45I.js +1 -0
  525. package/dist/assets/xstate-behavior.inspector-vJJyuifc.js +1 -0
  526. package/dist/assets/xstate-behavior.menu-BXbPICIh.js +1 -0
  527. package/dist/assets/xstate-inspection-BsZv8LS9.js +1 -0
  528. package/dist/vgai-shared-react.json +10 -0
  529. package/dist/vgai-shared-three.json +3 -0
  530. package/dist-node/cli.js +9320 -0
  531. package/dist-node/create.js +3239 -0
  532. package/package.json +91 -0
  533. package/presets.mjs +2 -0
  534. package/src/contributions.d.ts +4 -0
  535. package/src/index.ts +38 -0
  536. package/starter/cube.blend +0 -0
  537. package/starter/cube.py +81 -0
  538. package/template/.agents/references/project-manual.md +341 -0
  539. package/template/.agents/skills/editor/SKILL.md +53 -0
  540. package/template/.agents/skills/editor/agents/openai.yaml +4 -0
  541. package/template/.agents/skills/editor/references/editor-control.md +363 -0
  542. package/template/.agents/skills/vgai-3d-models/SKILL.md +64 -0
  543. package/template/.agents/skills/vgai-ingest-existing-game/SKILL.md +112 -0
  544. package/template/.agents/skills/vgai-threejs-authoring/SKILL.md +347 -0
  545. package/template/.agents/skills/vgai-threejs-authoring/agents/openai.yaml +4 -0
  546. package/template/.agents/skills/vgai-threejs-authoring/references/helper-catalog.md +65 -0
  547. package/template/.claude/skills/editor/SKILL.md +53 -0
  548. package/template/.claude/skills/editor/agents/openai.yaml +4 -0
  549. package/template/.claude/skills/editor/references/editor-control.md +363 -0
  550. package/template/.claude/skills/vgai-3d-models/SKILL.md +64 -0
  551. package/template/.claude/skills/vgai-ingest-existing-game/SKILL.md +112 -0
  552. package/template/.claude/skills/vgai-threejs-authoring/SKILL.md +347 -0
  553. package/template/.claude/skills/vgai-threejs-authoring/agents/openai.yaml +4 -0
  554. package/template/.claude/skills/vgai-threejs-authoring/references/helper-catalog.md +65 -0
  555. package/template/.github/copilot-instructions.md +6 -0
  556. package/template/.github/skills/editor/SKILL.md +53 -0
  557. package/template/.github/skills/editor/agents/openai.yaml +4 -0
  558. package/template/.github/skills/editor/references/editor-control.md +363 -0
  559. package/template/.github/skills/vgai-3d-models/SKILL.md +64 -0
  560. package/template/.github/skills/vgai-ingest-existing-game/SKILL.md +112 -0
  561. package/template/.github/skills/vgai-threejs-authoring/SKILL.md +347 -0
  562. package/template/.github/skills/vgai-threejs-authoring/agents/openai.yaml +4 -0
  563. package/template/.github/skills/vgai-threejs-authoring/references/helper-catalog.md +65 -0
  564. package/template/.mcp.json +12 -0
  565. package/template/.vgai/assets.json +1 -0
  566. package/template/.vgai/provenance.json +4 -0
  567. package/template/.volter/tracker/validation/.preset.base.mts +178 -0
  568. package/template/.volter/tracker/validation/preset.mts +186 -0
  569. package/template/.volter/tracker/visualizer/.extension.base.tsx +14 -0
  570. package/template/.volter/tracker/visualizer/extension.tsx +14 -0
  571. package/template/.volter/tracker-config.json +17 -0
  572. package/template/AGENTS.md +176 -0
  573. package/template/CLAUDE.md +1 -0
  574. package/template/DEVLOG.md +20 -0
  575. package/template/IDIOMS.md +118 -0
  576. package/template/LICENSE +30 -0
  577. package/template/README.md +83 -0
  578. package/template/ROADMAP.md +20 -0
  579. package/template/asset-manifest.json +3 -0
  580. package/template/check-idioms.ts +1533 -0
  581. package/template/index.html +18 -0
  582. package/template/manifest-entry-modules-plugin.ts +53 -0
  583. package/template/package.json +62 -0
  584. package/template/public/jsm/libs/basis/basis_transcoder.js +19 -0
  585. package/template/public/jsm/libs/basis/basis_transcoder.wasm +0 -0
  586. package/template/public/jsm/libs/draco/gltf/draco_decoder.js +33 -0
  587. package/template/public/jsm/libs/draco/gltf/draco_decoder.wasm +0 -0
  588. package/template/public/jsm/libs/draco/gltf/draco_encoder.js +33 -0
  589. package/template/public/jsm/libs/draco/gltf/draco_wasm_wrapper.js +116 -0
  590. package/template/public/shaders/daylight-sky.frag.glsl +15 -0
  591. package/template/public/shaders/daylight-sky.vert.glsl +7 -0
  592. package/template/scripts/patch-drei-stats-gl.mjs +35 -0
  593. package/template/server/colyseus-setup.ts +111 -0
  594. package/template/server/loopback.ts +76 -0
  595. package/template/server/main.ts +78 -0
  596. package/template/server/rooms/arena-room.ts +488 -0
  597. package/template/server/rooms/game-room.ts +274 -0
  598. package/template/server/rooms.ts +15 -0
  599. package/template/server/tsconfig.json +19 -0
  600. package/template/src/bot/QaTester.tsx +35 -0
  601. package/template/src/bot/behaviors.ts +203 -0
  602. package/template/src/bot/bot-station.ts +192 -0
  603. package/template/src/bot/tester-run.ts +238 -0
  604. package/template/src/bot/tester-station.ts +193 -0
  605. package/template/src/components/environment/DaylightSky.tsx +54 -0
  606. package/template/src/components/environment/Ground.tsx +129 -0
  607. package/template/src/components/environment/SceneAtmosphere.tsx +14 -0
  608. package/template/src/components/environment/SoftGroundShadow.tsx +62 -0
  609. package/template/src/components/environment/SunShadowFit.tsx +141 -0
  610. package/template/src/contributions/README.md +98 -0
  611. package/template/src/contributions/analytics.analytics.tsx +26 -0
  612. package/template/src/contributions/data.document.tsx +35 -0
  613. package/template/src/contributions/pages.finder.ts +61 -0
  614. package/template/src/contributions/tester.inspector.tsx +64 -0
  615. package/template/src/contributions/use-game-modules.ts +80 -0
  616. package/template/src/data/README.md +17 -0
  617. package/template/src/input.ts +97 -0
  618. package/template/src/lib/audio/capability.json +4 -0
  619. package/template/src/lib/audio/sfx.ts +255 -0
  620. package/template/src/lib/react-root/capability.json +4 -0
  621. package/template/src/lib/react-root/index.ts +20 -0
  622. package/template/src/lib/react-root/react-root-adapter.tsx +57 -0
  623. package/template/src/lib/reflections/ReflectionProbe.tsx +201 -0
  624. package/template/src/lib/reflections/capability.json +4 -0
  625. package/template/src/lib/reflections/index.ts +19 -0
  626. package/template/src/lib/reflections/probe-controller.ts +75 -0
  627. package/template/src/lib/reflections/reflection-probe-registry.ts +402 -0
  628. package/template/src/lib/reflections/volume-reflection-material.ts +416 -0
  629. package/template/src/lib/static-batch/Frozen.tsx +91 -0
  630. package/template/src/lib/static-batch/capability.json +4 -0
  631. package/template/src/lib/static-batch/freeze.ts +579 -0
  632. package/template/src/lib/static-batch/index.ts +44 -0
  633. package/template/src/lib/static-batch/mutation-watch.ts +149 -0
  634. package/template/src/lib/static-batch/shadow-cache.ts +171 -0
  635. package/template/src/main.ts +63 -0
  636. package/template/src/manifest-entry-modules.d.ts +3 -0
  637. package/template/src/prefabs/HeroBox.stories.tsx +23 -0
  638. package/template/src/prefabs/HeroBox.tsx +35 -0
  639. package/template/src/scenes/MainScene.tsx +77 -0
  640. package/template/src/world.tsx +87 -0
  641. package/template/tsconfig.json +35 -0
  642. package/template/tsconfig.node.json +32 -0
  643. package/template/tsconfig.tools.json +22 -0
  644. package/template/validate-asset-content.ts +27 -0
  645. package/template/validate-assets.ts +60 -0
  646. package/template/validate-manifest.ts +55 -0
  647. package/template/vgai.adapter.ts +76 -0
  648. package/template/vgai.project.json +24 -0
  649. package/template/vite.config.ts +247 -0
  650. package/template-dotfiles/gitignore +63 -0
  651. package/workbench/src/media/game-cover.css +83 -0
  652. package/workbench/src/product.contribution.ts +188 -0
  653. package/workbench/src/vgaiGameSkew.ts +276 -0
@@ -0,0 +1,195 @@
1
+ /*!
2
+ * Copyright (c) 2026-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */function y(r){if(!r)throw new Error("Assertion failed.")}const Zt=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},ne=r=>r&&r[r.length-1],P=r=>{let e=0;for(;r.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+r.readBits(e)},fe=r=>{const e=P(r);return(e&1)===0?-(e>>1):e+1>>1},rn=(r,e,t,i)=>{for(let s=e;s<t;s++){const n=Math.floor(s/8);let a=r[n];const o=7-(s&7);a&=~(1<<o),a|=(i&1<<t-s-1)>>t-s-1<<o,r[n]=a}},me=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),O=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),oi=new TextDecoder,Le=new TextEncoder,Jt=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),Je={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Ie=Jt(Je),et={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Fe=Jt(et),tt={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Be=Jt(tt),nn=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,sn=r=>!r||r.primaries==null&&r.transfer==null&&r.matrix==null&&r.fullRange==null,an={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},pt=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class ci{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(s=>{let n=!1;e=()=>{n||(s(),this.pending--,n=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const fr=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),mr=r=>(r=r>>1&1431655765|(r&1431655765)<<1,r=r>>2&858993459|(r&858993459)<<2,r=r>>4&252645135|(r&252645135)<<4,r=r>>8&16711935|(r&16711935)<<8,r=r>>16&65535|(r&65535)<<16,r>>>0),se=(r,e,t)=>{let i=0,s=r.length-1,n=-1;for(;i<=s;){const a=i+(s-i+1)/2|0;t(r[a])<=e?(n=a,i=a+1):s=a-1}return n},j=()=>{let r,e;return{promise:new Promise((i,s)=>{r=i,e=s}),resolve:r,reject:e}},on=(r,e)=>{const t=r.indexOf(e);t!==-1&&r.splice(t,1)},cn=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},ln=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},un=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},ge=r=>{throw new Error(`Unexpected value: ${r}`)},er=(r,e,t)=>{const i=r.getUint8(e),s=r.getUint8(e+1),n=r.getUint8(e+2);return t?i|s<<8|n<<16:i<<16|s<<8|n},dn=(r,e,t)=>er(r,e,t)<<8>>8,li=(r,e,t,i)=>{t=t>>>0,t=t&16777215,i?(r.setUint8(e,t&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t>>>16&255)):(r.setUint8(e,t>>>16&255),r.setUint8(e+1,t>>>8&255),r.setUint8(e+2,t&255))},hn=(r,e,t,i)=>{t=N(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),li(r,e,t,i)},N=(r,e,t)=>Math.max(e,Math.min(t,r)),fn=(r,e,t)=>r+(e-r)*t,Wt="und",mn=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},pr=(r,e)=>Math.round(r/e)*e,Ge=(r,e)=>Math.round(r*e)/e,gr=(r,e)=>Math.floor(r*e)/e,pn=r=>{let e=0;for(;r!==0;)r&=r-1,e++;return e},gn=/^[a-z]{3}$/,ui=r=>gn.test(r),Te=1e6*(1+Number.EPSILON),wr=(r,e)=>{const t={...r,...e};if(r.headers||e.headers){const i=r.headers?Ut(r.headers):{},s=e.headers?Ut(e.headers):{},n={...i};Object.entries(s).forEach(([a,o])=>{const c=Object.keys(n).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete n[c],n[a]=o}),t.headers=n}return t},Ut=r=>{if(r instanceof Headers){const e={};return r.forEach((t,i)=>{e[i]=t}),e}if(Array.isArray(r)){const e={};return r.forEach(([t,i])=>{e[t]=i}),e}return r},yr=async(r,e,t,i,s)=>{let n=0;for(;;)try{return await r(e,t)}catch(a){if(s())throw a;n++;const o=i(n,a,e);if(o===null)throw a;if(D._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await ut(1e3*o),s())throw a}};class tr{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Tt=null;const wn=()=>Tt!==null?Tt:Tt=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let St=null;const di=()=>St!==null?St:St=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let _t=null;const yn=()=>_t!==null?_t:_t=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),rr=r=>typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext?`${r} 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.`:`${r} is not available in this environment.`,bn=(async()=>{})().constructor,I=r=>r instanceof bn||r instanceof Promise?!0:typeof r?.then=="function",qt=(r,e,t,i)=>r<=i&&t<=e,kn=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},Tn=r=>{switch(r.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}},Sn=(r,e)=>{if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0},ir=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},rt=r=>typeof r=="number"&&!Number.isNaN(r),_n=(r,e)=>{let t=0;for(let i=0;i<r.length;i++)e(r[i])&&t++;return t},hi=(r,e)=>{let t=-1,i=1/0;for(let s=0;s<r.length;s++){const n=e(r[s]);n<i&&(i=n,t=s)}return t},Ke=r=>{y(Number.isInteger(r.num)),y(Number.isInteger(r.den)),y(r.den!==0);let e=Math.abs(r.num),t=Math.abs(r.den);for(;t!==0;){const s=e%t;e=t,t=s}const i=e||1;return{num:r.num/i,den:r.den/i}},Ct=(r,e)=>{if(typeof r!="object"||!r)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)},ut=r=>new Promise(e=>setTimeout(e,r)),br=r=>Array.isArray(r)?r:[r];class it{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const s={fn:t,once:i?.once??!1};return this._listeners.get(e).add(s),()=>{this._listeners.get(e)?.delete(s)}}_emit(...e){const[t,i]=e,s=this._listeners.get(t);if(s)for(const n of s){try{n.fn(i)}catch(a){console.error(a)}n.once&&s.delete(n)}}}const Cn=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");/*!
8
+ * Copyright (c) 2026-present, Vanilagy and contributors
9
+ *
10
+ * This Source Code Form is subject to the terms of the Mozilla Public
11
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
12
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
13
+ */var ae;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(ae||(ae={}));class D{constructor(){}static get level(){return D._level}static set level(e){if(e!==ae.Silent&&e!==ae.Errors&&e!==ae.Warnings&&e!==ae.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");D._level=e}static get _emitter(){return D._emitterInstance??=new it}static on(e,t,i){return D._emitter.on(e,t,i)}static _error(...e){D._emitter._emit("error",e),D._level>=ae.Errors&&console.error(...e)}static _warn(...e){D._emitter._emit("warn",e),D._level>=ae.Warnings&&console.warn(...e)}static _info(...e){D._emitter._emit("info",e),D._level>=ae.Info&&console.info(...e)}}D._level=ae.Info;D._emitterInstance=null;/*!
14
+ * Copyright (c) 2026-present, Vanilagy and contributors
15
+ *
16
+ * This Source Code Form is subject to the terms of the Mozilla Public
17
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
18
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
19
+ */class En{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class nr{constructor(e,t,i,s){if(this.data=e,this.mimeType=t,this.name=i,this.description=s,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}}const Pn=r=>{if(!r||typeof r!="object")throw new TypeError("tags must be an object.");if(r.title!==void 0&&typeof r.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(r.description!==void 0&&typeof r.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(r.artist!==void 0&&typeof r.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(r.album!==void 0&&typeof r.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(r.albumArtist!==void 0&&typeof r.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(r.trackNumber!==void 0&&(!Number.isInteger(r.trackNumber)||r.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(r.tracksTotal!==void 0&&(!Number.isInteger(r.tracksTotal)||r.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(r.discNumber!==void 0&&(!Number.isInteger(r.discNumber)||r.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(r.discsTotal!==void 0&&(!Number.isInteger(r.discsTotal)||r.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(r.genre!==void 0&&typeof r.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(r.date!==void 0&&(!(r.date instanceof Date)||Number.isNaN(r.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(r.lyrics!==void 0&&typeof r.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(r.images!==void 0){if(!Array.isArray(r.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of r.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(r.comment!==void 0&&typeof r.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(r.raw!==void 0){if(!r.raw||typeof r.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(r.raw))if(e!==null&&typeof e!="string"&&!(Array.isArray(e)&&e.every(t=>typeof t=="string"))&&!(e instanceof Uint8Array)&&!(e instanceof En)&&!(e instanceof nr)&&!Cn(e))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},xn={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},vn=r=>{if(!r||typeof r!="object")throw new TypeError("disposition must be an object.");if(r.default!==void 0&&typeof r.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(r.primary!==void 0&&typeof r.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(r.forced!==void 0&&typeof r.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(r.original!==void 0&&typeof r.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(r.commentary!==void 0&&typeof r.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(r.hearingImpaired!==void 0&&typeof r.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(r.visuallyImpaired!==void 0&&typeof r.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};/*!
20
+ * Copyright (c) 2026-present, Vanilagy and contributors
21
+ *
22
+ * This Source Code Form is subject to the terms of the Mozilla Public
23
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
24
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
25
+ */class U{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),s=(t&1<<i)>>i;return this.pos++,s}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let s=this.pos;s<i;s++){const n=Math.floor(s/8);let a=this.bytes[n];const o=7-(s&7);a&=~(1<<o),a|=(t&1<<i-s-1)>>i-s-1<<o,this.bytes[n]=a}this.pos=i}copyBits(e,t){let i=0;for(i;i<e-7;i+=8)this.writeBits(8,t.readBits(8));const s=e-i;s>0&&this.writeBits(s,t.readBits(s))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new U(this.bytes);return e.pos=this.pos,e}}/*!
26
+ * Copyright (c) 2026-present, Vanilagy and contributors
27
+ *
28
+ * This Source Code Form is subject to the terms of the Mozilla Public
29
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
30
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
31
+ */const dt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],sr=[-1,1,2,3,4,5,6,8],fi=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new U(r),t=Et(e),{frequencyIndex:i,sampleRate:s}=Pt(e),n=e.readBits(4);let a=null;n>=1&&n<=7&&(a=sr[n]);let o=t,c=!1,l=s;if(t===5||t===29)c=t===29,l=Pt(e).sampleRate,o=Et(e),o===22&&e.skipBits(4);else for(;e.getBitsLeft()>15;){const u=e.pos;if(e.readBits(11)!==695){e.pos=u+1;continue}Et(e)===5&&e.readBits(1)&&(l=Pt(e).sampleRate,e.getBitsLeft()>11&&e.readBits(11)===1352&&(c=!!e.readBits(1)));break}return a!==null&&a>1&&(c=!1),{objectType:t,coreObjectType:o,frequencyIndex:i,channelConfiguration:n,outputSampleRate:l,outputNumberOfChannels:c&&a===1?2:a}},Et=r=>{const e=r.readBits(5);return e===31?32+r.readBits(6):e},Pt=r=>{const e=r.readBits(4);return e===15?{frequencyIndex:e,sampleRate:r.readBits(24)}:{frequencyIndex:e,sampleRate:e<dt.length?dt[e]:null}},mi=r=>{const e=r.objectType===5||r.objectType===29,t=r.objectType===29,i=e?r.outputSampleRate/2:r.outputSampleRate,s=t?1:r.outputNumberOfChannels,n=sr.indexOf(s);if(n===-1)throw new TypeError(`Unsupported number of channels: ${r.outputNumberOfChannels}`);let a=16;r.objectType>=32&&(a+=6),Ht(i)===15&&(a+=24),e&&(a+=9,Ht(r.outputSampleRate)===15&&(a+=24));const o=Math.ceil(a/8),c=new Uint8Array(o),l=new U(c);return kr(l,r.objectType),Tr(l,i),l.writeBits(4,n),e&&(Tr(l,r.outputSampleRate),kr(l,2)),l.writeBits(3,0),c},kr=(r,e)=>{e<32?r.writeBits(5,e):(r.writeBits(5,31),r.writeBits(6,e-32))},Tr=(r,e)=>{const t=Ht(e);r.writeBits(4,t),t===15&&r.writeBits(24,e)},Ht=r=>{const e=dt.indexOf(r);return e===-1?15:e};/*!
32
+ * Copyright (c) 2026-present, Vanilagy and contributors
33
+ *
34
+ * This Source Code Form is subject to the terms of the Mozilla Public
35
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
36
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
37
+ */var pe;(function(r){r[r.NON_IDR_SLICE=1]="NON_IDR_SLICE",r[r.SLICE_DPA=2]="SLICE_DPA",r[r.SLICE_DPB=3]="SLICE_DPB",r[r.SLICE_DPC=4]="SLICE_DPC",r[r.IDR=5]="IDR",r[r.SEI=6]="SEI",r[r.SPS=7]="SPS",r[r.PPS=8]="PPS",r[r.AUD=9]="AUD",r[r.SPS_EXT=13]="SPS_EXT"})(pe||(pe={}));var Q;(function(r){r[r.RASL_N=8]="RASL_N",r[r.RASL_R=9]="RASL_R",r[r.BLA_W_LP=16]="BLA_W_LP",r[r.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",r[r.VPS_NUT=32]="VPS_NUT",r[r.SPS_NUT=33]="SPS_NUT",r[r.PPS_NUT=34]="PPS_NUT",r[r.AUD_NUT=35]="AUD_NUT",r[r.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",r[r.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(Q||(Q={}));const gt=function*(r){let e=0,t=-1;for(;e<r.length-2;){const i=r.indexOf(0,e);if(i===-1||i>=r.length-2)break;e=i;let s=0;if(e+3<r.length&&r[e+1]===0&&r[e+2]===0&&r[e+3]===1?s=4:r[e+1]===0&&r[e+2]===1&&(s=3),s===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+s,e=t}t!==-1&&t<r.length&&(yield{offset:t,length:r.length-t})},pi=function*(r,e){let t=0;const i=new DataView(r.buffer,r.byteOffset,r.byteLength);for(;t+e<=r.length;){let s;e===1?s=i.getUint8(t):e===2?s=i.getUint16(t,!1):e===3?s=er(i,t,!1):(y(e===4),s=i.getUint32(t,!1)),t+=e,yield{offset:t,length:s},t+=s}},An=(r,e)=>{if(e.description){const s=(me(e.description)[4]&3)+1;return pi(r,s)}else return gt(r)},gi=r=>r&31,wt=r=>{const e=[],t=r.length;for(let i=0;i<t;i++)i+2<t&&r[i]===0&&r[i+1]===0&&r[i+2]===3?(e.push(0,0),i+=2):e.push(r[i]);return new Uint8Array(e)},Rn=r=>{try{const e=[],t=[],i=[];for(const o of gt(r)){const c=r.subarray(o.offset,o.offset+o.length),l=gi(c[0]);l===pe.SPS?e.push(c):l===pe.PPS?t.push(c):l===pe.SPS_EXT&&i.push(c)}if(e.length===0||t.length===0)return null;const s=e[0],n=yi(s);y(n!==null);const a=n.profileIdc===100||n.profileIdc===110||n.profileIdc===122||n.profileIdc===144;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?n.chromaFormatIdc:null,bitDepthLumaMinus8:a?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?i:null}}catch(e){return D._error("Error building AVC Decoder Configuration Record:",e),null}},In=r=>{try{const e=O(r);let t=0;const i=e.getUint8(t++),s=e.getUint8(t++),n=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,l=[];for(let m=0;m<c;m++){const p=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+p)),t+=p}const u=e.getUint8(t++),d=[];for(let m=0;m<u;m++){const p=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+p)),t+=p}const h={configurationVersion:i,avcProfileIndication:s,profileCompatibility:n,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((s===100||s===110||s===122||s===144)&&t+4<=r.length){const m=e.getUint8(t++)&3,p=e.getUint8(t++)&7,b=e.getUint8(t++)&7,w=e.getUint8(t++);h.chromaFormat=m,h.bitDepthLumaMinus8=p,h.bitDepthChromaMinus8=b;const g=[];for(let T=0;T<w;T++){const k=e.getUint16(t,!1);t+=2,g.push(r.subarray(t,t+k)),t+=k}h.sequenceParameterSetExt=g}return h}catch(e){return D._error("Error deserializing AVC Decoder Configuration Record:",e),null}},wi={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}},yi=r=>{try{const e=wt(r),t=new U(e);if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;const s=t.readAlignedByte(),n=t.readAlignedByte(),a=t.readAlignedByte();P(t);let o=1,c=0,l=0,u=0;if((s===100||s===110||s===122||s===244||s===44||s===83||s===86||s===118||s===128)&&(o=P(t),o===3&&(u=t.readBits(1)),c=P(t),l=P(t),t.skipBits(1),t.readBits(1))){for(let V=0;V<(o!==3?8:12);V++)if(t.readBits(1)){const re=V<6?16:64;let ie=8,K=8;for(let we=0;we<re;we++){if(K!==0){const Ee=fe(t);K=(ie+Ee+256)%256}ie=K===0?ie:K}}}P(t);const d=P(t);if(d===0)P(t);else if(d===1){t.skipBits(1),fe(t),fe(t);const W=P(t);for(let V=0;V<W;V++)fe(t)}P(t),t.skipBits(1);const h=P(t),m=P(t),p=16*(h+1),b=16*(m+1);let w=p,g=b;const T=t.readBits(1);if(T||t.skipBits(1),t.skipBits(1),t.readBits(1)){const W=P(t),V=P(t),te=P(t),re=P(t);let ie,K;if((u===0?o:0)===0)ie=1,K=2-T;else{const Ee=o===3?1:2,ot=o===1?2:1;ie=Ee,K=ot*(2-T)}w-=ie*(W+V),g-=K*(te+re)}let x=2,C=2,A=2,v=0,S={num:1,den:1},_=null,E=null,R=null,B=null;const z=t.pos;if(t.readBits(1)){if(t.readBits(1)){const Ee=t.readBits(8);if(Ee===255)S={num:t.readBits(16),den:t.readBits(16)};else{const ot=wi[Ee];ot&&(S=ot)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),v=t.readBits(1),t.readBits(1)&&(x=t.readBits(8),C=t.readBits(8),A=t.readBits(8))),t.readBits(1)&&(P(t),P(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const K=t.readBits(1);K&&Sr(t);const we=t.readBits(1);we&&Sr(t),(K||we)&&t.skipBits(1),t.skipBits(1),R=t.pos,B=t.readBits(1),B&&(t.skipBits(1),P(t),P(t),P(t),P(t),_=P(t),E=P(t))}if(_===null){y(E===null);const W=n&16;if((s===44||s===86||s===100||s===110||s===122||s===244)&&W)_=0,E=0;else{const V=h+1,te=m+1,re=(2-T)*te,ie=ht.find(we=>we.level>=a)??ne(ht),K=Math.min(Math.floor(ie.maxDpbMbs/(V*re)),16);_=K,E=K}}return y(E!==null),{emulationUnpreventedBytes:e,profileIdc:s,constraintFlags:n,levelIdc:a,frameMbsOnlyFlag:T,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:p,codedHeight:b,displayWidth:w,displayHeight:g,pixelAspectRatio:S,colourPrimaries:x,matrixCoefficients:A,transferCharacteristics:C,fullRangeFlag:v,numReorderFrames:_,maxDecFrameBuffering:E,vuiParametersFlagBitOffset:z,bitstreamRestrictionFlagBitOffset:R,bitstreamRestrictionFlag:B}}catch(e){return D._error("Error parsing AVC SPS:",e),null}},Sr=r=>{const e=P(r);r.skipBits(4),r.skipBits(4);for(let t=0;t<=e;t++)P(r),P(r),r.skipBits(1);r.skipBits(5),r.skipBits(5),r.skipBits(5),r.skipBits(5)},Fn=(r,e)=>{if(e.description){const s=(me(e.description)[21]&3)+1;return pi(r,s)}else return gt(r)},Lt=r=>r>>1&63,bi=r=>{try{const e=new U(wt(r));e.skipBits(16),e.readBits(4);const t=e.readBits(3),i=e.readBits(1),{general_profile_space:s,general_tier_flag:n,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Dn(e,t);P(e);const u=P(e);let d=0;u===3&&(d=e.readBits(1));const h=P(e),m=P(e);let p=h,b=m;if(e.readBits(1)){const B=P(e),z=P(e),L=P(e),W=P(e);let V=1,te=1;const re=d===0?u:0;re===1?(V=2,te=2):re===2&&(V=2,te=1),p-=(B+z)*V,b-=(L+W)*te}const w=P(e),g=P(e);P(e);const k=e.readBits(1)?0:t;let x=0;for(let B=k;B<=t;B++)P(e),x=P(e),P(e);P(e),P(e),P(e),P(e),P(e),P(e),e.readBits(1)&&e.readBits(1)&&On(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),P(e),P(e),e.skipBits(1));const C=P(e);if(Mn(e,C),e.readBits(1)){const B=P(e);for(let z=0;z<B;z++)P(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let A=2,v=2,S=2,_=0,E=0,R={num:1,den:1};if(e.readBits(1)){const B=Vn(e,t);R=B.pixelAspectRatio,A=B.colourPrimaries,v=B.transferCharacteristics,S=B.matrixCoefficients,_=B.fullRangeFlag,E=B.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:b,pixelAspectRatio:R,colourPrimaries:A,transferCharacteristics:v,matrixCoefficients:S,fullRangeFlag:_,maxDecFrameBuffering:x+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:s,generalTierFlag:n,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:w,bitDepthChromaMinus8:g,minSpatialSegmentationIdc:E}}catch(e){return D._error("Error parsing HEVC SPS:",e),null}},Bn=r=>{try{const e=[],t=[],i=[],s=[];for(const l of gt(r)){const u=r.subarray(l.offset,l.offset+l.length),d=Lt(u[0]);d===Q.VPS_NUT?e.push(u):d===Q.SPS_NUT?t.push(u):d===Q.PPS_NUT?i.push(u):(d===Q.PREFIX_SEI_NUT||d===Q.SUFFIX_SEI_NUT)&&s.push(u)}if(t.length===0||i.length===0)return null;const n=bi(t[0]);if(!n)return null;let a=0;if(i.length>0){const l=i[0],u=new U(wt(l));u.skipBits(16),P(u),P(u),u.skipBits(1),u.skipBits(1),u.skipBits(3),u.skipBits(1),u.skipBits(1),P(u),P(u),fe(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&P(u),fe(u),fe(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);const d=u.readBits(1),h=u.readBits(1);!d&&!h?a=0:d&&!h?a=2:!d&&h?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:Q.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:Q.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Q.PPS_NUT,nalUnits:i}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Lt(s[0][0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:n.generalProfileSpace,generalTierFlag:n.generalTierFlag,generalProfileIdc:n.generalProfileIdc,generalProfileCompatibilityFlags:n.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:n.generalConstraintIndicatorFlags,generalLevelIdc:n.generalLevelIdc,minSpatialSegmentationIdc:n.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:n.chromaFormatIdc,bitDepthLumaMinus8:n.bitDepthLumaMinus8,bitDepthChromaMinus8:n.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:n.spsMaxSubLayersMinus1+1,temporalIdNested:n.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return D._error("Error building HEVC Decoder Configuration Record:",e),null}},Dn=(r,e)=>{const t=r.readBits(2),i=r.readBits(1),s=r.readBits(5);let n=0;for(let u=0;u<32;u++)n=n<<1|r.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);const o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:a,general_level_idc:o}},On=r=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!r.readBits(1))P(r);else{const s=Math.min(64,1<<4+(e<<1));e>1&&fe(r);for(let n=0;n<s;n++)fe(r)}},Mn=(r,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=zn(r,i,e,t)},zn=(r,e,t,i)=>{let s=0,n=0,a=0;if(e!==0&&(n=r.readBits(1)),n){if(e===t){const c=P(r);a=e-(c+1)}else a=e-1;r.readBits(1),P(r);const o=i[a]??0;for(let c=0;c<=o;c++)r.readBits(1)||r.readBits(1);s=i[a]}else{const o=P(r),c=P(r);for(let l=0;l<o;l++)P(r),r.readBits(1);for(let l=0;l<c;l++)P(r),r.readBits(1);s=o+c}return s},Vn=(r,e)=>{let t=2,i=2,s=2,n=0,a=0,o={num:1,den:1};if(r.readBits(1)){const c=r.readBits(8);if(c===255)o={num:r.readBits(16),den:r.readBits(16)};else{const l=wi[c];l&&(o=l)}}return r.readBits(1)&&r.readBits(1),r.readBits(1)&&(r.readBits(3),n=r.readBits(1),r.readBits(1)&&(t=r.readBits(8),i=r.readBits(8),s=r.readBits(8))),r.readBits(1)&&(P(r),P(r)),r.readBits(1),r.readBits(1),r.readBits(1),r.readBits(1)&&(P(r),P(r),P(r),P(r)),r.readBits(1)&&(r.readBits(32),r.readBits(32),r.readBits(1)&&P(r),r.readBits(1)&&Nn(r,!0,e)),r.readBits(1)&&(r.readBits(1),r.readBits(1),r.readBits(1),a=P(r),P(r),P(r),P(r),P(r)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:i,matrixCoefficients:s,fullRangeFlag:n,minSpatialSegmentationIdc:a}},Nn=(r,e,t)=>{let i=!1,s=!1,n=!1;i=r.readBits(1)===1,s=r.readBits(1)===1,(i||s)&&(n=r.readBits(1)===1,n&&(r.readBits(8),r.readBits(5),r.readBits(1),r.readBits(5)),r.readBits(4),r.readBits(4),n&&r.readBits(4),r.readBits(5),r.readBits(5),r.readBits(5));for(let a=0;a<=t;a++){const o=r.readBits(1)===1;let c=!0;o||(c=r.readBits(1)===1);let l=!1;c?P(r):l=r.readBits(1)===1;let u=1;l||(u=P(r)+1),i&&_r(r,u,n),s&&_r(r,u,n)}},_r=(r,e,t)=>{for(let i=0;i<e;i++)P(r),P(r),t&&(P(r),P(r)),r.readBits(1)},Wn=r=>{try{const e=O(r);let t=0;const i=e.getUint8(t++),s=e.getUint8(t++),n=s>>6&3,a=s>>5&1,o=s&31,c=e.getUint32(t,!1);t+=4;const l=r.subarray(t,t+6);t+=6;const u=e.getUint8(t++),d=(e.getUint8(t++)&15)<<8|e.getUint8(t++),h=e.getUint8(t++)&3,m=e.getUint8(t++)&3,p=e.getUint8(t++)&7,b=e.getUint8(t++)&7,w=e.getUint16(t,!1);t+=2;const g=e.getUint8(t++),T=g>>6&3,k=g>>3&7,x=g>>2&1,C=g&3,A=e.getUint8(t++),v=[];for(let S=0;S<A;S++){const _=e.getUint8(t++),E=_>>7&1,R=_&63,B=e.getUint16(t,!1);t+=2;const z=[];for(let L=0;L<B;L++){const W=e.getUint16(t,!1);t+=2,z.push(r.subarray(t,t+W)),t+=W}v.push({arrayCompleteness:E,nalUnitType:R,nalUnits:z})}return{configurationVersion:i,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:h,chromaFormatIdc:m,bitDepthLumaMinus8:p,bitDepthChromaMinus8:b,avgFrameRate:w,constantFrameRate:T,numTemporalLayers:k,temporalIdNested:x,lengthSizeMinusOne:C,arrays:v}}catch(e){return D._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var Cr;(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(Cr||(Cr={}));const Un={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}},qn=r=>{const e=new U(r);if(e.readBits(2)!==2)return null;const i=e.readBits(1),n=(e.readBits(1)<<1)+i;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;n>=2&&(l=e.readBits(1)?12:10);const u=e.readBits(3);let d=0,h=0;if(u!==7)if(h=e.readBits(1),n===1||n===3){const S=e.readBits(1),_=e.readBits(1);d=!S&&!_?3:S&&!_?2:1,e.skipBits(1)}else d=1;else d=3,h=1;const m=e.readBits(16),p=e.readBits(16),b=m+1,w=p+1,g=b*w;let T=ne(Se).level;for(const v of Se)if(g<=v.maxPictureSize){T=v.level;break}const k=Un[u],x=k?.colourPrimaries??2,C=k?.transferCharacteristics??2,A=k?.matrixCoefficients??2;return{profile:n,level:T,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:x,transferCharacteristics:C,matrixCoefficients:A}},ki=function*(r){const e=new U(r),t=()=>{let i=0;for(let s=0;s<8;s++){const n=e.readAlignedByte();if(i+=(n&127)*2**(s*7),!(n&128))break;if(s===7&&n&128)return null}return i>2**32-1?null:i};for(;e.getBitsLeft()>=8;){e.skipBits(1);const i=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let a;if(n){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);y(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},Hn=r=>{for(const{type:e,data:t}of ki(r)){if(e!==1)continue;const i=new U(t),s=i.readBits(3);i.readBits(1);const n=i.readBits(1);let a=0,o=0,c=0;if(n)a=i.readBits(5);else{const _=i.readBits(1);let E=0;if(_){if(i.skipBits(32),i.skipBits(32),i.readBits(1)){let L=0;for(;L<32&&!i.readBits(1);)L++;L<32&&i.skipBits(L)}E=i.readBits(1),E&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5))}const R=i.readBits(1),B=i.readBits(5);for(let z=0;z<=B;z++){i.skipBits(12);const L=i.readBits(5);if(z===0&&(a=L),L>7){const W=i.readBits(1);z===0&&(o=W)}if(E&&i.readBits(1)){const V=c+1;i.skipBits(V),i.skipBits(V),i.skipBits(1)}R&&i.readBits(1)&&i.skipBits(4)}}const l=i.readBits(4),u=i.readBits(4),d=l+1;i.skipBits(d);const h=u+1;i.skipBits(h);let m=0;if(n?m=0:m=i.readBits(1),m&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!n){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const _=i.readBits(1);_&&(i.skipBits(1),i.skipBits(1));const E=i.readBits(1);let R=0;E?R=2:R=i.readBits(1),R>0&&(i.readBits(1)||i.skipBits(1)),_&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const p=i.readBits(1);let b=8;s===2&&p?b=i.readBits(1)?12:10:s<=2&&(b=p?10:8);let w=0;s!==1&&(w=i.readBits(1));let g=2,T=2,k=2;i.readBits(1)&&(g=i.readBits(8),T=i.readBits(8),k=i.readBits(8));let C=0,A=1,v=1,S=0;return w?C=i.readBits(1):g===1&&T===13&&k===0?(C=1,A=0,v=0):(C=i.readBits(1),s===0?(A=1,v=1):s===1?(A=0,v=0):b===12?(A=i.readBits(1),v=A?i.readBits(1):0):(A=1,v=0),A&&v&&(S=i.readBits(2))),{profile:s,level:a,tier:o,bitDepth:b,monochrome:w,chromaSubsamplingX:A,chromaSubsamplingY:v,chromaSamplePosition:S,videoFullRangeFlag:C,colourPrimaries:g,transferCharacteristics:T,matrixCoefficients:k}}return null},Ln=r=>{if(r.length<36)return null;const t=O(r);return t.getUint32(4)!==1768124518||t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},jn=r=>{const e=O(r),t=e.getUint8(9),i=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=r.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:s,outputGain:n,channelMappingFamily:a,channelMappingTable:o}},Ti=(r,e,t)=>{switch(r){case"avc":{for(const i of An(t,e)){const s=t[i.offset],n=gi(s);if(n>=pe.NON_IDR_SLICE&&n<=pe.SLICE_DPC)return"delta";if(n===pe.IDR)return"key";if(n===pe.SEI&&!yn()){const a=t.subarray(i.offset,i.offset+i.length),o=wt(a);let c=1;do{let l=0;for(;;){const h=o[c++];if(h===void 0||(l+=h,h<255))break}let u=0;for(;;){const h=o[c++];if(h===void 0||(u+=h,h<255))break}if(l===6){const h=new U(o);h.pos=8*c;const m=P(h),p=h.readBits(1);if(m===0&&p===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(const i of Fn(t,e)){const s=Lt(t[i.offset]);if(s<Q.BLA_W_LP)return"delta";if(s<=Q.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new U(t);if(i.readBits(2)!==2)return null;const s=i.readBits(1);return(i.readBits(1)<<1)+s===3&&i.skipBits(1),i.readBits(1)?null:i.readBits(1)===0?"key":"delta"}case"av1":{let i=!1;for(const{type:s,data:n}of ki(t))if(s===1){const a=new U(n);a.skipBits(4),i=!!a.readBits(1)}else if(s===3||s===6||s===7){if(i)return"key";const a=new U(n);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:ge(r),y(!1)}};var Er;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(Er||(Er={}));const $n=1683496997,Gn=18,Kn=10,Pr=32,Qn=8,Xn=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Yn=[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],Zn=[16,16,20,20,0,24,24,0],xr=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Jn=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],es=8,ts=[32e3,44100,48e3,0],rs=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],is=r=>{const e=ss(r),t=O(r);let i=e?Math.ceil(e.frameSize/4)*4:0,s=null;for(;i+4<=r.length&&t.getUint32(i)===$n;){const a=as(r.subarray(i));if(!a)break;s??=a,i+=a.frameSize}if(e)return{frameSize:s?i:e.frameSize,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,sampleCount:e.sampleCount,channelLayout:e.channelLayout,pcmResolution:e.pcmResolution,bitRate:e.bitRate,core:e,hasExtensions:s!==null};if(!s?.asset)return null;const{asset:n}=s;return{frameSize:i,sampleRate:n.sampleRate,numberOfChannels:n.numberOfChannels,sampleCount:n.sampleCount,channelLayout:n.channelLayout,pcmResolution:n.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},ns=r=>{const e=is(r);return e?.core?e.hasExtensions?"dtsh":"dtsc":null},ss=r=>{if(r.length<Gn||r[0]!==127||r[1]!==254||r[2]!==128||r[3]!==1)return null;const e=new U(r);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==Pr-1)return null;const t=e.readBits(1),i=e.readBits(7)+1;if(i%Qn!==0)return null;const s=e.readBits(14)+1;if(s<96)return null;const n=e.readBits(6);if(n>=xr.length)return null;const a=Xn[e.readBits(4)];if(a===0)return null;const o=Yn[e.readBits(5)];if(e.readBits(1)!==0)return null;e.skipBits(4),e.skipBits(5);const c=e.readBits(2);if(c===3)return null;e.skipBits(1),t&&e.skipBits(16),e.skipBits(7);const l=Zn[e.readBits(3)];if(l===0)return null;const u=c!==0;return{frameSize:s,sampleRate:a,numberOfChannels:xr[n]+(u?1:0),sampleCount:i*Pr,channelLayout:Jn[n]|(u?es:0),amode:n,lfePresent:u,bitRate:o,pcmResolution:l}},as=r=>{if(r.length<Kn||r[0]!==100||r[1]!==88||r[2]!==32||r[3]!==37)return null;const e=new U(r);e.skipBits(32),e.skipBits(8);const t=e.readBits(2),i=e.readBits(1),s=8+4*i,n=16+4*i;e.skipBits(s);const a=e.readBits(n)+1,o={frameSize:a,asset:null};if(!e.readBits(1))return o;const c=ts[e.readBits(2)],l=512*(e.readBits(3)+1);e.readBits(1)&&e.skipBits(36);const u=e.readBits(3)+1,d=e.readBits(3)+1,h=[];for(let g=0;g<u;g++)h.push(e.readBits(t+1));for(const g of h)e.skipBits(8*pn(g));if(e.readBits(1)){e.skipBits(2);const g=e.readBits(2)+1<<2,T=e.readBits(2)+1;e.skipBits(T*g)}for(let g=0;g<d;g++)e.skipBits(n);e.skipBits(9),e.skipBits(3),e.readBits(1)&&e.skipBits(4),e.readBits(1)&&e.skipBits(24),e.readBits(1)&&e.skipBits(8*(e.readBits(10)+1));const m=e.readBits(5)+1,p=rs[e.readBits(4)],b=e.readBits(8)+1;let w=0;if(e.readBits(1)&&(b>2&&e.skipBits(1),b>6&&e.skipBits(1),e.readBits(1))){const g=e.readBits(2)+1<<2;w=e.readBits(g)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:p,numberOfChannels:b,sampleCount:Math.round(l*p/c),channelLayout:w,pcmResolution:m}}};/*!
38
+ * Copyright (c) 2026-present, Vanilagy and contributors
39
+ *
40
+ * This Source Code Form is subject to the terms of the Mozilla Public
41
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
42
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
43
+ */const Ce=["avc","hevc","vp9","av1","vp8","prores"],X=["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"],Si=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],Re=[...Si,...X],Qe=["webvtt"],ht=[{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}],vr=[{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}],Se=[{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}],Ar=[{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}],Rr=".01.01.01.01.00",Ir=".0.110.01.01.01.0",Oe=["ap4x","ap4h","apch","apcn","apcs","apco"],jt=["dtsc","dtsh","dtsl","dtse"],os=[{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}],cs=(r,e,t,i,s)=>{if(r==="avc"){const a=Math.ceil(e/16)*Math.ceil(t/16),o=ht.find(h=>a<=h.maxMacroblocks&&i<=h.maxBitrate)??ne(ht),c=o?o.level:0,l="64".padStart(2,"0"),u="00",d=c.toString(16).padStart(2,"0");return`avc1.${l}${u}${d}`}else if(r==="hevc"){const c=e*t,l=vr.find(d=>c<=d.maxPictureSize&&i<=d.maxBitrate)??ne(vr);return`hev1.1.6.${l.tier}${l.level}.B0`}else{if(r==="vp8")return"vp8";if(r==="vp9"){const a=e*t;return`vp09.00.${(Se.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??ne(Se)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const a=e*t,o=Ar.find(u=>a<=u.maxPictureSize&&i<=u.maxBitrate)??ne(Ar);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}else if(r==="prores"){const a=Math.pow(e*t/2073600,.95),o=os.filter(u=>u.alpha===s);let c=o[0].fourCc,l=1/0;for(const{fourCc:u,bitrate:d}of o){const h=Math.abs(d*a-i);h<l&&(l=h,c=u)}return c}else ge(r)}throw new TypeError(`Unhandled codec '${String(r)}'.`)},ls=r=>{const e=r.split("."),t=Number(e[1]),i=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,i,3,1,s,4,1,n]},us=r=>{const e=r.split("."),s=(1<<7)+1,n=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(n<<5)+o,l=a.slice(-1)==="H"?1:0,u=Number(e[3]),d=u===8?0:1,h=u===12?1:0,m=e[4]?Number(e[4]):0,p=e[5]?Number(e[5][0]):1,b=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,g=(l<<7)+(d<<6)+(h<<5)+(m<<4)+(p<<3)+(b<<2)+w;return[s,c,g,0]},ds=r=>{const{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=r;if(e==="avc"){if(y(r.avcType!==null),s){const l=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${r.avcType}.${fr(l)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${r.avcType}.${fr(t.subarray(1,4))}`}else if(e==="hevc"){let l,u,d,h,m,p;if(n)l=n.generalProfileSpace,u=n.generalProfileIdc,d=mr(n.generalProfileCompatibilityFlags),h=n.generalTierFlag,m=n.generalLevelIdc,p=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const w=O(t),g=w.getUint8(1);l=g>>6&3,u=g&31,d=mr(w.getUint32(2)),h=g>>5&1,m=w.getUint8(12),p=[];for(let T=0;T<6;T++)p.push(w.getUint8(6+T))}let b="hev1.";for(b+=["","A","B","C"][l]+u,b+=".",b+=d.toString(16).toUpperCase(),b+=".",b+=h===0?"L":"H",b+=m;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(b+=".",b+=p.map(w=>w.toString(16).toUpperCase()).join(".")),b}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const T=r.width*r.height;let k=ne(Se).level;for(const x of Se)if(T<=x.maxPictureSize){k=x.level;break}return`vp09.00.${k.toString().padStart(2,"0")}.08`}const l=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),d=a.bitDepth.toString().padStart(2,"0"),h=a.chromaSubsampling.toString().padStart(2,"0"),m=a.colourPrimaries.toString().padStart(2,"0"),p=a.transferCharacteristics.toString().padStart(2,"0"),b=a.matrixCoefficients.toString().padStart(2,"0"),w=a.videoFullRangeFlag.toString().padStart(2,"0");let g=`vp09.${l}.${u}.${d}.${h}`;return g+=`.${m}.${p}.${b}.${w}`,g.endsWith(Rr)&&(g=g.slice(0,-Rr.length)),g}else if(e==="av1"){if(!o){const x=r.width*r.height;let C=ne(Se).level;for(const A of Se)if(x<=A.maxPictureSize){C=A.level;break}return`av01.0.${C.toString().padStart(2,"0")}M.08`}const l=o.profile,u=o.level.toString().padStart(2,"0"),d=o.tier?"H":"M",h=o.bitDepth.toString().padStart(2,"0"),m=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),b=i?.primaries?Je[i.primaries]:1,w=i?.transfer?et[i.transfer]:1,g=i?.matrix?tt[i.matrix]:1,T=i?.fullRange?1:0;let k=`av01.${l}.${u}${d}.${h}`;return k+=`.${m}.${p.toString().padStart(3,"0")}`,k+=`.${b.toString().padStart(2,"0")}`,k+=`.${w.toString().padStart(2,"0")}`,k+=`.${g.toString().padStart(2,"0")}`,k+=`.${T}`,k.endsWith(Ir)&&(k=k.slice(0,-Ir.length)),k}else{if(e==="prores")return c??"apch";e!==null&&ge(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},hs=r=>{switch(r.codec){case"avc":{let e=r.avcCodecInfo?.sequenceParameterSets[0];if(!e&&r.codecDescription&&(e=In(r.codecDescription)?.sequenceParameterSets[0]),e){const t=yi(e);if(t)return{primaries:Ie[t.colourPrimaries],transfer:Fe[t.transferCharacteristics],matrix:Be[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"hevc":{let e=r.hevcCodecInfo?.arrays.find(t=>t.nalUnitType===Q.SPS_NUT)?.nalUnits[0];if(!e&&r.codecDescription&&(e=Wn(r.codecDescription)?.arrays.find(t=>t.nalUnitType===Q.SPS_NUT)?.nalUnits[0]),e){const t=bi(e);if(t)return{primaries:Ie[t.colourPrimaries],transfer:Fe[t.transferCharacteristics],matrix:Be[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(r.vp9CodecInfo)return{primaries:Ie[r.vp9CodecInfo.colourPrimaries],transfer:Fe[r.vp9CodecInfo.transferCharacteristics],matrix:Be[r.vp9CodecInfo.matrixCoefficients],fullRange:!!r.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(r.av1CodecInfo)return{primaries:Ie[r.av1CodecInfo.colourPrimaries],transfer:Fe[r.av1CodecInfo.transferCharacteristics],matrix:Be[r.av1CodecInfo.matrixCoefficients],fullRange:!!r.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(r.proresCodecInfo)return{primaries:Ie[r.proresCodecInfo.colourPrimaries],transfer:Fe[r.proresCodecInfo.transferCharacteristics],matrix:Be[r.proresCodecInfo.matrixCoefficients],fullRange:r.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},fs=(r,e,t)=>{if(r==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(r==="mp3")return"mp3";if(r==="opus")return"opus";if(r==="vorbis")return"vorbis";if(r==="flac")return"flac";if(r==="ac3")return"ac-3";if(r==="eac3")return"ec-3";if(r==="dts")return"dtsc";if(X.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},ms=r=>{const{codec:e,codecDescription:t,aacCodecInfo:i,dtsFormat:s}=r;if(e==="aac"){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";{let n;return i.objectType!==null?n=i.objectType:n=fi(t).objectType,`mp4a.40.${n}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e==="dts")return s??"dtsc";if(e&&X.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},_i=48e3,Ci=/^pcm-([usf])(\d+)(be)?$/,ar=r=>{if(y(X.includes(r)),r==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(r==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Ci.exec(r);y(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,s=e[3]!=="be",n=r==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:s,silentValue:n}},yt=r=>r.startsWith("avc1")||r.startsWith("avc3")?"avc":r.startsWith("hev1")||r.startsWith("hvc1")?"hevc":r==="vp8"?"vp8":r.startsWith("vp09")?"vp9":r.startsWith("av01")?"av1":Oe.includes(r)?"prores":r==="mp3"||r==="mp4a.69"||r==="mp4a.6B"||r==="mp4a.6b"||r==="mp4a.40.34"?"mp3":r.startsWith("mp4a.40.")||r==="mp4a.67"?"aac":r==="opus"?"opus":r==="vorbis"?"vorbis":r==="flac"?"flac":r==="ac-3"||r==="ac3"?"ac3":r==="ec-3"||r==="eac3"?"eac3":jt.includes(r)?"dts":r==="ulaw"?"ulaw":r==="alaw"?"alaw":Ci.test(r)?r:r==="webvtt"?"webvtt":null,ps=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},gs=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},ws=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...Oe],ys=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,bs=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,ks=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Ts=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Ei=(r,e)=>{if(!r)throw new TypeError("Video chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Video chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!ws.some(t=>r.decoderConfig.codec.startsWith(t)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.codedWidth)||r.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(r.decoderConfig.codedHeight)||r.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(r.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectWidth)||r.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(r.decoderConfig.displayAspectHeight)||r.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(r.decoderConfig.displayAspectWidth!==void 0!=(r.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(r.decoderConfig.description!==void 0&&!pt(r.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.colorSpace!==void 0){const{colorSpace:t}=r.decoderConfig;if(typeof t!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(Je);if(t.primaries!=null&&!i.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const s=Object.keys(et);if(t.transfer!=null&&!s.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${s.join(", ")}.`);const n=Object.keys(tt);if(t.matrix!=null&&!n.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.join(", ")}.`);if(t.fullRange!=null&&typeof t.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(r.decoderConfig.codec.startsWith("avc1")||r.decoderConfig.codec.startsWith("avc3")){if(!ys.test(r.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(r.decoderConfig.codec.startsWith("hev1")||r.decoderConfig.codec.startsWith("hvc1")){if(!bs.test(r.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(r.decoderConfig.codec.startsWith("vp8")){if(r.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(r.decoderConfig.codec.startsWith("vp09")){if(!ks.test(r.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(r.decoderConfig.codec.startsWith("av01")){if(!Ts.test(r.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(Oe.some(t=>r.decoderConfig.codec.startsWith(t))&&!Oe.some(t=>r.decoderConfig.codec===t))throw new TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${Oe.join(", ")}.`);if(e!==null&&yt(r.decoderConfig.codec)!==e)throw new TypeError(`Video chunk metadata decoder configuration codec string '${r.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},Ss=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],Pi=(r,e)=>{if(!r)throw new TypeError("Audio chunk metadata must be provided.");if(typeof r!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!r.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof r.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof r.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!Ss.some(t=>r.decoderConfig.codec.startsWith(t)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(r.decoderConfig.sampleRate)||r.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(r.decoderConfig.numberOfChannels)||r.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(r.decoderConfig.description!==void 0&&!pt(r.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(r.decoderConfig.codec.startsWith("mp4a")&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(r.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(r.decoderConfig.codec.startsWith("mp3")||r.decoderConfig.codec.startsWith("mp4a")){if(r.decoderConfig.codec!=="mp3"&&r.decoderConfig.codec!=="mp4a.69"&&r.decoderConfig.codec!=="mp4a.6B"&&r.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(r.decoderConfig.codec.startsWith("opus")){if(r.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(r.decoderConfig.description&&r.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(r.decoderConfig.codec.startsWith("vorbis")){if(r.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!r.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(r.decoderConfig.codec.startsWith("flac")){if(r.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!r.decoderConfig.description||r.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(r.decoderConfig.codec.startsWith("ac-3")||r.decoderConfig.codec.startsWith("ac3")){if(r.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(r.decoderConfig.codec.startsWith("ec-3")||r.decoderConfig.codec.startsWith("eac3")){if(r.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if(r.decoderConfig.codec.startsWith("dts")){if(!jt.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${jt.join(", ")}.`)}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!X.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${X.join(", ")}).`);if(e!==null&&yt(r.decoderConfig.codec)!==e)throw new TypeError(`Audio chunk metadata decoder configuration codec string '${r.decoderConfig.codec}' does not fit to the track codec '${e}'.`)},_s=r=>{if(!r)throw new TypeError("Subtitle metadata must be provided.");if(typeof r!="object")throw new TypeError("Subtitle metadata must be an object.");if(!r.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof r.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof r.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*!
44
+ * Copyright (c) 2026-present, Vanilagy and contributors
45
+ *
46
+ * This Source Code Form is subject to the terms of the Mozilla Public
47
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
48
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
49
+ */class Cs{constructor(e){this.input=e}dispose(){}}/*!
50
+ * Copyright (c) 2026-present, Vanilagy and contributors
51
+ *
52
+ * This Source Code Form is subject to the terms of the Mozilla Public
53
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
54
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
55
+ */const ft=new Uint8Array(0);class H{constructor(e,t,i,s,n=-1,a,o){if(this.data=e,this.type=t,this.timestamp=i,this.duration=s,this.sequenceNumber=n,e===ft&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<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=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===ft}get microsecondTimestamp(){return Math.trunc(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*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(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(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(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new H(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new H(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}/*!
56
+ * Copyright (c) 2026-present, Vanilagy and contributors
57
+ *
58
+ * This Source Code Form is subject to the terms of the Mozilla Public
59
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
60
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
61
+ */class $t{constructor(e){this.value=e}}class Gt{constructor(e){this.value=e}}class xi{constructor(e){this.value=e}}class ye{constructor(e){this.value=e}}var f;(function(r){r[r.EBML=440786851]="EBML",r[r.EBMLVersion=17030]="EBMLVersion",r[r.EBMLReadVersion=17143]="EBMLReadVersion",r[r.EBMLMaxIDLength=17138]="EBMLMaxIDLength",r[r.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",r[r.DocType=17026]="DocType",r[r.DocTypeVersion=17031]="DocTypeVersion",r[r.DocTypeReadVersion=17029]="DocTypeReadVersion",r[r.Void=236]="Void",r[r.Segment=408125543]="Segment",r[r.SeekHead=290298740]="SeekHead",r[r.Seek=19899]="Seek",r[r.SeekID=21419]="SeekID",r[r.SeekPosition=21420]="SeekPosition",r[r.Duration=17545]="Duration",r[r.Info=357149030]="Info",r[r.TimestampScale=2807729]="TimestampScale",r[r.MuxingApp=19840]="MuxingApp",r[r.WritingApp=22337]="WritingApp",r[r.Tracks=374648427]="Tracks",r[r.TrackEntry=174]="TrackEntry",r[r.TrackNumber=215]="TrackNumber",r[r.TrackUID=29637]="TrackUID",r[r.TrackType=131]="TrackType",r[r.FlagEnabled=185]="FlagEnabled",r[r.FlagDefault=136]="FlagDefault",r[r.FlagForced=21930]="FlagForced",r[r.FlagOriginal=21934]="FlagOriginal",r[r.FlagHearingImpaired=21931]="FlagHearingImpaired",r[r.FlagVisualImpaired=21932]="FlagVisualImpaired",r[r.FlagCommentary=21935]="FlagCommentary",r[r.FlagLacing=156]="FlagLacing",r[r.Name=21358]="Name",r[r.Language=2274716]="Language",r[r.LanguageBCP47=2274717]="LanguageBCP47",r[r.CodecID=134]="CodecID",r[r.CodecPrivate=25506]="CodecPrivate",r[r.CodecDelay=22186]="CodecDelay",r[r.SeekPreRoll=22203]="SeekPreRoll",r[r.DefaultDuration=2352003]="DefaultDuration",r[r.Video=224]="Video",r[r.PixelWidth=176]="PixelWidth",r[r.PixelHeight=186]="PixelHeight",r[r.DisplayWidth=21680]="DisplayWidth",r[r.DisplayHeight=21690]="DisplayHeight",r[r.DisplayUnit=21682]="DisplayUnit",r[r.AlphaMode=21440]="AlphaMode",r[r.Audio=225]="Audio",r[r.SamplingFrequency=181]="SamplingFrequency",r[r.Channels=159]="Channels",r[r.BitDepth=25188]="BitDepth",r[r.SimpleBlock=163]="SimpleBlock",r[r.BlockGroup=160]="BlockGroup",r[r.Block=161]="Block",r[r.BlockAdditions=30113]="BlockAdditions",r[r.BlockMore=166]="BlockMore",r[r.BlockAdditional=165]="BlockAdditional",r[r.BlockAddID=238]="BlockAddID",r[r.BlockDuration=155]="BlockDuration",r[r.ReferenceBlock=251]="ReferenceBlock",r[r.Cluster=524531317]="Cluster",r[r.Timestamp=231]="Timestamp",r[r.Cues=475249515]="Cues",r[r.CuePoint=187]="CuePoint",r[r.CueTime=179]="CueTime",r[r.CueTrackPositions=183]="CueTrackPositions",r[r.CueTrack=247]="CueTrack",r[r.CueClusterPosition=241]="CueClusterPosition",r[r.Colour=21936]="Colour",r[r.MatrixCoefficients=21937]="MatrixCoefficients",r[r.TransferCharacteristics=21946]="TransferCharacteristics",r[r.Primaries=21947]="Primaries",r[r.Range=21945]="Range",r[r.Projection=30320]="Projection",r[r.ProjectionType=30321]="ProjectionType",r[r.ProjectionPoseRoll=30325]="ProjectionPoseRoll",r[r.Attachments=423732329]="Attachments",r[r.AttachedFile=24999]="AttachedFile",r[r.FileDescription=18046]="FileDescription",r[r.FileName=18030]="FileName",r[r.FileMediaType=18016]="FileMediaType",r[r.FileData=18012]="FileData",r[r.FileUID=18094]="FileUID",r[r.Chapters=272869232]="Chapters",r[r.Tags=307544935]="Tags",r[r.Tag=29555]="Tag",r[r.Targets=25536]="Targets",r[r.TargetTypeValue=26826]="TargetTypeValue",r[r.TargetType=25546]="TargetType",r[r.TagTrackUID=25541]="TagTrackUID",r[r.TagEditionUID=25545]="TagEditionUID",r[r.TagChapterUID=25540]="TagChapterUID",r[r.TagAttachmentUID=25542]="TagAttachmentUID",r[r.SimpleTag=26568]="SimpleTag",r[r.TagName=17827]="TagName",r[r.TagLanguage=17530]="TagLanguage",r[r.TagString=17543]="TagString",r[r.TagBinary=17541]="TagBinary",r[r.ContentEncodings=28032]="ContentEncodings",r[r.ContentEncoding=25152]="ContentEncoding",r[r.ContentEncodingOrder=20529]="ContentEncodingOrder",r[r.ContentEncodingScope=20530]="ContentEncodingScope",r[r.ContentCompression=20532]="ContentCompression",r[r.ContentCompAlgo=16980]="ContentCompAlgo",r[r.ContentCompSettings=16981]="ContentCompSettings",r[r.ContentEncryption=20533]="ContentEncryption"})(f||(f={}));const Es=[f.EBML,f.Segment],Xe=[f.SeekHead,f.Info,f.Cluster,f.Tracks,f.Cues,f.Attachments,f.Chapters,f.Tags],lt=[...Es,...Xe],Fr=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,Br=r=>r<1n<<8n?1:r<1n<<16n?2:r<1n<<24n?3:r<1n<<32n?4:r<1n<<40n?5:r<1n<<48n?6:r<1n<<56n?7:8,Dr=r=>r>=-64&&r<64?1:r>=-8192&&r<8192?2:r>=-1048576&&r<1<<20?3:r>=-134217728&&r<1<<27?4:r>=-17179869184&&r<2**34?5:6,Ps=r=>{if(r<127)return 1;if(r<16383)return 2;if(r<(1<<21)-1)return 3;if(r<(1<<28)-1)return 4;if(r<2**35-1)return 5;if(r<2**42-1)return 6;throw new Error("EBML varint size not supported "+r)};class xs{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=Fr(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/2**40|0);case 5:this.helperView.setUint8(i++,e/2**32|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=Br(e)){let i=0;for(let s=t-1;s>=0;s--)this.helperView.setUint8(i++,Number(e>>BigInt(s*8)&0xffn));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=Dr(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=Ps(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/2**32&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/2**40&3),this.helperView.setUint8(i++,e/2**32|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),i=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);const s=this.writer.getPos();if(this.dataOffsets.set(e,s),this.writeEBML(e.data),e.size!==-1){const n=this.writer.getPos()-s,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,i),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??Fr(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??Br(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof $t)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof Gt)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof xi){const t=e.size??Dr(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof ye){const t=Le.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else ge(e.data)}}const Kt=8,J=2,he=2*Kt,vi=r=>{if(r.remainingLength<1)return null;const e=ce(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;return r.remainingLength<t?null:t},je=r=>{if(r.remainingLength<1)return null;const e=ce(r);if(e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;if(r.remainingLength<t-1)return null;let s=e&i-1;for(let n=1;n<t;n++)s*=256,s+=ce(r);return s},F=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i<e;i++)t*=256,t+=ce(r);return t},vs=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i<e;i++)t<<=8n,t+=BigInt(ce(r));return t},or=r=>{const e=vi(r);return e===null||r.remainingLength<e?null:F(r,e)},Ai=r=>{if(r.remainingLength<1)return null;if(ce(r)===255)return;r.skip(-1);const t=je(r);if(t===null)return null;if(t!==72057594037927940)return t},de=r=>{y(r.remainingLength>=J);const e=or(r);if(e===null)return null;const t=Ai(r);return t===null?null:{id:e,size:t}},De=(r,e)=>{const t=Z(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return String.fromCharCode(...t.subarray(0,i))},ze=(r,e)=>{const t=Z(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return oi.decode(t.subarray(0,i))},xt=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?wa(r):ya(r)},Qt=async(r,e,t,i)=>{const s=new Set(t);let n=e;for(;i===null||n<i;){let a=r.requestSliceRange(n,J,he);if(I(a)&&(a=await a),!a)break;const o=de(a);if(!o)break;if(s.has(o.id))return{pos:n,found:!0};be(o.size),n=a.filePos+o.size}return{pos:i!==null&&i>n?i:n,found:!1}},Ri=async(r,e,t,i)=>{const n=new Set(t);let a=e;for(;a<i;){let o=r.requestSliceRange(a,0,Math.min(65536,i-a));if(I(o)&&(o=await o),!o||o.length<Kt)break;for(let c=0;c<o.length-Kt;c++){o.filePos=a;const l=or(o);if(l!==null&&n.has(l))return a;a++}}return null},G={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 be(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}/*!
62
+ * Copyright (c) 2026-present, Vanilagy and contributors
63
+ *
64
+ * This Source Code Form is subject to the terms of the Mozilla Public
65
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
66
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
67
+ */const Ii=r=>{let t=(r.hasVideo?"video/":r.hasAudio?"audio/":"application/")+(r.isWebM?"webm":"x-matroska");if(r.codecStrings.length>0){const i=[...new Set(r.codecStrings.filter(Boolean))];t+=`; codecs="${i.join(", ")}"`}return t};/*!
68
+ * Copyright (c) 2026-present, Vanilagy and contributors
69
+ *
70
+ * This Source Code Form is subject to the terms of the Mozilla Public
71
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
72
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
73
+ */var le;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(le||(le={}));var mt;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(mt||(mt={}));var $e;(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})($e||($e={}));const vt=[{id:f.SeekHead,flag:"seekHeadSeen"},{id:f.Info,flag:"infoSeen"},{id:f.Tracks,flag:"tracksSeen"},{id:f.Cues,flag:"cuesSeen"}],Fi=10*2**20;class As extends Cs{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.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(i=>i.getDecoderConfig().then(s=>s?.codec??null)));return Ii({isWebM:this.isWebM,hasVideo:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="video")),hasAudio:this.segments.some(i=>i.tracks.some(s=>s.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,J,he);if(I(t)&&(t=await t),!t)break;const i=de(t);if(!i)break;const s=i.id;let n=i.size;const a=t.filePos;if(s===f.EBML){be(n);let o=this.reader.requestSlice(a,n);if(I(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(s===f.Segment){if(await this.readSegment(a,n),n===void 0||this.reader.fileSize===null)break}else if(s===f.Cluster){if(this.reader.fileSize===null)break;n===void 0&&(n=(await Qt(this.reader,a,lt,this.reader.fileSize)).pos-a);const o=ne(this.segments);o&&(o.elementEndPos=a+n)}be(n),e=a+n}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(i,J,he);if(I(o)&&(o=await o),!o)break;const c=i,l=de(o);if(!l||!Xe.includes(l.id)&&l.id!==f.Void){const p=await Ri(this.reader,c,Xe,Math.min(this.currentSegment.elementEndPos??1/0,c+Fi));if(p){i=p;continue}else break}const{id:u,size:d}=l,h=o.filePos,m=vt.findIndex(p=>p.id===u);if(m!==-1){const p=vt[m].flag;this.currentSegment[p]=!0,be(d);let b=this.reader.requestSlice(h,d);I(b)&&(b=await b),b&&this.readContiguousElements(b)}else if(u===f.Tags||u===f.Attachments){u===f.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,be(d);let p=this.reader.requestSlice(h,d);I(p)&&(p=await p),p&&this.readContiguousElements(p)}else if(u===f.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;i=h+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=vt.find(p=>p.id===o.id);if(!c||this.currentSegment[c.flag])continue;let l=this.reader.requestSliceRange(e+o.segmentPosition,J,he);if(I(l)&&(l=await l),!l)continue;const u=de(l);if(!u)continue;const{id:d,size:h}=u;if(d!==c.id)continue;be(h),this.currentSegment[c.flag]=!0;let m=this.reader.requestSlice(l.filePos,h);I(m)&&(m=await m),m&&this.readContiguousElements(m)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);const s=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=s.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,l)=>c.time-l.time);for(let c=0;c<o.cuePoints.length-1;c++){const l=o.cuePoints[c],u=o.cuePoints[c+1];l.time===u.time&&(o.cuePoints.splice(c+1,1),c--)}}let n=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,n=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=n.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,J,he);I(i)&&(i=await i),y(i);const s=e,n=de(i);y(n);const a=n.id;y(a===f.Cluster);let o=n.size;const c=i.filePos;o===void 0&&(o=(await Qt(this.reader,c,lt,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);I(l)&&(l=await l);const u={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=u,l){const d=this.readContiguousElements(l,lt);u.elementEndPos=d}for(const[,d]of u.trackData){const h=d.track;y(d.blocks.length>0);let m=!1;for(let g=0;g<d.blocks.length;g++){const T=d.blocks[g];T.timestamp+=u.timestamp,m||=T.lacing!==le.None}d.presentationTimestamps=d.blocks.map((g,T)=>({timestamp:g.timestamp,blockIndex:T})).sort((g,T)=>g.timestamp-T.timestamp);for(let g=0;g<d.presentationTimestamps.length;g++){const T=d.presentationTimestamps[g],k=d.blocks[T.blockIndex];if(d.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(d.firstKeyFrameTimestamp=k.timestamp),g<d.presentationTimestamps.length-1){const x=d.presentationTimestamps[g+1];k.duration=x.timestamp-k.timestamp}else k.duration===0&&h.defaultDuration!=null&&k.lacing===le.None&&(k.duration=h.defaultDuration)}m&&(this.expandLacedBlocks(d.blocks,h),d.presentationTimestamps=d.blocks.map((g,T)=>({timestamp:g.timestamp,blockIndex:T})).sort((g,T)=>g.timestamp-T.timestamp));const p=d.blocks[d.presentationTimestamps[0].blockIndex],b=d.blocks[ne(d.presentationTimestamps).blockIndex];d.startTimestamp=p.timestamp,d.endTimestamp=b.timestamp+b.duration;const w=se(h.clusterPositionCache,d.startTimestamp,g=>g.startTimestamp);(w===-1||h.clusterPositionCache[w].elementStartPos!==s)&&h.clusterPositionCache.splice(w+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const s=e.segment.tracks.find(n=>n.id===t);if(!s)return null;i={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.lacing===le.None)continue;s.decoded||(s.data=this.decodeBlockData(t,s.data),s.decoded=!0);const n=oe.tempFromBytes(s.data),a=[],o=ce(n)+1;switch(s.lacing){case le.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;n.bufferPos<n.length;){const h=ce(n);if(d+=h,h<255){a.push(d),l+=d;break}}}a.push(n.length-(n.bufferPos+l))}break;case le.FixedSize:{const l=n.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case le.Ebml:{const l=je(n);y(l!==null);let u=l;a.push(u);let d=u;for(let h=1;h<o-1;h++){const m=n.bufferPos,p=je(n);y(p!==null);const b=p,g=(1<<(n.bufferPos-m)*7-1)-1,T=b-g;u+=T,a.push(u),d+=u}a.push(n.length-(n.bufferPos+d))}break;default:y(!1)}y(a.length===o),e.splice(i,1);const c=s.duration||o*(t.defaultDuration??0);for(let l=0;l<o;l++){const u=a[l],d=Z(n,u),h=s.timestamp+c*l/o,m=c/o;e.splice(i+l,0,{timestamp:h,duration:m,isKeyFrame:s.isKeyFrame,data:d,lacing:le.None,decoded:!0,postProcessed:!1,mainAdditional:s.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===f.Tags&&!e.tagsSeen)){if(!(t.id===f.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,J,he);if(I(i)&&(i=await i),!i)continue;const s=de(i);if(!s||s.id!==t.id)continue;const{size:n}=s;be(n),y(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(i.filePos,n);I(a)&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===f.Tags?e.tagsSeen=!0:t.id===f.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=J;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=de(e);if(!i||t&&t.includes(i.id))return!1;const{id:s,size:n}=i,a=e.filePos;switch(be(n),s){case f.DocType:this.isWebM=De(e,n)==="webm";break;case f.Seek:{if(!this.currentSegment)break;const o={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(o),this.readContiguousElements(e.slice(a,n)),(o.id===-1||o.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case f.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=F(e,n)}break;case f.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=F(e,n)}break;case f.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=F(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case f.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=xt(e,n)}break;case f.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...xn,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(a,n)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==mt.Block||o.data.algorithm!==$e.HeaderStripping)&&(D._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const o=this.currentTrack.codecId.indexOf("/"),c=o===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,o);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){const u=this.currentTrack.info.displayWidth*this.currentTrack.info.height,d=this.currentTrack.info.displayHeight*this.currentTrack.info.width;u>0&&d>0&&(u>d?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*u/d):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*d/u))}if(this.currentTrack.codecId===G.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===G.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===G.vp8)this.currentTrack.info.codec="vp8";else if(c===G.vp9)this.currentTrack.info.codec="vp9";else if(c===G.av1)this.currentTrack.info.codec="av1";else if(c===G.prores){const u=this.currentTrack.codecPrivate?oi.decode(this.currentTrack.codecPrivate):"";Oe.includes(u)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=u)}const l=this.currentTrack;this.currentTrack.trackBacking=new Rs(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===G.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===G.mp3?this.currentTrack.info.codec="mp3":c===G.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=_i):c===G.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===G.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===G.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===G.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===G.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"));const l=this.currentTrack;this.currentTrack.trackBacking=new Is(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case f.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=F(e,n)}break;case f.TrackType:{if(!this.currentTrack)break;const o=F(e,n);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...an},alphaMode:!1,proresFormat:null}:o===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case f.FlagEnabled:{if(!this.currentTrack)break;F(e,n)||(this.currentTrack=null)}break;case f.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!F(e,n)}break;case f.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!F(e,n)}break;case f.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!F(e,n)}break;case f.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!F(e,n)}break;case f.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!F(e,n)}break;case f.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!F(e,n)}break;case f.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=De(e,n)}break;case f.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=Z(e,n)}break;case f.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=F(e,n)}break;case f.Name:{if(!this.currentTrack)break;this.currentTrack.name=ze(e,n)}break;case f.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=De(e,n),ui(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Wt)}break;case f.LanguageBCP47:{if(!this.currentTrack)break;const c=De(e,n).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Wt,this.currentTrack.hasLanguageBcp47=!0}break;case f.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case f.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=F(e,n)}break;case f.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=F(e,n)}break;case f.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=F(e,n)}break;case f.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=F(e,n)}break;case f.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=F(e,n)}break;case f.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=F(e,n)===1}break;case f.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case f.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video")break;const o=F(e,n),c=Be[o];this.currentTrack.info.colorSpace.matrix=c}break;case f.Range:{if(this.currentTrack?.info?.type!=="video")break;const o=F(e,n);this.currentTrack.info.colorSpace.fullRange=o===1||o===2?o===2:void 0}break;case f.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video")break;const o=F(e,n),c=Fe[o];this.currentTrack.info.colorSpace.transfer=c}break;case f.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=F(e,n),c=Ie[o];this.currentTrack.info.colorSpace.primaries=c}break;case f.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case f.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-xt(e,n);try{this.currentTrack.info.rotation=Zt(c)}catch{}}break;case f.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,n))}break;case f.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=xt(e,n)}break;case f.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=F(e,n)}break;case f.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=F(e,n)}break;case f.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,n)),this.currentCueTime=null}break;case f.CueTime:this.currentCueTime=F(e,n);break;case f.CueTrackPositions:{if(this.currentCueTime===null)break;y(this.currentSegment);const o={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(o),this.readContiguousElements(e.slice(a,n)),(o.trackId===-1||o.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case f.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=F(e,n)}break;case f.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;y(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+F(e,n)}break;case f.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=F(e,n)}break;case f.SimpleBlock:{if(!this.currentCluster)break;const o=je(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=Jr(e),u=ce(e),d=u>>1&3;let h=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(h=!0);const m=Z(e,n-(e.filePos-a)),p=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:h,data:m,lacing:d,decoded:!p,postProcessed:!1,mainAdditional:null})}break;case f.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,n)),this.currentBlock=null}break;case f.Block:{if(!this.currentCluster)break;const o=je(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=Jr(e),d=ce(e)>>1&3,h=Z(e,n-(e.filePos-a)),m=c.track.decodingInstructions.length>0;this.currentBlock={timestamp:l,duration:0,isKeyFrame:!0,data:h,lacing:d,decoded:!m,postProcessed:!1,mainAdditional:null},c.blocks.push(this.currentBlock)}break;case f.BlockAdditions:this.readContiguousElements(e.slice(a,n));break;case f.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,n)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case f.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Z(e,n)}break;case f.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=F(e,n)}break;case f.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=F(e,n)}break;case f.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case f.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,n));break;case f.Targets:this.readContiguousElements(e.slice(a,n));break;case f.TargetTypeValue:F(e,n)!==50&&(this.currentTagTargetIsMovie=!1);break;case f.TagTrackUID:case f.TagEditionUID:case f.TagChapterUID:case f.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case f.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,n))}break;case f.TagName:this.currentSimpleTagName=ze(e,n);break;case f.TagString:{if(!this.currentSimpleTagName)break;const o=ze(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case f.TagBinary:{if(!this.currentSimpleTagName)break;const o=Z(e,n);this.processTagValue(this.currentSimpleTagName,o)}break;case f.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,n));const o=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(o.raw??={},o.raw[this.currentAttachedFile.fileUid.toString()]=new nr(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){const c=this.currentAttachedFile.fileName;let l="unknown";if(c){const u=c.toLowerCase();u.startsWith("cover.")?l="coverFront":u.startsWith("back.")&&(l="coverBack")}o.images??=[],o.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 f.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=vs(e,n)}break;case f.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ze(e,n)}break;case f.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=De(e,n)}break;case f.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=Z(e,n)}break;case f.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ze(e,n)}break;case f.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,n)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case f.ContentEncoding:this.currentDecodingInstruction={order:0,scope:mt.Block,data:null},this.readContiguousElements(e.slice(a,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case f.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=F(e,n)}break;case f.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=F(e,n)}break;case f.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:$e.Zlib,settings:null},this.readContiguousElements(e.slice(a,n))}break;case f.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=F(e,n)}break;case f.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=Z(e,n)}break;case f.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+n,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let i=t;for(const s of e.decodingInstructions)switch(y(s.data),s.data.type){case"decompress":switch(s.data.algorithm){case $e.HeaderStripping:if(s.data.settings&&s.data.settings.length>0){const n=s.data.settings,a=new Uint8Array(n.length+i.length);a.set(n,0),a.set(i,n.length),i=a}break}break}return i}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=t,typeof t=="string")switch(e.toLowerCase()){case"title":i.title??=t;break;case"description":i.description??=t;break;case"artist":i.artist??=t;break;case"album":i.album??=t;break;case"album_artist":i.albumArtist??=t;break;case"genre":i.genre??=t;break;case"comment":i.comment??=t;break;case"lyrics":i.lyrics??=t;break;case"date":{const s=new Date(t);Number.isNaN(s.getTime())||(i.date??=s)}break;case"track_number":case"part_number":{const s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.trackNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{const s=t.split("/"),n=Number.parseInt(s[0],10),a=s[1]&&Number.parseInt(s[1],10);Number.isInteger(n)&&n>0&&(i.discNumber??=n),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}break}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(const s of e.tracks){y(s.trackBacking);const n=await s.trackBacking.getFirstPacket({metadataOnly:!0});n&&(t=Math.min(t??1/0,n.timestamp))}let i=e.duration/e.timestampFactor;return i+=t??0,i}}class Bi{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const s of e.segments)for(const n of s.tracks)if(n.trackBacking.getType()===t&&i++,n===this.internalTrack)break;return i}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(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return mn(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=se(n.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){const n=s.trackData.get(this.internalTrack.id);if(i.blockIndex+1<n.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=cn(n.presentationTimestamps,l=>n.blocks[l.blockIndex].isKeyFrame&&l.timestamp<=i),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,s=>{if(s===i.cluster){const a=s.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>i.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const n=s.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){const a=n.blocks.findIndex(o=>o.isKeyFrame);return y(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];if(y(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0),!n.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(n.data.length>=8&&n.data[4]===105&&n.data[5]===99&&n.data[6]===112&&n.data[7]===102)){const h=new Uint8Array(n.data.length+8);O(h).setUint32(0,h.length,!1),h[4]=105,h[5]=99,h[6]=112,h[7]=102,h.set(n.data,8),n.data=h}n.postProcessed=!0}const a=i.metadataOnly?ft:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?ft:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);const u=new H(a,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength,l);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u}async performClusterLookup(e,t,i,s,n){const{demuxer:a,segment:o}=this.internalTrack;let c=null,l=null,u=-1;if(e){const{blockIndex:g,correctBlockFound:T}=t(e);if(T)return this.fetchPacketInCluster(e,g,n);g!==-1&&(l=e,u=g)}const d=se(this.internalTrack.cuePoints,i,g=>g.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,m=se(this.internalTrack.clusterPositionCache,i,g=>g.startTimestamp),p=m!==-1?this.internalTrack.clusterPositionCache[m]:null,b=Math.max(h?.clusterPosition??0,p?.elementStartPos??0)||null;let w;for(e?b===null||e.elementStartPos>=b?(w=e.elementEndPos,c=e):w=b:w=b??o.clusterSeekStartPos;o.elementEndPos===null||w<=o.elementEndPos-J;){if(c){const S=c.trackData.get(this.internalTrack.id);if(S&&S.startTimestamp>s)break}let g=a.reader.requestSliceRange(w,J,he);if(I(g)&&(g=await g),!g)break;const T=w,k=de(g);if(!k||!Xe.includes(k.id)&&k.id!==f.Void){const S=await Ri(a.reader,T,Xe,Math.min(o.elementEndPos??1/0,T+Fi));if(S){w=S;continue}else break}const x=k.id;let C=k.size;const A=g.filePos;if(x===f.Cluster){c=await a.readCluster(T,o),C=c.elementEndPos-A;const{blockIndex:S,correctBlockFound:_}=t(c);if(_)return this.fetchPacketInCluster(c,S,n);S!==-1&&(l=c,u=S)}C===void 0&&(y(x!==f.Cluster),C=(await Qt(a.reader,A,lt,o.elementEndPos)).pos-A);const v=A+C;if(o.elementEndPos===null){let S=a.reader.requestSliceRange(v,J,he);if(I(S)&&(S=await S),!S)break;if(or(S)===f.Segment){o.elementEndPos=v;break}}w=v}if(h&&(!l||l.elementStartPos<h.clusterPosition)){const g=this.internalTrack.cuePoints[d-1];y(!g||g.time<h.time);const T=g?.time??-1/0;return this.performClusterLookup(null,t,T,s,n)}return l?this.fetchPacketInCluster(l,u,n):null}}class Rs extends Bi{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){const 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({}));const i={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?Rn(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Bn(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?qn(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?Hn(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Ln(e.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!nn(this.internalTrack.info.colorSpace)){const n=hs(i);this.internalTrack.info.colorSpace.primaries??=n.primaries,this.internalTrack.info.colorSpace.transfer??=n.transfer,this.internalTrack.info.colorSpace.matrix??=n.matrix,this.internalTrack.info.colorSpace.fullRange??=n.fullRange}const s={codec:ds(i),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)&&(s.displayAspectWidth=this.internalTrack.info.squarePixelWidth,s.displayAspectHeight=this.internalTrack.info.squarePixelHeight),s})():null}}class Is extends Bi{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}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){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&ns(e.data)}return{codec:ms({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}}/*!
74
+ * Copyright (c) 2026-present, Vanilagy and contributors
75
+ *
76
+ * This Source Code Form is subject to the terms of the Mozilla Public
77
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
78
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
79
+ */const Fs=7,Bs=9,Or=r=>{const e=r.filePos,t=Z(r,9),i=new U(t);if(i.readBits(12)!==4095||(i.skipBits(1),i.readBits(2)!==0))return null;const a=i.readBits(1),o=i.readBits(2)+1,c=i.readBits(4);if(c===15)return null;i.skipBits(1);const l=i.readBits(3);if(l===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const u=i.readBits(13);i.skipBits(11);const d=i.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?r.filePos-=2:h=i.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:l,frameLength:u,numberOfAacFrames:d,crcCheck:h,startPos:e}};/*!
80
+ * Copyright (c) 2026-present, Vanilagy and contributors
81
+ *
82
+ * This Source Code Form is subject to the terms of the Mozilla Public
83
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
84
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
85
+ */ir();const Di=0,Oi=1/0;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(r=>{r()});class _e extends it{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 $;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Di,Oi),e=this._getFileSize(),y(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new $;const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Us(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new cr(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class cr{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}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.");const e=this.source;y(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Mi extends _e{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=s=>{if(!(s instanceof _e||s instanceof cr))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const n=s instanceof _e?s.ref():s;return n.source._usedForHls||=this._usedForHls,n};return I(t)?t.then(i):i(t)}}const Mr=(r,e)=>r.path===e.path;typeof FinalizationRegistry<"u"&&new FinalizationRegistry(r=>{r.cancel().catch(()=>{})});const Ds=.5*2**20,Os=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let s=null;try{typeof window<"u"&&typeof window.location<"u"&&(s=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&s!==null&&s!==window.location.origin)return D._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**(r-2),16)}),zr=new Set;class zi extends Mi{constructor(e,t={}){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(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!rt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");const i=e instanceof Request?e.url:e instanceof URL?e.href:e;super(i,a=>new zi(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Os,this._requestInit={...t.requestInit};let s=null;if(t.requestInit?.headers){const a={...Ut(t.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(s=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){const a=e.headers.get("Range");if(a!==null){s??=a;const o=new Request(e);o.headers.delete("Range"),this._url=o}}if(s!==null){const a=zs(s);a&&(this._offset=a.offset,this._length=a.length)}const n=2;this._orchestrator=new Ws({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??n,runWorker:this._runWorker.bind(this),prefetchProfile:Ns.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:N(e-this._offset,0,this._length??1/0)}_read(e,t,i,s){if(this._length!==null&&t>this._length)return null;const n=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(n+e,n+t):this._orchestrator.read(n+e,n+t,Math.max(n+i,n),n+Math.min(s,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return I(a)?a.then(o):o(a)}async _runWorker(e){for(;;){const t=new AbortController,i=await yr(this._options.fetchFn??fetch,this._url,wr(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);i.redirected&&(this.rootPath=i.url);e:if(this._orchestrator.fileSize===null&&(i.status===206||i.type==="basic"&&!i.headers.has("Content-Encoding"))){const n=i.headers.get("Content-Range");if(n){const o=/\/(\d+)/.exec(n);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=i.headers.get("Content-Length");if(a){const o=i.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(o+Number(a))}}if(this._fileSizeDetermined=!0,!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(i.status!==206){if(this._sequentialBacking){i.body.cancel();return}if(!this._usedForHls){const n=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);n.origin!=="null"&&!(n.pathname.endsWith(".m3u8")||n.pathname.endsWith(".m3u"))&&(zr.has(n.origin)||(D._warn(`HTTP server (origin ${n.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.`),zr.add(n.origin)))}this._transitionToSequentialMode(i.body);return}const s=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let n;try{n=await s.read()}catch(c){if(this._disposed)throw c;const l=this._getRetryDelay(1,c,this._url);if(l!==null){D._error("Error while reading response stream. Attempting to resume.",c),await ut(1e3*l);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=n;if(a){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+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_transitionToSequentialMode(e){let t=e.getReader(),i=0,s=0;const n=new ReadableStream({pull:async c=>{for(;;){let l;try{l=await t.read()}catch(d){if(this._disposed)throw d;const h=this._getRetryDelay(1,d,this._url);if(h===null)throw d;D._error("Error while reading response stream. Attempting to resume.",d),await ut(1e3*h);const m=await yr(this._options.fetchFn??fetch,this._url,wr(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!m.ok)throw new Error(`Error fetching ${String(this._url)}: ${m.status} ${m.statusText}`);if(!m.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=m.body.getReader(),s=m.status===206?0:i;continue}if(l.done){c.close();return}let u=l.value;if(s>0){const d=Math.min(s,u.length);s-=d,u=u.subarray(d)}if(u.length!==0){i+=u.length,c.enqueue(u);return}}},cancel:()=>t.cancel()}),a=new Vs(n,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});a._endIndex=this._orchestrator.fileSize,a._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.",a.on("read",({start:c,end:l})=>this._dispatchRead(c,l)),this._sequentialBacking=a;const o=new Set;for(const c of this._orchestrator.workers){for(const l of c.pendingSlices)o.add(l);c.aborted=!0,c.pendingSlices.length=0}for(const c of this._orchestrator.queuedReads)for(const l of c.pendingSlices)o.add(l);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const c of o){const l=a._read(c.start,c.start+c.bytes.length);I(l)?l.then(u=>{u?(y(u.offset===c.start),c.resolve(u.bytes)):c.resolve(null)},u=>c.reject(u)):(y(l===null),c.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Ms=/^bytes=(\d+)-(\d*)$/,zs=r=>{const e=Ms.exec(r.trim());if(!e)return null;const t=Number(e[1]),i=e[2]===""?null:Number(e[2]);return i!==null&&i<t?null:{offset:t,length:i!==null?i-t+1:null}};class Vs extends _e{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!rt(t.maxCacheSize)||t.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=t.maxCacheSize??32*2**20,this._handleUnhandledError=t.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=se(this._cache,e,u=>u.start),s=i!==-1?this._cache[i]:null;if(s&&s.start<=e&&t<=s.end)return{bytes:s.bytes,view:s.view,offset:s.start};let n=e;const a=new Uint8Array(t-e);if(i!==-1)for(let u=i;u<this._cache.length;u++){const d=this._cache[u];if(d.start>=t)break;const h=Math.max(e,d.start);h>n&&this._throwDueToCacheMiss();const m=Math.min(t,d.end);h<m&&(a.set(d.bytes.subarray(h-d.start,m-d.start),h-e),n=m)}if(n===t)return{bytes:a,view:O(a),offset:e};this._currentIndex>n&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=j();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(u=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(u)),this._pendingSlices.length=0;else if(this._handleUnhandledError)this._handleUnhandledError(u);else throw u})),o}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const n of this._pendingSlices)n.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const i=this._currentIndex,s=this._currentIndex+t.byteLength;this._dispatchRead(i,s);for(let n=0;n<this._pendingSlices.length;n++){const a=this._pendingSlices[n],o=Math.max(i,a.start),c=Math.min(s,a.end);o<c&&(a.bytes.set(t.subarray(o-i,c-i),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:O(a.bytes),offset:a.start}),this._pendingSlices.splice(n,1),n--))}for(this._cache.push({start:i,end:s,bytes:t,view:O(t),age:0});this._cache.length>0;){const n=this._cache[0];if(this._maxRequestedIndex-n.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new $);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Ns={network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(const s of t){const a=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(qt(r,e,a,s.targetPos)){const o=s.targetPos-s.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,s.startPos+u)}}return e=Math.max(e,r+Ds),{start:r,end:e}}};class Ws{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,s){y(!this.disposed);const n=this.options.prefetchProfile(e,t,this.workers),a=Math.max(n.start,i),o=Math.min(n.end,this.fileSize??1/0,s);y(a<=e&&t<=o);let c=null;const l=se(this.cache,e,C=>C.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});const d=se(this.cache,a,C=>C.start),h=c?null:new Uint8Array(t-e);let m=0,p=a;const b=[];if(d!==-1){for(let C=d;C<this.cache.length;C++){const A=this.cache[C];if(A.start>=o)break;if(A.end<=a)continue;const v=Math.max(a,A.start),S=Math.min(o,A.end);if(y(v<=S),p<v&&b.push({start:p,end:v}),p=S,h){const _=Math.max(e,A.start),E=Math.min(t,A.end);if(_<E){const R=_-e;h.set(A.bytes.subarray(_-A.start,E-A.start),R),R===m&&(m=E-e)}}A.age=this.nextAge++}p<o&&b.push({start:p,end:o})}else b.push({start:a,end:o});if(h&&m>=h.length&&(c={bytes:h,view:O(h),offset:e}),b.length===0)return y(c),c;const{promise:w,resolve:g,reject:T}=j(),k=[];for(const C of b){const A=Math.max(e,C.start),v=Math.min(t,C.end);A===C.start&&v===C.end?k.push(C):A<v&&k.push({start:A,end:v})}const x=h&&{start:e,bytes:h,holes:k,resolve:g,reject:T};e:for(const C of b){for(const S of this.workers)if(this.checkHoleAgainstWorker(S,C,x?[x]:[])){this.checkQueuedReadsAgainstWorker(S);continue e}const A=C.end<o||this.fileSize!==null,v=this.createWorker(C.start,C.end,A);if(v)x&&(v.pendingSlices=[x]),this.runWorker(v);else{let S=se(this.queuedReads,C.start,E=>E.hole.start),_=S!==-1?this.queuedReads[S]:null;for(_&&C.start<=_.hole.end?(_.hole.end=Math.max(_.hole.end,C.end),_.strictTarget&&=A,x&&_.pendingSlices.push(x)):(S++,_={hole:{start:C.start,end:C.end},strictTarget:A,pendingSlices:x?[x]:[],age:this.nextAge++},this.queuedReads.splice(S,0,_));S+1<this.queuedReads.length;){const E=this.queuedReads[S+1];if(E.hole.start>_.hole.end)break;_.hole.end=Math.max(_.hole.end,E.hole.end),_.pendingSlices.push(...E.pendingSlices),_.strictTarget&&=E.strictTarget,_.age=Math.min(_.age,E.age),this.queuedReads.splice(S+1,1)}}}return c?w.catch(C=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(C);else throw C}):(y(h),c=w.then(C=>C&&{bytes:C,view:O(C),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(qt(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let n=0;n<i.length;n++){const a=i[n];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){const s=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,s.hole,s.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){if(this.workers.length>=this.options.maxWorkerCount){let n=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!n||c.age<n.age)&&(a=o,n=c)}if(n)y(a!==null),y(n.pendingSlices.length===0),this.workers.splice(a,1),this.options.onIdleWorkerRemoved?.(n);else return null}const s={startPos:e,currentPos:e,targetPos:t,strictTarget:i,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(s),s}runWorker(e){y(!e.running),y(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(i=>i.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(t);else throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let t=0;for(let n=1;n<this.queuedReads.length;n++)this.queuedReads[n].age<this.queuedReads[t].age&&(t=n);const i=this.queuedReads[t],s=this.createWorker(i.hole.start,i.hole.end,i.strictTarget);if(!s)return;this.queuedReads.splice(t,1),s.pendingSlices=i.pendingSlices,this.runWorker(s)}})}supplyWorkerData(e,t){y(!e.aborted);const i=e.currentPos,s=i+t.length;this.insertIntoCache({start:i,end:s,bytes:t,view:O(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;n<e.pendingSlices.length;n++){const a=e.pendingSlices[n],o=Math.max(i,a.start),c=Math.min(s,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-i,c-i),o-a.start);for(let l=0;l<a.holes.length;l++){const u=a.holes[l];i<=u.start&&s>u.start&&(u.start=s),u.end<=u.start&&(a.holes.splice(l,1),l--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){const a=this.workers[n];e===a||a.running||qt(i,s,a.currentPos,a.targetPos)&&(this.workers.splice(n,1),this.options.onIdleWorkerRemoved?.(a),n--)}}supplyFileSize(e){y(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){const s=t.pendingSlices[i];for(const n of s.holes)if(n.end>e){s.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){const i=this.queuedReads[t];if(i.hole.start>=e){for(const s of i.pendingSlices)s.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let s=0;s<i.pendingSlices.length;s++){const n=i.pendingSlices[s];n.start>=e&&(n.resolve(null),i.pendingSlices.splice(s,1),s--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const t=this.workers.indexOf(e);y(t!==-1),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=se(this.cache,e.start,i=>i.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const s=new Uint8Array(e.end-i.start);s.set(i.bytes,0),s.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=s,i.view=O(s),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i<this.cache.length;i++){const s=this.cache[i];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length,i--;continue}const n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=O(n),e.end=s.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let i=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){const a=this.cache[n];a.age<s.age&&(i=n,s=a)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(i,1),this.currentCacheSize-=s.bytes.length}}dispose(){for(const e of this.workers){for(const t of e.pendingSlices)t.reject(new $);e.pendingSlices.length=0,e.aborted=!0,e.running||this.options.onIdleWorkerRemoved?.(e)}for(const e of this.queuedReads)for(const t of e.pendingSlices)t.reject(new $);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class Us extends _e{constructor(e,t,i){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=i??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:N(e-this._offset,0,this._length??1/0)}_read(e,t,i,s){if(this._length!==null&&t>this._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+s),a=o=>o?(o.offset-=this._offset,o):null;return I(n)?n.then(a):a(n)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}/*!
86
+ * Copyright (c) 2026-present, Vanilagy and contributors
87
+ *
88
+ * This Source Code Form is subject to the terms of the Mozilla Public
89
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
90
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
91
+ */class Vi{constructor(){this._isIsobmff=!1}}class qs extends Vi{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,he);if(I(i)&&(i=await i),!i)return!1;const s=vi(i);if(s===null||s<1||s>8||F(i,s)!==f.EBML)return!1;const a=Ai(i);if(typeof a!="number")return!1;let o=e._reader.requestSlice(i.filePos,a);if(I(o)&&(o=await o),!o)return!1;const c=i.filePos;for(;o.filePos<=c+a-J;){const l=de(o);if(!l)break;const{id:u,size:d}=l,h=o.filePos;if(d===void 0)return!1;switch(u){case f.EBMLVersion:if(F(o,d)!==1)return!1;break;case f.EBMLReadVersion:if(F(o,d)!==1)return!1;break;case f.DocType:if(De(o,d)!==t)return!1;break;case f.DocTypeVersion:if(F(o,d)>4)return!1;break}o.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new As(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Hs extends qs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}const Na=new Hs,Ls=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(r.isobmff!==void 0){if(!r.isobmff||typeof r.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(r.isobmff.resolveKeyId!==void 0&&typeof r.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}if(r.hls!==void 0){if(!r.hls||typeof r.hls!="object")throw new TypeError(`${e}.hls, when provided, must be an object.`);if(r.hls.offsetTimestampsByDateTime!==void 0&&typeof r.hls.offsetTimestampsByDateTime!="boolean")throw new TypeError(`${e}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}};/*!
92
+ * Copyright (c) 2026-present, Vanilagy and contributors
93
+ *
94
+ * This Source Code Form is subject to the terms of the Mozilla Public
95
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
96
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
97
+ */var js=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(s=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");s&&(i=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},$s=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,s=0;function n(){for(;i=e.stack.pop();)try{if(!i.async&&s===1)return s=0,e.stack.push(i),Promise.resolve().then(n);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});ir();let Vr=-1/0,Nr=-1/0,Ye=null;typeof FinalizationRegistry<"u"&&(Ye=new FinalizationRegistry(r=>{const e=performance.now();r.type==="video"?(e-Vr>=1e3&&(D._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."),Vr=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-Nr>=1e3&&(D._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."),Nr=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class Pe{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Xt=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Gs=new Set(Xt);class Y{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(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!Gs.has(t.format))throw new TypeError("init.format must be one of: "+Xt.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const n of t.layout){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(n.offset)||n.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(n.stride)||n.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&Ct(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??Xs(t.format,t.codedWidth,t.codedHeight);let s=t.colorSpace??null;s===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?s={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:s={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?me(e):me(e).slice(),this._layout=i,this.colorSpace=new At(s)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&Ct(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new At(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.visibleRect!==void 0&&Ct(t.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new Y(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Te),duration:Math.trunc((t.duration??0)*Te)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,s=0;if("naturalWidth"in e?(i=e.naturalWidth,s=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,s=e.videoHeight):"width"in e&&(i=Number(e.width),s=Number(e.height)),!i||!s)throw new TypeError("Could not determine dimensions.");const n=t.visibleRect??{left:0,top:0,width:i,height:s},a=new OffscreenCanvas(n.width,n.height),o=a.getContext("2d",{alpha:di(),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(e,-n.left,-n.top),this._data=a,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n.width,height:n.height},this.squarePixelWidth=n.width,this.squarePixelHeight=n.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new At({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Pe){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!Xt.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.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=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=Ke({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ye?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(this._data!==null),this._data instanceof Pe?new Y(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Ne(this._data)?new Y(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(y(this._layout),new Y(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new Y(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(Ye?.unregister(this),this._data instanceof Pe?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ne(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Hr(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return Ne(this._data)?this._data.allocationSize(e):Lr(this,e).allocationSize}async copyTo(e,t={}){if(!pt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Hr(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(y(this._data!==null),Ne(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof Pe){const l={stack:[],error:void 0,hasError:!1};try{const u=js(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(u instanceof Y))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(u.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${u.format}' instead.`);return await u.copyTo(e,t)}catch(u){l.error=u,l.hasError=!0}finally{$s(l)}}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.");const l=this.toVideoFrame(),u=await l.copyTo(e,t);return l.close(),u}const i=Lr(this,t);y(this.format);const s=me(e);if(s.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${s.byteLength}`);const n=bt(this.format);let a;if(this._data instanceof Pe){let l=this._data.getDataPlanes();if(I(l)&&(l=await l),!Array.isArray(l)||l.some(u=>!(u.data instanceof Uint8Array)||!Number.isInteger(u.stride)||u.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=l}else if(this._data instanceof Uint8Array)y(this._layout),y(this._layout.length===n.length),a=this._layout.map((l,u)=>{const d=Math.ceil(this.codedHeight/n[u].heightDivisor);return{data:this._data.subarray(l.offset,l.offset+l.stride*d),stride:l.stride}});else{const u=this._data.getContext("2d");y(u);const d=u.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:me(d.data),stride:4*this.codedWidth}]}const o=[],c=n.length;for(let l=0;l<c;l++){const u=i.computedLayouts[l],d=a[l].stride,h=a[l].data;let m=u.sourceTop*d;m+=u.sourceLeftBytes;let p=u.destinationOffset;const b=u.sourceWidthBytes,w={offset:p,stride:u.destinationStride};for(let g=0;g<u.sourceHeight;g++){if(m+b>h.byteLength)throw new Error("Source buffer OOB read.");if(p+b>s.byteLength)throw new Error("Destination buffer OOB write.");const T=h.subarray(m,m+b);s.set(T,p),m+=d,p+=u.destinationStride}o.push(w)}if(t.format!==void 0){const l=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),u=this.format.includes("X")&&t.format.includes("A");if(l||u)for(let d=0;d<i.allocationSize;d+=4){if(l){const h=s[d],m=s[d+2];s[d]=m,s[d+2]=h}u&&(s[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(y(this._data!==null),this._data instanceof Pe){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(I(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((a,o)=>a+o.data.byteLength,0),i=new Uint8Array(t);let s=0;const n=[];for(const a of e)i.set(a.data,s),n.push(s),s+=a.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((a,o)=>({offset:n[o],stride:a.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 Ne(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(y(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(e,t,i,s,n,a,o,c,l){let u=0,d=0,h=this.displayWidth,m=this.displayHeight,p=0,b=0,w=this.displayWidth,g=this.displayHeight;if(a!==void 0?(u=t,d=i,h=s,m=n,p=a,b=o,c!==void 0?(w=c,g=l):(w=h,g=m)):(p=t,b=i,s!==void 0&&(w=s,g=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(u))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(m)||m<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(b))throw new TypeError("dy must be a number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:u,sy:d,sWidth:h,sHeight:m}=this._rotateSourceRegion(u,d,h,m,this.rotation));const T=this.toCanvasImageSource();e.save();const k=p+w/2,x=b+g/2;e.translate(k,x),e.rotate(this.rotation*Math.PI/180);const C=this.rotation%180===0?1:w/g;e.scale(1/C,C),e.drawImage(T,u,d,h,m,-w/2,-g/2,w,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Yt(t.crop,"options.");const i=e.canvas.width,s=e.canvas.height,n=t.rotation??this.rotation,[a,o]=n%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=t.crop;c&&(c=qr(c,a,o));let l,u,d,h;const{sx:m,sy:p,sWidth:b,sHeight:w}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,n);if(t.fit==="fill")l=0,u=0,d=i,h=s;else{const[T,k]=t.crop?[t.crop.width,t.crop.height]:[a,o],x=t.fit==="contain"?Math.min(i/T,s/k):Math.max(i/T,s/k);d=T*x,h=k*x,l=(i-d)/2,u=(s-h)/2}e.save();const g=n%180===0?1:d/h;e.translate(i/2,s/2),e.rotate(n*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-s/2),e.drawImage(this.toCanvasImageSource(),m,p,b,w,l,u,d,h),e.restore()}_rotateSourceRegion(e,t,i,s,n){return n===90?[e,t,i,s]=[t,this.squarePixelHeight-e-i,s,i]:n===180?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-s]:n===270&&([e,t,i,s]=[this.squarePixelWidth-t-s,e,s,i]),{sx:e,sy:t,sWidth:i,sHeight:s}}_drawWithFitAndMipmapping(e,t,i){const s=e.width,n=e.height,[a,o]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],c=i.crop?i.crop.width:a,l=i.crop?i.crop.height:o;let u=0;2*s<c&&2*n<l&&(u=Math.floor(Math.log2(Math.min(c/s,l/n))));const d=s*2**u,h=n*2**u,{canvas:m,context:p,isNew:b}=u>0?Ur(d,h):{canvas:e,context:t,isNew:i.targetIsFresh};p.imageSmoothingQuality="high",i.fillBlack?(p.fillStyle="black",p.fillRect(0,0,d,h)):b||p.clearRect(0,0,d,h),this.drawWithFit(p,{fit:i.fit,rotation:i.rotation,crop:i.crop}),p.globalCompositeOperation="copy";for(let w=u;w>1;w--){const g=s*2**w,T=n*2**w;p.drawImage(m,0,0,g,T,0,0,g/2,T/2)}p.globalCompositeOperation="source-over",u>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(m,0,0,2*s,2*n,0,0,s,n),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(y(this._data!==null),this._data instanceof Pe||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, 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.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&Yt(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=Zt(this.rotation+(e.rotate??0)),[i,s]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let n=e.crop;n&&(n=qr(n,i,s));const a=n?n.width:i,o=n?n.height:s,c=a/o;let l,u;e.width!==void 0&&e.height===void 0?(l=e.width,u=l/c):e.width===void 0&&e.height!==void 0?(u=e.height,l=u*c):e.width!==void 0&&e.height!==void 0?(l=e.width,u=e.height):(l=a,u=o),l=pr(l,e.roundDimensionsTo??1),u=pr(u,e.roundDimensionsTo??1);const d={width:l,height:u,fit:e.fit??"fill",rotation:t,crop:n??{left:0,top:0,width:i,height:s},alpha:e.alpha??"keep"};for(const b of Ks){let w=b(this,d);if(I(w)&&(w=await w),w!==null)return w}const{canvas:h,context:m,isNew:p}=Ur(d.width,d.height);return this._drawWithFitAndMipmapping(h,m,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:p,fillBlack:d.alpha==="discard"}),new Y(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||typeof e!="object")throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Ks=[],Qs=3,Ve=[];let Wr=0;const Ur=(r,e)=>{for(const s of Ve)if(s.canvas.width===r&&s.canvas.height===e)return s.age=Wr++,{canvas:s.canvas,context:s.context,isNew:!1};let t;if(typeof OffscreenCanvas<"u")t=new OffscreenCanvas(r,e);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().");t=document.createElement("canvas"),t.width=r,t.height=e}const i=t.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!i)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Ve.length>=Qs&&Ve.splice(hi(Ve,s=>s.age),1),Ve.push({canvas:t,context:i,age:Wr++}),{canvas:t,context:i,isNew:!0}};class At{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(Je);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(et);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const s=Object.keys(tt);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Ne=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,qr=(r,e,t)=>{const i=Math.min(r.left,e),s=Math.min(r.top,t),n=Math.min(r.width,e-i),a=Math.min(r.height,t-s);return y(n>=0),y(a>=0),{left:i,top:s,width:n,height:a}},Yt=(r,e)=>{if(!r||typeof r!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(r.left)||r.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(r.top)||r.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(r.width)||r.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(r.height)||r.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},Hr=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.colorSpace!==void 0&&!["display-p3","srgb"].includes(r.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(r.format!==void 0&&typeof r.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(r.layout!==void 0){if(!Array.isArray(r.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of r.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(r.rect!==void 0){if(!r.rect||typeof r.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(r.rect.x!==void 0&&(!Number.isInteger(r.rect.x)||r.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(r.rect.y!==void 0&&(!Number.isInteger(r.rect.y)||r.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(r.rect.width!==void 0&&(!Number.isInteger(r.rect.width)||r.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(r.rect.height!==void 0&&(!Number.isInteger(r.rect.height)||r.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Xs=(r,e,t)=>{const i=bt(r),s=[];let n=0;for(const a of i){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),l=o*a.sampleBytes,u=l*c;s.push({offset:n,stride:l}),n+=u}return s},bt=r=>{const e=(t,i,s,n,a)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:i,widthDivisor:s,heightDivisor:n},{sampleBytes:i,widthDivisor:s,heightDivisor:n}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(r){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(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:ge(r),y(!1)}},Lr=(r,e)=>{const t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=e.rect,s=Ys(t,i,r.codedWidth,r.codedHeight,r.format),n=e.layout;let a;if(!e.format||e.format===r.format)a=r.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return Js(s,a,n)},Ys=(r,e,t,i,s)=>{const n={...r};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>i)throw new TypeError("visibleRect exceeds codedHeight.");n.x=e.x||0,n.y=e.y||0,n.width=e.width||0,n.height=e.height||0}if(!Zs(s,n))throw new TypeError("visibleRect alignment is invalid for the format.");return n},Zs=(r,e)=>{if(r===null)return!0;const t=bt(r);for(let i=0;i<t.length;i++){const s=t[i],n=s.widthDivisor,a=s.heightDivisor;if((e.x||0)%n!==0||(e.y||0)%a!==0)return!1}return!0},Js=(r,e,t)=>{const i=bt(e),s=i.length;if(t!==void 0&&t.length!==s)throw new TypeError(`Layout must have ${s} planes.`);let n=0;const a=[],o=[];for(let c=0;c<s;c++){const l=i[c],u=l.sampleBytes,d=l.widthDivisor,h=l.heightDivisor,m={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(m.sourceTop=Math.ceil(Math.trunc(r.y||0)/h),m.sourceHeight=Math.ceil(Math.trunc(r.height||0)/h),m.sourceLeftBytes=Math.floor(Math.trunc(r.x||0)/d)*u,m.sourceWidthBytes=Math.floor(Math.trunc(r.width||0)/d)*u,t!==void 0){const w=t[c];if(w.stride<m.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);m.destinationOffset=w.offset,m.destinationStride=w.stride}else m.destinationOffset=n,m.destinationStride=m.sourceWidthBytes;const b=m.destinationStride*m.sourceHeight+m.destinationOffset;if(b>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(b),n=Math.max(n,b);for(let w=0;w<c;w++){const g=a[w];if(!(o[c]<=g.destinationOffset||o[w]<=m.destinationOffset))throw new TypeError("Planes overlap.")}a.push(m)}return{allocationSize:n,computedLayouts:a}},ct=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class We{constructor(){this._referenceCount=0}}class q{get microsecondTimestamp(){return Math.trunc(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*this.duration)}constructor(e){if(this._closed=!1,Ue(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof We){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!ct.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!ct.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(ke(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const s=this.numberOfFrames*this.numberOfChannels*ke(this.format);if(i.byteLength<s)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}Ye?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){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&&!ct.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.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(s>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const n=ke(t),a=ve(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?s:s*this.numberOfChannels)*n}copyTo(e,t){if(!pt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");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&&!ct.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.");const{format:i,frameCount:s,frameOffset:n}=t;let{planeIndex:a}=t,o=this.format;const c=i??this.format;if(!c)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=n??0;if(d>=l)throw new RangeError("frameOffset out of range");const h=s!==void 0?s:l-d;if(h>l-d)throw new RangeError("frameCount out of range");const m=ke(c),p=ve(c);if(p&&a>=u)throw new RangeError("planeIndex out of range");if(!p&&a!==0)throw new RangeError("planeIndex out of range");const w=(p?h:h*u)*m;if(e.byteLength<w)throw new RangeError("Destination buffer is too small");const g=O(e),T=Wi(c);if(Ue(this._data))if(wn()&&u>2&&c!==o){ta(this._data,g,o,c,u,a,d,h);return}else try{this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:h,format:c});return}catch(S){if(c==="f32-planar")throw S;o="f32-planar"}const k=Ni(o),x=ke(o),C=ve(o);let A;if(this._data instanceof We){const S=_=>{const E=this._data.getDataPlane(_);if(!(E instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const R=l*x*(C?1:u);if(E.byteLength!==R)throw new TypeError(`Data plane ${_} has invalid size. Expected exactly ${R} bytes, got ${E.byteLength} bytes.`);return E};if(C)if(p)A=S(a),a=0;else{A=new Uint8Array(l*x*u);for(let _=0;_<u;_++){const E=S(_);A.set(E,_*l*x)}}else A=S(0)}else if(this._data instanceof Uint8Array)A=this._data;else if(y(o==="f32-planar"),p)A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:a})),this._data.copyTo(A,{format:"f32-planar",planeIndex:a}),a=0;else{A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*u);for(let S=0;S<u;S++)this._data.copyTo(A.subarray(S*l*x,(S+1)*l*x),{format:"f32-planar",planeIndex:S})}const v=O(A);for(let S=0;S<h;S++)if(p){const _=S*m;let E;C?E=(a*l+(S+d))*x:E=((S+d)*u+a)*x;const R=k(v,E);T(g,_,R)}else for(let _=0;_<u;_++){const R=(S*u+_)*m;let B;C?B=(_*l+(S+d))*x:B=((S+d)*u+_)*x;const z=k(v,B);T(g,R,z)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof We){const e=new q(this._data);return e.setTimestamp(this.timestamp),e}else if(Ue(this._data)){const e=new q(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new q({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startFrame must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endFrame must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t<e)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");const i=t-e,s=ke(this.format);let n;if(ve(this.format)){const a=i*s;if(n=new Uint8Array(a*this.numberOfChannels),i>0)for(let o=0;o<this.numberOfChannels;o++)this.copyTo(n.subarray(o*a,(o+1)*a),{planeIndex:o,format:this.format,frameOffset:e,frameCount:i})}else n=new Uint8Array(i*this.numberOfChannels*s),i>0&&this.copyTo(n,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new q({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(Ye?.unregister(this),this._data instanceof We?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Ue(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 We?this._createAudioDataFromData():Ue(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(ve(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(i/s);let c=0,l=a;for(;l>0;){const u=Math.min(o,l),d=new Float32Array(s*u);for(let h=0;h<s;h++)e.copyFromChannel(d.subarray(h*u,(h+1)*u),h,c);yield new q({format:"f32-planar",sampleRate:n,numberOfFrames:u,numberOfChannels:s,timestamp:t+c/n,data:d}),c+=u,l-=u}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(i/s);let c=0,l=a;const u=[];for(;l>0;){const d=Math.min(o,l),h=new Float32Array(s*d);for(let p=0;p<s;p++)e.copyFromChannel(h.subarray(p*d,(p+1)*d),p,c);const m=new q({format:"f32-planar",sampleRate:n,numberOfFrames:d,numberOfChannels:s,timestamp:t+c/n,data:h});u.push(m),c+=d,l-=d}return u}}const ke=r=>{switch(r){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")}},ve=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Ni=r=>{switch(r){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Wi=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,N((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,N(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,N(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Ue=r=>typeof AudioData<"u"&&r instanceof AudioData,ea=r=>{switch(r){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return r}},ta=(r,e,t,i,s,n,a,o)=>{const c=Ni(t),l=Wi(i),u=ke(t),d=ke(i),h=ve(t);if(ve(i))if(h){const p=new ArrayBuffer(o*u),b=O(p);r.copyTo(p,{planeIndex:n,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const g=w*u,T=w*d,k=c(b,g);l(e,T,k)}}else{const p=new ArrayBuffer(o*s*u),b=O(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const g=(w*s+n)*u,T=w*d,k=c(b,g);l(e,T,k)}}else if(h){const p=o*u,b=new ArrayBuffer(p),w=O(b);for(let g=0;g<s;g++){r.copyTo(b,{planeIndex:g,frameOffset:a,frameCount:o,format:t});for(let T=0;T<o;T++){const k=T*u,x=(T*s+g)*d,C=c(w,k);l(e,x,C)}}}else{const p=new ArrayBuffer(o*s*u),b=O(p);r.copyTo(p,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++)for(let g=0;g<s;g++){const T=w*s+g,k=T*u,x=T*d,C=c(b,k);l(e,x,C)}}},ra=(r,e)=>{const t=r.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return r.copyTo(i,{format:e,planeIndex:0}),new q({data:i,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};/*!
98
+ * Copyright (c) 2026-present, Vanilagy and contributors
99
+ *
100
+ * This Source Code Form is subject to the terms of the Mozilla Public
101
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
102
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
103
+ */const jr=new Map,$r=new Map,ia=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Ce.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${Ce.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0)throw new TypeError("config.quality must be provided.");if(r.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(r.quality!==void 0&&!(r.quality instanceof ee))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof ee)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.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(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(r.transform.crop!==void 0&&Yt(r.transform.crop,"config.transform."),r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(r.transform.frameRate!==void 0&&(!Number.isFinite(r.transform.frameRate)||r.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(r.transform.force!==void 0&&typeof r.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Ui(r.codec,r)},Ui=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&yt(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},qi=r=>{const e=r.bitrateMode,t=r.quality._toVideoRateControl(r.codec,r.width,r.height,e),i=(n,a,o)=>({codec:r.fullCodecString??cs(r.codec,r.width,r.height,o,r.alpha==="keep"),width:r.width,height:r.height,displayWidth:r.squarePixelWidth,displayHeight:r.squarePixelHeight,bitrate:n,bitrateMode:a,alpha:r.alpha??"discard",framerate:r.framerate,latencyMode:r.latencyMode,hardwareAcceleration:r.hardwareAcceleration,scalabilityMode:r.scalabilityMode,contentHint:r.contentHint,...ps(r.codec)}),s=[];return t.quantizer!==null&&s.push({config:i(void 0,"quantizer",t.bitrate),quantizer:t.quantizer}),t.bitrateMode!=="quantizer"&&s.push({config:i(t.bitrate,t.bitrateMode,t.bitrate),quantizer:null}),y(s.length>0),s},Hi=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!Re.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${Re.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0&&!(X.includes(r.codec)||r.codec==="flac"))throw new TypeError("config.quality must be provided for compressed audio codecs.");if(r.quality!==void 0&&e!==void 0)throw new TypeError("config.quality and config.bitrate cannot both be provided.");if(r.quality!==void 0&&!(r.quality instanceof ee))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof ee)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Li(r.codec,r)},Li=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");const t=e.bitrateMode;if(t!==void 0&&!["constant","variable"].includes(t))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&yt(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},ji=r=>{const e=r.bitrateMode;return{codec:r.fullCodecString??fs(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:r.quality?._toAudioBitrate(r.codec),bitrateMode:r.quality?._bitrateMode??e,...gs(r.codec)}};class ee{constructor(e){if((typeof e=="number"||typeof e=="string")&&(e={quality:e}),!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in e){if(typeof e.quality=="string"?!(e.quality in Gr):typeof e.quality!="number"||Number.isNaN(e.quality))throw new TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(e.preferBitrate!==void 0&&typeof e.preferBitrate!="boolean")throw new TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in e||"quantizer"in e)throw new TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality=typeof e.quality=="string"?Gr[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(e.bitrate!==void 0&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("options.bitrate, when provided, must be a positive integer.");if(e.quantizer!==void 0&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw new TypeError("options.quantizer, when provided, must be a non-negative integer.");if(e.bitrate===void 0&&e.quantizer===void 0)throw new TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in e)throw new TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,t,i,s){const n=na[e];let a=null,o=this._bitrateMode??s??"variable";if(this._quantizer!==void 0){if(n)if(this._quantizer<n.min||this._quantizer>n.max){if(this._bitrate===void 0)throw new Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${n.min} and ${n.max}.`)}else a=this._quantizer,this._bitrate===void 0&&(o="quantizer");else if(this._bitrate===void 0)throw new Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else this._bitrate===void 0&&n&&!this._preferBitrate&&(y(this._quality!==void 0),a=N(Math.round(fn(n.worst,n.best,this._quality)),n.min,n.max));let c;if(this._bitrate!==void 0)c=this._bitrate;else{let l=this._quality;l===void 0&&(y(a!==null&&n),l=N((a-n.worst)/(n.best-n.worst),0,1)),c=Kr(e,t,i,Rt(l))}return{quantizer:a,bitrate:c,bitrateMode:o}}_toVideoBitrate(e,t,i){return this._bitrate!==void 0?this._bitrate:(y(this._quality!==void 0),Kr(e,t,i,Rt(this._quality)))}_toAudioBitrate(e){if(X.includes(e)||e==="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.");const t=Rt(this._quality),s={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!s)throw new Error(`Unhandled codec: ${e}`);let n=s*t;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((o,c)=>Math.abs(c-n)<Math.abs(o-n)?c:o):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,c)=>Math.abs(c-n)<Math.abs(o-n)?c:o)),Math.round(n/1e3)*1e3}}const Gr={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},na={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:{min:0,max:63,worst:52,best:20},av1:{min:0,max:255,worst:208,best:80}},Rt=r=>.3*Math.exp(2.5538*r),Kr=(r,e,t,i)=>{const s=e*t,n=1920*1080,a=3e6,o=Math.pow(s/n,.95),c=a*o,l={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:22e7/a},d=c*l[r]*i;return Math.ceil(d/1e3)*1e3},$i=(r,e)=>{if(r==="avc")return{avc:{quantizer:e}};if(r==="hevc")return{hevc:{quantizer:e}};if(r==="vp9")return{vp9:{quantizer:e}};if(r==="av1")return{av1:{quantizer:e}};y(!1)},Wa=async(r,e={})=>{const{width:t=1280,height:i=720,quality:s,bitrate:n,...a}=e;if(!Ce.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(s!==void 0&&!(s instanceof ee))throw new TypeError("quality, when provided, must be a Quality.");if(s!==void 0&&n!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(n!==void 0&&!(n instanceof ee)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer or a quality.");Ui(r,a);const o=kt(s,n)??new ee("medium");let c;try{c=qi({codec:r,width:t,height:i,quality:o,framerate:void 0,...a,alpha:"discard"})}catch{return!1}const l=JSON.stringify(c),u=jr.get(l);if(u)return u;const d=(async()=>{for(const{config:h}of c)if(Ki.some(m=>m.supports(r,h)))return!0;if(typeof VideoEncoder>"u")return!1;for(const{config:h,quantizer:m}of c){try{if(!(await VideoEncoder.isConfigSupported(h)).supported)continue}catch{continue}if(!di()||await new Promise(async b=>{try{const w=new VideoEncoder({output:()=>{},error:()=>b(!1)});w.configure(h);const g=new Uint8Array(t*i*4),T=new VideoFrame(g,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});w.encode(T,m!==null?$i(r,m):void 0),T.close(),await w.flush(),b(!0)}catch{b(!1)}}))return!0}return!1})();return jr.set(l,d),d},Ua=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,quality:s,bitrate:n,...a}=e;if(!Re.includes(r))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(s!==void 0&&!(s instanceof ee))throw new TypeError("quality, when provided, must be a Quality.");if(s!==void 0&&n!==void 0)throw new TypeError("quality and bitrate cannot both be provided.");if(n!==void 0&&!(n instanceof ee)&&(!Number.isInteger(n)||n<=0))throw new TypeError("bitrate must be a positive integer.");Li(r,a);const o=kt(s,n)??new ee("medium"),c=ji({codec:r,numberOfChannels:t,sampleRate:i,quality:o,...a}),l=JSON.stringify(c),u=$r.get(l);if(u)return u;const d=(async()=>{if(Qi.some(h=>h.supports(r,c))||X.includes(r))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return $r.set(l,d),d},kt=(r,e)=>{if(r!==void 0)return r;if(e!==void 0)return e instanceof ee?e:new ee({bitrate:e})};/*!
104
+ * Copyright (c) 2026-present, Vanilagy and contributors
105
+ *
106
+ * This Source Code Form is subject to the terms of the Mozilla Public
107
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
108
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
109
+ */const sa=[],Gi=[],Ki=[],Qi=[];/*!
110
+ * Copyright (c) 2026-present, Vanilagy and contributors
111
+ *
112
+ * This Source Code Form is subject to the terms of the Mozilla Public
113
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
114
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
115
+ */const aa=r=>{let i=r,s=4096,n=0,a=12,o=0;for(i<0&&(i=-i,n=128),i+=33,i>8191&&(i=8191);(i&s)!==s&&a>=5;)s>>=1,a--;return o=i>>a-4&15,~(n|a-5<<4|o)&255},oa=r=>{let t=0,i=0,s=~r;s&128&&(s&=-129,t=-1),i=((s&240)>>4)+5;const n=(1<<i|(s&15)<<i-4|1<<i-5)-33;return t===0?n:-n},ca=r=>{let t=2048,i=0,s=11,n=0,a=r;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&s>=5;)t>>=1,s--;return n=a>>(s===4?1:s-4)&15,(i|s-4<<4|n)^85},la=r=>{let e=0,t=0,i=r^85;i&128&&(i&=-129,e=-1),t=((i&240)>>4)+4;let s=0;return t!==4?s=1<<t|(i&15)<<t-4|1<<t-5:s=i<<1|1,e===0?s:-s};/*!
116
+ * Copyright (c) 2026-present, Vanilagy and contributors
117
+ *
118
+ * This Source Code Form is subject to the terms of the Mozilla Public
119
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
120
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
121
+ */const xe=r=>{if(!r||typeof r!="object")throw new TypeError("options must be an object.");if(r.metadataOnly!==void 0&&typeof r.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(r.verifyKeyPackets!==void 0&&typeof r.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(r.verifyKeyPackets&&r.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(r.skipLiveWait!==void 0&&typeof r.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Me=r=>{if(!rt(r))throw new TypeError("timestamp must be a number.")},It=(r,e,t)=>t.verifyKeyPackets?e.then(async i=>{if(!i||i.type==="delta")return i;const s=await r.determinePacketType(i);return s&&(i.type=s),i}):e;class lr{constructor(e){if(!(e instanceof nt))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(xe(e),this._track.input._disposed)throw new $;return It(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){xe(e);const t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Me(e),xe(t),this._track.input._disposed)throw new $;return It(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");if(xe(t),this._track.input._disposed)throw new $;return It(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Me(e),xe(t),this._track.input._disposed)throw new $;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);return i&&(y(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i)}async getNextKeyPacket(e,t={}){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");if(xe(t),this._track.input._disposed)throw new $;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);return i&&(y(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,t):i)}packets(e,t,i={}){if(e!==void 0&&!(e instanceof H))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof H))throw new TypeError("endPacket must be an EncodedPacket.");if(xe(i),this._track.input._disposed)throw new $;const s=[];let{promise:n,resolve:a}=j(),{promise:o,resolve:c}=j(),l=!1,u=!1,d=null,h=!1;const m=[],p=()=>Math.max(2,m.length);(async()=>{let w=e??await this.getFirstPacket(i);for(;w&&!u&&!this._track.input._disposed&&!(t&&w.sequenceNumber>=t?.sequenceNumber);){if(s.length>p()){({promise:o,resolve:c}=j()),await o;continue}s.push(w),a(),{promise:n,resolve:a}=j(),w=await this.getNextPacket(w,i)}l=!0,a()})().catch(w=>{h||(d=w,h=!0,a())});const b=this._track;return{async next(){for(;;){if(b.input._disposed)throw new $;if(u)return{value:void 0,done:!0};if(h)throw d;if(s.length>0){const w=s.shift(),g=performance.now();for(m.push(g);m.length>0&&g-m[0]>=1e3;)m.shift();return c(),{value:w,done:!1}}else{if(l)return{value:void 0,done:!0};await n}}},async return(){return u=!0,c(),a(),{value:void 0,done:!0}},async throw(w){throw w},[Symbol.asyncIterator](){return this}}}}class Xi{constructor(e,t){this.onSample=e,this.onError=t}}class ua{mediaSamplesInRange(e=-1/0,t=1/0,i){Me(e),Me(t);const s=[];let n=!1,a=null,{promise:o,resolve:c}=j(),{promise:l,resolve:u}=j(),d=!1,h=!1,m=!1,p=null,b=null,w=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{p=await this._createDecoder(_=>{if(u(),_.timestamp>=t&&(h=!0),h){_.close();return}a&&(_.timestamp>e?(s.push(a),n=!0):a.close()),_.timestamp>=e&&(s.push(_),n=!0),a=n?null:_,s.length>0&&(c(),{promise:o,resolve:c}=j())},_=>{w||(b=_,w=!0,c())});const x=this._createPacketSink(),C=await x.getKeyPacket(e,g)??await x.getFirstKeyPacket(g);let A=C;const S=x.packets(C??void 0,void 0,g);for(await S.next();A&&!h&&!this._track.input._disposed;){const _=Qr(s.length);if(s.length+p.getDecodeQueueSize()>_){({promise:l,resolve:u}=j()),await l;continue}p.decode(A);const E=await S.next();if(E.done)break;A=E.value}await S.return(),!m&&!this._track.input._disposed&&await p.flush(),!n&&a&&s.push(a),d=!0,c()})().catch(x=>{w||(b=x,w=!0,c())}).finally(()=>{p?.close()});const T=this._track,k=()=>{a?.close();for(const x of s)x.close()};return{async next(){for(;;){if(T.input._disposed)throw m=!0,h=!0,k(),new $;if(m)return{value:void 0,done:!0};if(w)throw m=!0,h=!0,k(),b;if(s.length>0){const x=s.shift();return u(),{value:x,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return m=!0,h=!0,u(),c(),k(),{value:void 0,done:!0}},async throw(x){throw x},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){un(e);const i=ln(e),s=[],n=[];let{promise:a,resolve:o}=j(),{promise:c,resolve:l}=j(),u=!1,d=!1,h=null,m=null,p=!1;const b=k=>{n.push(k),o(),{promise:a,resolve:o}=j()},w={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(_=>{if(l(),d){_.close();return}let E=0;for(;s.length>0&&_.timestamp-s[0]>-1e-10;)E++,s.shift();if(E>0)for(let R=0;R<E;R++)b(R<E-1?_.clone():_);else _.close()},_=>{p||(m=_,p=!0,o())});const k=this._createPacketSink();let x=null,C=null,A=-1;const v=async()=>{y(C),y(h);let _=C;for(h.decode(_);_.sequenceNumber<A;){const E=Qr(n.length);for(;n.length+h.getDecodeQueueSize()>E&&!d;)({promise:c,resolve:l}=j()),await c;if(d)break;const R=await k.getNextPacket(_,w);y(R),h.decode(R),_=R}A=-1},S=async()=>{y(h),await h.flush();for(let _=0;_<s.length;_++)b(null);s.length=0};for await(const _ of i){if(Me(_),d||this._track.input._disposed)break;const E=await k.getPacket(_,w),R=E&&await k.getKeyPacket(_,w);if(!R){A!==-1&&(await v(),await S()),b(null),x=null;continue}x&&(R.sequenceNumber!==C.sequenceNumber||E.timestamp<x.timestamp)&&(await v(),await S()),s.push(E.timestamp),A=Math.max(E.sequenceNumber,A),x=E,C=R}!d&&!this._track.input._disposed&&(A!==-1&&await v(),await S()),u=!0,o()})().catch(k=>{p||(m=k,p=!0,o())}).finally(()=>{h?.close()});const g=this._track,T=()=>{for(const k of n)k?.close()};return{async next(){for(;;){if(g.input._disposed)throw d=!0,T(),new $;if(d)return{value:void 0,done:!0};if(p)throw d=!0,T(),m;if(n.length>0){const k=n.shift();return y(k!==void 0),l(),{value:k,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),T(),{value:void 0,done:!0}},async throw(k){throw k},[Symbol.asyncIterator](){return this}}}}const Qr=r=>r===0?40:8;class da extends Xi{constructor(e,t,i,s){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new tr,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=o=>{let c=o.timestamp;this.expectedFirstTimestamp!==null&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-c),c+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(c-this.currentTimestamp)>=o.duration)&&(this.currentTimestamp=c);const l=this.currentTimestamp;if(this.currentTimestamp+=o.duration,o.numberOfFrames===0){o.close();return}const u=s.sampleRate;o.setTimestamp(Math.round(l*u)/u),e(o)},a=Gi.find(o=>o.supports(i,s));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=s,this.customDecoder.onSample=o=>{if(!(o instanceof q))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(o)},this.customDecoder.onError=o=>{t(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(o=>t(o));else{const o=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{n(new q(c))}catch(l){this.onError(l)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(s)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>this.customDecoderQueueSize--)):(y(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}}class ha extends Xi{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,y(X.includes(i.codec)),this.codec=i.codec;const{dataType:s,sampleSize:n,littleEndian:a}=ar(this.codec);switch(this.inputSampleSize=n,n){case 1:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:s==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):s==="ulaw"?this.readInputValue=(o,c)=>oa(o.getUint8(c)):s==="alaw"?this.readInputValue=(o,c)=>la(o.getUint8(c)):y(!1);break;case 2:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:s==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):y(!1);break;case 3:s==="unsigned"?this.readInputValue=(o,c)=>er(o,c,a)-2**23:s==="signed"?this.readInputValue=(o,c)=>dn(o,c,a):y(!1);break;case 4:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:s==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):s==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):y(!1);break;case 8:s==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):y(!1);break;default:ge(n),y(!1)}switch(n){case 1:s==="ulaw"||s==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,l)=>o.setUint8(c,l+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,l)=>o.setInt16(c,l,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l<<8,!0);break;case 4:this.outputSampleSize=4,s==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,l)=>o.setInt32(c,l,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,l)=>o.setFloat32(c,l,!0);break;default:ge(n),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=O(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,s=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(s),a=new DataView(n);for(let u=0;u<i*this.decoderConfig.numberOfChannels;u++){const d=u*this.inputSampleSize,h=u*this.outputSampleSize,m=this.readInputValue(t,d);this.writeOutputValue(a,h,m)}const o=i/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);const c=this.currentTimestamp;this.currentTimestamp+=o;const l=new q({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}}class qa extends ua{constructor(e){if(!(e instanceof ur))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof AudioDecoder>"u"?new Error(rr("AudioDecoder")):new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.");const i=await this._track.getCodec(),s=await this._track.getDecoderConfig();return y(i&&s),X.includes(s.codec)?new ha(e,t,s):new da(e,t,i,s)}_createPacketSink(){return new lr(this._track)}async getSample(e,t={}){Me(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}/*!
122
+ * Copyright (c) 2026-present, Vanilagy and contributors
123
+ *
124
+ * This Source Code Form is subject to the terms of the Mozilla Public
125
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
126
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
127
+ */class nt{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Yi}isAudioTrack(){return this instanceof ur}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return M(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return M(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return M(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return M(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return M(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(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),i=(t?.timestamp??0)+(t?.duration??0);return Ge(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new lr(this);let s=1/0,n=-1/0,a=0,o=0;for await(const c of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=n)break;s=Math.min(s,c.timestamp),n=Math.max(n,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(n-s)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(n-s)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof nt))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Ae({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Ae({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Ae({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Ae({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Ae({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Ft(e);const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Ft(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Ft(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const M=(r,e,t)=>{if(I(r))throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},Ft=r=>{if(r!==void 0&&typeof r!="function")throw new TypeError("predicate, when provided, must be a function.");return r?e=>{const t=s=>{if(typeof s!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return s},i=r(e);return I(i)?i.then(t):t(i)}:void 0};class Yi extends nt{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return M(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 M(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return M(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return M(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return M(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return M(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Ke({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Ke({num:M(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*M(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:M(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*M(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){const e=await this._backing.getMetadataDisplayWidth?.();return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){const s=M(e,"displayWidth","getDisplayWidth");if(s!==null)return s}const i=M(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return M(i,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await this._backing.getMetadataDisplayHeight?.();return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){const s=M(e,"displayHeight","getDisplayHeight");if(s!==null)return s}const i=M(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return M(i,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const 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(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return y(t!==null),sa.some(s=>s.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return D._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(t===null)return null;const i=await this.getDecoderConfig();return y(i),Ti(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.targetPacketCount!==void 0&&(!rt(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,s=new lr(this),n=[];let a=-1/0,o=0;for await(const E of s.packets(void 0,void 0,{metadataOnly:!0})){if(n.length>=i&&E.timestamp>=a)break;n.push(E.timestamp),a=Math.max(a,E.timestamp),o++}const c=new Float64Array(n.length);for(let E=0;E<n.length;E++)c[E]=Math.round(n[E]*t);c.sort();let l=1;for(let E=1;E<c.length;E++)c[E]!==c[l-1]&&(c[l++]=c[E]);if(l<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:o};const u=c.subarray(0,l),d=fa(u,t),h=d??t,m=d!==null?t/d:null,p=new Map;let b=1/0,w=-1/0,g=0;for(let E=1;E<l;E++){const R=u[E]-u[E-1],B=m!==null?Math.max(1,Math.round(R/m)):R;p.set(B,(p.get(B)??0)+1),b=Math.min(b,B),w=Math.max(w,B),g+=B}const T=l-1,k=[...p.keys()].sort((E,R)=>E-R),x=T-1>>1,C=T>>1;let A=0,v=0,S=0;for(const E of k)if(S+=p.get(E),A===0&&S>x&&(A=E),S>C){v=E;break}const _=(h/A+h/v)/2;return{underlyingFrameRate:d,bestGuessFrameRate:d!==null?d:ma(_),minFrameRate:h/w,maxFrameRate:h/b,averageFrameRate:h*T/g,medianFrameRate:_,frameRateIsConstant:d!==null&&b===1&&w===1,probedPacketCount:o}}}class ur extends nt{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return M(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return M(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return M(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getMetadataCodecParameterString?.();return e??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return y(t!==null),Gi.some(i=>i.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return D._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof H))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const Xr=r=>-(r??-1/0),qe=r=>-r,He=r=>{if(typeof r!="object"||!r)throw new TypeError("query must be an object.");if(r.filter!==void 0&&typeof r.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(r.sortBy!==void 0&&typeof r.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:r.filter?e=>{const t=s=>{if(typeof s!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return s},i=r.filter(e);return I(i)?i.then(t):t(i)}:void 0,sortBy:r.sortBy?e=>{const t=s=>{if(typeof s!="number"&&(!Array.isArray(s)||!s.every(n=>typeof n=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return s},i=r.sortBy(e);return I(i)?i.then(t):t(i)}:void 0}},Ae=(r,e)=>({filter:r?.filter||e?.filter?t=>{const i=r?.filter?.(t)??!0,s=n=>n===!1?!1:e?.filter?.(t)??!0;return I(i)?i.then(s):s(i)}:void 0,sortBy:r?.sortBy||e?.sortBy?t=>{const i=r?.sortBy?.(t)??[],s=e?.sortBy?.(t)??[],n=(a,o)=>[...Array.isArray(a)?a:[a],...Array.isArray(o)?o:[o]];return I(i)||I(s)?Promise.all([i,s]).then(([a,o])=>n(a,o)):n(i,s)}:void 0}),Bt=async(r,e)=>{let t=r;if(e?.filter){const a=r.map(c=>e.filter(c));if(a.some(c=>I(c))){const c=await Promise.all(a);t=r.filter((l,u)=>c[u])}else t=r.filter((c,l)=>a[l])}if(!e?.sortBy)return t;const i=t.map(a=>e.sortBy(a)),n=i.some(a=>I(a))?await Promise.all(i):i;return t.map((a,o)=>({track:a,sortValue:n[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],l=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],u=Math.max(c.length,l.length);for(let d=0;d<u;d++){const h=c[d]??0,m=l[d]??0;if(h!==m)return h-m}return 0}).map(a=>a.track)},fa=(r,e)=>{const s=1.000000001,n=1e3,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(r.length<2)return null;const o=new Float64Array(r.length-1);for(let v=1;v<r.length;v++){const S=r[v]-r[v-1];if(!(S>0))return null;o[v-1]=S}const c=o.slice();c.sort();let l=c[Math.floor(c.length*.05)];for(let v=0;v<6;v++){let S=0,_=0;for(const R of o){const B=Math.max(1,Math.round(R/l));Math.abs(R-B*l)>=s||(S+=R,_+=B)}if(_===0)return null;const E=S/_;if(Math.abs(E-l)<=1e-12*Math.max(1,l)){l=E;break}l=E}let u=0,d=0,h=0;for(const v of o){const S=Math.max(1,Math.round(v/l));Math.abs(v-S*l)>=s||(u++,d+=v,h+=S)}if(u/o.length<.98)return null;l=d/h;const m=1/Math.min(h,n),p=Math.max(Number.EPSILON,l-m),b=l+m,w=e/b,g=e/p,T=e/l;let k=null,x=1/0;for(const v of a){if(v<w||v>g)continue;const S=Math.abs(v/T-1);S<x&&(k=v,x=S)}if(k===null){const v=Yr(p,b,1e6),S=Yr(w,g,1e6);if(S&&(!v||S.den<v.den||S.den===v.den&&S.num<=v.num))k=S.num/S.den;else if(v)k=e*v.den/v.num;else return null}const C=e/k;let A=0;for(const v of o){const S=Math.max(1,Math.round(v/C));Math.abs(v-S*C)<s&&A++}return A/o.length<.98?null:k},Yr=(r,e,t)=>{for(let i=1;i<=t;i++){const s=Math.floor(r*i)+1;if(s/i<e)return Ke({num:s,den:i})}return null},ma=r=>{const e=[23.976023976023978,29.970029970029973,59.940059940059946,119.88011988011989],t=[12,15,20,24,25,30,48,50,60,100,120,144,240],i=5e-4,s=.025;for(const o of e)if(Math.abs(o/r-1)<=i)return o;let n=r,a=1/0;for(const o of t){const c=Math.abs(o/r-1);c<=s&&c<a&&(n=o,a=c)}return n};/*!
128
+ * Copyright (c) 2026-present, Vanilagy and contributors
129
+ *
130
+ * This Source Code Form is subject to the terms of the Mozilla Public
131
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
132
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
133
+ */ir();const pa=1;class Zi extends it{get disposed(){return this._disposed}constructor(e){if(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,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof Vi)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof _e||e.source instanceof cr))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof _e&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Zi))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&Ls(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof _e?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){y(this._rootSource instanceof Mi);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=pa){const i=this._sourceCache.find(a=>a.cacheGroup===t&&Mr(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const s=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Mr(a.request,e));if(s)return s.promise.then(a=>a.sourceRef.source.ref());const n=(async()=>{const a=await this._getSourceUncached(e);if(_n(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=hi(this._sourceCache,m=>m.cacheGroup===t&&m.sourceRef.source._refCount===1?m.age:1/0);y(d!==-1);const h=this._sourceCache[d];this._sourceCache.splice(d,1),h.sourceRef.free(),on(this._sourceRefs,h.sourceRef)}this._sourceRefs.push(a);const l=this._sourceCachePromises.findIndex(d=>d.request===e);return y(l!==-1),this._sourceCachePromises.splice(l,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new ga(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new Zr})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),y(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Zr)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();const t=e.filter(n=>n!==null);if(t.length===0)return 0;const i=await Promise.all(t.map(n=>n._backing.getFirstPacket({metadataOnly:!0}))),s=Math.min(...i.map(n=>n?.timestamp??1/0));return s===1/0?0:s}async computeDuration(e,t){e??=await this.getTracks();const i=e.filter(n=>n!==null);if(i.length===0)return 0;const s=await Promise.all(i.map(n=>n.computeDuration(t)));return Math.max(...s)}async getDurationFromMetadata(e,t){e??=await this.getTracks();const i=e.filter(a=>a!==null),n=(await Promise.all(i.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return n.length===0?null:Math.max(...n)}async getTracks(e){e&&=He(e);const i=(await this._getTrackBackings()).map(s=>this._wrapBackingAsTrack(s));return Bt(i,e)}async getVideoTracks(e){e&&=He(e);const i=(await this.getTracks()).filter(s=>s.isVideoTrack());return Bt(i,e)}async getAudioTracks(e){e&&=He(e);const i=(await this.getTracks()).filter(s=>s.isAudioTrack());return Bt(i,e)}async getPrimaryVideoTrack(e){e&&=He(e);const t=Ae(e,{sortBy:async s=>[qe((await s.getDisposition()).default),qe(await s.hasPairableAudioTrack()),qe(!await s.hasOnlyKeyPackets()),Xr(await s.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=He(e);const t=await this.getPrimaryVideoTrack(),i=Ae(e,{sortBy:async n=>[qe(!t||n.canBePairedWith(t)),qe((await n.getDisposition()).default),Xr(await n.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const s=e.getType()==="video"?new Yi(this,e):new ur(this,e);return this._backingToTrack.set(e,s),s}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class Zr extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class $ extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}/*!
134
+ * Copyright (c) 2026-present, Vanilagy and contributors
135
+ *
136
+ * This Source Code Form is subject to the terms of the Mozilla Public
137
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
138
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
139
+ */class ga{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new $;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const n=new Uint8Array(0);return new oe(n,O(n),0,e,e)}const i=e+t,s=this.source._read(e,i,Di,Oi);return I(s)?s.then(n=>n?new oe(n.bytes,n.view,n.offset,e,i):null):s?new oe(s.bytes,s.view,s.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new $;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,N(this.fileSizeNonStrict-e,t,i));{const s=this.requestSlice(e,i),n=a=>a||(y(this.fileSizeNonStrict!==null),this.requestSlice(e,N(this.fileSizeNonStrict-e,t,i)));return I(s)?s.then(n):n(s)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let i=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let a=this.requestSliceRange(i,0,e);if(I(a)&&(a=await a),!a||a.length===0)break;const o=Z(a,a.length);t.push(o),i+=a.length}const s=new Uint8Array(i);let n=0;for(const a of t)s.set(a,n),n+=a.length;return new oe(s,O(s),0,0,i)})()}}class oe{constructor(e,t,i,s,n){this.bytes=e,this.view=t,this.offset=i,this.start=s,this.end=n,this.bufferPos=s-i}static tempFromBytes(e){return new oe(e,O(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new oe(this.bytes,this.view,this.offset,e,e+t)}}const st=(r,e)=>{if(r.filePos<r.start||r.filePos+e>r.end)throw new RangeError(`Tried reading [${r.filePos}, ${r.filePos+e}), but slice is [${r.start}, ${r.end}). This is likely an internal error, please report it alongside the file that caused it.`)},Z=(r,e)=>{st(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},ce=r=>(st(r,1),r.view.getUint8(r.bufferPos++)),Jr=r=>{st(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},wa=r=>{st(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},ya=r=>{st(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e};/*!
140
+ * Copyright (c) 2026-present, Vanilagy and contributors
141
+ *
142
+ * This Source Code Form is subject to the terms of the Mozilla Public
143
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
144
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
145
+ */class ba{constructor(e){this.mutex=new ci,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){let s=this.trackTimestampInfo.get(e);if(s){if(i&&(s.maxTimestampBeforeLastKeyPacket=s.maxTimestamp),s.maxTimestampBeforeLastKeyPacket!==null&&t<s.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 ${t}s, but largest timestamp is ${s.maxTimestampBeforeLastKeyPacket}s.`);s.maxTimestamp=Math.max(s.maxTimestamp,t)}else{if(!i)throw new Error("First packet must be a key packet.");s={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,s)}}}/*!
146
+ * Copyright (c) 2026-present, Vanilagy and contributors
147
+ *
148
+ * This Source Code Form is subject to the terms of the Mozilla Public
149
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
150
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
151
+ */const ei=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ka=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Ta=r=>{const e=ka.exec(r);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},Sa=r=>{const e=Math.floor(r/36e5),t=Math.floor(r%(3600*1e3)/(60*1e3)),i=Math.floor(r%(60*1e3)/1e3),s=r%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};/*!
152
+ * Copyright (c) 2026-present, Vanilagy and contributors
153
+ *
154
+ * This Source Code Form is subject to the terms of the Mozilla Public
155
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
156
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
157
+ */class _a{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){y(!this.started),this.target._start(),this.started=!0}write(e){y(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return y(this.started&&!this.finalized),this.target._flush()}async finalize(){y(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const i=t+e.byteLength-this.trackedStart;let s=this.trackedWrites.byteLength;for(;s<i;)s*=2;if(s!==this.trackedWrites.byteLength){const n=new Uint8Array(s);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.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.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}/*!
158
+ * Copyright (c) 2026-present, Vanilagy and contributors
159
+ *
160
+ * This Source Code Form is subject to the terms of the Mozilla Public
161
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
162
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
163
+ */class ue extends it{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new Ca(this,e)}}const Dt=2**16,Ot=2**32;class Ha extends ue{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!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(Dt,{maxByteLength:Ot})}catch{this._buffer=new ArrayBuffer(Dt),this._supportsResize=!1}else this._buffer=new ArrayBuffer(Dt);this._bytes=new Uint8Array(this._buffer)}_ensureSize(e){let t=this._buffer.byteLength;for(;t<e;)t*=2;if(t!==this._buffer.byteLength){if(t>Ot)throw new Error(`ArrayBuffer exceeded maximum size of ${Ot} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const i=new ArrayBuffer(t),s=new Uint8Array(i);s.set(this._bytes,0),this._buffer=i,this._bytes=s}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+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,t){return this._bytes.slice(e,t)}}class Ca extends ue{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class Mt{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}}/*!
164
+ * Copyright (c) 2026-present, Vanilagy and contributors
165
+ *
166
+ * This Source Code Form is subject to the terms of the Mozilla Public
167
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
168
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
169
+ */const Ea=-32768,Pa=2**15-1,ti="Mediabunny",ri=6,ii=5,xa={video:1,audio:2,subtitle:17};class va extends ba{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=j(),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=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new xs(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush();for(const t of this.output.tracks)t.isVideoTrack()&&t.metadata.decoderConfig?this.getVideoTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig}):t.isAudioTrack()&&t.metadata.decoderConfig&&this.getAudioTrackData(t,t.metadata.primingPacket??null,{decoderConfig:t.metadata.decoderConfig});e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:f.EBML,data:[{id:f.EBMLVersion,data:1},{id:f.EBMLReadVersion,data:1},{id:f.EBMLMaxIDLength,data:4},{id:f.EBMLMaxSizeLength,data:8},{id:f.DocType,data:this.format instanceof Vt?"webm":"matroska"},{id:f.DocTypeVersion,data:2},{id:f.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,i)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),s=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:f.SeekHead,data:[{id:f.Seek,data:[{id:f.SeekID,data:t},{id:f.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:f.Seek,data:[{id:f.SeekID,data:i},{id:f.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:f.Seek,data:[{id:f.SeekID,data:s},{id:f.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:f.Seek,data:[{id:f.SeekID,data:n},{id:f.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:f.Seek,data:[{id:f.SeekID,data:a},{id:f.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:f.Duration,data:new Gt(0)};this.segmentDuration=e;const t={id:f.Info,data:[{id:f.TimestampScale,data:1e6},{id:f.MuxingApp,data:ti},{id:f.WritingApp,data:ti},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:f.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){let i=G[t.track.source._codec];y(i),t.type==="audio"&&t.track.source._codec==="dts"&&(t.info.decoderConfig.codec==="dtse"?i="A_DTS/EXPRESS":t.info.decoderConfig.codec==="dtsl"&&(i="A_DTS/LOSSLESS"));let s=0;if(t.type==="audio"&&t.track.source._codec==="opus"){s=1e6*80;const n=t.info.decoderConfig.description;if(n){const a=me(n),o=jn(a);s=Math.round(1e9*(o.preSkip/_i))}}e.data.push({id:f.TrackEntry,data:[{id:f.TrackNumber,data:t.track.id},{id:f.TrackUID,data:t.track.id},{id:f.TrackType,data:xa[t.type]},t.track.metadata.disposition?.default===!1?{id:f.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:f.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:f.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:f.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:f.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:f.FlagCommentary,data:1}:null,{id:f.FlagLacing,data:0},{id:f.Language,data:t.track.metadata.languageCode??Wt},{id:f.CodecID,data:i},t.codecPrivate?{id:f.CodecPrivate,data:me(t.codecPrivate)}:null,{id:f.CodecDelay,data:0},{id:f.SeekPreRoll,data:s},t.track.metadata.name!==void 0?{id:f.Name,data:new ye(t.track.metadata.name)}:null,t.type==="video"?this.videoSpecificTrackInfo(t):null,t.type==="audio"?this.audioSpecificTrackInfo(t):null,t.type==="subtitle"?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:i}=e.track.metadata,s=[t?{id:f.DefaultDuration,data:1e9/t}:null],n=i?Zt(-i):0,a=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,o=e.info.decoderConfig.colorSpace,c={id:f.Video,data:[{id:f.PixelWidth,data:e.info.width},{id:f.PixelHeight,data:e.info.height},a?{id:f.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:f.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:f.DisplayUnit,data:3}:null,e.info.alphaMode?{id:f.AlphaMode,data:1}:null,sn(o)?null:{id:f.Colour,data:[{id:f.MatrixCoefficients,data:o?.matrix!=null?tt[o.matrix]:2},{id:f.TransferCharacteristics,data:o?.transfer!=null?et[o.transfer]:2},{id:f.Primaries,data:o?.primaries!=null?Je[o.primaries]:2},{id:f.Range,data:o?.fullRange!=null?o.fullRange?2:1:0}]},n?{id:f.Projection,data:[{id:f.ProjectionType,data:0},{id:f.ProjectionPoseRoll,data:new $t((n+180)%360-180)}]}:null]};return s.push(c),s}audioSpecificTrackInfo(e){const t=X.includes(e.track.source._codec)?ar(e.track.source._codec):null;return[{id:f.Audio,data:[{id:f.SamplingFrequency,data:new $t(e.info.sampleRate)},{id:f.Channels,data:e.info.numberOfChannels},t?{id:f.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){const e=[],t=(n,a)=>{e.push({id:f.SimpleTag,data:[{id:f.TagName,data:new ye(n)},typeof a=="string"?{id:f.TagString,data:new ye(a)}:{id:f.TagBinary,data:a}]})},i=this.output._metadataTags,s=new Set;for(const{key:n,value:a}of kn(i))switch(n){case"title":t("TITLE",a),s.add("TITLE");break;case"description":t("DESCRIPTION",a),s.add("DESCRIPTION");break;case"artist":t("ARTIST",a),s.add("ARTIST");break;case"album":t("ALBUM",a),s.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),s.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),s.add("GENRE");break;case"comment":t("COMMENT",a),s.add("COMMENT");break;case"lyrics":t("LYRICS",a),s.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),s.add("DATE");break;case"trackNumber":{const o=i.tracksTotal!==void 0?`${a}/${i.tracksTotal}`:a.toString();t("PART_NUMBER",o),s.add("PART_NUMBER")}break;case"discNumber":{const o=i.discsTotal!==void 0?`${a}/${i.discsTotal}`:a.toString();t("DISC",o),s.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:ge(n)}if(i.raw)for(const n in i.raw){const a=i.raw[n];a==null||s.has(n)||(typeof a=="string"||a instanceof Uint8Array)&&t(n,a)}e.length!==0&&(this.tagsElement={id:f.Tags,data:[{id:f.Tag,data:[{id:f.Targets,data:[{id:f.TargetTypeValue,data:50},{id:f.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],i=new Set,s=e.images??[];for(const n of s){let a=n.name;a===void 0&&(a=(n.kind==="coverFront"?"cover":n.kind==="coverBack"?"back":"image")+(Tn(n.mimeType)??""));let o;for(;;){o=0n;for(let c=0;c<8;c++)o<<=8n,o|=BigInt(Math.floor(Math.random()*256));if(o!==0n&&!i.has(o))break}i.add(o),t.push({id:f.AttachedFile,data:[n.description!==void 0?{id:f.FileDescription,data:new ye(n.description)}:null,{id:f.FileName,data:new ye(a)},{id:f.FileMediaType,data:n.mimeType},{id:f.FileData,data:n.data},{id:f.FileUID,data:o}]})}for(const[n,a]of Object.entries(e.raw??{}))!(a instanceof nr)||!/^\d+$/.test(n)||s.find(c=>c.mimeType===a.mimeType&&Sn(c.data,a.data))||t.push({id:f.AttachedFile,data:[a.description!==void 0?{id:f.FileDescription,data:new ye(a.description)}:null,{id:f.FileName,data:new ye(a.name??"")},{id:f.FileMediaType,data:a.mimeType??""},{id:f.FileData,data:a.data},{id:f.FileUID,data:BigInt(n)}]});t.length!==0&&(this.attachmentsElement={id:f.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:f.Segment,size:this.format._options.appendOnly?-1:ri,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){const{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,i)}}createCues(){this.cues={id:f.Cues,data:[]}}get segmentDataOffset(){return y(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Ii({isWebM:this.format instanceof Vt,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const s=this.trackDatas.find(l=>l.track===e);if(s)return s;Ei(i,e.source._codec),y(i),y(i.decoderConfig),y(i.decoderConfig.codedWidth!==void 0),y(i.decoderConfig.codedHeight!==void 0);const n=i.decoderConfig.displayAspectWidth,a=i.decoderConfig.displayAspectHeight,o=n===void 0||a===void 0?null:Ke({num:n,den:a}),c={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:i.decoderConfig,alphaMode:t?!!t.sideData.alpha:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return e.source._codec==="vp9"?c.codecPrivate=new Uint8Array(ls(c.info.decoderConfig.codec)):e.source._codec==="av1"?c.codecPrivate=new Uint8Array(us(c.info.decoderConfig.codec)):e.source._codec==="prores"&&(c.codecPrivate=Le.encode(i.decoderConfig.codec)),this.trackDatas.push(c),this.trackDatas.sort((l,u)=>l.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,i){const s=this.trackDatas.find(c=>c.track===e);if(s)return s;Pi(i,e.source._codec),y(i),y(i.decoderConfig);const n={...i.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!n.description){if(!t)throw new Error("No AAC description provided; you must therefore provide a priming packet.");const c=Or(oe.tempFromBytes(t.data));if(!c)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.");const l=dt[c.samplingFrequencyIndex],u=sr[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");n.description=mi({objectType:c.objectType,outputSampleRate:l,outputNumberOfChannels:u}),a=!0}const o={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:a},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:n.description??null,closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,l)=>c.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;_s(t),y(t),y(t.config);const s={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Le.encode(t.config.description),closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,i);n.info.alphaMode??=!!t.sideData.alpha;let a=t.data;if(e.source._codec==="prores"){if(a.byteLength<8)throw new Error("ProRes packet too small, expected at least 8 bytes.");a=a.subarray(8)}const o=t.type==="key";this.validateTimestamp(n.track,t.timestamp,o);let c=t.timestamp,l=t.duration;e.metadata.frameRate!==void 0&&(c=Ge(c,e.metadata.frameRate),l=Ge(l,e.metadata.frameRate));const u=n.info.alphaMode?t.sideData.alpha??null:null,d=this.createInternalChunk(a,c,l,t.type,u);e.source._codec==="vp9"&&this.fixVP9ColorSpace(n,d),n.chunkQueue.push(d),await this.interleaveChunks()}finally{s()}}async addEncodedAudioPacket(e,t,i){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,t,i);let a=t.data;if(n.info.requiresAdtsStripping){const l=Or(oe.tempFromBytes(a));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const u=l.crcCheck===null?Fs:Bs;a=a.subarray(u)}const o=t.type==="key";this.validateTimestamp(n.track,t.timestamp,o);const c=this.createInternalChunk(a,t.timestamp,t.duration,t.type);n.chunkQueue.push(c),await this.interleaveChunks()}finally{s()}}async addSubtitleCue(e,t,i){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i);this.validateTimestamp(n.track,t.timestamp,!0);let a=t.text;const o=Math.round(t.timestamp*1e3);ei.lastIndex=0,a=a.replace(ei,d=>{const m=Ta(d.slice(1,-1))-o;return`<${Sa(m)}>`});const c=Le.encode(a),l=`${t.settings??""}
170
+ ${t.identifier??""}
171
+ ${t.notes??""}`,u=this.createInternalChunk(c,t.timestamp,t.duration,"key",l.trim()?Le.encode(l):null);n.chunkQueue.push(u),await this.interleaveChunks()}finally{s()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.chunkQueue.length===0&&!n.closed)break e;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<i&&(t=n,i=n.chunkQueue[0].timestamp)}if(!t)break;const s=t.chunkQueue.shift();this.writeBlock(t,s)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const i=new U(t.data);i.skipBits(2);const s=i.readBits(1),a=(i.readBits(1)<<1)+s;if(a===3&&i.skipBits(1),i.readBits(1)||i.readBits(1)!==0||(i.skipBits(2),i.readBits(24)!==4817730))return;a>=2&&i.skipBits(1);const u={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];rn(t.data,i.pos,i.pos+3,u)}createInternalChunk(e,t,i,s,n=null){return{data:e,type:s,timestamp:t,duration:i,additions:n}}writeBlock(e,t){this.segment||this.createSegment();const i=Math.round(1e3*t.timestamp),s=this.trackDatas.every(d=>{if(e===d)return t.type==="key";const h=d.chunkQueue[0];return h?h.type==="key":d.closed});let n=!1;if(!this.currentCluster)n=!0;else{y(this.currentClusterStartMsTimestamp!==null),y(this.currentClusterMaxMsTimestamp!==null);const d=i-this.currentClusterStartMsTimestamp;n=s&&i>this.currentClusterMaxMsTimestamp&&d>=1e3*(this.format._options.minimumClusterDuration??1)||d>Pa}n&&this.createNewCluster(i);const a=i-this.currentClusterStartMsTimestamp;if(a<Ea){if(!this.warnedAboutTooNegativeTimestamp){const d=this.format instanceof Vt?"WebM":"Matroska";D._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${d}.`),this.warnedAboutTooNegativeTimestamp=!0}return}const o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,a,!1);const l=Math.round(1e3*t.duration);if(!!t.additions||e.type==="subtitle"){const d={id:f.BlockGroup,data:[{id:f.Block,data:[o,t.data]},t.type==="delta"?{id:f.ReferenceBlock,data:new xi(e.lastWrittenMsTimestamp-i)}:null,t.additions?{id:f.BlockAdditions,data:[{id:f.BlockMore,data:[{id:f.BlockAddID,data:1},{id:f.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:f.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(d)}else{c.setUint8(3,+(t.type==="key")<<7);const d={id:f.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(d)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+l),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:f.Cluster,size:this.format._options.appendOnly?-1:ii,data:[{id:f.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(y(this.currentCluster),!this.format._options.appendOnly){const s=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),n=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(s,ii),this.writer.seek(n)}if(this.format._options.onCluster){y(this.currentClusterStartMsTimestamp!==null);const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onCluster(s,n,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[s,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(s);const i=[...t.entries()].sort((s,n)=>s[0]-n[0]);for(const[s,n]of i)y(this.cues),this.cues.data.push({id:f.CuePoint,data:[{id:f.CueTime,data:Math.max(0,s)},...n.map(a=>({id:f.CueTrackPositions,data:[{id:f.CueTrack,data:a.track.id},{id:f.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(s=>s.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),y(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,ri);const i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Gt(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),y(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}/*!
172
+ * Copyright (c) 2026-present, Vanilagy and contributors
173
+ *
174
+ * This Source Code Form is subject to the terms of the Mozilla Public
175
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
176
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
177
+ */class Aa{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){y(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(i,s)=>i[s*e]:e===1&&t===4?this.channelMixer=(i,s,n)=>i[s*e]*+(n<2):e===1&&t===6?this.channelMixer=(i,s,n)=>i[s*e]*+(n===2):e===2&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return .5*(i[n]+i[n+1])}:e===2&&t===4?this.channelMixer=(i,s,n)=>n<2?i[s*e+n]:0:e===2&&t===6?this.channelMixer=(i,s,n)=>n<2?i[s*e+n]:0:e===4&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return .25*(i[n]+i[n+1]+i[n+2]+i[n+3])}:e===4&&t===2?this.channelMixer=(i,s,n)=>{const a=s*e;return .5*(i[a+n]+i[a+n+2])}:e===4&&t===6?this.channelMixer=(i,s,n)=>{const a=s*e;return n<2?i[a+n]:n===2||n===3?0:i[a+n-2]}:e===6&&t===1?this.channelMixer=(i,s)=>{const n=s*e;return Math.SQRT1_2*(i[n]+i[n+1])+i[n+2]+.5*(i[n+4]+i[n+5])}:e===6&&t===2?this.channelMixer=(i,s,n)=>{const a=s*e;return i[a+n]+Math.SQRT1_2*(i[a+2]+i[a+n+4])}:e===6&&t===4?this.channelMixer=(i,s,n)=>{const a=s*e;return n<2?i[a+n]+Math.SQRT1_2*i[a+2]:i[a+n+2]}:this.channelMixer=(i,s,n)=>n<e?i[s*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const i=new Float32Array(t);i.set(this.tempSourceBuffer),this.tempSourceBuffer=i}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),y(this.startTime!==null);const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const i=e.allocationSize({planeIndex:0,format:"f32"}),s=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(s,{planeIndex:0,format:"f32"});const n=e.timestamp-this.startTime,a=n+e.duration,o=Math.floor((n-1/this.sourceSampleRate)*this.targetSampleRate)+1,c=Math.ceil(a*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const u=l-this.bufferStartFrame;y(u<this.bufferSizeInFrames);const m=(l/this.targetSampleRate-n)*this.sourceSampleRate,p=Math.floor(m),b=Math.ceil(m),w=m-p;for(let g=0;g<this.targetNumberOfChannels;g++){let T=0,k=0;p>=0&&p<e.numberOfFrames&&(T=this.channelMixer(s,p,g)),b>=0&&b<e.numberOfFrames&&(k=this.channelMixer(s,b,g));const x=T+w*(k-T),C=u*this.targetNumberOfChannels+g;this.outputBuffer[C]+=x}this.maxWrittenFrame===null?this.maxWrittenFrame=u:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,u)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;y(this.startTime!==null);const e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const i=new q({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}/*!
178
+ * Copyright (c) 2026-present, Vanilagy and contributors
179
+ *
180
+ * This Source Code Form is subject to the terms of the Mozilla Public
181
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
182
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
183
+ */var Ra=function(r,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var i,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");i=e[Symbol.asyncDispose]}if(i===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");i=e[Symbol.dispose],t&&(s=i)}if(typeof i!="function")throw new TypeError("Object not disposable.");s&&(i=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),r.stack.push({value:e,dispose:i,async:t})}else t&&r.stack.push({async:!0});return e},Ia=(function(r){return function(e){function t(a){e.error=e.hasError?new r(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var i,s=0;function n(){for(;i=e.stack.pop();)try{if(!i.async&&s===1)return s=0,e.stack.push(i),Promise.resolve().then(n);if(i.dispose){var a=i.dispose.call(i.value);if(i.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(r,e,t){var i=new Error(t);return i.name="SuppressedError",i.error=r,i.suppressed=e,i});class dr{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_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(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}}class Ji extends dr{constructor(e){if(super(),this._connectedTrack=null,!Ce.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Ce.join(", ")}.`);this._codec=e}}const ni=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Fa{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,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 tr,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}async add(e,t,i){const s=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const n=this.encodingConfig,a=n.sizeChangeBehavior??"deny";let o=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,a==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(n.transform?.width!==void 0||n.transform?.height!==void 0||n.transform?.rotate!==void 0||n.transform?.crop!==void 0||n.transform?.force===!0||o&&a!=="passThrough"){let d=n.transform?.width,h=n.transform?.height,m=n.transform?.fit??"fill";o&&a!=="passThrough"&&(y(this.outputWidth),y(this.outputHeight),y(a!=="deny"),d=this.outputWidth,h=this.outputHeight,m=a);const p=await e.transform({width:d,height:h,roundDimensionsTo:2,crop:n.transform?.crop,rotate:n.transform?.rotate,fit:m,alpha:n.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=p.displayWidth,this.outputHeight=p.displayHeight),t&&e.close(),e=p,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const u=n.transform?.frameRate;if(u!==void 0){const d=e.timestamp+e.duration,h=gr(e.timestamp,u);if(this.frameRateLastSample!==null)if(h<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=d;return}else await this.padFrameRate(h,i);e===s&&(e=e.clone(),t=!0),e.setTimestamp(h),e.setDuration(1/u),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=h,this.frameRateLastEndTimestamp=d}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;let s;if(i.transform?.process){let n=i.transform.process(e);if(I(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);const a=[];try{for(const o of n)o instanceof Y?a.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?a.push(new Y(o)):a.push(new Y(o,{timestamp:e.timestamp,duration:e.duration}))}catch(o){for(const c of a)c!==e&&c.close();for(const c of n)(c instanceof Y&&c!==e||typeof VideoFrame<"u"&&c instanceof VideoFrame)&&c.close();throw o}s=a}else s=[e];try{for(const n of s){if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(n),this.encoderInitialized||await this.ensureEncoderPromise),y(this.encoderInitialized),this.closed)break;const a=this.encodingConfig.keyFrameInterval??2,o=Math.floor(n.timestamp/a),c={...this.defaultEncodeOptions,...n.encodeOptions,...t},l={...c,keyFrame:c.keyFrame!==void 0?c.keyFrame:a===0||o!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=o,this.encodingConfig.onEncodedSample?.(n),this.customEncoder){this.customEncoderQueueSize++;const u=n.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(u,l)).catch(h=>this.setError(h)).finally(()=>{this.customEncoderQueueSize--,u.close()});this.customEncoderQueueSize>=4&&await d}else{y(this.encoder);const u=n.toVideoFrame(),d=se(this.preciseTimings,u.timestamp,m=>m.microsecondTimestamp),h=d!==-1?this.preciseTimings[d]:null;if(h&&h.microsecondTimestamp===u.timestamp?(h.timestamp!==n.timestamp&&(h.timestampIsValid=!1),h.duration!==n.duration&&(h.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:n.timestamp,duration:n.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(u,l)}finally{u.close()}}else{this.splitter||(this.splitter=new Ba);const{colorFrame:p,alphaFrame:b}=await this.splitter.split(u);this.alphaFrameQueue.push(b);try{this.encoder.encode(p,l)}finally{p.close()}}else try{this.encoder.encode(u,l)}finally{u.close()}this.encoder.encodeQueueSize>=4&&await new Promise(m=>this.encoder.addEventListener("dequeue",m,{once:!0}))}await this.lastMuxerPromise}}finally{for(const n of s)n!==e&&n.close()}}async padFrameRate(e,t){const i=this.encodingConfig.transform.frameRate;y(this.frameRateLastSample);const s=Math.round((e-this.frameRateLastTimestamp)*i);for(let n=1;n<s;n++){const a={stack:[],error:void 0,hasError:!1};try{const o=Ra(a,this.frameRateLastSample.clone(),!1);o.setTimestamp(this.frameRateLastTimestamp+n/i),o.setDuration(1/i),await this.processAndEncode(o,t)}catch(o){a.error=o,a.hasError=!0}finally{Ia(a)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const t=kt(this.encodingConfig.quality,this.encodingConfig.bitrate);y(t!==void 0);const i=qi({...this.encodingConfig,quality:t,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});let s=null,n;for(const o of i){const c=o.config;if(this.encodingConfig.onEncoderConfig?.(c),n=Ki.find(u=>u.supports(this.encodingConfig.codec,c)),n){s=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){s=o;break}}catch{}}if(!s){if(typeof VideoEncoder>"u")throw new Error(rr("VideoEncoder"));const o=i[0].config,c=i.map(({config:l,quantizer:u})=>u!==null?`quantizer ${u}`:`${l.bitrate} bps`);throw new Error(`This specific encoder configuration (${o.codec}, ${c.join(" / ")}, ${o.width}x${o.height}, hardware acceleration: ${o.hardwareAcceleration??"no-preference"}) is not supported in this environment. Consider using another codec or changing your video parameters.`)}const a=s.config;if(s.quantizer!==null&&(this.defaultEncodeOptions=$i(this.encodingConfig.codec,s.quantizer)),n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof H))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.");ni(this.source._connectedTrack,o),this.encodingConfig.onEncodedPacket?.(o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(l=>{this.setError(l)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else{const o=[],c=[];let l=0,u=0;const d=(m,p,b)=>{const w={};if(p){const C=new Uint8Array(p.byteLength);p.copyTo(C),w.alpha=C}let g=H.fromEncodedChunk(m,w);const T=se(this.preciseTimings,m.timestamp,C=>C.microsecondTimestamp),k=T!==-1?this.preciseTimings[T]:null;let x=null;this.emittedEncoderPackets===0&&g.type==="delta"&&b?.decoderConfig&&(x=Ti(this.encodingConfig.codec,b.decoderConfig,g.data)),(k&&k.microsecondTimestamp===m.timestamp||x!==null)&&(g=g.clone({timestamp:k?.timestampIsValid?k.timestamp:void 0,duration:k?.durationIsValid?k.duration:void 0,type:x??void 0})),ni(this.source._connectedTrack,g),this.encodingConfig.onEncodedPacket?.(g,b),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,g,b).catch(C=>{this.setError(C)}),this.emittedEncoderPackets++},h=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(m,p)=>{if(!this.alphaEncoder){d(m,null,p);return}const b=this.alphaFrameQueue.shift();y(b!==void 0),b?(this.alphaEncoder.encode(b,{...this.defaultEncodeOptions,keyFrame:m.type==="key"}),u++,b.close(),o.push({chunk:m,meta:p})):u===0?d(m,null,p):(c.push(l+u),o.push({chunk:m,meta:p}))},error:m=>{m.stack=h,this.setError(m)}}),this.encoder.configure(a),this.encodingConfig.alpha==="keep"){const m=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(p,b)=>{u--;const w=o.shift();for(y(w!==void 0),d(w.chunk,p,w.meta),l++;c.length>0&&c[0]===l;){c.shift();const g=o.shift();y(g!==void 0),d(g.chunk,null,g.meta)}},error:p=>{p.stack=m,this.setError(p)}}),this.alphaEncoder.configure(a)}}y(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){const t=this.encodingConfig.transform.frameRate,i=gr(this.frameRateLastEndTimestamp,t);await this.padFrameRate(i)}this.closed=!0,e||(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await ut(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(t=>this.setError(t)):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.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}let zt=null;class Ba{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!zt){const s=new Blob([`(${Da.toString()})()`],{type:"application/javascript"});zt=URL.createObjectURL(s)}this.worker=new Worker(zt),this.worker.addEventListener("message",s=>{const n=s.data,a=this.pendingRequests.get(n.id);a&&(this.pendingRequests.delete(n.id),"error"in n?a.reject(new Error(n.error)):a.resolve({colorFrame:n.colorFrame,alphaFrame:n.alphaFrame}))}),this.worker.addEventListener("error",s=>{const n=new Error(s.message||"Color/alpha splitter worker error.");for(const a of this.pendingRequests.values())a.reject(n);this.pendingRequests.clear()})}const t=this.nextRequestId++,i=j();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.worker?.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Da=()=>{let r=null,e=Promise.resolve();self.addEventListener("message",n=>{const{id:a,sourceFrame:o}=n.data;e=e.then(async()=>{try{const{colorFrame:c,alphaFrame:l}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:l},{transfer:[c,l]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});const t=async n=>{const a=n.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=n.allocationSize();if((!r||r.byteLength!==o)&&(r=new Uint8Array(o)),await n.copyTo(r),a==="RGBA"||a==="BGRA")return i(r,a,n);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return s(r,a,n);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},i=(n,a,o)=>{const c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=c*l,d=Math.ceil(c/2),h=Math.ceil(l/2),m=u+d*h*2,p=new Uint8Array(m);for(let T=0,k=3;T<u;T++,k+=4)p[T]=n[k];p.fill(128,u);const b=new VideoFrame(n,{format:a==="RGBA"?"RGBX":"BGRX",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),w={format:"I420",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[p.buffer]},g=new VideoFrame(p,w);return{colorFrame:b,alphaFrame:g}},s=(n,a,o)=>{const c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=a.includes("P10"),d=a.includes("P12"),h=u||d?2:1;let m,p;a.startsWith("I420")?(m=Math.ceil(c/2),p=Math.ceil(l/2)):a.startsWith("I422")?(m=Math.ceil(c/2),p=l):(m=c,p=l);const b=c*l,w=m*p,g=b*h,T=w*h,k=b*h,x=g+T*2,C=a.replace("A",""),A=Math.ceil(c/2),v=Math.ceil(l/2),S=A*v,_=S*h,E=k+2*_,R=new Uint8Array(E),B=x;R.set(n.subarray(B,B+k),0);const z=k,L=u?512:d?2048:128;h===1?R.fill(L,z):new Uint16Array(R.buffer,z,2*S).fill(L);const W=u?"I420P10":d?"I420P12":"I420",V=new VideoFrame(n.subarray(0,x),{format:C,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),te={format:W,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[R.buffer]},re=new VideoFrame(R,te);return{colorFrame:V,alphaFrame:re}}};class La extends Ji{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ia(t),super(t.codec),this._encoder=new Fa(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const s=new Y(this._canvas,{timestamp:e,duration:t});return this._encoder.add(s,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class hr extends dr{constructor(e){if(super(),this._connectedTrack=null,!Re.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Re.join(", ")}.`);this._codec=e}}class en{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new tr,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const i=this.encodingConfig;i.transform?.numberOfChannels!==void 0||i.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new Aa({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.transform.sampleRate??e.sampleRate,onSample:async n=>{await this.processAndEncode(n,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;if(i.transform?.sampleFormat!==void 0&&ea(e.format)!==i.transform.sampleFormat){const s=ra(e,i.transform.sampleFormat);t&&e.close(),e=s,t=!0}if(i.transform?.process)try{let s=i.transform.process(e);if(I(s)&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]);try{for(const n of s)if(!(n instanceof q))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(const n of s)await this.encodeSample(n,!0)}finally{for(const n of s)n instanceof q&&n.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),y(this.encoderInitialized),this.closed)return;{const i=Math.round(e.timestamp*e.sampleRate),s=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=s;else{const n=i-this.lastEndSampleIndex;if(n>=64){const a=new q({data:new Float32Array(n*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),s=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).catch(n=>this.setError(n)).finally(()=>{this.customEncoderQueueSize--,i.close()});this.customEncoderQueueSize>=4&&await s,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{y(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(s=>this.encoder.addEventListener("dequeue",s,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){y(this.outputSampleSize),y(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:s,sampleRate:n,timestamp:a}=e,o=2048,c=[];for(let h=0;h<s;h+=o){const m=Math.min(o,e.numberOfFrames-h),p=m*i*this.outputSampleSize,b=new ArrayBuffer(p),w=new DataView(b);c.push({frameCount:m,view:w})}const l=e.allocationSize({planeIndex:0,format:"f32-planar"}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let h=0;h<i;h++){e.copyTo(u,{planeIndex:h,format:"f32-planar"});for(let m=0;m<c.length;m++){const{frameCount:p,view:b}=c[m];for(let w=0;w<p;w++)this.writeOutputValue(b,(w*i+h)*this.outputSampleSize,u[m*o+w])}}t&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:n}};for(let h=0;h<c.length;h++){const{frameCount:m,view:p}=c[h],b=p.buffer,w=h*o,g=new H(new Uint8Array(b),"key",a+w/n,m/n);this.encodingConfig.onEncodedPacket?.(g,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,g,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i}=e,s=kt(this.encodingConfig.quality,this.encodingConfig.bitrate),n=ji({numberOfChannels:t,sampleRate:i,...this.encodingConfig,quality:s});this.encodingConfig.onEncoderConfig?.(n);const a=Qi.find(o=>o.supports(this.encodingConfig.codec,n));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof H))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(l=>{this.setError(l)})},this.customEncoder.onError=o=>{this.setError(o)},await this.customEncoder.init();else if(X.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(rr("AudioEncoder"));let o;try{o=(await AudioEncoder.isConfigSupported(n)).supported??!1}catch{o=!1}if(!o)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported in this environment. Consider using another codec or changing your audio parameters.`);const c=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(l,u)=>{if(this.encodingConfig.codec==="aac"&&u?.decoderConfig){let h=!1;if(!u.decoderConfig.description||u.decoderConfig.description.byteLength<2?h=!0:h=fi(me(u.decoderConfig.description)).objectType===0,h){const m=Number(ne(n.codec.split(".")));u.decoderConfig.description=mi({objectType:m,outputNumberOfChannels:u.decoderConfig.numberOfChannels,outputSampleRate:u.decoderConfig.sampleRate})}}let d=H.fromEncodedChunk(l);d=d.clone({timestamp:Ge(d.timestamp,n.sampleRate),duration:l.duration!=null?Ge(d.duration,n.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,u).catch(h=>{this.setError(h)})},error:l=>{l.stack=c,this.setError(l)}}),this.encoder.configure(n)}y(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:s}=ar(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint8(a,N((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,a,o)=>{n.setInt8(a,N(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,a,o)=>{const c=N(Math.floor(o*32767),-32768,32767);n.setUint8(a,aa(c))}:t==="alaw"?this.writeOutputValue=(n,a,o)=>{const c=N(Math.floor(o*32767),-32768,32767);n.setUint8(a,ca(c))}:y(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint16(a,N((o+1)*32767.5,0,65535),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt16(a,N(Math.round(o*32767),-32768,32767),s):y(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,a,o)=>li(n,a,N((o+1)*83886075e-1,0,16777215),s):t==="signed"?this.writeOutputValue=(n,a,o)=>hn(n,a,N(Math.round(o*8388607),-8388608,8388607),s):y(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint32(a,N((o+1)*21474836475e-1,0,4294967295),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt32(a,N(Math.round(o*2147483647),-2147483648,2147483647),s):t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat32(a,o,s):y(!1);break;case 8:t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat64(a,o,s):y(!1);break;default:ge(i),y(!1)}}async flushAndClose(e){try{e||(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,e||(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(t=>this.setError(t)):this.encoder&&this.encoder.state!=="closed"&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}class ja extends hr{constructor(e){Hi(e),super(e.codec),this._encoder=new en(this,e)}add(e){if(!(e instanceof q))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class $a extends hr{constructor(e,t={}){if(Hi(e),typeof t!="object"||!t)throw new TypeError("options must be an object.");if(t.startTimestamp!==void 0&&!Number.isFinite(t.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(e.codec),this._encoder=new en(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=q._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const i of t)await this._encoder.add(i,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Oa extends dr{constructor(e){if(super(),this._connectedTrack=null,!Qe.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Qe.join(", ")}.`);this._codec=e}}/*!
184
+ * Copyright (c) 2026-present, Vanilagy and contributors
185
+ *
186
+ * This Source Code Form is subject to the terms of the Mozilla Public
187
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
188
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
189
+ */class tn{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Ce.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Re.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Qe.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class si extends tn{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!rt(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new va(e,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,...Si,...X.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...Qe]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class Vt extends si{constructor(e){super(e)}getSupportedCodecs(){return[...Ce.filter(e=>["vp8","vp9","av1"].includes(e)),...Re.filter(e=>["opus","vorbis"].includes(e)),...Qe]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new si().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}/*!
190
+ * Copyright (c) 2026-present, Vanilagy and contributors
191
+ *
192
+ * This Source Code Form is subject to the terms of the Mozilla Public
193
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
194
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
195
+ */const ai=["video","audio","subtitle"];class at{constructor(e,t,i,s,n){this.id=e,this.output=t,this.type=i,this.source=s,this.metadata=n}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof at))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=br(this.metadata.group),i=br(e.metadata.group);for(const s of t)if(this.type!==e.type&&i.some(o=>s===o)||i.some(o=>s._pairedGroups.has(o)))return!0;return!1}}class Ma extends at{constructor(e,t,i,s){super(e,t,"video",i,s)}}class za extends at{constructor(e,t,i,s){super(e,t,"audio",i,s)}}class Va extends at{constructor(e,t,i,s){super(e,t,"subtitle",i,s)}}class Ze{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof Ze))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const Nt=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!ui(r.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(r.name!==void 0&&typeof r.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(r.disposition!==void 0&&vn(r.disposition),r.maximumPacketCount!==void 0&&(!Number.isInteger(r.maximumPacketCount)||r.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(r.group!==void 0&&!(r.group instanceof Ze)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof Ze))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class Ga extends it{get target(){const 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);const t=this._getRootTarget();if(I(t))throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new Ze,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new ci,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof tn))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof ue||e.target instanceof Mt))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof ue&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof ue)&&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 ue&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){y(this._target instanceof Mt);const t=this._target.getTarget(e),i=s=>{if(!(s instanceof ue))throw new TypeError("getTarget must return a Target.");return s};return I(t)?t.then(i):i(t)}async _getTarget(e){y(this._target instanceof Mt);const t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(y(this._initTarget!==null),this._initTarget instanceof ue)return this._initTarget;const 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 ue)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),i=s=>(this.state==="canceled"?s._close():this._rememberTarget(s),this._emit("target",{target:s,request:e,isRoot:!0}),this._rootTarget=s,s);return I(t)?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const t=await this._getRootTarget(),i=new _a(t,typeof e=="boolean"?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof Ji))throw new TypeError("source must be a VideoSource.");if(Nt(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(t.decoderConfig!==void 0&&Ei({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof H))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Ma(this.tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof hr))throw new TypeError("source must be an AudioSource.");if(Nt(t),t.decoderConfig!==void 0&&Pi({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof H))throw new TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(t.decoderConfig===void 0)throw new TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new za(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof Oa))throw new TypeError("source must be a SubtitleSource.");Nt(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Va(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(Pn(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.");const t=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),s=t[e.type].max;if(i===s)throw new Error(s===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${s} ${e.type} track${s===1?"":"s"}.`);const n=t.total.max;if(this.tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} tracks${n===1?"":"s"} in total.`);if(e.isVideoTrack()){const a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){const e=this.format.getSupportedTrackCounts();for(const i of ai){const s=this.tracks.reduce((a,o)=>a+(o.type===i?1:0),0),n=e[i].min;if(s<n)return!1}const t=e.total.min;return!(this.tracks.length<t)}async start(){const e=this.format.getSupportedTrackCounts();for(const i of ai){const s=this.tracks.reduce((a,o)=>a+(o.type===i?1:0),0),n=e[i].min;if(s<n)throw new Error(n===e[i].max?`${this.format._name} requires exactly ${n} ${i} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${i} track${n===1?"":"s"}.`)}const t=e.total.min;if(this.tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(D._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const i=this._mutex.acquire();try{await this._muxer.start();const s=this.tracks.map(n=>n.source._start());await Promise.all(s)}finally{(await i)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return D._warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&D._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const t=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(i=>i._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?(D._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const t=this.tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const i=await this._rootWriterPromise;i.finalized||(await i.flush(),await i.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{await Promise.all([...this._unfinalizedTargets].map(t=>t._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}export{ja as A,Ha as B,La as C,Zi as I,Ga as O,ee as Q,zi as U,Vt as W,Na as a,qa as b,Wa as c,$a as d,Ua as e};