@clickmax/studio-bridge 0.0.0-stage → 12.5.7

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 (521) hide show
  1. package/README.md +22 -2
  2. package/dist/clickmax-bridge.js +291 -0
  3. package/editor/assets/__vite-browser-external-CV6URZNE.js +1 -0
  4. package/editor/assets/chunk-UYWON5AX-NUuRHjnO.js +1 -0
  5. package/editor/assets/dist-DFhRmUKu.js +56 -0
  6. package/editor/assets/domEditingLayers-KBTPQKGA-tvsAmAbb.js +1 -0
  7. package/editor/assets/hyperframes-player-CAjGal_q.js +473 -0
  8. package/editor/assets/index-CxuF8nIS.js +406 -0
  9. package/editor/assets/index-D5lVrSDr.css +1 -0
  10. package/editor/assets/lib-DlEuZBGC.js +1 -0
  11. package/editor/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  12. package/editor/assets/src-DDA8OuTJ.js +117 -0
  13. package/editor/index.html +39 -0
  14. package/moments/catalog.json +2436 -0
  15. package/package.json +41 -3
  16. package/plugin/.claude-plugin/plugin.json +6 -0
  17. package/plugin/hooks/creative-check.mjs +116 -0
  18. package/plugin/hooks/hooks.json +15 -0
  19. package/plugin/skills/achadinho/SKILL.md +71 -0
  20. package/plugin/skills/brasil-mapas/SKILL.md +139 -0
  21. package/plugin/skills/brasil-mapas/geo/br-municipios.topojson +1 -0
  22. package/plugin/skills/brasil-mapas/geo/br-regioes.topojson +1 -0
  23. package/plugin/skills/brasil-mapas/geo/br-uf.topojson +1 -0
  24. package/plugin/skills/brasil-mapas/scripts/mapa-base.mjs +527 -0
  25. package/plugin/skills/brasil-mapas/scripts/seca.mjs +258 -0
  26. package/plugin/skills/criativos/SKILL.md +182 -0
  27. package/plugin/skills/design-criativos/SKILL.md +153 -0
  28. package/plugin/skills/imagens/SKILL.md +57 -0
  29. package/plugin/skills/imagens/scripts/gerar-imagem.mjs +141 -0
  30. package/prompts/agent-system-prompt.md +27 -0
  31. package/prompts/creative-system-prompt.md +17 -0
  32. package/templates/creative/agenda-aberta-calendario/page-01.html +217 -0
  33. package/templates/creative/agenda-aberta-calendario/preview.jpg +0 -0
  34. package/templates/creative/agenda-aberta-calendario/template.json +8 -0
  35. package/templates/creative/agenda-lotando-fim-de-ano/page-01.html +201 -0
  36. package/templates/creative/agenda-lotando-fim-de-ano/preview.jpg +0 -0
  37. package/templates/creative/agenda-lotando-fim-de-ano/template.json +8 -0
  38. package/templates/creative/alerta-vencimento-mensal/page-01.html +163 -0
  39. package/templates/creative/alerta-vencimento-mensal/preview.jpg +0 -0
  40. package/templates/creative/alerta-vencimento-mensal/template.json +8 -0
  41. package/templates/creative/ano-novo-agradecimento/page-01.html +244 -0
  42. package/templates/creative/ano-novo-agradecimento/preview.jpg +0 -0
  43. package/templates/creative/ano-novo-agradecimento/template.json +8 -0
  44. package/templates/creative/antes-depois/assets/img/exemplo-antes.jpg +0 -0
  45. package/templates/creative/antes-depois/assets/img/exemplo-depois.jpg +0 -0
  46. package/templates/creative/antes-depois/page-01.html +123 -0
  47. package/templates/creative/antes-depois/preview.jpg +0 -0
  48. package/templates/creative/antes-depois/template.json +8 -0
  49. package/templates/creative/anuncio-link/assets/img/exemplo-escritorio.jpg +0 -0
  50. package/templates/creative/anuncio-link/page-01.html +86 -0
  51. package/templates/creative/anuncio-link/preview.jpg +0 -0
  52. package/templates/creative/anuncio-link/template.json +8 -0
  53. package/templates/creative/aula-ao-vivo-retrato/assets/img/exemplo-confeiteira.jpg +0 -0
  54. package/templates/creative/aula-ao-vivo-retrato/page-01.html +148 -0
  55. package/templates/creative/aula-ao-vivo-retrato/preview.jpg +0 -0
  56. package/templates/creative/aula-ao-vivo-retrato/template.json +8 -0
  57. package/templates/creative/aula-experimental-gratis/assets/img/exemplo-treino-barra.jpg +0 -0
  58. package/templates/creative/aula-experimental-gratis/page-01.html +136 -0
  59. package/templates/creative/aula-experimental-gratis/preview.jpg +0 -0
  60. package/templates/creative/aula-experimental-gratis/template.json +8 -0
  61. package/templates/creative/avaliacao-google-qr/page-01.html +158 -0
  62. package/templates/creative/avaliacao-google-qr/preview.jpg +0 -0
  63. package/templates/creative/avaliacao-google-qr/template.json +8 -0
  64. package/templates/creative/aviso-feriado-fechado/page-01.html +157 -0
  65. package/templates/creative/aviso-feriado-fechado/preview.jpg +0 -0
  66. package/templates/creative/aviso-feriado-fechado/template.json +8 -0
  67. package/templates/creative/banner-oferta-semana/assets/img/exemplo-emporio.jpg +0 -0
  68. package/templates/creative/banner-oferta-semana/page-01.html +126 -0
  69. package/templates/creative/banner-oferta-semana/preview.jpg +0 -0
  70. package/templates/creative/banner-oferta-semana/template.json +8 -0
  71. package/templates/creative/black-friday-escuro-dourado/assets/img/exemplo-retrato.jpg +0 -0
  72. package/templates/creative/black-friday-escuro-dourado/page-01.html +191 -0
  73. package/templates/creative/black-friday-escuro-dourado/preview.jpg +0 -0
  74. package/templates/creative/black-friday-escuro-dourado/template.json +8 -0
  75. package/templates/creative/black-friday-sofisticada/page-01.html +149 -0
  76. package/templates/creative/black-friday-sofisticada/preview.jpg +0 -0
  77. package/templates/creative/black-friday-sofisticada/template.json +8 -0
  78. package/templates/creative/bonus-empilhados/page-01.html +203 -0
  79. package/templates/creative/bonus-empilhados/preview.jpg +0 -0
  80. package/templates/creative/bonus-empilhados/template.json +8 -0
  81. package/templates/creative/campanha-vacinacao-pet/assets/img/exemplo-cao-vacina.jpg +0 -0
  82. package/templates/creative/campanha-vacinacao-pet/page-01.html +182 -0
  83. package/templates/creative/campanha-vacinacao-pet/preview.jpg +0 -0
  84. package/templates/creative/campanha-vacinacao-pet/template.json +8 -0
  85. package/templates/creative/capa-live-youtube/assets/img/exemplo-evento.jpg +0 -0
  86. package/templates/creative/capa-live-youtube/page-01.html +124 -0
  87. package/templates/creative/capa-live-youtube/preview.jpg +0 -0
  88. package/templates/creative/capa-live-youtube/template.json +8 -0
  89. package/templates/creative/capa-video-aula/assets/img/exemplo-escritorio.jpg +0 -0
  90. package/templates/creative/capa-video-aula/page-01.html +108 -0
  91. package/templates/creative/capa-video-aula/preview.jpg +0 -0
  92. package/templates/creative/capa-video-aula/template.json +8 -0
  93. package/templates/creative/cardapio-do-dia-lousa/page-01.html +191 -0
  94. package/templates/creative/cardapio-do-dia-lousa/preview.jpg +0 -0
  95. package/templates/creative/cardapio-do-dia-lousa/template.json +8 -0
  96. package/templates/creative/cardapio-tv-pizza/assets/img/exemplo-pizza.jpg +0 -0
  97. package/templates/creative/cardapio-tv-pizza/page-01.html +145 -0
  98. package/templates/creative/cardapio-tv-pizza/preview.jpg +0 -0
  99. package/templates/creative/cardapio-tv-pizza/template.json +8 -0
  100. package/templates/creative/carrinho-aberto-curso/page-01.html +219 -0
  101. package/templates/creative/carrinho-aberto-curso/preview.jpg +0 -0
  102. package/templates/creative/carrinho-aberto-curso/template.json +8 -0
  103. package/templates/creative/carrossel-catalogo/assets/img/exemplo-cafe-pacote.webp +0 -0
  104. package/templates/creative/carrossel-catalogo/assets/img/exemplo-emporio.jpg +0 -0
  105. package/templates/creative/carrossel-catalogo/assets/img/exemplo-produto.webp +0 -0
  106. package/templates/creative/carrossel-catalogo/assets/img/exemplo-queijo.webp +0 -0
  107. package/templates/creative/carrossel-catalogo/page-01.html +91 -0
  108. package/templates/creative/carrossel-catalogo/page-02.html +110 -0
  109. package/templates/creative/carrossel-catalogo/page-03.html +110 -0
  110. package/templates/creative/carrossel-catalogo/page-04.html +110 -0
  111. package/templates/creative/carrossel-catalogo/page-05.html +91 -0
  112. package/templates/creative/carrossel-catalogo/preview.jpg +0 -0
  113. package/templates/creative/carrossel-catalogo/template.json +8 -0
  114. package/templates/creative/carrossel-dicas/assets/img/exemplo-escritorio.jpg +0 -0
  115. package/templates/creative/carrossel-dicas/page-01.html +102 -0
  116. package/templates/creative/carrossel-dicas/page-02.html +113 -0
  117. package/templates/creative/carrossel-dicas/page-03.html +113 -0
  118. package/templates/creative/carrossel-dicas/page-04.html +113 -0
  119. package/templates/creative/carrossel-dicas/page-05.html +105 -0
  120. package/templates/creative/carrossel-dicas/preview.jpg +0 -0
  121. package/templates/creative/carrossel-dicas/template.json +8 -0
  122. package/templates/creative/carrossel-direitos/assets/img/exemplo-advogada.jpg +0 -0
  123. package/templates/creative/carrossel-direitos/page-01.html +95 -0
  124. package/templates/creative/carrossel-direitos/page-02.html +103 -0
  125. package/templates/creative/carrossel-direitos/page-03.html +103 -0
  126. package/templates/creative/carrossel-direitos/page-04.html +102 -0
  127. package/templates/creative/carrossel-direitos/page-05.html +102 -0
  128. package/templates/creative/carrossel-direitos/page-06.html +85 -0
  129. package/templates/creative/carrossel-direitos/preview.jpg +0 -0
  130. package/templates/creative/carrossel-direitos/template.json +8 -0
  131. package/templates/creative/carrossel-erros-iniciante/page-01.html +179 -0
  132. package/templates/creative/carrossel-erros-iniciante/page-02.html +187 -0
  133. package/templates/creative/carrossel-erros-iniciante/page-03.html +187 -0
  134. package/templates/creative/carrossel-erros-iniciante/page-04.html +182 -0
  135. package/templates/creative/carrossel-erros-iniciante/page-05.html +179 -0
  136. package/templates/creative/carrossel-erros-iniciante/preview.jpg +0 -0
  137. package/templates/creative/carrossel-erros-iniciante/template.json +8 -0
  138. package/templates/creative/carrossel-lancamento-planta/assets/img/exemplo-predio.jpg +0 -0
  139. package/templates/creative/carrossel-lancamento-planta/page-01.html +123 -0
  140. package/templates/creative/carrossel-lancamento-planta/page-02.html +121 -0
  141. package/templates/creative/carrossel-lancamento-planta/page-03.html +121 -0
  142. package/templates/creative/carrossel-lancamento-planta/page-04.html +122 -0
  143. package/templates/creative/carrossel-lancamento-planta/page-05.html +129 -0
  144. package/templates/creative/carrossel-lancamento-planta/page-06.html +111 -0
  145. package/templates/creative/carrossel-lancamento-planta/preview.jpg +0 -0
  146. package/templates/creative/carrossel-lancamento-planta/template.json +8 -0
  147. package/templates/creative/carrossel-lancamento-prato/assets/img/exemplo-burger-gourmet.jpg +0 -0
  148. package/templates/creative/carrossel-lancamento-prato/page-01.html +255 -0
  149. package/templates/creative/carrossel-lancamento-prato/page-02.html +256 -0
  150. package/templates/creative/carrossel-lancamento-prato/page-03.html +254 -0
  151. package/templates/creative/carrossel-lancamento-prato/page-04.html +255 -0
  152. package/templates/creative/carrossel-lancamento-prato/preview.jpg +0 -0
  153. package/templates/creative/carrossel-lancamento-prato/template.json +8 -0
  154. package/templates/creative/carrossel-perguntas-saude/page-01.html +108 -0
  155. package/templates/creative/carrossel-perguntas-saude/page-02.html +142 -0
  156. package/templates/creative/carrossel-perguntas-saude/page-03.html +142 -0
  157. package/templates/creative/carrossel-perguntas-saude/page-04.html +142 -0
  158. package/templates/creative/carrossel-perguntas-saude/page-05.html +112 -0
  159. package/templates/creative/carrossel-perguntas-saude/page-06.html +100 -0
  160. package/templates/creative/carrossel-perguntas-saude/preview.jpg +0 -0
  161. package/templates/creative/carrossel-perguntas-saude/template.json +8 -0
  162. package/templates/creative/carrossel-plano-anual/assets/img/exemplo-academia.jpg +0 -0
  163. package/templates/creative/carrossel-plano-anual/page-01.html +119 -0
  164. package/templates/creative/carrossel-plano-anual/page-02.html +140 -0
  165. package/templates/creative/carrossel-plano-anual/page-03.html +127 -0
  166. package/templates/creative/carrossel-plano-anual/page-04.html +129 -0
  167. package/templates/creative/carrossel-plano-anual/preview.jpg +0 -0
  168. package/templates/creative/carrossel-plano-anual/template.json +8 -0
  169. package/templates/creative/carrossel-servico-novo/assets/img/exemplo-sobrancelha.jpg +0 -0
  170. package/templates/creative/carrossel-servico-novo/page-01.html +110 -0
  171. package/templates/creative/carrossel-servico-novo/page-02.html +116 -0
  172. package/templates/creative/carrossel-servico-novo/page-03.html +105 -0
  173. package/templates/creative/carrossel-servico-novo/page-04.html +141 -0
  174. package/templates/creative/carrossel-servico-novo/preview.jpg +0 -0
  175. package/templates/creative/carrossel-servico-novo/template.json +8 -0
  176. package/templates/creative/cartao-fidelidade-carimbos/page-01.html +182 -0
  177. package/templates/creative/cartao-fidelidade-carimbos/page-02.html +114 -0
  178. package/templates/creative/cartao-fidelidade-carimbos/page-03.html +113 -0
  179. package/templates/creative/cartao-fidelidade-carimbos/preview.jpg +0 -0
  180. package/templates/creative/cartao-fidelidade-carimbos/template.json +8 -0
  181. package/templates/creative/chaves-entregues/assets/img/exemplo-casal-chave.jpg +0 -0
  182. package/templates/creative/chaves-entregues/page-01.html +135 -0
  183. package/templates/creative/chaves-entregues/preview.jpg +0 -0
  184. package/templates/creative/chaves-entregues/template.json +8 -0
  185. package/templates/creative/checklist-revisao-viagem/assets/img/exemplo-carro-elevador.jpg +0 -0
  186. package/templates/creative/checklist-revisao-viagem/page-01.html +201 -0
  187. package/templates/creative/checklist-revisao-viagem/page-02.html +202 -0
  188. package/templates/creative/checklist-revisao-viagem/page-03.html +202 -0
  189. package/templates/creative/checklist-revisao-viagem/page-04.html +202 -0
  190. package/templates/creative/checklist-revisao-viagem/page-05.html +200 -0
  191. package/templates/creative/checklist-revisao-viagem/page-06.html +200 -0
  192. package/templates/creative/checklist-revisao-viagem/preview.jpg +0 -0
  193. package/templates/creative/checklist-revisao-viagem/template.json +8 -0
  194. package/templates/creative/checklist-semanal-carrossel/page-01.html +142 -0
  195. package/templates/creative/checklist-semanal-carrossel/page-02.html +154 -0
  196. package/templates/creative/checklist-semanal-carrossel/page-03.html +154 -0
  197. package/templates/creative/checklist-semanal-carrossel/page-04.html +154 -0
  198. package/templates/creative/checklist-semanal-carrossel/page-05.html +154 -0
  199. package/templates/creative/checklist-semanal-carrossel/page-06.html +155 -0
  200. package/templates/creative/checklist-semanal-carrossel/preview.jpg +0 -0
  201. package/templates/creative/checklist-semanal-carrossel/template.json +8 -0
  202. package/templates/creative/citacao/page-01.html +81 -0
  203. package/templates/creative/citacao/preview.jpg +0 -0
  204. package/templates/creative/citacao/template.json +8 -0
  205. package/templates/creative/cliente-usando-produto/assets/img/exemplo-cliente-moletom.jpg +0 -0
  206. package/templates/creative/cliente-usando-produto/page-01.html +146 -0
  207. package/templates/creative/cliente-usando-produto/preview.jpg +0 -0
  208. package/templates/creative/cliente-usando-produto/template.json +8 -0
  209. package/templates/creative/combo-cafe-da-manha/assets/img/exemplo-cafe.jpg +0 -0
  210. package/templates/creative/combo-cafe-da-manha/page-01.html +220 -0
  211. package/templates/creative/combo-cafe-da-manha/preview.jpg +0 -0
  212. package/templates/creative/combo-cafe-da-manha/template.json +8 -0
  213. package/templates/creative/combo-dia-de-beleza/page-01.html +216 -0
  214. package/templates/creative/combo-dia-de-beleza/preview.jpg +0 -0
  215. package/templates/creative/combo-dia-de-beleza/template.json +8 -0
  216. package/templates/creative/combo-familia-entrega/assets/img/exemplo-mesa-burgers.jpg +0 -0
  217. package/templates/creative/combo-familia-entrega/page-01.html +146 -0
  218. package/templates/creative/combo-familia-entrega/preview.jpg +0 -0
  219. package/templates/creative/combo-familia-entrega/template.json +8 -0
  220. package/templates/creative/comparativo-tres-opcoes/page-01.html +184 -0
  221. package/templates/creative/comparativo-tres-opcoes/preview.jpg +0 -0
  222. package/templates/creative/comparativo-tres-opcoes/template.json +8 -0
  223. package/templates/creative/comprar-ou-alugar/page-01.html +100 -0
  224. package/templates/creative/comprar-ou-alugar/page-02.html +129 -0
  225. package/templates/creative/comprar-ou-alugar/page-03.html +131 -0
  226. package/templates/creative/comprar-ou-alugar/page-04.html +105 -0
  227. package/templates/creative/comprar-ou-alugar/page-05.html +94 -0
  228. package/templates/creative/comprar-ou-alugar/preview.jpg +0 -0
  229. package/templates/creative/comprar-ou-alugar/template.json +8 -0
  230. package/templates/creative/conheca-a-equipe/assets/img/exemplo-equipe.jpg +0 -0
  231. package/templates/creative/conheca-a-equipe/page-01.html +131 -0
  232. package/templates/creative/conheca-a-equipe/preview.jpg +0 -0
  233. package/templates/creative/conheca-a-equipe/template.json +8 -0
  234. package/templates/creative/consulta-gratuita-vagas/assets/img/exemplo-balanca-justica.jpg +0 -0
  235. package/templates/creative/consulta-gratuita-vagas/page-01.html +154 -0
  236. package/templates/creative/consulta-gratuita-vagas/preview.jpg +0 -0
  237. package/templates/creative/consulta-gratuita-vagas/template.json +8 -0
  238. package/templates/creative/contagem-prazo-final/page-01.html +152 -0
  239. package/templates/creative/contagem-prazo-final/preview.jpg +0 -0
  240. package/templates/creative/contagem-prazo-final/template.json +8 -0
  241. package/templates/creative/contagem-reveillon/assets/img/exemplo-piscina-noite.jpg +0 -0
  242. package/templates/creative/contagem-reveillon/page-01.html +170 -0
  243. package/templates/creative/contagem-reveillon/preview.jpg +0 -0
  244. package/templates/creative/contagem-reveillon/template.json +8 -0
  245. package/templates/creative/cupom-recortavel/page-01.html +164 -0
  246. package/templates/creative/cupom-recortavel/preview.jpg +0 -0
  247. package/templates/creative/cupom-recortavel/template.json +8 -0
  248. package/templates/creative/data-institucional/page-01.html +114 -0
  249. package/templates/creative/data-institucional/preview.jpg +0 -0
  250. package/templates/creative/data-institucional/template.json +8 -0
  251. package/templates/creative/depoimento/assets/img/exemplo-retrato.jpg +0 -0
  252. package/templates/creative/depoimento/page-01.html +112 -0
  253. package/templates/creative/depoimento/preview.jpg +0 -0
  254. package/templates/creative/depoimento/template.json +8 -0
  255. package/templates/creative/depoimento-familia-viagem/assets/img/exemplo-familia-praia.jpg +0 -0
  256. package/templates/creative/depoimento-familia-viagem/page-01.html +157 -0
  257. package/templates/creative/depoimento-familia-viagem/preview.jpg +0 -0
  258. package/templates/creative/depoimento-familia-viagem/template.json +8 -0
  259. package/templates/creative/depoimento-print-conversa/page-01.html +188 -0
  260. package/templates/creative/depoimento-print-conversa/preview.jpg +0 -0
  261. package/templates/creative/depoimento-print-conversa/template.json +8 -0
  262. package/templates/creative/desafio-30-dias/assets/img/exemplo-alunos-comemorando.jpg +0 -0
  263. package/templates/creative/desafio-30-dias/page-01.html +192 -0
  264. package/templates/creative/desafio-30-dias/preview.jpg +0 -0
  265. package/templates/creative/desafio-30-dias/template.json +8 -0
  266. package/templates/creative/dia-da-feira-hortifruti/assets/img/exemplo-frutas.webp +0 -0
  267. package/templates/creative/dia-da-feira-hortifruti/assets/img/exemplo-tomates.webp +0 -0
  268. package/templates/creative/dia-da-feira-hortifruti/page-01.html +209 -0
  269. package/templates/creative/dia-da-feira-hortifruti/preview.jpg +0 -0
  270. package/templates/creative/dia-da-feira-hortifruti/template.json +8 -0
  271. package/templates/creative/dica-rapida-story/page-01.html +128 -0
  272. package/templates/creative/dica-rapida-story/preview.jpg +0 -0
  273. package/templates/creative/dica-rapida-story/template.json +8 -0
  274. package/templates/creative/dicas-verao-pet/page-01.html +138 -0
  275. package/templates/creative/dicas-verao-pet/page-02.html +139 -0
  276. package/templates/creative/dicas-verao-pet/page-03.html +139 -0
  277. package/templates/creative/dicas-verao-pet/page-04.html +139 -0
  278. package/templates/creative/dicas-verao-pet/page-05.html +138 -0
  279. package/templates/creative/dicas-verao-pet/preview.jpg +0 -0
  280. package/templates/creative/dicas-verao-pet/template.json +8 -0
  281. package/templates/creative/drop-colecao-numerada/assets/img/exemplo-moletom.jpg +0 -0
  282. package/templates/creative/drop-colecao-numerada/page-01.html +208 -0
  283. package/templates/creative/drop-colecao-numerada/preview.jpg +0 -0
  284. package/templates/creative/drop-colecao-numerada/template.json +8 -0
  285. package/templates/creative/encarte-ofertas/assets/img/exemplo-cafe-pacote.webp +0 -0
  286. package/templates/creative/encarte-ofertas/assets/img/exemplo-frutas.webp +0 -0
  287. package/templates/creative/encarte-ofertas/assets/img/exemplo-queijo.webp +0 -0
  288. package/templates/creative/encarte-ofertas/assets/img/exemplo-tomates.webp +0 -0
  289. package/templates/creative/encarte-ofertas/page-01.html +154 -0
  290. package/templates/creative/encarte-ofertas/preview.jpg +0 -0
  291. package/templates/creative/encarte-ofertas/template.json +8 -0
  292. package/templates/creative/encomenda-bolo-tamanhos/assets/img/exemplo-bolo.webp +0 -0
  293. package/templates/creative/encomenda-bolo-tamanhos/page-01.html +158 -0
  294. package/templates/creative/encomenda-bolo-tamanhos/preview.jpg +0 -0
  295. package/templates/creative/encomenda-bolo-tamanhos/template.json +8 -0
  296. package/templates/creative/enquete-caixa-pergunta/page-01.html +122 -0
  297. package/templates/creative/enquete-caixa-pergunta/preview.jpg +0 -0
  298. package/templates/creative/enquete-caixa-pergunta/template.json +8 -0
  299. package/templates/creative/evento/assets/img/exemplo-evento.jpg +0 -0
  300. package/templates/creative/evento/page-01.html +122 -0
  301. package/templates/creative/evento/preview.jpg +0 -0
  302. package/templates/creative/evento/template.json +8 -0
  303. package/templates/creative/faixa-frete-gratis-site/page-01.html +159 -0
  304. package/templates/creative/faixa-frete-gratis-site/preview.jpg +0 -0
  305. package/templates/creative/faixa-frete-gratis-site/template.json +8 -0
  306. package/templates/creative/feira-adocao/assets/img/exemplo-filhote-caramelo.jpg +0 -0
  307. package/templates/creative/feira-adocao/page-01.html +182 -0
  308. package/templates/creative/feira-adocao/preview.jpg +0 -0
  309. package/templates/creative/feira-adocao/template.json +8 -0
  310. package/templates/creative/festa-junina-oferta/page-01.html +153 -0
  311. package/templates/creative/festa-junina-oferta/preview.jpg +0 -0
  312. package/templates/creative/festa-junina-oferta/template.json +8 -0
  313. package/templates/creative/ficha-imovel-preco/assets/img/exemplo-sala.jpg +0 -0
  314. package/templates/creative/ficha-imovel-preco/page-01.html +174 -0
  315. package/templates/creative/ficha-imovel-preco/preview.jpg +0 -0
  316. package/templates/creative/ficha-imovel-preco/template.json +8 -0
  317. package/templates/creative/garantia-refazemos/assets/img/exemplo-equipe.jpg +0 -0
  318. package/templates/creative/garantia-refazemos/page-01.html +175 -0
  319. package/templates/creative/garantia-refazemos/preview.jpg +0 -0
  320. package/templates/creative/garantia-refazemos/template.json +8 -0
  321. package/templates/creative/homenagem-dia-das-maes/assets/img/exemplo-flores.jpg +0 -0
  322. package/templates/creative/homenagem-dia-das-maes/page-01.html +103 -0
  323. package/templates/creative/homenagem-dia-das-maes/preview.jpg +0 -0
  324. package/templates/creative/homenagem-dia-das-maes/template.json +8 -0
  325. package/templates/creative/horario-especial-festas/page-01.html +134 -0
  326. package/templates/creative/horario-especial-festas/preview.jpg +0 -0
  327. package/templates/creative/horario-especial-festas/template.json +8 -0
  328. package/templates/creative/horarios-clinica-story/assets/img/exemplo-recepcao.jpg +0 -0
  329. package/templates/creative/horarios-clinica-story/page-01.html +145 -0
  330. package/templates/creative/horarios-clinica-story/preview.jpg +0 -0
  331. package/templates/creative/horarios-clinica-story/template.json +8 -0
  332. package/templates/creative/horarios-contados-agenda/assets/img/exemplo-unhas-nude.jpg +0 -0
  333. package/templates/creative/horarios-contados-agenda/page-01.html +167 -0
  334. package/templates/creative/horarios-contados-agenda/preview.jpg +0 -0
  335. package/templates/creative/horarios-contados-agenda/template.json +8 -0
  336. package/templates/creative/inauguracao-unidade/assets/img/exemplo-fachada.jpg +0 -0
  337. package/templates/creative/inauguracao-unidade/page-01.html +160 -0
  338. package/templates/creative/inauguracao-unidade/preview.jpg +0 -0
  339. package/templates/creative/inauguracao-unidade/template.json +8 -0
  340. package/templates/creative/indicacao-premiada-pix/page-01.html +169 -0
  341. package/templates/creative/indicacao-premiada-pix/preview.jpg +0 -0
  342. package/templates/creative/indicacao-premiada-pix/template.json +8 -0
  343. package/templates/creative/indique-e-ganhe-passos/page-01.html +115 -0
  344. package/templates/creative/indique-e-ganhe-passos/page-02.html +142 -0
  345. package/templates/creative/indique-e-ganhe-passos/page-03.html +161 -0
  346. package/templates/creative/indique-e-ganhe-passos/preview.jpg +0 -0
  347. package/templates/creative/indique-e-ganhe-passos/template.json +8 -0
  348. package/templates/creative/kit-presente-data/assets/img/exemplo-caixa-presente.jpg +0 -0
  349. package/templates/creative/kit-presente-data/page-01.html +208 -0
  350. package/templates/creative/kit-presente-data/preview.jpg +0 -0
  351. package/templates/creative/kit-presente-data/template.json +8 -0
  352. package/templates/creative/lancamento/assets/img/exemplo-cafe.jpg +0 -0
  353. package/templates/creative/lancamento/page-01.html +95 -0
  354. package/templates/creative/lancamento/preview.jpg +0 -0
  355. package/templates/creative/lancamento/template.json +8 -0
  356. package/templates/creative/lista-de-espera-banner/assets/img/exemplo-brigadeiros.jpg +0 -0
  357. package/templates/creative/lista-de-espera-banner/page-01.html +156 -0
  358. package/templates/creative/lista-de-espera-banner/preview.jpg +0 -0
  359. package/templates/creative/lista-de-espera-banner/template.json +8 -0
  360. package/templates/creative/look-do-dia-precos/assets/img/exemplo-look-streetwear.jpg +0 -0
  361. package/templates/creative/look-do-dia-precos/page-01.html +170 -0
  362. package/templates/creative/look-do-dia-precos/preview.jpg +0 -0
  363. package/templates/creative/look-do-dia-precos/template.json +8 -0
  364. package/templates/creative/mensagem-de-natal/page-01.html +161 -0
  365. package/templates/creative/mensagem-de-natal/preview.jpg +0 -0
  366. package/templates/creative/mensagem-de-natal/template.json +8 -0
  367. package/templates/creative/mito-ou-verdade/page-01.html +160 -0
  368. package/templates/creative/mito-ou-verdade/preview.jpg +0 -0
  369. package/templates/creative/mito-ou-verdade/template.json +8 -0
  370. package/templates/creative/mudanca-endereco-banner/assets/img/exemplo-recepcao-espelhos.jpg +0 -0
  371. package/templates/creative/mudanca-endereco-banner/page-01.html +140 -0
  372. package/templates/creative/mudanca-endereco-banner/preview.jpg +0 -0
  373. package/templates/creative/mudanca-endereco-banner/template.json +8 -0
  374. package/templates/creative/natal-pet-foto/page-01.html +168 -0
  375. package/templates/creative/natal-pet-foto/preview.jpg +0 -0
  376. package/templates/creative/natal-pet-foto/template.json +8 -0
  377. package/templates/creative/novidades-emporio-carrossel/assets/img/exemplo-cafe-pacote.webp +0 -0
  378. package/templates/creative/novidades-emporio-carrossel/assets/img/exemplo-queijo.webp +0 -0
  379. package/templates/creative/novidades-emporio-carrossel/page-01.html +155 -0
  380. package/templates/creative/novidades-emporio-carrossel/page-02.html +163 -0
  381. package/templates/creative/novidades-emporio-carrossel/page-03.html +163 -0
  382. package/templates/creative/novidades-emporio-carrossel/page-04.html +108 -0
  383. package/templates/creative/novidades-emporio-carrossel/preview.jpg +0 -0
  384. package/templates/creative/novidades-emporio-carrossel/template.json +8 -0
  385. package/templates/creative/oferta-parcelada-discreta/page-01.html +176 -0
  386. package/templates/creative/oferta-parcelada-discreta/preview.jpg +0 -0
  387. package/templates/creative/oferta-parcelada-discreta/template.json +8 -0
  388. package/templates/creative/open-house-convite/assets/img/exemplo-casa.jpg +0 -0
  389. package/templates/creative/open-house-convite/page-01.html +173 -0
  390. package/templates/creative/open-house-convite/preview.jpg +0 -0
  391. package/templates/creative/open-house-convite/template.json +8 -0
  392. package/templates/creative/orcamento-em-minutos/assets/img/exemplo-mecanico.jpg +0 -0
  393. package/templates/creative/orcamento-em-minutos/page-01.html +170 -0
  394. package/templates/creative/orcamento-em-minutos/preview.jpg +0 -0
  395. package/templates/creative/orcamento-em-minutos/template.json +8 -0
  396. package/templates/creative/orcamento-por-foto/assets/img/exemplo-sala.jpg +0 -0
  397. package/templates/creative/orcamento-por-foto/page-01.html +175 -0
  398. package/templates/creative/orcamento-por-foto/preview.jpg +0 -0
  399. package/templates/creative/orcamento-por-foto/template.json +8 -0
  400. package/templates/creative/pacote-feriado-pousada/assets/img/exemplo-pousada.jpg +0 -0
  401. package/templates/creative/pacote-feriado-pousada/page-01.html +194 -0
  402. package/templates/creative/pacote-feriado-pousada/preview.jpg +0 -0
  403. package/templates/creative/pacote-feriado-pousada/template.json +8 -0
  404. package/templates/creative/pacote-ultimos-quartos/assets/img/exemplo-festa.jpg +0 -0
  405. package/templates/creative/pacote-ultimos-quartos/page-01.html +208 -0
  406. package/templates/creative/pacote-ultimos-quartos/preview.jpg +0 -0
  407. package/templates/creative/pacote-ultimos-quartos/template.json +8 -0
  408. package/templates/creative/parcela-em-destaque/assets/img/exemplo-tenis.webp +0 -0
  409. package/templates/creative/parcela-em-destaque/page-01.html +144 -0
  410. package/templates/creative/parcela-em-destaque/preview.jpg +0 -0
  411. package/templates/creative/parcela-em-destaque/template.json +8 -0
  412. package/templates/creative/parceria-duas-marcas/assets/img/exemplo-aperto-mao.jpg +0 -0
  413. package/templates/creative/parceria-duas-marcas/page-01.html +169 -0
  414. package/templates/creative/parceria-duas-marcas/preview.jpg +0 -0
  415. package/templates/creative/parceria-duas-marcas/template.json +8 -0
  416. package/templates/creative/pequenos-reparos-banner/assets/img/exemplo-torneira-reparo.jpg +0 -0
  417. package/templates/creative/pequenos-reparos-banner/page-01.html +115 -0
  418. package/templates/creative/pequenos-reparos-banner/preview.jpg +0 -0
  419. package/templates/creative/pequenos-reparos-banner/template.json +8 -0
  420. package/templates/creative/pergunta/page-01.html +126 -0
  421. package/templates/creative/pergunta/preview.jpg +0 -0
  422. package/templates/creative/pergunta/template.json +8 -0
  423. package/templates/creative/pergunta-do-seguidor/page-01.html +132 -0
  424. package/templates/creative/pergunta-do-seguidor/preview.jpg +0 -0
  425. package/templates/creative/pergunta-do-seguidor/template.json +8 -0
  426. package/templates/creative/pneus-black-friday-banner/assets/img/exemplo-pneus.jpg +0 -0
  427. package/templates/creative/pneus-black-friday-banner/page-01.html +141 -0
  428. package/templates/creative/pneus-black-friday-banner/preview.jpg +0 -0
  429. package/templates/creative/pneus-black-friday-banner/template.json +8 -0
  430. package/templates/creative/prazo-imposto-renda/page-01.html +196 -0
  431. package/templates/creative/prazo-imposto-renda/preview.jpg +0 -0
  432. package/templates/creative/prazo-imposto-renda/template.json +8 -0
  433. package/templates/creative/produto-destaque/assets/img/exemplo-produto.webp +0 -0
  434. package/templates/creative/produto-destaque/page-01.html +129 -0
  435. package/templates/creative/produto-destaque/preview.jpg +0 -0
  436. package/templates/creative/produto-destaque/template.json +8 -0
  437. package/templates/creative/projeto-verao-semanas/assets/img/exemplo-kettlebell.jpg +0 -0
  438. package/templates/creative/projeto-verao-semanas/page-01.html +168 -0
  439. package/templates/creative/projeto-verao-semanas/preview.jpg +0 -0
  440. package/templates/creative/projeto-verao-semanas/template.json +8 -0
  441. package/templates/creative/promo-relampago-delivery/assets/img/exemplo-hamburguer.jpg +0 -0
  442. package/templates/creative/promo-relampago-delivery/page-01.html +198 -0
  443. package/templates/creative/promo-relampago-delivery/preview.jpg +0 -0
  444. package/templates/creative/promo-relampago-delivery/template.json +8 -0
  445. package/templates/creative/promocao/assets/img/exemplo-tenis.webp +0 -0
  446. package/templates/creative/promocao/page-01.html +167 -0
  447. package/templates/creative/promocao/preview.jpg +0 -0
  448. package/templates/creative/promocao/template.json +8 -0
  449. package/templates/creative/queima-de-estoque/page-01.html +182 -0
  450. package/templates/creative/queima-de-estoque/preview.jpg +0 -0
  451. package/templates/creative/queima-de-estoque/template.json +8 -0
  452. package/templates/creative/resultado-aluno-numeros/page-01.html +173 -0
  453. package/templates/creative/resultado-aluno-numeros/preview.jpg +0 -0
  454. package/templates/creative/resultado-aluno-numeros/template.json +8 -0
  455. package/templates/creative/resultado-com-aviso/assets/img/exemplo-sorriso.jpg +0 -0
  456. package/templates/creative/resultado-com-aviso/page-01.html +145 -0
  457. package/templates/creative/resultado-com-aviso/preview.jpg +0 -0
  458. package/templates/creative/resultado-com-aviso/template.json +8 -0
  459. package/templates/creative/roteiro-um-dia-carrossel/assets/img/exemplo-praia-espelho.jpg +0 -0
  460. package/templates/creative/roteiro-um-dia-carrossel/assets/img/exemplo-vila-trancoso.jpg +0 -0
  461. package/templates/creative/roteiro-um-dia-carrossel/page-01.html +119 -0
  462. package/templates/creative/roteiro-um-dia-carrossel/page-02.html +123 -0
  463. package/templates/creative/roteiro-um-dia-carrossel/page-03.html +125 -0
  464. package/templates/creative/roteiro-um-dia-carrossel/page-04.html +125 -0
  465. package/templates/creative/roteiro-um-dia-carrossel/page-05.html +140 -0
  466. package/templates/creative/roteiro-um-dia-carrossel/preview.jpg +0 -0
  467. package/templates/creative/roteiro-um-dia-carrossel/template.json +8 -0
  468. package/templates/creative/selo-garantia-7-dias/page-01.html +158 -0
  469. package/templates/creative/selo-garantia-7-dias/preview.jpg +0 -0
  470. package/templates/creative/selo-garantia-7-dias/template.json +8 -0
  471. package/templates/creative/sorteio-aniversario/page-01.html +224 -0
  472. package/templates/creative/sorteio-aniversario/preview.jpg +0 -0
  473. package/templates/creative/sorteio-aniversario/template.json +8 -0
  474. package/templates/creative/story-contagem/assets/img/exemplo-pizza.jpg +0 -0
  475. package/templates/creative/story-contagem/page-01.html +135 -0
  476. package/templates/creative/story-contagem/preview.jpg +0 -0
  477. package/templates/creative/story-contagem/template.json +8 -0
  478. package/templates/creative/story-oferta/assets/img/exemplo-fundo-story.jpg +0 -0
  479. package/templates/creative/story-oferta/assets/img/exemplo-produto.webp +0 -0
  480. package/templates/creative/story-oferta/page-01.html +119 -0
  481. package/templates/creative/story-oferta/preview.jpg +0 -0
  482. package/templates/creative/story-oferta/template.json +8 -0
  483. package/templates/creative/tabela-banho-tosa/assets/img/exemplo-shihtzu.webp +0 -0
  484. package/templates/creative/tabela-banho-tosa/page-01.html +171 -0
  485. package/templates/creative/tabela-banho-tosa/preview.jpg +0 -0
  486. package/templates/creative/tabela-banho-tosa/template.json +8 -0
  487. package/templates/creative/tabela-planos-academia/page-01.html +187 -0
  488. package/templates/creative/tabela-planos-academia/preview.jpg +0 -0
  489. package/templates/creative/tabela-planos-academia/template.json +8 -0
  490. package/templates/creative/tabela-precos-servicos/page-01.html +192 -0
  491. package/templates/creative/tabela-precos-servicos/preview.jpg +0 -0
  492. package/templates/creative/tabela-precos-servicos/template.json +8 -0
  493. package/templates/creative/temporada-reservas-banner/assets/img/exemplo-praia.jpg +0 -0
  494. package/templates/creative/temporada-reservas-banner/page-01.html +148 -0
  495. package/templates/creative/temporada-reservas-banner/preview.jpg +0 -0
  496. package/templates/creative/temporada-reservas-banner/template.json +8 -0
  497. package/templates/creative/troca-facil-passos/page-01.html +109 -0
  498. package/templates/creative/troca-facil-passos/page-02.html +107 -0
  499. package/templates/creative/troca-facil-passos/page-03.html +107 -0
  500. package/templates/creative/troca-facil-passos/page-04.html +106 -0
  501. package/templates/creative/troca-facil-passos/preview.jpg +0 -0
  502. package/templates/creative/troca-facil-passos/template.json +8 -0
  503. package/templates/creative/troca-oleo-preco/assets/img/exemplo-galao-oleo.webp +0 -0
  504. package/templates/creative/troca-oleo-preco/page-01.html +178 -0
  505. package/templates/creative/troca-oleo-preco/preview.jpg +0 -0
  506. package/templates/creative/troca-oleo-preco/template.json +8 -0
  507. package/templates/creative/ultimas-vagas-mentoria/assets/img/exemplo-retrato.jpg +0 -0
  508. package/templates/creative/ultimas-vagas-mentoria/page-01.html +140 -0
  509. package/templates/creative/ultimas-vagas-mentoria/preview.jpg +0 -0
  510. package/templates/creative/ultimas-vagas-mentoria/template.json +8 -0
  511. package/templates/creative/vaga-emprego-funcoes/page-01.html +178 -0
  512. package/templates/creative/vaga-emprego-funcoes/preview.jpg +0 -0
  513. package/templates/creative/vaga-emprego-funcoes/template.json +8 -0
  514. package/templates/creative/voltou-ao-estoque/assets/img/exemplo-produto.webp +0 -0
  515. package/templates/creative/voltou-ao-estoque/page-01.html +155 -0
  516. package/templates/creative/voltou-ao-estoque/preview.jpg +0 -0
  517. package/templates/creative/voltou-ao-estoque/template.json +8 -0
  518. package/templates/creative/voucher-presente/assets/img/exemplo-voucher-flor.jpg +0 -0
  519. package/templates/creative/voucher-presente/page-01.html +181 -0
  520. package/templates/creative/voucher-presente/preview.jpg +0 -0
  521. package/templates/creative/voucher-presente/template.json +8 -0
@@ -0,0 +1,117 @@
1
+ import{a as e}from"./rolldown-runtime-B0Z9INg1.js";import{t}from"./__vite-browser-external-CV6URZNE.js";function n(e){if(!e)throw Error(`Assertion failed.`)}var r=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},i=e=>e&&e[e.length-1],a=e=>e>=0&&e<2**32,o=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},s=e=>{let t=o(e);return t&1?t+1>>1:-(t>>1)},c=(e,t,n,r)=>{for(let i=t;i<n;i++){let t=Math.floor(i/8),a=e[t],o=7-(i&7);a&=~(1<<o),a|=(r&1<<n-i-1)>>n-i-1<<o,e[t]=a}},l=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),u=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),d=new TextDecoder,f=new TextEncoder,p=e=>{for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0},m=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),h={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},g=m(h),_={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},v=m(_),y={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},b=m(y),x=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,S=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),C=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},ee=/^[0-9a-fA-F]+$/,te=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),ne=e=>{n(e.length%2==0);let t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.slice(n,n+2),16);return t},re=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),ie=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},w=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},ae=(e,t,n)=>{let r=w(e,n(t),n);e.splice(r+1,0,t)},T=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},oe=(e,t)=>{let n=e.indexOf(t);n!==-1&&e.splice(n,1)},se=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},ce=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},le=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},ue=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},E=e=>{throw Error(`Unexpected value: ${e}`)},de=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},fe=(e,t,n)=>de(e,t,n)<<8>>8,pe=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},me=(e,t,n,r)=>{n=D(n,-8388608,8388607),n<0&&(n=n+16777216&16777215),pe(e,t,n,r)},he=(e,t,n,r)=>{r?(e.setUint32(t+0,n,!0),e.setInt32(t+4,Math.floor(n/2**32),!0)):(e.setInt32(t+0,Math.floor(n/2**32),!0),e.setUint32(t+4,n,!0))},ge=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return(){return e.return()},throw(t){return e.throw(t)},[Symbol.asyncIterator](){return this}}),D=(e,t,n)=>Math.max(t,Math.min(n,e)),_e=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},ve=(e,t)=>Math.round(e/t)*t,ye=(e,t)=>Math.round(e*t)/t,be=(e,t)=>Math.floor(e/t)*t,xe=(e,t)=>Math.floor(e*t)/t,Se=e=>{let t=0;for(;e;)t++,e>>=1;return t},Ce=/^[a-z]{3}$/,we=e=>Ce.test(e),Te=1e6*(1+2**-52),Ee=(e,t)=>{let n={...e,...t};if(e.headers||t.headers){let r=e.headers?De(e.headers):{},i=t.headers?De(t.headers):{},a={...r};Object.entries(i).forEach(([e,t])=>{let n=Object.keys(a).find(t=>t.toLowerCase()===e.toLowerCase());n&&delete a[n],a[e]=t}),n.headers=a}return n},De=e=>{if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}if(Array.isArray(e)){let t={};return e.forEach(([e,n])=>{t[e]=n}),t}return e},Oe=async(e,t,n,r,i)=>{let a=0;for(;;)try{return await e(t,n)}catch(e){if(i())throw e;a++;let n=r(a,e,t);if(n===null)throw e;if(console.error(`Retrying failed fetch. Error:`,e),!Number.isFinite(n)||n<0)throw TypeError(`Retry delay must be a non-negative finite number.`);if(n>0&&await ct(1e3*n),i())throw e}},ke=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{num:n*a,den:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{num:n*a,den:o}},Ae=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},je=null,Me=()=>je===null?je=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):je,Ne=null,Pe=()=>Ne===null?Ne=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):Ne,Fe=null,Ie=()=>Fe===null?Fe=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):Fe,Le=null,Re=()=>{if(Le!==null)return Le;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?Le=Number(e[1]):null},ze=(e,t)=>e===-1?t:e,Be=(e,t,n,r)=>e<=r&&n<=t,Ve=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},He=e=>{switch(e.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}},Ue=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},We=e=>{let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)},Ge=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},Ke=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},qe=e=>typeof e==`number`&&!Number.isNaN(e),O=(e,t)=>{if(t.includes(`://`))return t;if(e.includes(`://`)){let t=e.indexOf(`?`);t!==-1&&(e=e.slice(0,t))}let n;if(t.startsWith(`/`)){let r=e.indexOf(`://`);if(r===-1)n=t;else{let i=e.indexOf(`/`,r+3);n=i===-1?e+t:e.slice(0,i)+t}}else{let r=e.lastIndexOf(`/`);n=r===-1?t:e.slice(0,r+1)+t}let r=``,i=n.indexOf(`://`);if(i!==-1){let e=n.indexOf(`/`,i+3);e!==-1&&(r=n.slice(0,e),n=n.slice(e))}let a=n.split(`/`),o=[];for(let e of a)e===`..`?o.pop():e!==`.`&&o.push(e);return r+o.join(`/`)},Je=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)t(e[r])&&n++;return n},Ye=(e,t)=>{let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a<r&&(r=a,n=i)}return n},Xe=(e,t)=>{let n=-1,r=-1/0;for(let i=0;i<e.length;i++){let a=t(e[i]);a>r&&(r=a,n=i)}return n},Ze=e=>{n(Number.isInteger(e.num)),n(Number.isInteger(e.den)),n(e.den!==0);let t=Math.abs(e.num),r=Math.abs(e.den);for(;r!==0;){let e=t%r;t=r,r=e}let i=t||1;return{num:e.num/i,den:e.den/i}},Qe=(e,t)=>{if(typeof e!=`object`||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},$e,et=1,tt=new Map,nt=new Map,rt=()=>typeof window>`u`,it=()=>{let e=new Map,t=new Map;self.onmessage=n=>{let r=n.data;switch(r.type){case`set-timeout`:{let t=setTimeout(()=>{e.delete(r.timerId),self.postMessage({type:`fire`,timerId:r.timerId})},r.delay);e.set(r.timerId,t)}break;case`set-interval`:{let e=setInterval(()=>{self.postMessage({type:`fire`,timerId:r.timerId})},r.delay);t.set(r.timerId,e)}break;case`clear-timeout`:{let t=e.get(r.timerId);t!==void 0&&(clearTimeout(t),e.delete(r.timerId))}break;case`clear-interval`:{let e=t.get(r.timerId);e!==void 0&&(clearInterval(e),t.delete(r.timerId))}}}},at=()=>{if($e)return $e;let e=`(${it.toString()})();`,t=URL.createObjectURL(new Blob([e],{type:`text/javascript`}));return $e=new Worker(t),URL.revokeObjectURL(t),$e.onmessage=e=>{let t=e.data,n=tt.get(t.timerId);if(n){tt.delete(t.timerId),n();return}let r=nt.get(t.timerId);r&&r()},$e},ot=(e,t)=>{if(rt())return{id:setInterval(e,t)};let n=et++;return nt.set(n,()=>{e()}),at().postMessage({type:`set-interval`,timerId:n,delay:t}),{id:n}},st=e=>{if(rt()){clearInterval(e.id);return}n(typeof e.id==`number`),nt.delete(e.id),at().postMessage({type:`clear-interval`,timerId:e.id})},ct=e=>new Promise(t=>setTimeout(t,e)),lt=e=>Array.isArray(e)?e:[e],ut=class{constructor(){this._listeners=new Map}on(e,t,n){this._listeners.has(e)||this._listeners.set(e,new Set);let r={fn:t,once:n?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,n]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(n)}catch(e){console.error(e)}e.once&&r.delete(e)}}},dt=e=>Math.ceil(e/2)*2,ft=class{constructor(e){this._queue=[],this._errored=!1,this.parallelism=e}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(e){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);let t=e();this._queue.push(t),t.then(()=>oe(this._queue,t)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}},pt=e=>typeof e==`object`&&!!e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>typeof e==`string`),mt=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},ht=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},gt=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(t instanceof Uint8Array)&&!(t instanceof mt)&&!(t instanceof ht)&&!pt(t))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.`)}},_t=e=>e.title===void 0&&e.description===void 0&&e.artist===void 0&&e.album===void 0&&e.albumArtist===void 0&&e.trackNumber===void 0&&e.tracksTotal===void 0&&e.discNumber===void 0&&e.discsTotal===void 0&&e.genre===void 0&&e.date===void 0&&e.lyrics===void 0&&(!e.images||e.images.length===0)&&e.comment===void 0&&(e.raw===void 0||Object.keys(e.raw).length===0),vt={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},yt=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.primary!==void 0&&typeof e.primary!=`boolean`)throw TypeError(`disposition.primary must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},k=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let 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(){let t=new e(this.bytes);return t.pos=this.pos,t}},bt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],xt=[-1,1,2,3,4,5,6,8],St=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new k(e),n=t.readBits(5);n===31&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;r===15?i=t.readBits(24):r<bt.length&&(i=bt[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=xt[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},Ct=e=>{let t=bt.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=xt.indexOf(e.numberOfChannels);if(r===-1)throw TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let i=13;e.objectType>=32&&(i+=6),t===15&&(i+=24);let a=Math.ceil(i/8),o=new Uint8Array(a),s=new k(o);return e.objectType<32?s.writeBits(5,e.objectType):(s.writeBits(5,31),s.writeBits(6,e.objectType-32)),s.writeBits(4,t),t===15&&s.writeBits(24,n),s.writeBits(4,r),o},wt=e=>{let t=new Uint8Array(7),n=new k(t),{objectType:r,frequencyIndex:i,channelConfiguration:a}=e,o=r-1;return n.writeBits(12,4095),n.writeBits(1,0),n.writeBits(2,0),n.writeBits(1,1),n.writeBits(2,o),n.writeBits(4,i),n.writeBits(1,0),n.writeBits(3,a),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(1,0),n.skipBits(13),n.writeBits(11,2047),n.writeBits(2,0),{header:t,bitstream:n}},Tt=(e,t)=>{e.pos=30,e.writeBits(13,t)},A=[`avc`,`hevc`,`vp9`,`av1`,`vp8`],j=[`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`],Et=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`],M=[...Et,...j],Dt=[`webvtt`],Ot=[{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}],kt=[{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}],At=[{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}],jt=[{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}],Mt=`.01.01.01.01.00`,Nt=`.0.110.01.01.01.0`,Pt=(e,t,n,r)=>{if(e===`avc`){let e=Math.ceil(t/16)*Math.ceil(n/16),a=Ot.find(t=>e<=t.maxMacroblocks&&r<=t.maxBitrate)??i(Ot),o=a?a.level:0;return`avc1.${`64`.padStart(2,`0`)}00${o.toString(16).padStart(2,`0`)}`}if(e===`hevc`){let e=t*n,a=kt.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??i(kt);return`hev1.1.6.${a.tier}${a.level}.B0`}if(e===`vp8`)return`vp8`;if(e===`vp9`){let e=t*n;return`vp09.00.${(At.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??i(At)).level.toString().padStart(2,`0`)}.08`}if(e===`av1`){let e=t*n,a=jt.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??i(jt);return`av01.0.${a.level.toString().padStart(2,`0`)}${a.tier}.08`}throw TypeError(`Unhandled codec '${e}'.`)},Ft=e=>{let t=e.split(`.`);return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},It=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=+(r.slice(-1)===`H`),s=Number(t[3])===8?0:1,c=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1,u=t[5]?Number(t[5][1]):1,d=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(s<<6)+0+(c<<4)+(l<<3)+(u<<2)+d,0]},Lt=e=>{let{codec:t,codecDescription:r,colorSpace:a,avcCodecInfo:o,hevcCodecInfo:s,vp9CodecInfo:c,av1CodecInfo:l}=e;if(t===`avc`){if(n(e.avcType!==null),o){let t=new Uint8Array([o.avcProfileIndication,o.profileCompatibility,o.avcLevelIndication]);return`avc${e.avcType}.${te(t)}`}if(!r||r.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${te(r.subarray(1,4))}`}if(t===`hevc`){let e,t,n,i,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,n=re(s.generalProfileCompatibilityFlags),i=s.generalTierFlag,a=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let s=u(r),c=s.getUint8(1);e=c>>6&3,t=c&31,n=re(s.getUint32(2)),i=c>>5&1,a=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=n.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=a;o.length>0&&o[o.length-1]===0;)o.pop();return o.length>0&&(c+=`.`,c+=o.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}if(t===`vp8`)return`vp8`;if(t===`vp9`){if(!c){let t=e.width*e.height,n=i(At).level;for(let e of At)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=c.profile.toString().padStart(2,`0`),n=c.level.toString().padStart(2,`0`),r=c.bitDepth.toString().padStart(2,`0`),a=c.chromaSubsampling.toString().padStart(2,`0`),o=c.colourPrimaries.toString().padStart(2,`0`),s=c.transferCharacteristics.toString().padStart(2,`0`),l=c.matrixCoefficients.toString().padStart(2,`0`),u=c.videoFullRangeFlag.toString().padStart(2,`0`),d=`vp09.${t}.${n}.${r}.${a}`;return d+=`.${o}.${s}.${l}.${u}`,d.endsWith(Mt)&&(d=d.slice(0,-15)),d}if(t===`av1`){if(!l){let t=e.width*e.height,n=i(At).level;for(let e of At)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=l.profile,n=l.level.toString().padStart(2,`0`),r=l.tier?`H`:`M`,o=l.bitDepth.toString().padStart(2,`0`),s=l.monochrome?`1`:`0`,c=100*l.chromaSubsamplingX+10*l.chromaSubsamplingY+1*(l.chromaSubsamplingX&&l.chromaSubsamplingY?l.chromaSamplePosition:0),u=a?.primaries?h[a.primaries]:1,d=a?.transfer?_[a.transfer]:1,f=a?.matrix?y[a.matrix]:1,p=+!!a?.fullRange,m=`av01.${t}.${n}${r}.${o}`;return m+=`.${s}.${c.toString().padStart(3,`0`)}`,m+=`.${u.toString().padStart(2,`0`)}`,m+=`.${d.toString().padStart(2,`0`)}`,m+=`.${f.toString().padStart(2,`0`)}`,m+=`.${p}`,m.endsWith(Nt)&&(m=m.slice(0,-17)),m}throw TypeError(`Unhandled codec '${t}'.`)},Rt=(e,t,n)=>{if(e===`aac`)return t>=2&&n<=24e3?`mp4a.40.29`:n<=24e3?`mp4a.40.5`:`mp4a.40.2`;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(j.includes(e))return e;throw TypeError(`Unhandled codec '${e}'.`)},zt=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?St(n).objectType:r.objectType,`mp4a.40.${e}`}}if(t===`mp3`)return`mp3`;if(t===`opus`)return`opus`;if(t===`vorbis`)return`vorbis`;if(t===`flac`)return`flac`;if(t===`ac3`)return`ac-3`;if(t===`eac3`)return`ec-3`;if(t&&j.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},Bt=e=>{switch(e.codec){case`flac`:{let t=Ue(`ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw`);return e.sampleRate>=1<<20||e.numberOfChannels>8?!1:(t[18]=e.sampleRate>>>12,t[19]=e.sampleRate>>>4,t[20]=(e.sampleRate&15)<<4|e.numberOfChannels-1<<1,t)}case`vorbis`:{let t=Ue(`Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA==`),n=u(t);return n.setUint8(15,e.numberOfChannels),n.setUint32(16,e.sampleRate,!0),t}default:return}},Vt=48e3,Ht=/^pcm-([usf])(\d+)(be)?$/,Ut=e=>{if(n(j.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=Ht.exec(e);n(t);let r;r=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let i=Number(t[2])/8,a=t[3]!==`be`;return{dataType:r,sampleSize:i,littleEndian:a,silentValue:e===`pcm-u8`?2**7:0}},Wt=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`||e===`mp4a.40.34`?`mp3`:e.startsWith(`mp4a.40.`)||e===`mp4a.67`?`aac`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:Ht.test(e)?e:e===`webvtt`?`webvtt`:null,Gt=e=>e===`avc`?{avc:{format:`avc`}}:e===`hevc`?{hevc:{format:`hevc`}}:{},Kt=e=>e===`aac`?{aac:{format:`aac`}}:e===`opus`?{opus:{format:`opus`}}:{},qt=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`],Jt=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Yt=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Xt=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Zt=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Qt=e=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!qt.some(t=>e.decoderConfig.codec.startsWith(t)))throw 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(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError(`Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.`);if(e.decoderConfig.displayAspectWidth!==void 0!=(e.decoderConfig.displayAspectHeight!==void 0))throw TypeError(`Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.`);if(e.decoderConfig.description!==void 0&&!S(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(h);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(_);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(y);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!Jt.test(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!Yt.test(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!Xt.test(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`av01`)&&!Zt.test(e.decoderConfig.codec))throw 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/.`)},$t=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`],en=e=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!$t.some(t=>e.decoderConfig.codec.startsWith(t)))throw 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(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!S(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw 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(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw 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(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw 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(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw 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(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!j.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${j.join(`, `)}).`)},tn=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},nn=[44100,48e3,32e3],rn=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],an=1483304551,on=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,sn=(e,t,n,r)=>t===0?0:t===1?144*n/(r<<e):t===2?144*n/r:12*n/r*4,cn=(e,t)=>e===3?t===3?21:36:t===3?13:21,ln=(e,t)=>{let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=rn[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=nn[d]>>o+s,x=on(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,lowSamplingFrequency:o,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},un=e=>{let t=127,n=0,r=e;for(;t^2147483647;)n=r&~t,n<<=1,n|=r&t,t=(t+1<<8)-1,r=n;return n},dn=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n},fn;(function(e){e[e.FrameCount=1]=`FrameCount`,e[e.FileSize=2]=`FileSize`,e[e.Toc=4]=`Toc`})(fn||={});var pn=e=>e===3?1:2,mn=[48e3,44100,32e3],hn=[24e3,22050,16e3],gn;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(gn||={});var N;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(N||={});var _n=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},vn=function*(e,t){let r=0,i=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;r+t<=e.length;){let e;t===1?e=i.getUint8(r):t===2?e=i.getUint16(r,!1):t===3?e=de(i,r,!1):(n(t===4),e=i.getUint32(r,!1)),r+=t,yield{offset:r,length:e},r+=e}},yn=(e,t)=>t.description?vn(e,(l(t.description)[4]&3)+1):_n(e),bn=e=>e&31,xn=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},Sn=new Uint8Array([0,0,0,1]),Cn=e=>{let t=e.reduce((e,t)=>e+Sn.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(Sn,r),r+=Sn.byteLength,n.set(t,r),r+=t.byteLength;return n},wn=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:pe(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1)}i+=t,r.set(n,i),i+=n.byteLength}return r},Tn=(e,t)=>t.description?wn(e,(l(t.description)[4]&3)+1):Cn(e),En=e=>{try{let t=[],r=[],i=[];for(let n of _n(e)){let a=e.subarray(n.offset,n.offset+n.length),o=bn(a[0]);o===gn.SPS?t.push(a):o===gn.PPS?r.push(a):o===gn.SPS_EXT&&i.push(a)}if(t.length===0||r.length===0)return null;let a=t[0],o=An(a);n(o!==null);let s=o.profileIdc===100||o.profileIdc===110||o.profileIdc===122||o.profileIdc===144;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:s?o.chromaFormatIdc:null,bitDepthLumaMinus8:s?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:s?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:s?i:null}}catch(e){return console.error(`Error building AVC Decoder Configuration Record:`,e),null}},Dn=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if(e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144){n(e.chromaFormat!==null),n(e.bitDepthLumaMinus8!==null),n(e.bitDepthChromaMinus8!==null),n(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},On=e=>{try{let t=u(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let d=t.getUint8(n++),f=[];for(let r=0;r<d;r++){let r=t.getUint16(n,!1);n+=2,f.push(e.subarray(n,n+r)),n+=r}let p={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:f,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);p.chromaFormat=r,p.bitDepthLumaMinus8=i,p.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}p.sequenceParameterSetExt=s}return p}catch(e){return console.error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},kn={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}},An=e=>{try{let t=new k(xn(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let r=t.readAlignedByte(),a=t.readAlignedByte(),c=t.readAlignedByte();o(t);let l=1,u=0,d=0,f=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(l=o(t),l===3&&(f=t.readBits(1)),u=o(t),d=o(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(l===3?12:8);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(i!==0){let e=s(t);i=(r+e+256)%256}r=i===0?r:i}}}o(t);let p=o(t);if(p===0)o(t);else if(p===1){t.skipBits(1),s(t),s(t);let e=o(t);for(let n=0;n<e;n++)s(t)}o(t),t.skipBits(1);let m=o(t),h=o(t),g=16*(m+1),_=16*(h+1),v=g,y=_,b=t.readBits(1);if(b||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e=o(t),n=o(t),r=o(t),i=o(t),a,s;if((f===0?l:0)===0)a=1,s=2-b;else{let e=l===3?1:2,t=l===1?2:1;a=e,s=t*(2-b)}v-=a*(e+n),y-=s*(r+i)}let x=2,S=2,C=2,ee=0,te={num:1,den:1},ne=null,re=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(e===255)te={num:t.readBits(16),den:t.readBits(16)};else{let t=kn[e];t&&(te=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),ee=t.readBits(1),t.readBits(1)&&(x=t.readBits(8),S=t.readBits(8),C=t.readBits(8))),t.readBits(1)&&(o(t),o(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&jn(t);let n=t.readBits(1);n&&jn(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),o(t),o(t),o(t),o(t),ne=o(t),re=o(t))}if(ne===null){n(re===null);let e=a&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&e)ne=0,re=0;else{let e=m+1,t=h+1,n=(2-b)*t,r=Ot.find(e=>e.level>=c)??i(Ot),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);ne=a,re=a}}return n(re!==null),{profileIdc:r,constraintFlags:a,levelIdc:c,frameMbsOnlyFlag:b,chromaFormatIdc:l,bitDepthLumaMinus8:u,bitDepthChromaMinus8:d,codedWidth:g,codedHeight:_,displayWidth:v,displayHeight:y,pixelAspectRatio:te,colourPrimaries:x,matrixCoefficients:C,transferCharacteristics:S,fullRangeFlag:ee,numReorderFrames:ne,maxDecFrameBuffering:re}}catch(e){return console.error(`Error parsing AVC SPS:`,e),null}},jn=e=>{let t=o(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)o(e),o(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Mn=(e,t)=>t.description?wn(e,(l(t.description)[21]&3)+1):Cn(e),Nn=(e,t)=>t.description?vn(e,(l(t.description)[21]&3)+1):_n(e),Pn=e=>e>>1&63,Fn=e=>{try{let t=new k(xn(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:s,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:u}=Ln(t,n);o(t);let d=o(t),f=0;d===3&&(f=t.readBits(1));let p=o(t),m=o(t),h=p,g=m;if(t.readBits(1)){let e=o(t),n=o(t),r=o(t),i=o(t),a=1,s=1,c=f===0?d:0;c===1?(a=2,s=2):c===2&&(a=2,s=1),h-=(e+n)*a,g-=(r+i)*s}let _=o(t),v=o(t);o(t);let y=t.readBits(1)?0:n,b=0;for(let e=y;e<=n;e++)o(t),b=o(t),o(t);if(o(t),o(t),o(t),o(t),o(t),o(t),t.readBits(1)&&t.readBits(1)&&Rn(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),o(t),o(t),t.skipBits(1)),zn(t,o(t)),t.readBits(1)){let e=o(t);for(let n=0;n<e;n++)o(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let x=2,S=2,C=2,ee=0,te=0,ne={num:1,den:1};if(t.readBits(1)){let e=Vn(t,n);ne=e.pixelAspectRatio,x=e.colourPrimaries,S=e.transferCharacteristics,C=e.matrixCoefficients,ee=e.fullRangeFlag,te=e.minSpatialSegmentationIdc}return{displayWidth:h,displayHeight:g,pixelAspectRatio:ne,colourPrimaries:x,transferCharacteristics:S,matrixCoefficients:C,fullRangeFlag:ee,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,chromaFormatIdc:d,bitDepthLumaMinus8:_,bitDepthChromaMinus8:v,minSpatialSegmentationIdc:te}}catch(e){return console.error(`Error parsing HEVC SPS:`,e),null}},In=e=>{try{let t=[],n=[],r=[],i=[];for(let a of _n(e)){let o=e.subarray(a.offset,a.offset+a.length),s=Pn(o[0]);s===N.VPS_NUT?t.push(o):s===N.SPS_NUT?n.push(o):s===N.PPS_NUT?r.push(o):(s===N.PREFIX_SEI_NUT||s===N.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Fn(n[0]);if(!a)return null;let c=0;if(r.length>0){let e=r[0],t=new k(xn(e));t.skipBits(16),o(t),o(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),o(t),o(t),s(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&o(t),s(t),s(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);c=!n&&!i?0:n&&!i?2:!n&&i?3:0}let l=[...t.length?[{arrayCompleteness:1,nalUnitType:N.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:N.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:N.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Pn(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:c,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(e){return console.error(`Error building HEVC Decoder Configuration Record:`,e),null}},Ln=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Rn=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))o(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&s(e);for(let t=0;t<n;t++)s(e)}},zn=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Bn(e,r,t,n)},Bn=(e,t,n,r)=>{let i=0,a=0,s=0;if(t!==0&&(a=e.readBits(1)),a){s=t===n?t-(o(e)+1):t-1,e.readBits(1),o(e);let a=r[s]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[s]}else{let t=o(e),n=o(e);for(let n=0;n<t;n++)o(e),e.readBits(1);for(let t=0;t<n;t++)o(e),e.readBits(1);i=t+n}return i},Vn=(e,t)=>{let n=2,r=2,i=2,a=0,s=0,c={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)c={num:e.readBits(16),den:e.readBits(16)};else{let e=kn[t];e&&(c=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(o(e),o(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(o(e),o(e),o(e),o(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&o(e),e.readBits(1)&&Hn(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),s=o(e),o(e),o(e),o(e),o(e)),{pixelAspectRatio:c,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:s}},Hn=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let s=!1;n?o(e):s=e.readBits(1)===1;let c=1;s||(c=o(e)+1),r&&Un(e,c,a),i&&Un(e,c,a)}},Un=(e,t,n)=>{for(let r=0;r<t;r++)o(e),o(e),n&&(o(e),o(e)),e.readBits(1)},Wn=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},Gn=e=>{try{let t=u(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=i>>6&3,o=i>>5&1,s=i&31,c=t.getUint32(n,!1);n+=4;let l=e.subarray(n,n+6);n+=6;let d=t.getUint8(n++),f=(t.getUint8(n++)&15)<<8|t.getUint8(n++),p=t.getUint8(n++)&3,m=t.getUint8(n++)&3,h=t.getUint8(n++)&7,g=t.getUint8(n++)&7,_=t.getUint16(n,!1);n+=2;let v=t.getUint8(n++),y=v>>6&3,b=v>>3&7,x=v>>2&1,S=v&3,C=t.getUint8(n++),ee=[];for(let r=0;r<C;r++){let r=t.getUint8(n++),i=r>>7&1,a=r&63,o=t.getUint16(n,!1);n+=2;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}ee.push({arrayCompleteness:i,nalUnitType:a,nalUnits:s})}return{configurationVersion:r,generalProfileSpace:a,generalTierFlag:o,generalProfileIdc:s,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:d,minSpatialSegmentationIdc:f,parallelismType:p,chromaFormatIdc:m,bitDepthLumaMinus8:h,bitDepthChromaMinus8:g,avgFrameRate:_,constantFrameRate:y,numTemporalLayers:b,temporalIdNested:x,lengthSizeMinusOne:S,arrays:ee}}catch(e){return console.error(`Error deserializing HEVC Decoder Configuration Record:`,e),null}},P;(function(e){e[e.audAllowed=0]=`audAllowed`,e[e.beforeFirstVcl=1]=`beforeFirstVcl`,e[e.afterFirstVcl=2]=`afterFirstVcl`,e[e.eoBitstreamAllowed=3]=`eoBitstreamAllowed`,e[e.noMoreDataAllowed=4]=`noMoreDataAllowed`})(P||={});var Kn=(e,t)=>{let n=new Set,r=P.audAllowed;for(let i of Nn(e,t)){if(r===P.noMoreDataAllowed){n.add(i.offset);continue}let t=Pn(e[i.offset]);if(r===P.eoBitstreamAllowed&&t!==37){n.add(i.offset);continue}let a=!1;t===35?r>P.audAllowed?a=!0:r=P.beforeFirstVcl:t<=31?r>P.afterFirstVcl?a=!0:r=P.afterFirstVcl:t===36?r===P.afterFirstVcl?r=P.eoBitstreamAllowed:a=!0:t===37?r<P.afterFirstVcl?a=!0:r=P.noMoreDataAllowed:t===32||t===33||t===34||t===39||t>=41&&t<=44||t>=48&&t<=55?r>P.beforeFirstVcl?a=!0:r=P.beforeFirstVcl:(t===38||t===40||t>=45&&t<=47||t>=56&&t<=63)&&r<P.afterFirstVcl&&(a=!0),a&&n.add(i.offset)}if(n.size===0)return null;let i=[];for(let r of Nn(e,t))n.has(r.offset)||i.push(e.subarray(r.offset,r.offset+r.length));return Mn(i,t)},qn=e=>{let t=new k(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let a=8;r>=2&&(a=t.readBits(1)?12:10);let o=t.readBits(3),s=0,c=0;if(o!==7)if(c=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);s=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else s=1;else s=3,c=1;let l=t.readBits(16),u=t.readBits(16),d=(l+1)*(u+1),f=i(At).level;for(let e of At)if(d<=e.maxPictureSize){f=e.level;break}return{profile:r,level:f,bitDepth:a,chromaSubsampling:s,videoFullRangeFlag:c,colourPrimaries:o===2?1:o===1?6:2,transferCharacteristics:o===2?1:o===1?6:2,matrixCoefficients:o===7?0:o===2?1:o===1?6:2}},Jn=function*(e){let t=new k(e),r=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e|=(r&127)<<n*7,!(r&128))break;if(n===7&&r&128)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let i=t.readBits(4),a=t.readBits(1),o=t.readBits(1);t.skipBits(1),a&&t.skipBits(8);let s;if(o){let e=r();if(e===null)return;s=e}else s=Math.floor(t.getBitsLeft()/8);n(t.pos%8==0),yield{type:i,data:e.subarray(t.pos/8,t.pos/8+s)},t.skipBits(s*8)}},Yn=e=>{for(let{type:t,data:n}of Jn(e)){if(t!==1)continue;let e=new k(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(r===0&&(a=n),n>7){let t=e.readBits(1);r===0&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=1,_=1,v=0;return h||(r===0?(g=1,_=1):r===1?(g=0,_=0):m===12&&(g=e.readBits(1),g&&(_=e.readBits(1))),g&&_&&(v=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:g,chromaSubsamplingY:_,chromaSamplePosition:v}}return null},Xn=e=>{let t=u(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},Zn=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],Qn=e=>({durationInSamples:Zn[e[0]>>3]}),$n=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new k(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},er=(e,t,r)=>{switch(e){case`avc`:for(let e of yn(r,t)){let t=r[e.offset],n=bn(t);if(n>=gn.NON_IDR_SLICE&&n<=gn.SLICE_DPC)return`delta`;if(n===gn.IDR)return`key`;if(n===gn.SEI&&(!Ie()||Re()>=144)){let t=xn(r.subarray(e.offset,e.offset+e.length)),n=1;do{let e=0;for(;;){let r=t[n++];if(r===void 0||(e+=r,r<255))break}let r=0;for(;;){let e=t[n++];if(e===void 0||(r+=e,e<255))break}if(e===6){let e=new k(t);e.pos=8*n;let r=o(e),i=e.readBits(1);if(r===0&&i===1)return`key`}n+=r}while(n<t.length-1)}}return`delta`;case`hevc`:for(let e of Nn(r,t)){let t=Pn(r[e.offset]);if(t<N.BLA_W_LP)return`delta`;if(t<=N.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return r[0]&1?`delta`:`key`;case`vp9`:{let e=new k(r);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:n}of Jn(r))if(t===1){let t=new k(n);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new k(n);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}default:E(e),n(!1)}},tr;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(tr||={});var nr=(e,t)=>{let n=u(e),r=0,i=n.getUint32(r,!0);r+=4;let a=d.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=d.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let s=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(t.raw??={},t.raw[s]??=c,s){case`TITLE`:t.title??=c;break;case`DESCRIPTION`:t.description??=c;break;case`ARTIST`:t.artist??=c;break;case`ALBUM`:t.album??=c;break;case`ALBUMARTIST`:t.albumArtist??=c;break;case`COMMENT`:t.comment??=c;break;case`LYRICS`:t.lyrics??=c;break;case`TRACKNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case`GENRE`:t.genre??=c;break;case`METADATA_BLOCK_PICTURE`:{let e=Ue(c),n=u(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=d.decode(e.subarray(12+i,12+i+o)),l=n.getUint32(i+o+28),f=e.subarray(i+o+32,i+o+32+l);t.images??=[],t.images.push({data:f,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:s||void 0})}}}},rr=(e,t,n)=>{let r=[e],i=f.encode(`Mediabunny`),a=new Uint8Array(4+i.length),o=new DataView(a.buffer);o.setUint32(0,i.length,!0),a.set(i,4),r.push(a);let s=new Set,c=(e,t)=>{let n=`${e}=${t}`,i=f.encode(n);a=new Uint8Array(4+i.length),o=new DataView(a.buffer),o.setUint32(0,i.length,!0),a.set(i,4),r.push(a),s.add(e)};for(let{key:e,value:r}of Ve(t))switch(e){case`title`:c(`TITLE`,r);break;case`description`:c(`DESCRIPTION`,r);break;case`artist`:c(`ARTIST`,r);break;case`album`:c(`ALBUM`,r);break;case`albumArtist`:c(`ALBUMARTIST`,r);break;case`genre`:c(`GENRE`,r);break;case`date`:{let e=t.raw?.DATE??t.raw?.date;e&&typeof e==`string`?c(`DATE`,e):c(`DATE`,r.toISOString().slice(0,10))}break;case`comment`:c(`COMMENT`,r);break;case`lyrics`:c(`LYRICS`,r);break;case`trackNumber`:c(`TRACKNUMBER`,r.toString());break;case`tracksTotal`:c(`TRACKTOTAL`,r.toString());break;case`discNumber`:c(`DISCNUMBER`,r.toString());break;case`discsTotal`:c(`DISCTOTAL`,r.toString());break;case`images`:if(!n)break;for(let e of r){let t=e.kind===`coverFront`?3:e.kind===`coverBack`?4:0,n=new Uint8Array(e.mimeType.length);for(let t=0;t<e.mimeType.length;t++)n[t]=e.mimeType.charCodeAt(t);let r=f.encode(e.description??``),i=new Uint8Array(8+n.length+4+r.length+16+4+e.data.length),a=u(i);a.setUint32(0,t,!1),a.setUint32(4,n.length,!1),i.set(n,8),a.setUint32(8+n.length,r.length,!1),i.set(r,12+n.length),a.setUint32(28+n.length+r.length,e.data.length,!1),i.set(e.data,32+n.length+r.length),c(`METADATA_BLOCK_PICTURE`,We(i))}break;case`raw`:break;default:E(e)}if(t.raw)for(let e in t.raw){let n=t.raw[e]??t.raw[e.toLowerCase()];e===`vendor`||n==null||s.has(e)||typeof n==`string`&&c(e,n)}let l=new Uint8Array(4);u(l).setUint32(0,s.size,!0),r.splice(2,0,l);let d=r.reduce((e,t)=>e+t.length,0),p=new Uint8Array(d),m=0;for(let e of r)p.set(e,m),m+=e.length;return p},ir=[2,1,2,3,3,4,4,5],ar=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new k(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},or=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],sr=1536,cr=new Uint8Array([5,4,65,67,45,51]),lr=new Uint8Array([5,4,69,65,67,51]),ur=[1,2,3,6],dr=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new k(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=ur[o],d;return d=i<3?mn[i]/1e3:hn[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},fr=e=>{if(e.length<2)return null;let t=new k(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},pr=e=>{let t=e.substreams[0];return n(t),t.fscod<3?mn[t.fscod]:t.fscod2!==null&&t.fscod2<3?hn[t.fscod2]:null},mr=e=>{let t=e.substreams[0];n(t);let r=ir[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let n=0;n<9;n++)t.chanLoc&1<<8-n&&(r+=e[n])}return r},hr=class{constructor(e){this.input=e}dispose(){}},gr=new Uint8Array,F=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===gr&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw 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===gr}get microsecondTimestamp(){return Math.trunc(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`Your browser does not support EncodedAudioChunk.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},_r=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},vr=e=>{let t=u(e),n=0,r=t.getUint8(n);n+=1,n+=3;let i=te(e.subarray(n,n+16));n+=16;let a=null;if(r>0){let r=t.getUint32(n);if(n+=4,r>0){a=[];for(let t=0;t<r;t++)a.push(te(e.subarray(n,n+16))),n+=16}}let o=t.getUint32(n);return n+=4,{systemId:i,keyIds:a,data:e.slice(n,n+o)}},yr=(e,t)=>e.systemId===t.systemId&&Ge(e.data,t.data),br=e=>{let t=U(e),n=W(e,4),r=8;t===1&&(t=ml(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},xr=e=>dl(e)/65536,Sr=e=>dl(e)/1073741824,Cr=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=V(e);if(t|=n&127,!(n&128))break}return t},wr=e=>{let t=H(e);return e.skip(2),t=Math.min(t,e.remainingLength),d.decode(B(e,t))},Tr=e=>{let t=br(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=U(e);e.skip(4);let r=B(e,t.contentSize-8);switch(n){case 1:return d.decode(r);case 2:return new TextDecoder(`utf-16be`).decode(r);case 13:return new mt(r,`image/jpeg`);case 14:return new mt(r,`image/png`);case 27:return new mt(r,`image/bmp`);default:return r}},Er=new Uint32Array(256),Dr=new Uint32Array(256),Or=new Uint32Array(256),kr=new Uint32Array(256),Ar=new Uint32Array(256),I=new Uint32Array(256),jr=new Uint32Array(10),Mr=!1,Nr=()=>{let e=new Uint8Array(256),t=new Uint8Array(256),n=new Uint8Array(256);for(let e=0,r=1;e<256;e++)n[e]=r,t[r]=e,r=r^r<<1^(r&128?283:0);let r=(e,r)=>e&&r?n[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let i=n[255-t[r]],a=i^i<<1^i<<2^i<<3^i<<4;a=a>>>8^a&255^99,e[r]=a}for(let t=0;t<256;t++){let n=e[t],i=e.indexOf(t);Er[t]=n<<24|n<<16|n<<8|n,I[t]=i<<24|i<<16|i<<8|i;let a=r(i,14),o=r(i,9),s=r(i,13),c=r(i,11),l=a<<24|o<<16|s<<8|c;Dr[t]=l,Or[t]=l>>>8|l<<24,kr[t]=l>>>16|l<<16,Ar[t]=l>>>24|l<<8}let i=1;for(let e=0;e<10;e++)jr[e]=i<<24,i=i<<1^(i&128?283:0);Mr=!0},Pr=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(16),this.out=new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){n(e.byteLength===16),n(t.byteLength===16),Mr||Nr();let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=i.getUint32(0,!1),this.iv[1]=i.getUint32(4,!1),this.iv[2]=i.getUint32(8,!1),this.iv[3]=i.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^Er[t>>>16&255]&4278190080^Er[t>>>8&255]&16711680^Er[t>>>0&255]&65280^Er[t>>>24&255]&255^jr[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;e<t;e+=4,t-=4)for(let n=0;n<4;n++){let r=this.roundkey[e+n];this.roundkey[e+n]=this.roundkey[t+n],this.roundkey[t+n]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let n=this.roundkey[e+t];this.roundkey[e+t]=Dr[Er[n>>>24&255]&255]^Or[Er[n>>>16&255]&255]^kr[Er[n>>>8&255]&255]^Ar[Er[n>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3],i=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),s=this.inView.getUint32(12,!1),c,l,u,d;for(let i=1;i<10;i++){let a=i*4;c=Dr[e>>>24]^Or[r>>>16&255]^kr[n>>>8&255]^Ar[t&255]^this.roundkey[a],l=Dr[t>>>24]^Or[e>>>16&255]^kr[r>>>8&255]^Ar[n&255]^this.roundkey[a+1],u=Dr[n>>>24]^Or[t>>>16&255]^kr[e>>>8&255]^Ar[r&255]^this.roundkey[a+2],d=Dr[r>>>24]^Or[n>>>16&255]^kr[t>>>8&255]^Ar[e&255]^this.roundkey[a+3],e=c,t=l,n=u,r=d}let f=I[e>>>24&255]&4278190080^I[r>>>16&255]&16711680^I[n>>>8&255]&65280^I[t>>>0&255]&255^this.roundkey[40],p=I[t>>>24&255]&4278190080^I[e>>>16&255]&16711680^I[r>>>8&255]&65280^I[n>>>0&255]&255^this.roundkey[41],m=I[n>>>24&255]&4278190080^I[t>>>16&255]&16711680^I[e>>>8&255]&65280^I[r>>>0&255]&255^this.roundkey[42],h=I[r>>>24&255]&4278190080^I[n>>>16&255]&16711680^I[t>>>8&255]&65280^I[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,f^this.iv[0],!1),this.outView.setUint32(4,p^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,h^this.iv[3],!1),this.iv[0]=i,this.iv[1]=a,this.iv[2]=o,this.iv[3]=s}},Fr=(e,t,n)=>{let r=!1,i=0,a=2**16,o=new Pr;return new ReadableStream({pull:async s=>{r||=(o.init(await t()),!0);let c=a+16,l=e.requestSliceRange(i,0,c);if(l instanceof Promise&&(l=await l),!l||l.length===0)throw Error(`Invalid ciphertext.`);let u=l.length;if(u%16!=0)throw Error(`Invalid ciphertext.`);let d=u===c?u-16:u,f=B(l,d),p=new Uint8Array(d);for(let e=0;e<d;e+=16)o.in.set(f.subarray(e,e+16)),o.decrypt(),p.set(o.out,e);if(d<u)s.enqueue(p),i+=d;else{let e=p[d-1];if(e===0||e>16)throw Error(`Invalid PKCS#7 padding. Incorrect key or corrupted data.`);let t=p.subarray(0,d-e);s.enqueue(t),s.close(),n()}},cancel:()=>{n()}})},Ir=class e extends hr{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return _r({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let t=0,r=!1;for(;;){let i=this.reader.requestSliceRange(t,8,16);if(i instanceof Promise&&(i=await i),!i)break;let a=t,o=br(i);if(!o)break;if(o.name===`ftyp`||o.name===`styp`){let e=W(i,4);this.isQuickTime=e===`qt `}else if(o.name===`moov`){let e=this.reader.requestSlice(i.filePos,o.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}r=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>a+o.totalSize;break}else if(o.name===`moof`){if(!this.input._initInput)throw Error(`"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.`);let t=await this.input._initInput._getDemuxer();if(t.constructor!==e)throw Error(`Init input must match the input's format.`);await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(let e of t.tracks){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};e.trackBacking&&(n(t.info),t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new Rr(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new zr(t),this.tracks.push(t)))}r=!1;break}t=a+o.totalSize}if(r){n(this.reader.fileSize!==null);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),n(e);let t=U(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(e instanceof Promise&&(e=await e),e){let t=br(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);n instanceof Promise&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;n(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&j.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){n(e.info?.type===`audio`);let r=Ut(e.info.codec),a=[],o=[];for(let n=0;n<t.sampleToChunk.length;n++){let s=t.sampleToChunk[n],c=t.sampleToChunk[n+1],l=(c?c.startChunkIndex:t.chunkOffsets.length)-s.startChunkIndex;for(let n=0;n<l;n++){let c=s.startSampleIndex+n*s.samplesPerChunk,l=c+s.samplesPerChunk,u=w(t.sampleTimingEntries,c,e=>e.startIndex),d=t.sampleTimingEntries[u],f=w(t.sampleTimingEntries,l,e=>e.startIndex),p=t.sampleTimingEntries[f],m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta,h=p.startDecodeTimestamp+(l-p.startIndex)*p.delta-m,g=i(a);g&&g.delta===h?g.count++:a.push({startIndex:s.startChunkIndex+n,startDecodeTimestamp:m,count:1,delta:h});let _=s.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;o.push(_)}s.startSampleIndex=s.startChunkIndex,s.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),n(t);let r=br(t);n(r?.name===`moof`);let i=this.reader.requestSlice(e,r.totalSize);i instanceof Promise&&(i=await i),n(i),this.traverseBox(i);let a=this.lastReadFragment;n(a&&a.moofOffset===e);for(let[,e]of a.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===a.moofOffset);if(r)Wr(e,r.timestamp);else{let t=w(n,a.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];Wr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=w(n,e.startTimestamp,e=>e.startTimestamp);if((r===-1||n[r].moofOffset!==a.moofOffset)&&n.splice(r+1,0,{moofOffset:a.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){let n=await Jr(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,n.length);t++){let r=n[t];e.samples[t].encryption=r}}}return a}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=br(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,a=br(e);if(!a)return!1;let o=e.filePos,s=t+a.totalSize;switch(a.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:case`sinf`:case`schi`:this.readContiguousBoxes(e.slice(o,a.contentSize));break;case`mvhd`:{let t=V(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=U(e),this.movieDurationInTimescale=ml(e)):(e.skip(8),this.movieTimescale=U(e),this.movieDurationInTimescale=U(e))}break;case`trak`:{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...vt,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(o,a.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null&&(t.info.type===`video`&&t.info.width!==-1?(t.trackBacking=new Rr(t),this.tracks.push(t)):t.info.type===`audio`&&t.info.numberOfChannels!==-1&&(t.trackBacking=new zr(t),this.tracks.push(t))),this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let i=V(e),a=!!(sl(e)&1);if(t.disposition.default=a,i===0)e.skip(8),t.id=U(e),e.skip(4),t.durationInMovieTimescale=U(e);else if(i===1)e.skip(16),t.id=U(e),e.skip(4),t.durationInMovieTimescale=ml(e);else throw Error(`Incorrect track header version ${i}.`);e.skip(16);let o=r(ve(Gr([xr(e),xr(e),Sr(e),xr(e),xr(e),Sr(e),xr(e),xr(e),Sr(e)]),90));n(o===0||o===90||o===180||o===270),t.rotation=o}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3);let r=!1,i=0,a=U(e);for(let o=0;o<a;o++){let a=n===1?ml(e):U(e),o=n===1?hl(e):dl(e),s=xr(e);if(a!==0){if(r){console.warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){console.warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=V(e);e.skip(3),n===0?(e.skip(8),t.timescale=U(e),t.durationInMediaTimescale=U(e)):n===1&&(e.skip(16),t.timescale=U(e),t.durationInMediaTimescale=ml(e));let r=H(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;we(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=W(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case`stbl`:{let n=this.currentTrack;if(!n)break;n.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(o,a.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=V(e);e.skip(3);let r=U(e);for(let i=0;i<r;i++){let r=e.filePos,i=br(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`){e.skip(24),t.info.width=H(e),t.info.height=H(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let n=a===`encv`?t.frmaCodecString:a;t.frmaCodecString=null,n===`avc1`||n===`avc3`?(t.info.codec=`avc`,t.info.avcType=n===`avc1`?1:3):n===`hvc1`||n===`hev1`?t.info.codec=`hevc`:n===`vp08`?t.info.codec=`vp8`:n===`vp09`?t.info.codec=`vp9`:n===`av01`?t.info.codec=`av1`:console.warn(n===null?`Unknown encrypted video codec due to missing frma box.`:`Unsupported video codec (sample entry type '${i.name}').`)}else{e.skip(8);let o=H(e);e.skip(6);let s=H(e),c=H(e);e.skip(4);let l=U(e)/65536,u=null;n===0&&o>0&&(o===1?(e.skip(4),c=8*U(e),e.skip(8)):o===2&&(e.skip(4),l=vl(e),s=U(e),e.skip(4),c=U(e),u=U(e),e.skip(8))),t.info.numberOfChannels=s,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));let d=a===`enca`?t.frmaCodecString:a;if(t.frmaCodecString=null,d!==`mp4a`)if(d===`opus`)t.info.codec=`opus`,t.info.sampleRate=Vt;else if(d===`flac`)t.info.codec=`flac`;else if(d===`ulaw`)t.info.codec=`ulaw`;else if(d===`alaw`)t.info.codec=`alaw`;else if(d===`ac-3`)t.info.codec=`ac3`;else if(d===`ec-3`)t.info.codec=`eac3`;else if(d===`twos`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=t.info.pcmLittleEndian?`pcm-s16`:`pcm-s16be`:(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if(d===`sowt`)c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if(d===`raw `)t.info.codec=`pcm-u8`;else if(d===`in24`)t.info.codec=t.info.pcmLittleEndian?`pcm-s24`:`pcm-s24be`;else if(d===`in32`)t.info.codec=t.info.pcmLittleEndian?`pcm-s32`:`pcm-s32be`;else if(d===`fl32`)t.info.codec=t.info.pcmLittleEndian?`pcm-f32`:`pcm-f32be`;else if(d===`fl64`)t.info.codec=t.info.pcmLittleEndian?`pcm-f64`:`pcm-f64be`;else if(d===`ipcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===16?t.info.codec=`pcm-s16`:e===24?t.info.codec=`pcm-s24`:e===32?t.info.codec=`pcm-s32`:(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):e===16?t.info.codec=`pcm-s16be`:e===24?t.info.codec=`pcm-s24be`:e===32?t.info.codec=`pcm-s32be`:(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if(d===`fpcm`){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?e===32?t.info.codec=`pcm-f32`:e===64?t.info.codec=`pcm-f64`:(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):e===32?t.info.codec=`pcm-f32be`:e===64?t.info.codec=`pcm-f64be`:(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if(d===`lpcm`&&u!==null){let e=c+7>>3,n=!!(u&1),r=!!(u&2),i=u&4?-1:0;c>0&&c<=64&&(n?c===32&&(t.info.codec=r?`pcm-f32be`:`pcm-f32`):i&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=r?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=r?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=r?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&console.warn(`Unsupported PCM format.`)}else console.warn(d===null?`Unknown encrypted audio codec due to missing frma box.`:`Unsupported audio codec (sample entry type '${i.name}').`)}e.filePos=r+i.totalSize}}break;case`frma`:{let t=this.currentTrack;if(!t)break;t.frmaCodecString=W(e,4).toLowerCase()}break;case`schm`:{let t=this.currentTrack;if(!t)break;e.skip(4);let n=W(e,4);n===`cenc`||n===`cens`||n===`cbcs`?t.encryptionInfo={scheme:n,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:console.warn(`Unsupported encryption scheme '${n}'.`)}break;case`tenc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);e.skip(3),e.skip(1);let r=V(e);if(n>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=r&15):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=V(e)!==0,t.encryptionInfo.defaultPerSampleIvSize=V(e),t.encryptionInfo.defaultKid=te(B(e,16)),t.encryptionInfo.defaultIsProtected&&t.encryptionInfo.defaultPerSampleIvSize===0){let n=V(e),r=new Uint8Array(16);r.set(B(e,n),0),t.encryptionInfo.defaultConstantIv=r}}break;case`avcC`:{let t=this.currentTrack;if(!t)break;n(t.info),t.info.codecDescription=B(e,a.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t)break;n(t.info),t.info.codecDescription=B(e,a.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`),e.skip(4);let r=V(e),i=V(e),a=V(e),o=a>>4,s=a>>1&7,c=a&1,l=V(e),u=V(e),d=V(e);t.info.vp9CodecInfo={profile:r,level:i,bitDepth:o,chromaSubsampling:s,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:u,matrixCoefficients:d}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`),e.skip(1);let r=V(e),i=r>>5,a=r&31,o=V(e),s=o>>7,c=o>>6&1,l=o>>5&1,u=o>>4&1,d=o>>3&1,f=o>>2&1,p=o&3,m=i===2&&c?l?12:10:c?10:8;t.info.av1CodecInfo={profile:i,level:a,tier:s,bitDepth:m,monochrome:u,chromaSubsamplingX:d,chromaSubsamplingY:f,chromaSamplePosition:p}}break;case`colr`:{let t=this.currentTrack;if(!t||(n(t.info?.type===`video`),W(e,4)!==`nclx`))break;let r=H(e),i=H(e),a=H(e),o=!!(V(e)&128);t.info.colorSpace={primaries:g[r],transfer:v[i],matrix:b[a],fullRange:o}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`video`);let r=U(e),i=U(e);r>0&&i>0&&(r>i?t.info.squarePixelWidth=Math.round(t.info.width*r/i):t.info.squarePixelHeight=Math.round(t.info.height*i/r))}break;case`wave`:this.readContiguousBoxes(e.slice(o,a.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(4),n(V(e)===3),Cr(e),e.skip(2);let r=V(e),i=!!(r&128),a=!!(r&64),o=!!(r&32);if(i&&e.skip(2),a){let t=V(e);e.skip(t)}o&&e.skip(2),n(V(e)===4);let s=Cr(e),c=e.filePos,l=V(e);if(l===64||l===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:l===103,objectType:null}):l===105||l===107?t.info.codec=`mp3`:l===221?t.info.codec=`vorbis`:console.warn(`Unsupported audio codec (objectTypeIndication ${l}) - discarding track.`),e.skip(12),s>e.filePos-c){n(V(e)===5);let r=Cr(e);if(t.info.codecDescription=B(e,r),t.info.codec===`aac`){let e=St(t.info.codecDescription);e.numberOfChannels!==null&&(t.info.numberOfChannels=e.numberOfChannels),e.sampleRate!==null&&(t.info.sampleRate=e.sampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),t.info.pcmLittleEndian=!!(H(e)&255)}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(4);let r=V(e);t.info.pcmLittleEndian=!!(r&1),t.info.pcmSampleSize=V(e)}break;case`dOps`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(1);let r=V(e),i=H(e),a=U(e),o=cl(e),s=V(e),c;c=s===0?new Uint8Array:B(e,2+r);let l=new Uint8Array(19+c.byteLength),u=new DataView(l.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,r),u.setUint16(10,i,!0),u.setUint32(12,a,!0),u.setInt16(16,o,!0),u.setUint8(18,s),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`),e.skip(4);let r=e.filePos;for(;e.filePos<s;){let n=V(e),r=sl(e);if((n&127)===tr.STREAMINFO){e.skip(10);let n=U(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let i=e.filePos;e.filePos=r;let a=B(e,i-r),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let r=new k(B(e,3)),i=r.readBits(2);r.skipBits(8);let a=r.readBits(3),o=r.readBits(1);i<3&&(t.info.sampleRate=mn[i]),t.info.numberOfChannels=ir[a]+o}break;case`dec3`:{let t=this.currentTrack;if(!t)break;n(t.info?.type===`audio`);let r=fr(B(e,a.contentSize));if(!r){console.warn(`Invalid dec3 box contents, ignoring.`);break}let i=pr(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=mr(r)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e),r=0,i=0;for(let a=0;a<n;a++){let n=U(e),a=U(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e),r=0;for(let i=0;i<n;i++){let n=U(e),i=dl(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e),r=U(e);if(n===0)for(let n=0;n<r;n++){let n=U(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=V(e),r=U(e),i=new k(B(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=U(e);for(let r=0;r<n;r++){let n=U(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e);for(let r=0;r<n;r++){let n=U(e)-1,r=U(e),i=U(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e);for(let r=0;r<n;r++){let n=U(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=U(e);for(let r=0;r<n;r++){let n=ml(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,a.contentSize));break;case`mehd`:{let t=V(e);e.skip(3);let n=t===1?ml(e):U(e);this.movieDurationInTimescale=n}break;case`trex`:{e.skip(4);let t=U(e),n=U(e),r=U(e),i=U(e),a=U(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=V(e);e.skip(3);let n=U(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=U(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[V,H,sl,U],l=c[a],u=c[o],d=c[s],f=U(e);for(let n=0;n<f;n++){let n=t===1?ml(e):U(e),i=t===1?ml(e):U(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:a.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(o,a.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(n(this.currentFragment),this.readContiguousBoxes(e.slice(o,a.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){this.currentFragment.implicitBaseDataOffset=e.currentOffset,e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let n=e.presentationTimestamps[t],r=e.samples[n.sampleIndex];e.firstKeyFrameTimestamp===null&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-n.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],r=e.samples[i(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=r.presentationTimestamp+r.duration;let{currentFragmentState:a}=this.currentTrack;n(a),a.startTimestamp!==null&&(Wr(e,a.startTimestamp),e.startTimestampIsFinal=!0),a.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=a.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`pssh`:{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=vr(B(e,a.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case`tfhd`:{n(this.currentFragment),e.skip(1);let t=sl(e),r=!!(t&1),i=!!(t&2),a=!!(t&8),o=!!(t&16),s=!!(t&32),c=!!(t&65536),l=!!(t&131072),u=U(e),d=this.tracks.find(e=>e.id===u);if(!d)break;let f=this.fragmentTrackDefaults.find(e=>e.trackId===u);this.currentTrack=d,d.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:f?.defaultSampleDescriptionIndex??null,defaultSampleDuration:f?.defaultSampleDuration??null,defaultSampleSize:f?.defaultSampleSize??null,defaultSampleFlags:f?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},r?d.currentFragmentState.baseDataOffset=ml(e):l&&(d.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),i&&(d.currentFragmentState.sampleDescriptionIndex=U(e)),a&&(d.currentFragmentState.defaultSampleDuration=U(e)),o&&(d.currentFragmentState.defaultSampleSize=U(e)),s&&(d.currentFragmentState.defaultSampleFlags=U(e)),c&&(d.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;n(t.currentFragmentState);let r=V(e);e.skip(3);let i=r===0?U(e):ml(e);t.currentFragmentState.startTimestamp=i}break;case`trun`:{let t=this.currentTrack;if(!t)break;n(this.currentFragment),n(t.currentFragmentState);let r=V(e),i=sl(e),a=!!(i&1),o=!!(i&4),s=!!(i&256),c=!!(i&512),l=!!(i&1024),u=!!(i&2048),d=U(e),f=null;a&&(f=dl(e));let p=null;o&&(p=U(e));let m;if(this.currentFragment.trackData.has(t.id)?(m=this.currentFragment.trackData.get(t.id),f!==null&&(m.currentOffset=t.currentFragmentState.baseDataOffset+f)):(m={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(f??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,m)),d===0){this.currentFragment.implicitBaseDataOffset=m.currentOffset;break}for(let i=0;i<d;i++){let a;s?a=U(e):(n(t.currentFragmentState.defaultSampleDuration!==null),a=t.currentFragmentState.defaultSampleDuration);let o;c?o=U(e):(n(t.currentFragmentState.defaultSampleSize!==null),o=t.currentFragmentState.defaultSampleSize);let d;l?d=U(e):(n(t.currentFragmentState.defaultSampleFlags!==null),d=t.currentFragmentState.defaultSampleFlags),i===0&&p!==null&&(d=p);let f=0;u&&(f=r===0?U(e):dl(e));let h=!(d&65536);m.samples.push({presentationTimestamp:m.currentTimestamp+f,duration:a,byteOffset:m.currentOffset,byteSize:o,isKeyFrame:h,encryption:null}),m.currentOffset+=o,m.currentTimestamp+=a}}break;case`saiz`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),sl(e)&1){let n=W(e,4),r=U(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let n=V(e),r=U(e),i=null;n===0&&r>0&&(i=B(e,r));let a=qr(t);a.defaultSampleInfoSize=n,a.sampleSizes=i,a.sampleCount=r}break;case`saio`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let n=V(e);if(sl(e)&1){let n=W(e,4),r=U(e);if(n!==t.encryptionInfo.scheme||r!==0)break}let r=U(e);if(r===0)break;r>1&&console.warn(`Multiple saio entries are not supported; using the first offset only.`);let i=n===0?U(e):Number(ml(e));this.currentFragment&&(i+=this.currentFragment.moofOffset);let a=qr(t);a.offset=i}break;case`senc`:{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;n(this.currentFragment);let r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);let i=!!(sl(e)&2),a=U(e),o=t.encryptionInfo.defaultPerSampleIvSize;n(o!==null);for(let n=0;n<Math.min(a,r.samples.length);n++){let a=new Uint8Array(16);o>0?a.set(B(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(i){let t=H(e);s=[];for(let n=0;n<t;n++){let t=H(e),n=U(e);s.push({clearLen:t,protectedLen:n})}}let c=r.samples[n];c.encryption={iv:a,subsamples:s}}}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(o,a.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=wr(n):this.metadataTags.raw[e.name]??=B(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=d.decode(B(n,e.contentSize)):this.metadataTags.title??=wr(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=wr(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=wr(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=wr(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=wr(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=wr(n));break;case`©day`:if(!this.currentTrack){let e=new Date(wr(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=wr(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=wr(n))}}}break;case`meta`:{if(this.currentTrack)break;let t=U(e)!==0;this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(o,a.contentSize)):this.readContiguousBoxes(e.slice(o+4,a.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=U(e);for(let n=0;n<t;n++){let t=U(e);e.skip(4);let r=d.decode(B(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(o,a.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=Tr(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof mt?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=u(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=u(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}}}}}return e.filePos=s,!0}},Lr=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(n(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return _e(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Br(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Kr(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=w(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=Vr(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!Kr(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=ce(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let r=this.packetToSampleIndex.get(e);if(r!==void 0){let e=Ur(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r);return this.fetchPacketForSampleIndex(e,t)}let i=this.packetToFragmentLocation.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>i.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return n(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let r=Hr(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!r)return null;let i;if(t.metadataOnly)i=gr;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(t instanceof Promise&&(t=await t),!t)return null;if(i=B(t,r.sampleSize),this.internalTrack.encryptionAuxInfo){n(this.internalTrack.encryptionInfo);let t=await Jr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<t.length&&(i=await Yr(this.internalTrack,t[e],i,null))}}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new F(i,r.isKeyFrame?`key`:`delta`,a,o,e,r.sampleSize);return this.packetToSampleIndex.set(s,e),s}async fetchPacketInFragment(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).samples[t];n(i);let a;if(r.metadataOnly)a=gr;else{let t=this.internalTrack.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(t instanceof Promise&&(t=await t),!t)return null;a=B(t,i.byteSize),i.encryption&&(a=await Yr(this.internalTrack,i.encryption,a,e))}let o=(i.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,s=i.duration/this.internalTrack.timescale,c=new F(a,i.isKeyFrame?`key`:`delta`,o,s,e.moofOffset+t,i.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:t}),c}async performFragmentedLookup(e,t,r,i,a){let o=this.internalTrack.demuxer,s=null,c=null,l=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,a);n!==-1&&(c=e,l=n)}let u=w(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),d=u===-1?null:this.internalTrack.fragmentLookupTable[u],f=w(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),p=f===-1?null:this.internalTrack.fragmentPositionCache[f],m=Math.max(d?.moofOffset??0,p?.moofOffset??0)||null,h;for(e?m===null||e.moofOffset>=m?(h=e.moofOffset+e.moofSize,s=e):h=m:h=m??0;;){if(s){let e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=o.reader.requestSliceRange(h,8,16);if(e instanceof Promise&&(e=await e),!e)break;let n=h,r=br(e);if(!r)break;if(r.name===`moof`){s=await o.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(s);if(r)return this.fetchPacketInFragment(s,e,a);e!==-1&&(c=s,l=e)}h=n+r.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){let e=this.internalTrack.fragmentLookupTable[u-1];n(!e||e.timestamp<d.timestamp);let r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,i,a)}return c?this.fetchPacketInFragment(c,l,a):null}},Rr=class extends Lr{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.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`vp9`&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&qn(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Yn(e.data)}let e={codec:Lt(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})():null}},zr=class extends Lr{constructor(e){super(e),this.decoderConfig=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.decoderConfig??={codec:zt(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Br=(e,t)=>{if(e.presentationTimestamps){let n=w(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}{let n=w(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},Vr=(e,t)=>{if(!e.keySampleIndices)return Br(e,t);if(e.presentationTimestamps){let n=w(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(ie(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}{let n=Br(e,t),r=w(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},Hr=(e,t)=>{let r=w(e.sampleTimingEntries,t,e=>e.startIndex),i=e.sampleTimingEntries[r];if(!i||i.startIndex+i.count<=t)return null;let a=i.startDecodeTimestamp+(t-i.startIndex)*i.delta,o=w(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),s=e.sampleCompositionTimeOffsets[o];s&&t-s.startIndex<s.count&&(a+=s.offset);let c=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],l=w(e.sampleToChunk,t,e=>e.startSampleIndex),u=e.sampleToChunk[l];n(u);let d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),f=e.chunkOffsets[d],p=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,m=0,h=f;if(e.sampleSizes.length===1)h+=c*(t-p),m+=c*u.samplesPerChunk;else for(let n=p;n<p+u.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(h+=r),m+=r}let g=i.delta;if(e.presentationTimestamps){let r=e.presentationTimestampIndexMap[t];n(r!==void 0),r<e.presentationTimestamps.length-1&&(g=e.presentationTimestamps[r+1].presentationTimestamp-a)}return{presentationTimestamp:a,duration:g,sampleOffset:h,sampleSize:c,chunkOffset:f,chunkSize:m,isKeyFrame:!e.keySampleIndices||ie(e.keySampleIndices,t,e=>e)!==-1}},Ur=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=w(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},Wr=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},Gr=e=>{let[t,n]=e,r=Math.atan2(n,t);return Number.isFinite(r)?180/Math.PI*r:0},Kr=e=>e.sampleSizes.length===0,qr=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Jr=async(e,t,r)=>{if(r.resolved)return r.resolved;if(r.offset===null||r.sampleCount===0)throw Error(`Incomplete saiz/saio info; cannot resolve encryption data.`);let i=0;if(r.defaultSampleInfoSize>0)i=r.defaultSampleInfoSize*r.sampleCount;else{n(r.sampleSizes);for(let e=0;e<r.sampleCount;e++)i+=r.sampleSizes[e]}let a=e.requestSlice(r.offset,i);if(a instanceof Promise&&(a=await a),!a)throw Error(`Failed to read auxiliary encryption info.`);let o=t.defaultPerSampleIvSize;n(o!==null);let s=[];for(let e=0;e<r.sampleCount;e++){let n=r.defaultSampleInfoSize>0?r.defaultSampleInfoSize:r.sampleSizes[e],i=new Uint8Array(16);o>0?i.set(B(a,o),0):i.set(t.defaultConstantIv,0);let c=null;if(n>o){let e=H(a);c=[];for(let t=0;t<e;t++){let e=H(a),t=U(a);c.push({clearLen:e,protectedLen:t})}}s.push({iv:i,subsamples:c})}return r.resolved=s,s},Yr=async(e,t,r,i)=>{n(e.encryptionInfo);let a=e.encryptionInfo;n(a.defaultKid!==null);let o=a.defaultKid,s,c=e.demuxer.decryptionKeyCache.get(o);if(c)s=await c;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error(`Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.`);let t=(async()=>{let t=e.demuxer.psshBoxes;if(i){t=[...t,...i.psshBoxes].filter(e=>e.keyIds===null||e.keyIds.includes(o));for(let e=0;e<t.length-1;e++)for(let n=e+1;n<t.length;n++)yr(t[e],t[n])&&(t.splice(n,1),n--)}let n=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:o,psshBoxes:t});if(!(typeof n==`string`&&n.length===32&&ee.test(n)||n instanceof Uint8Array&&n.byteLength===16))throw TypeError(`resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.`);return n instanceof Uint8Array?n:ne(n)})();e.demuxer.decryptionKeyCache.set(o,t),s=await t}return a.scheme===`cenc`||a.scheme===`cens`?Xr(s,a,t,r):Zr(s,a,t,r)},Xr=async(e,t,r,i)=>{let a=new Uint8Array(16);a.set(r.iv,0);let o=await crypto.subtle.importKey(`raw`,e,{name:`AES-CTR`},!1,[`decrypt`]),s=async e=>{let t=await crypto.subtle.decrypt({name:`AES-CTR`,counter:a,length:64},o,e);return new Uint8Array(t)};if(!r.subsamples)return s(i);n(t.defaultCryptByteBlock!==null&&t.defaultSkipByteBlock!==null);let c=Qr(r.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),l=0;for(let e of c)for(let t of e.perSubsample)l+=t.length;let u=new Uint8Array(l),d=0;for(let e of c)for(let t of e.perSubsample)u.set(i.subarray(t.offset,t.offset+t.length),d),d+=t.length;let f=await s(u),p=new Uint8Array(i),m=0;for(let e of c)for(let t of e.perSubsample)p.set(f.subarray(m,m+t.length),t.offset),m+=t.length;return p},Zr=(e,t,r,i)=>{let a=new Pr;a.init({key:e,iv:r.iv});let o=t.defaultCryptByteBlock,s=t.defaultSkipByteBlock;if(n(o!==null&&s!==null),!r.subsamples){let e=new Uint8Array(i),t=Math.floor(i.length/16);for(let n=0;n<t;n++){let t=n*16;a.in.set(i.subarray(t,t+16)),a.decrypt(),e.set(a.out,t)}return e}if(o===0&&s===0)throw Error(`cbcs with subsamples requires pattern encryption.`);let c=new Uint8Array(i),l=Qr(r.subsamples,o,s),u=new DataView(r.iv.buffer,r.iv.byteOffset,16);for(let e of l){a.iv[0]=u.getUint32(0,!1),a.iv[1]=u.getUint32(4,!1),a.iv[2]=u.getUint32(8,!1),a.iv[3]=u.getUint32(12,!1);for(let t of e.perSubsample){let e=t.length/16;for(let n=0;n<e;n++){let e=t.offset+n*16;a.in.set(i.subarray(e,e+16)),a.decrypt(),c.set(a.out,e)}}}return c},Qr=(e,t,n)=>{let r=[],i=t!==0||n!==0,a=0;for(let o of e){a+=o.clearLen;let e=[];if(!i)o.protectedLen>0&&e.push({offset:a,length:o.protectedLen}),a+=o.protectedLen;else{let r=o.protectedLen,i=a;for(;r>0&&!(r<16*t);){let a=16*t;e.push({offset:i,length:a}),i+=a,r-=a;let o=Math.min(16*n,r);i+=o,r-=o}a+=o.protectedLen}r.push({perSubsample:e})}return r},$r=class{constructor(e){this.value=e}},ei=class{constructor(e){this.value=e}},ti=class{constructor(e){this.value=e}},ni=class{constructor(e){this.value=e}},L;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(L||={});var ri=[L.EBML,L.Segment],ii=[L.SeekHead,L.Info,L.Cluster,L.Tracks,L.Cues,L.Attachments,L.Chapters,L.Tags],ai=[...ri,...ii],oi=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,si=e=>e<1n<<8n?1:e<1n<<16n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,ci=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-134217728&&e<1<<27?4:e>=-(2**34)&&e<2**34?5:6,li=e=>{if(e<127)return 1;if(e<16383)return 2;if(e<(1<<21)-1)return 3;if(e<(1<<28)-1)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw Error(`EBML varint size not supported `+e)},ui=class{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=oi(e)){let n=0;switch(t){case 6:this.helperView.setUint8(n++,e/2**40|0);case 5:this.helperView.setUint8(n++,e/2**32|0);case 4:this.helperView.setUint8(n++,e>>24);case 3:this.helperView.setUint8(n++,e>>16);case 2:this.helperView.setUint8(n++,e>>8);case 1:this.helperView.setUint8(n++,e);break;default:throw Error(`Bad unsigned int size `+t)}this.writer.write(this.helper.subarray(0,n))}writeUnsignedBigInt(e,t=si(e)){let n=0;for(let r=t-1;r>=0;r--)this.helperView.setUint8(n++,Number(e>>BigInt(r*8)&255n));this.writer.write(this.helper.subarray(0,n))}writeSignedInt(e,t=ci(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=li(e)){let n=0;switch(t){case 1:this.helperView.setUint8(n++,128|e);break;case 2:this.helperView.setUint8(n++,64|e>>8),this.helperView.setUint8(n++,e);break;case 3:this.helperView.setUint8(n++,32|e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 4:this.helperView.setUint8(n++,16|e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 5:this.helperView.setUint8(n++,8|e/2**32&7),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;case 6:this.helperView.setUint8(n++,4|e/2**40&3),this.helperView.setUint8(n++,e/2**32|0),this.helperView.setUint8(n++,e>>24),this.helperView.setUint8(n++,e>>16),this.helperView.setUint8(n++,e>>8),this.helperView.setUint8(n++,e);break;default:throw Error(`Bad EBML varint size `+t)}this.writer.write(this.helper.subarray(0,n))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split(``).map(e=>e.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),n=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+n);let r=this.writer.getPos();if(this.dataOffsets.set(e,r),this.writeEBML(e.data),e.size!==-1){let e=this.writer.getPos()-r,i=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,n),this.writer.seek(i)}}else if(typeof e.data==`number`){let t=e.size??oi(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data==`bigint`){let t=e.size??si(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 $r)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof ei)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof ti){let t=e.size??ci(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof ni){let t=f.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else E(e.data)}},di=e=>{if(e.remainingLength<1)return null;let t=V(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},fi=e=>{if(e.remainingLength<1)return null;let t=V(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=V(e);return i},R=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=V(e);return n},pi=(e,t)=>{if(t<1)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(V(e));return n},mi=e=>{let t=di(e);return t===null||e.remainingLength<t?null:R(e,t)},hi=e=>{if(e.remainingLength<1)return null;if(V(e)===255)return;e.skip(-1);let t=fi(e);if(t===null)return null;if(t!==72057594037927940)return t},gi=e=>{n(e.remainingLength>=2);let t=mi(e);if(t===null)return null;let r=hi(e);return r===null?null:{id:t,size:r}},_i=(e,t)=>{let n=B(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},vi=(e,t)=>{let n=B(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return d.decode(n.subarray(0,r))},yi=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?_l(e):vl(e)},bi=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=gi(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};Ci(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},xi=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(t instanceof Promise&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=mi(t);if(e!==null&&a.has(e))return o;o++}}return null},Si={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,aac:`A_AAC`,mp3:`A_MPEG/L3`,opus:`A_OPUS`,vorbis:`A_VORBIS`,flac:`A_FLAC`,ac3:`A_AC3`,eac3:`A_EAC3`,"pcm-u8":`A_PCM/INT/LIT`,"pcm-s16":`A_PCM/INT/LIT`,"pcm-s16be":`A_PCM/INT/BIG`,"pcm-s24":`A_PCM/INT/LIT`,"pcm-s24be":`A_PCM/INT/BIG`,"pcm-s32":`A_PCM/INT/LIT`,"pcm-s32be":`A_PCM/INT/BIG`,"pcm-f32":`A_PCM/FLOAT/IEEE`,"pcm-f64":`A_PCM/FLOAT/IEEE`,webvtt:`S_TEXT/WEBVTT`};function Ci(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}var wi=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t},Ti;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(Ti||={});var Ei;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(Ei||={});var Di;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(Di||={});var Oi=[{id:L.SeekHead,flag:`seekHeadSeen`},{id:L.Info,flag:`infoSeen`},{id:L.Tracks,flag:`tracksSeen`},{id:L.Cues,flag:`cuesSeen`}],ki=10*2**20,Ai=class extends hr{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(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return wi({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsCollected||=(this.reader.fileSize!==null&&await this.loadSegmentMetadata(e),!0);let e={};for(let 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,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=gi(t);if(!n)break;let r=n.id,a=n.size,o=t.filePos;if(r===L.EBML){Ci(a);let e=this.reader.requestSlice(o,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===L.Segment){if(await this.readSegment(o,a),a===void 0||this.reader.fileSize===null)break}else if(r===L.Cluster){if(this.reader.fileSize===null)break;a===void 0&&(a=(await bi(this.reader,o,ai,this.reader.fileSize)).pos-o);let e=i(this.segments);e&&(e.elementEndPos=o+a)}Ci(a),e=o+a}})()}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 n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=n,r=gi(e);if(!r||!ii.includes(r.id)&&r.id!==L.Void){let e=await xi(this.reader,t,ii,Math.min(this.currentSegment.elementEndPos??1/0,t+ki));if(e){n=e;continue}break}let{id:i,size:a}=r,o=e.filePos,s=Oi.findIndex(e=>e.id===i);if(s!==-1){let e=Oi[s].flag;this.currentSegment[e]=!0,Ci(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===L.Tags||i===L.Attachments){i===L.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Ci(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===L.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(a===void 0)break;n=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=Oi.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=gi(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;Ci(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);let r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let n=e.cuePoints[t],r=e.cuePoints[t+1];n.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,16);r instanceof Promise&&(r=await r),n(r);let a=e,o=gi(r);n(o);let s=o.id;n(s===L.Cluster);let c=o.size,l=r.filePos;c===void 0&&(c=(await bi(this.reader,l,ai,t.elementEndPos)).pos-l);let u=this.reader.requestSlice(l,c);u instanceof Promise&&(u=await u);let d={segment:t,elementStartPos:a,elementEndPos:l+c,dataStartPos:l,timestamp:-1,trackData:new Map};this.currentCluster=d,u&&(d.elementEndPos=this.readContiguousElements(u,ai));for(let[,e]of d.trackData){let t=e.track;n(e.blocks.length>0);let r=!1;for(let t=0;t<e.blocks.length;t++){let n=e.blocks[t];n.timestamp+=d.timestamp,r||=n.lacing!==Ti.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===Ti.None&&(i.duration=t.defaultDuration)}r&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let o=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[i(e.presentationTimestamps).blockIndex];e.startTimestamp=o.timestamp,e.endTimestamp=s.timestamp+s.duration;let c=w(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(c===-1||t.clusterPositionCache[c].elementStartPos!==a)&&t.clusterPositionCache.splice(c+1,0,{elementStartPos:d.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=d,d}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){let i=e[r];if(i.lacing===Ti.None)continue;i.decoded||=(i.data=this.decodeBlockData(t,i.data),!0);let a=il.tempFromBytes(i.data),o=[],s=V(a)+1;switch(i.lacing){case Ti.Xiph:{let e=0;for(let t=0;t<s-1;t++){let t=0;for(;a.bufferPos<a.length;){let n=V(a);if(t+=n,n<255){o.push(t),e+=t;break}}}o.push(a.length-(a.bufferPos+e))}break;case Ti.FixedSize:{let e=a.length-1,t=Math.floor(e/s);for(let e=0;e<s;e++)o.push(t)}break;case Ti.Ebml:{let e=fi(a);n(e!==null);let t=e;o.push(t);let r=t;for(let e=1;e<s-1;e++){let e=a.bufferPos,i=fi(a);n(i!==null);let s=i-((1<<(a.bufferPos-e)*7-1)-1);t+=s,o.push(t),r+=t}o.push(a.length-(a.bufferPos+r))}break;default:n(!1)}n(o.length===s),e.splice(r,1);let c=i.duration||s*(t.defaultDuration??0);for(let t=0;t<s;t++){let n=o[t],l=B(a,n),u=i.timestamp+c*t/s,d=c/s;e.splice(r+t,0,{timestamp:u,duration:d,isKeyFrame:i.isKeyFrame,data:l,lacing:Ti.None,decoded:!0,mainAdditional:i.mainAdditional})}r+=s,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===L.Tags&&!e.tagsSeen)&&!(t.id===L.Attachments&&!e.attachmentsSeen))continue;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=gi(r);if(!i||i.id!==t.id)continue;let{size:a}=i;Ci(a),n(!this.currentSegment),this.currentSegment=e;let o=this.reader.requestSlice(r.filePos,a);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o),this.currentSegment=null,t.id===L.Tags?e.tagsSeen=!0:t.id===L.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let i=gi(e);if(!i||t&&t.includes(i.id))return!1;let{id:a,size:o}=i,s=e.filePos;switch(Ci(o),a){case L.DocType:this.isWebM=_i(e,o)===`webm`;break;case L.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,o)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case L.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=R(e,o)}break;case L.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=R(e,o)}break;case L.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=R(e,o),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case L.Duration:if(!this.currentSegment)break;this.currentSegment.duration=yi(e,o);break;case L.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...vt,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(s,o)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==Ei.Block||e.data.algorithm!==Di.HeaderStripping)&&(console.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){let e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if(this.currentTrack.info.type===`video`&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}this.currentTrack.codecId===Si.avc?(this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Si.hevc?(this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Si.vp8?this.currentTrack.info.codec=`vp8`:t===Si.vp9?this.currentTrack.info.codec=`vp9`:t===Si.av1&&(this.currentTrack.info.codec=`av1`);let e=this.currentTrack;this.currentTrack.trackBacking=new Mi(e),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`){t===Si.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===Si.mp3?this.currentTrack.info.codec=`mp3`:t===Si.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Vt):t===Si.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Si.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Si.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Si.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===`A_PCM/INT/LIT`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32`):this.currentTrack.codecId===`A_PCM/INT/BIG`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16be`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24be`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32be`):this.currentTrack.codecId===`A_PCM/FLOAT/IEEE`&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec=`pcm-f32`:this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec=`pcm-f64`));let e=this.currentTrack;this.currentTrack.trackBacking=new Ni(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case L.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=R(e,o);break;case L.TrackType:{if(!this.currentTrack)break;let t=R(e,o);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case L.FlagEnabled:if(!this.currentTrack)break;R(e,o)||(this.currentTrack=null);break;case L.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!R(e,o);break;case L.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!R(e,o);break;case L.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!R(e,o);break;case L.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!R(e,o);break;case L.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!R(e,o);break;case L.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!R(e,o);break;case L.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=_i(e,o);break;case L.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=B(e,o);break;case L.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=R(e,o);break;case L.Name:if(!this.currentTrack)break;this.currentTrack.name=vi(e,o);break;case L.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=_i(e,o),we(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case L.LanguageBCP47:{if(!this.currentTrack)break;let t=_i(e,o).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`,this.currentTrack.hasLanguageBcp47=!0}break;case L.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(s,o));break;case L.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=R(e,o);break;case L.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=R(e,o);break;case L.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=R(e,o);break;case L.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=R(e,o);break;case L.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=R(e,o);break;case L.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=R(e,o)===1;break;case L.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(s,o));break;case L.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=b[R(e,o)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case L.Range:if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=R(e,o)===2;break;case L.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=v[R(e,o)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case L.Primaries:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=g[R(e,o)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case L.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(s,o));break;case L.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-yi(e,o);try{this.currentTrack.info.rotation=r(t)}catch{}}break;case L.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(s,o));break;case L.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=yi(e,o);break;case L.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=R(e,o);break;case L.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=R(e,o);break;case L.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,o)),this.currentCueTime=null;break;case L.CueTime:this.currentCueTime=R(e,o);break;case L.CueTrackPositions:{if(this.currentCueTime===null)break;n(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,o)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case L.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=R(e,o)}break;case L.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;n(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+R(e,o)}break;case L.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=R(e,o);break;case L.SimpleBlock:{if(!this.currentCluster)break;let t=fi(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=cl(e),i=V(e),a=i>>1&3,c=!!(i&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=B(e,o-(e.filePos-s)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:a,decoded:!u,mainAdditional:null})}break;case L.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,o)),this.currentBlock=null;break;case L.Block:{if(!this.currentCluster)break;let t=fi(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=cl(e),i=V(e)>>1&3,a=B(e,o-(e.filePos-s)),c=n.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:a,lacing:i,decoded:!c,mainAdditional:null},n.blocks.push(this.currentBlock)}break;case L.BlockAdditions:this.readContiguousElements(e.slice(s,o));break;case L.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,o)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case L.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=B(e,o);break;case L.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=R(e,o);break;case L.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=R(e,o);break;case L.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case L.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,o));break;case L.Targets:this.readContiguousElements(e.slice(s,o));break;case L.TargetTypeValue:R(e,o)!==50&&(this.currentTagTargetIsMovie=!1);break;case L.TagTrackUID:case L.TagEditionUID:case L.TagChapterUID:case L.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case L.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,o));break;case L.TagName:this.currentSimpleTagName=vi(e,o);break;case L.TagString:{if(!this.currentSimpleTagName)break;let t=vi(e,o);this.processTagValue(this.currentSimpleTagName,t)}break;case L.TagBinary:{if(!this.currentSimpleTagName)break;let t=B(e,o);this.processTagValue(this.currentSimpleTagName,t)}break;case L.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,o));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new ht(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case L.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=pi(e,o);break;case L.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=vi(e,o);break;case L.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=_i(e,o);break;case L.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=B(e,o);break;case L.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=vi(e,o);break;case L.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,o)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case L.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ei.Block,data:null},this.readContiguousElements(e.slice(s,o)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case L.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=R(e,o);break;case L.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=R(e,o);break;case L.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:Di.Zlib,settings:null},this.readContiguousElements(e.slice(s,o));break;case L.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=R(e,o);break;case L.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=B(e,o);break;case L.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`}}return e.filePos=s+o,!0}decodeBlockData(e,t){n(e.decodingInstructions.length>0);let r=t;for(let t of e.decodingInstructions)if(n(t.data),t.data.type===`decompress`)switch(t.data.algorithm){case Di.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,n=new Uint8Array(e.length+r.length);n.set(e,0),n.set(r,e.length),r=n}}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=new Date(t);Number.isNaN(e.getTime())||(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}}}},ji=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),n=0;for(let r of e.segments)for(let e of r.tracks)if(e.trackBacking.getType()===t&&n++,e===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor,n=await this.getFirstPacket({metadataOnly:!0});return t+=n?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return _e(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=w(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=ce(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(t!==-1)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return n(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(t===-1)return null;let i=e.trackData.get(this.internalTrack.id).blocks[t];n(i),i.decoded||=(i.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,i.data),!0);let a=r.metadataOnly?gr:i.data,o=i.timestamp/this.internalTrack.segment.timestampFactor,s=i.duration/this.internalTrack.segment.timestampFactor,c={};i.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?gr:i.mainAdditional,c.alphaByteLength=i.mainAdditional.byteLength);let l=new F(a,i.isKeyFrame?`key`:`delta`,o,s,e.dataStartPos+t,i.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,i,a){let{demuxer:o,segment:s}=this.internalTrack,c=null,l=null,u=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,a);n!==-1&&(l=e,u=n)}let d=w(this.internalTrack.cuePoints,r,e=>e.time),f=d===-1?null:this.internalTrack.cuePoints[d],p=w(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),m=p===-1?null:this.internalTrack.clusterPositionCache[p],h=Math.max(f?.clusterPosition??0,m?.elementStartPos??0)||null,g;for(e?h===null||e.elementStartPos>=h?(g=e.elementEndPos,c=e):g=h:g=h??s.clusterSeekStartPos;s.elementEndPos===null||g<=s.elementEndPos-2;){if(c){let e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>i)break}let e=o.reader.requestSliceRange(g,2,16);if(e instanceof Promise&&(e=await e),!e)break;let r=g,d=gi(e);if(!d||!ii.includes(d.id)&&d.id!==L.Void){let e=await xi(o.reader,r,ii,Math.min(s.elementEndPos??1/0,r+ki));if(e){g=e;continue}break}let f=d.id,p=d.size,m=e.filePos;if(f===L.Cluster){c=await o.readCluster(r,s),p=c.elementEndPos-m;let{blockIndex:e,correctBlockFound:n}=t(c);if(n)return this.fetchPacketInCluster(c,e,a);e!==-1&&(l=c,u=e)}p===void 0&&(n(f!==L.Cluster),p=(await bi(o.reader,m,ai,s.elementEndPos)).pos-m);let h=m+p;if(s.elementEndPos===null){let e=o.reader.requestSliceRange(h,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(mi(e)===L.Segment){s.elementEndPos=h;break}}g=h}if(f&&(!l||l.elementStartPos<f.clusterPosition)){let e=this.internalTrack.cuePoints[d-1];n(!e||e.time<f.time);let r=e?.time??-1/0;return this.performClusterLookup(null,t,r,i,a)}return l?this.fetchPacketInCluster(l,u,a):null}},Mi=class extends ji{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(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){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===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));let t={codec:Lt({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?En(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?In(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?qn(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?Yn(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})():null}},Ni=class extends ji{constructor(e){super(e),this.decoderConfig=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.decoderConfig??={codec:zt({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Pi=async(e,t,n,r=null)=>{let i=2**16,a=t;for(;n===null||a<n;){let t=n===null?i:Math.min(i,n-a),o=e.requestSliceRange(a,4,t);if(o instanceof Promise&&(o=await o),!o||o.length<4)break;for(;o.remainingLength>=4;){let t=o.filePos,n=ln(U(o),e.fileSize===null?null:e.fileSize-a);if(n.header&&(!r||n.header.sampleRate===r.sampleRate&&n.header.mpegVersionId===r.mpegVersionId&&n.header.layer===r.layer&&pn(n.header.channel)===pn(r.channel)))return{header:n.header,startPos:a};o.filePos=t+n.bytesAdvanced,a=o.filePos}}return null},Fi=class extends hr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new C,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.trackBackings=[new Ii(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=wl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await Pi(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=cn(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(r instanceof Promise&&(r=await r),r){let t=U(r);if(t===1483304551||t===1231971951){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+n+4,12);if(t instanceof Promise&&(t=await t),t){let e=u(B(t,12)),n=e.getUint32(0,!1);this.xingData={frameCount:n&fn.FrameCount?e.getUint32(4,!1):null,fileSize:n&fn.FileSize?e.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return`audio/mpeg`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let n=this.reader.requestSlice(e,10);if(n instanceof Promise&&(n=await n),!n)break;let r=wl(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;Tl(i,r,this.metadataTags),e=n.filePos+r.size}if(!t&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),n(e),W(e,3)===`TAG`&&Sl(e,this.metadataTags)}return this.metadataTags}finally{e()}}},Ii=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(n(e.firstFrameHeader!==null),n(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){let t=sn(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),n=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return n(this.demuxer.firstFrameHeader),pn(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...vt}}async getDecoderConfig(){return n(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:pn(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=gr;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=B(e,n.dataSize)}return new F(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=ie(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=w(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Li=1399285583,Ri=79764919,zi=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^Ri:t<<1;zi[e]=t>>>0&4294967295}var Bi=e=>{let t=u(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^zi[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},Vi=(e,t,r)=>{let i=0,a=null;if(e.length>0)if(t.codec===`vorbis`){n(t.vorbisInfo);let o=t.vorbisInfo.modeBlockflags.length,s=(1<<Se(o-1))-1<<1,c=(e[0]&s)>>1;if(c>=t.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let l=r,u=t.vorbisInfo.modeBlockflags[c];if(a=t.vorbisInfo.blocksizes[u],u===1){let n=(s|1)+1,r=e[0]&n?1:0;l=t.vorbisInfo.blocksizes[r]}i=l===null?0:l+a>>2}else t.codec===`opus`&&(i=Qn(e).durationInSamples);return{durationInSamples:i,vorbisBlockSize:a}},Hi=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},Ui=65307,Wi=e=>{let t=e.filePos;if(ul(e)!==1399285583)return null;e.skip(1);let n=V(e),r=gl(e),i=ul(e),a=ul(e),o=ul(e),s=V(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=V(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},Gi=(e,t)=>{for(;e.filePos<t-3;){let t=ul(e),n=t&255,r=t>>>8&255,i=t>>>16&255,a=t>>>24&255;if(n===79||r===79||i===79||a===79){if(e.skip(-4),t===1399285583)return!0;e.skip(1)}}return!1},Ki=class extends hr{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(t instanceof Promise&&(t=await t),!t)break;let n=Wi(t);if(!n||!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.trackBackings.push(new qi(e,this)))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=[],o=e=>{for(;a.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(r.data.length);let s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=u(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:$n(i.data).modeBlockflags},nr(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=Xn(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=Vt,t.codecInfo.opusInfo={preSkip:i.preSkip},nr(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){n(t<e.lacingValues.length);let r=0;for(let n=0;n<t;n++)r+=e.lacingValues[n];let i=e,a=r,o=t,s=[];outer:for(;;){let t=this.reader.requestSlice(i.dataStartPos,i.dataSize);t instanceof Promise&&(t=await t),n(t);let c=B(t,i.dataSize);for(;;){if(o===i.lacingValues.length){s.push(c.subarray(r,a));break}let e=i.lacingValues[o];if(a+=e,e<255){s.push(c.subarray(r,a));break outer}o++}let l=i.headerStartPos+i.totalSize;for(;;){let t=this.reader.requestSliceRange(l,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let n=Wi(t);if(!n)return null;if(i=n,i.serialNumber===e.serialNumber)break;l=i.headerStartPos+i.totalSize}r=0,a=0,o=0}let c=s.reduce((e,t)=>e+t.length,0);if(c===0)return null;let l=new Uint8Array(c),u=0;for(let e=0;e<s.length;e++){let t=s[e];l.set(t,u),u+=t.length}return{data:l,endPage:i,endSegmentIndex:o}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(e.endPage.headerType&4)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(t,27,282);if(n instanceof Promise&&(n=await n),!n)return null;let r=Wi(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),Hi({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},qi=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new C,this.internalSampleRate=e.codecInfo.codec===`opus`?Vt:e.sampleRate}getType(){return`audio`}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return n(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return n(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...vt,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(n(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=Vi(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new F(n.metadataOnly?gr:e.data,`key`,Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}async getFirstPacket(e){n(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;this.bitstream.codecInfo.codec===`opus`&&(n(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let i=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(i,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let r=_e(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(t);if(r<0)return null;n(this.bitstream.lastMetadataPacket);let i=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!i)return null;let a=i.startPage,o=this.demuxer.reader.fileSize,s=[a];outer:for(;a.headerStartPos+a.totalSize<o;){let e=a.headerStartPos,t=Math.floor((e+o)/2),i=t;for(;;){let e=Math.min(i+Ui,o-27),c=this.demuxer.reader.requestSlice(i,e-i);if(c instanceof Promise&&(c=await c),n(c),!Gi(c,e)){o=t+27;continue outer}let l=this.demuxer.reader.requestSliceRange(c.filePos,27,282);l instanceof Promise&&(l=await l),n(l);let u=Wi(l);n(u);let d=!1;if(u.serialNumber===this.bitstream.serialNumber)d=!0;else{let e=this.demuxer.reader.requestSlice(u.headerStartPos,u.totalSize);e instanceof Promise&&(e=await e),n(e),d=Bi(B(e,u.totalSize))===u.checksum}if(!d){i=u.headerStartPos+4;continue}if(d&&u.serialNumber!==this.bitstream.serialNumber){i=u.headerStartPos+u.totalSize;continue}if(u.granulePosition===-1){i=u.headerStartPos+u.totalSize;continue}this.granulePositionToTimestampInSamples(u.granulePosition)>r?o=u.headerStartPos:(a=u,s.push(u));continue outer}}let c=i.startPage;for(let e of s){if(e.granulePosition===a.granulePosition)break;(!c||e.headerStartPos>c.headerStartPos)&&(c=e)}let l=c,u=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==a.granulePosition;){let e=l.headerStartPos+l.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),n(t);let r=Wi(t);n(r),l=r,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}n(l.granulePosition!==-1);let d=null,f,p,m=l,h=0;if(l.headerStartPos===i.startPage.headerStartPos)f=this.granulePositionToTimestampInSamples(0),p=!0,d=0;else{f=0,p=!1;for(let e=l.lacingValues.length-1;e>=0;e--)if(l.lacingValues[e]<255){d=e+1;break}if(d===null)throw Error(`Invalid page with granule position: no packets end on this page.`);h=d-1;let e={data:gr,endPage:m,endSegmentIndex:h};if(await this.demuxer.findNextPacketStart(e)){let e=Yi(u,l,d);n(e);let t=Ji(u,e.page,e.segmentIndex);t&&(l=t.page,d=t.segmentIndex)}else for(;;){let e=Yi(u,l,d);if(!e)break;let t=Ji(u,e.page,e.segmentIndex);if(!t)break;if(l=t.page,d=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,h=e.segmentIndex;break}}}let g=null,_=null;for(;l!==null;){n(d!==null);let e=await this.demuxer.readPacket(l,d);if(!e)break;if(!(l.headerStartPos===i.startPage.headerStartPos&&d<i.startSegmentIndex)){let i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:f,vorbisLastBlocksize:_?.vorbisBlockSize??null},t);n(i);let a=this.encodedPacketToMetadata.get(i);if(n(a),!p&&e.endPage.headerStartPos===m.headerStartPos&&e.endSegmentIndex===h?(f=this.granulePositionToTimestampInSamples(l.granulePosition),p=!0,i=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:f-a.durationInSamples,vorbisLastBlocksize:_?.vorbisBlockSize??null},t),n(i),a=this.encodedPacketToMetadata.get(i),n(a)):f+=a.durationInSamples,g=i,_=a,p&&(Math.max(f,0)>r||Math.max(a.timestampInSamples,0)===r))break}let a=await this.demuxer.findNextPacketStart(e);if(!a)break;l=a.startPage,d=a.startSegmentIndex}return g}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let r=_e(e*this.internalSampleRate);e=r/this.internalSampleRate;let a=w(this.sequentialScanCache,r,e=>e.timestampInSamples),o;if(a!==-1){let e=this.sequentialScanCache[a];o=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else o=await this.getFirstPacket(t);let s=0;for(;o&&o.timestamp<e;){let r=await this.getNextPacket(o,t);if(!r||r.timestamp>e)break;if(o=r,s++,s===100){s=0;let e=this.encodedPacketToMetadata.get(o);n(e),this.sequentialScanCache.length>0&&n(i(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return o}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Ji=(e,t,r)=>{let i=t,a=r;outer:for(;;){for(a--;a>=0;a--)if(i.lacingValues[a]<255){a++;break outer}if(n(a===-1),!(i.headerType&1)){a=0;break}let t=se(e,e=>e.headerStartPos<i.headerStartPos);if(!t)return null;i=t,a=i.lacingValues.length}if(n(a!==-1),a===i.lacingValues.length){let t=e[e.indexOf(i)+1];n(t),i=t,a=0}return{page:i,segmentIndex:a}},Yi=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=se(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null},Xi;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(Xi||={});var Zi=class extends hr{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),n(e);let t=W(e,4),r=t!==`RIFX`,i=t===`RF64`,a=ll(e,r),o=i?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if(W(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let s=0,c=null,l=e.filePos;for(;o===null||l<o;){let e=this.reader.requestSlice(l,8);if(e instanceof Promise&&(e=await e),!e)break;let t=W(e,4),n=ll(e,r),a=e.filePos;if(i&&s===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(a,n,r);else if(t===`data`){if(c??=n,this.dataStart=e.filePos,this.dataSize=Math.min(c,(o??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(a,n);if(e instanceof Promise&&(e=await e),!e)break;let t=pl(e,r);c=pl(e,r),o=Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(a,n,r):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(a,n);l=a+n+(n&1),s++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.trackBackings.push(new $i(this))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=ol(r,n),a=ol(r,n),o=ll(r,n);r.skip(4);let s=ol(r,n),c;if(c=t===14?8:ol(r,n),t>=18&&i!==357){let e=ol(r,n),a=t-18;if(Math.min(a,e)>=22&&i===Xi.EXTENSIBLE){r.skip(6);let e=B(r,16);i=e[0]|e[1]<<8}}(i===Xi.MULAW||i===Xi.ALAW)&&(c=8),this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=W(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=W(r,4),t=ll(r,n),i=B(r,t),o=0;for(let e=0;e<i.length&&i[e]!==0;e++)o++;let s=String.fromCharCode(...i.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case`INAM`:case`TITL`:this.metadataTags.title??=s;break;case`TIT3`:this.metadataTags.description??=s;break;case`IART`:this.metadataTags.artist??=s;break;case`IPRD`:this.metadataTags.album??=s;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=s.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:case`IDIT`:{let e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=s;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=s}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let r=wl(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&Tl(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(n(this.audioInfo),this.audioInfo.format===Xi.MULAW)return`ulaw`;if(this.audioInfo.format===Xi.ALAW)return`alaw`;if(this.audioInfo.format===Xi.PCM){if(this.audioInfo.sampleSizeInBytes===1)return`pcm-u8`;if(this.audioInfo.sampleSizeInBytes===2)return`pcm-s16`;if(this.audioInfo.sampleSizeInBytes===3)return`pcm-s24`;if(this.audioInfo.sampleSizeInBytes===4)return`pcm-s32`}return this.audioInfo.format===Xi.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?`pcm-f32`:null}async getMimeType(){return`audio/wav`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},Qi=2048,$i=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(n(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return n(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...vt}}async getPacketAtIndex(e,t){n(e>=0),n(this.demuxer.audioInfo);let r=e*Qi*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let i=Math.min(Qi*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);if(e instanceof Promise&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=gr;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,i);e instanceof Promise&&(e=await e),n(e),a=B(e,i)}let o=e*Qi/this.demuxer.audioInfo.sampleRate,s=i/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new F(a,`key`,o,s,e,i)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){n(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Qi,(this.demuxer.dataSize-1)/(Qi*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;let i=await this.getPacketAtIndex(r,t);if(i)return i;if(r===0)return null;n(this.demuxer.reader.fileSize===null);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){let e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){n(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Qi);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},ea=e=>{let t=e.filePos,n=new k(B(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},ta=1024,na=class extends hr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new C,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();n(this.firstFrameHeader),this.trackBackings=[new ra(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=wl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=ea(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=t;let r=bt[t.samplingFrequencyIndex];n(r!==void 0);let i=ta/r,a={timestamp:this.nextTimestampInSamples/r,duration:i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=ta,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return`audio/aac`}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;let n=wl(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;Tl(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},ra=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ta}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`aac`}getInternalCodecId(){return n(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){n(this.demuxer.firstFrameHeader);let e=xt[this.demuxer.firstFrameHeader.channelConfiguration];return n(e!==void 0),e}getSampleRate(){n(this.demuxer.firstFrameHeader);let e=bt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return n(e!==void 0),e}getDisposition(){return{...vt}}async getDecoderConfig(){return n(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=gr;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=B(e,n.dataSize)}return new F(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=ie(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=w(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},ia=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,aa=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return`uncommon-u8`;case 13:return`uncommon-u16`;case 14:return`uncommon-u16-10`;default:return null}},oa=e=>{let t=0,n=new k(B(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new k(B(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e|t<<n,0)},sa=(e,t)=>{if(t===`uncommon-u16`)return H(e)+1;if(t===`uncommon-u8`)return V(e)+1;if(typeof t==`number`)return t;E(t),n(!1)},ca=(e,t)=>t===`uncommon-u16`?H(e):t===`uncommon-u16-10`?H(e)*10:t===`uncommon-u8`?V(e):typeof t==`number`?t:null,la=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t},ua=class extends hr{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new C,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),n(this.trackBacking),[this.trackBacking]}async getMimeType(){return`audio/flac`}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);n(t);let r=V(t),i=sl(t),a=!!(r&128);switch(r&127){case tr.STREAMINFO:{let t=this.reader.requestSlice(e,i);if(t instanceof Promise&&(t=await t),n(t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let r=B(t,34),a=new k(r),o=a.readBits(16),s=a.readBits(16),c=a.readBits(24),l=a.readBits(24),u=a.readBits(20),d=a.readBits(3)+1;a.readBits(5);let f=a.readBits(36);a.skipBits(128);let p=new Uint8Array(42);p.set(new Uint8Array([102,76,97,67]),0),p.set(new Uint8Array([128,0,0,34]),4),p.set(r,8),this.audioInfo={numberOfChannels:d,sampleRate:u,totalSamples:f,minimumBlockSize:o,maximumBlockSize:s,minimumFrameSize:c,maximumFrameSize:l,description:p},this.trackBacking=new da(this);break}case tr.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,i);t instanceof Promise&&(t=await t),n(t),nr(B(t,i),this.metadataTags);break}case tr.PICTURE:{let t=this.reader.requestSlice(e,i);t instanceof Promise&&(t=await t),n(t);let r=U(t),a=U(t),o=d.decode(B(t,a)),s=U(t),c=d.decode(B(t,s));t.skip(16);let l=U(t),u=B(t,l);this.metadataTags.images??=[],this.metadataTags.images.push({data:u,mimeType:o,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,description:c});break}}if(e+=i,a){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw Error(`Missing STREAMINFO metadata block! Corrupted FLAC file.`)})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){n(this.audioInfo);let r=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,i=this.audioInfo.minimumFrameSize||10,a=(this.audioInfo.maximumFrameSize||r)+16,o=await this.reader.requestSliceRange(e,16,a);if(!o)return null;let s=this.readFlacFrameHeader({slice:o,isFirstPacket:t});if(!s)return null;for(o.filePos=e+i;;){if(o.filePos>o.end-6)return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:o.end-e,isLastFrame:!0};if(V(o)===255){let t=o.filePos;if(V(o)!==(this.blockingBit===1?249:248)){o.filePos=t;continue}o.skip(-2);let n=o.filePos-e,r=this.readFlacFrameHeader({slice:o,isFirstPacket:!1});if(!r){o.filePos=t;continue}if(this.blockingBit===0){if(r.num-s.num!==1){o.filePos=t;continue}}else if(r.num-s.num!==s.blockSize){o.filePos=t;continue}return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let r=e.filePos,i=new k(B(e,4));if(i.readBits(15)!==32764)return null;if(this.blockingBit===null){n(t);let e=i.readBits(1);this.blockingBit=e}else if(this.blockingBit===1){if(n(!t),i.readBits(1)!==1)return null}else if(this.blockingBit===0){if(n(!t),i.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let a=ia(i.readBits(4));if(!a)return null;n(this.audioInfo);let o=aa(i.readBits(4),this.audioInfo.sampleRate);if(!o||(i.readBits(4),i.readBits(3),i.readBits(1)!==0))return null;let s=oa(e),c=sa(e,a),l=ca(e,o);if(l===null||l!==this.audioInfo.sampleRate)return null;let u=e.filePos-r,d=V(e);return e.skip(-u),e.skip(-1),d===la(B(e,u))?{num:s,blockSize:c,sampleRate:l}:null}async advanceReader(){await this.readMetadata(),n(this.lastLoadedPos!==null),n(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],i={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos+=t.size,this.loadedSamples.push(i),t.isLastFrame){this.lastSampleLoaded=!0;return}}},da=class{constructor(e){this.demuxer=e}getType(){return`audio`}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return n(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...vt}}async getDecoderConfig(){return n(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(n(this.demuxer.audioInfo),e<0)return null;let r=await this.demuxer.readingMutex.acquire();try{for(;;){let n=w(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[n];if(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{r()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=gr;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;i=B(e,r.byteSize)}n(this.demuxer.audioInfo);let a=r.blockOffset/this.demuxer.audioInfo.sampleRate,o=r.blockSize/this.demuxer.audioInfo.sampleRate;return new F(i,`key`,a,o,e,r.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}},fa=9e4,pa=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},ma=`PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.`,ha=new Set,ga=class extends hr{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),n(e);let t=B(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let r=this.packetOffset,i=null,a=!1,o=!1;for(;;){let e=await this.readPacketHeader(r);if(!e)break;if(e.payloadUnitStartIndicator===0){r+=this.packetStride;continue}let t=await this.readSection(r,!0,!o);if(!t)break;let s=!1;if(!o&&t.pid!==0&&(t.payload[0]!==0||t.payload[1]!==0||t.payload[2]!==1)){let e=new k(t.payload),n=e.readAlignedByte();e.skipBits(8*n),s=e.readBits(8)===2}if(t.pid===0&&!a){let e=new k(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(14);let r=e.readBits(10);for(e.skipBits(40);8*(r+3)-e.pos>32;){let t=e.readBits(16);e.skipBits(3);let n=e.readBits(13);if(t!==0){if(i!==null)throw Error(`Only files with a single program are supported.`);i=n}}if(i===null)throw Error(`Program Association Table must link to a Program Map Table.`);a=!0}else if((t.pid===i||s)&&!o){let e=new k(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10);for(e.skipBits(8*i);8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,o=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8);t===106?a=!0:(t===122||t===204)&&(o=!0),e.skipBits(8*n)}let s=null;switch(t){case 27:case 36:s={type:`video`,codec:t===27?`avc`:`hevc`,decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let e;if(t===3||t===4)e=`mp3`;else if(t===15)e=`aac`;else if(t===129)e=`ac3`;else if(t===135)e=`eac3`;else throw Error(`Unreachable.`);s={type:`audio`,codec:e,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:o?s={type:`audio`,codec:`eac3`,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:a&&(s={type:`audio`,codec:`ac3`,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:ha.has(t)||(console.warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),ha.add(t))}s&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:s,referencePesPackets:[]})}o=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);outer:if(e&&!e.initialized){let r=va(t,!0);if(!r)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=t.randomAccessIndicator===1,this.input._initInput){let n=(await this.input._initInput._getDemuxer()).elementaryStreams.find(n=>n.pid===t.pid&&n.info.codec===e.info.codec);if(n){e.info=n.info,e.initialized=!0;break outer}}let i=new Ca(e,r);if(e.info.type===`video`){for(;;){let t=i;if(t.suppliedPacket=null,await i.markNextPacket(),e.info.codec===`avc`){if(!i.suppliedPacket)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.`);if(e.info.avcCodecInfo=En(i.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];n(t);let r=An(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;let a=r.pixelAspectRatio.num,o=r.pixelAspectRatio.den;a>0&&o>0&&(a>o?(e.info.squarePixelWidth=Math.round(e.info.width*a/o),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*o/a))),e.info.colorSpace={primaries:g[r.colourPrimaries],transfer:v[r.transferCharacteristics],matrix:b[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}if(e.info.codec===`hevc`){if(!i.suppliedPacket)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);if(e.info.hevcCodecInfo=In(i.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===N.SPS_NUT).nalUnits[0];n(t);let r=Fn(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:g[r.colourPrimaries],transfer:v[r.transferCharacteristics],matrix:b[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw Error(`Unhandled.`)}e.info.decoderConfig={codec:Lt({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},(e.info.width!==e.info.squarePixelWidth||e.info.height!==e.info.squarePixelHeight)&&(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await i.markNextPacket(),!i.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if(e.info.codec===`aac`){let t=ea(il.tempFromBytes(i.suppliedPacket.data));if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=xt[t.channelConfiguration],e.info.sampleRate=bt[t.samplingFrequencyIndex]}else if(e.info.codec===`mp3`){let t=ln(U(il.tempFromBytes(i.suppliedPacket.data)),i.suppliedPacket.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=pn(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if(e.info.codec===`ac3`){let t=ar(i.suppliedPacket.data);if(!t)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(t.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=ir[t.acmod]+t.lfeon,e.info.sampleRate=mn[t.fscod]}else if(e.info.codec===`eac3`){let t=dr(i.suppliedPacket.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let n=pr(t);if(n===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=mr(t),e.info.sampleRate=n}else throw Error(`Unhandled.`);e.info.decoderConfig={codec:zt({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}if(o&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!o)throw Error(a?`No Program Map Table found in the file.`:`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.info.type===`video`?this.trackBackingEntries.push(new ba(e)):this.trackBackingEntries.push(new xa(e))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),pa(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,n=!1){let r=e,i=e,a=[],o=0,s=null,c=!0,l=0;for(;;){let e=await this.readPacket(i);if(i+=this.packetStride,!e)break;if(s){if(e.pid!==s.pid){if(n)break;continue}if(e.payloadUnitStartIndicator===1)break}else{if(e.payloadUnitStartIndicator===0)break;s=e}let u=!!(e.adaptationFieldControl&2),d=!!(e.adaptationFieldControl&1),f=0;if(u&&(f=1+e.body[0],e===s&&f>1&&(l=e.body[1]>>6&1)),d&&(f===0?(a.push(e.body),o+=e.body.byteLength):(a.push(e.body.subarray(f)),o+=e.body.byteLength-f)),r=i,!t&&o>=64){c=!1;break}if(ie(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=w(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!s)return null;let u;if(a.length===1)u=a[0];else{let e=a.reduce((e,t)=>e+t.length,0);u=new Uint8Array(e);let t=0;for(let e of a)u.set(e,t),t+=e.length}return{startPos:e,endPos:t?r:null,pid:s.pid,payload:u,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(V(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=H(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=V(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=B(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}},_a=(e,t)=>{if(e.payload.byteLength<3)return null;let n=new k(e.payload);if(n.readBits(24)!==1)return null;let r=n.readBits(8);if(n.skipBits(16),r===188||r===190||r===191||r===240||r===241||r===255||r===242||r===248)return null;n.skipBits(8);let i=n.readBits(2);n.skipBits(14);let a=null;if(i===2||i===3)a=0,n.skipBits(4),a+=n.readBits(3)*(1<<30),n.skipBits(1),a+=n.readBits(15)*32768,n.skipBits(1),a+=n.readBits(15);else if(t)throw Error(ma);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:a,randomAccessIndicator:e.randomAccessIndicator}},va=(e,t)=>{n(e.endPos!==null);let r=_a(e,t);if(!r)return null;let i=new k(e.payload);i.skipBits(32);let a=i.readBits(16);i.skipBits(16);let o=i.readBits(8),s=i.pos+8*o;i.pos=s;let c=s/8;n(Number.isInteger(c));let l=e.payload.subarray(c,a>0?6+a:e.payload.byteLength);return{...r,data:l}},ya=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,r=this.elementaryStream.info.type,i=0;for(let a of t.trackBackingEntries)if(a.getType()===r&&i++,n(a instanceof e),a.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...vt,primary:!1}}getTimeResolution(){return fa}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new F(n.metadataOnly?gr:e.data,r,e.pts/fa,Math.max(t/fa,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;n(t);let r=va(t,!0);n(r);let i=new Ca(this.elementaryStream,r),a=new wa(this,i),o=await a.readNext();if(!o)return null;let s=this.createEncodedPacket(o.packet,o.duration,e);return this.packetBuffers.set(s,a),this.packetSectionStarts.set(s,o.packet.sectionStartPos),s}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){let n=await r.readNext();if(!n)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(n.packet,n.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,n.packet.sectionStartPos),i}let i=this.packetSectionStarts.get(e);if(i===void 0)throw Error(`Packet was not created from this track.`);let a=await this.elementaryStream.demuxer.readSection(i,!0);n(a);let o=va(a,!0);n(o);let s=new Ca(this.elementaryStream,o);r=new wa(this,s);let c=e.sequenceNumber;for(;;){let e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){let n=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(n,r),this.packetSectionStarts.set(n,e.packet.sectionStartPos),n}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,r){let a=_e(e*fa),o=this.elementaryStream.demuxer,{reader:s,seekChunkSize:c}=o,l=this.elementaryStream.pid,u=async(e,t,n)=>{let r=e;for(;r<t;){let e=await o.readPacketHeader(r);if(!e)return null;if(e.pid===l&&e.payloadUnitStartIndicator===1){let e=await o.readSection(r,n);if(!e)return null;let t=_a(e,!1);if(t&&t.pts!==null)return{pesPacketHeader:t,section:e}}r+=o.packetStride}return null},d=this.elementaryStream.firstSection;n(d);let f=_a(d,!0);if(n(f),a<f.pts)return null;let p,m=this.elementaryStream.referencePesPackets,h=w(m,a,e=>e.pts),g=h===-1?null:m[h];if(g&&a-g.pts<9e4/2)p=g.sectionStartPos;else{let e=0;if(s.fileSize!==null){let t=Math.ceil(s.fileSize/c);if(t>1){let n=0,r=t-1;for(e=n;n<=r;){let t=Math.floor((n+r)/2),i=be(t*c,o.packetStride)+f.sectionStartPos,s=await u(i,i+c,!1);if(!s){r=t-1;continue}s.pesPacketHeader.pts<=a?(e=t,n=t+1):r=t-1}}}p=be(e*c,o.packetStride)+f.sectionStartPos}let _=(await u(p,s.fileSize??1/0,!1))?.pesPacketHeader??null;_||=f;let v=this.getReorderSize(),y=async(e,t)=>{let s=await o.readSection(e,!0);n(s);let c=va(s,!0);n(c);let l=new Ca(this.elementaryStream,c),u=new wa(this,l);for(;!((i(u.presentationOrderPackets)?.pts??-1/0)>=a||!await u.readNextPacket()););let d=ce(u.presentationOrderPackets,t);if(d===-1)return null;let f=u.presentationOrderPackets[d],p=d===0?0:f.pts-u.presentationOrderPackets[d-1].pts;for(;u.decodeOrderPackets[0]!==f;)u.decodeOrderPackets.shift();u.lastDuration=p;let m=await u.readNext();n(m);let h=this.createEncodedPacket(m.packet,m.duration,r);return this.packetBuffers.set(h,u),this.packetSectionStarts.set(h,m.packet.sectionStartPos),h};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=_.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break outer;if(t.pid===l&&t.payloadUnitStartIndicator===1){let t=await o.readSection(e,!1);if(t){let e=_a(t,!1);if(e&&e.pts!==null){if(e.pts>a)break outer;_=e,Sa(this.elementaryStream,_);break}}}e+=o.packetStride}}outer:for(let e=0;e<v+1;e++){let e=_.sectionStartPos-o.packetStride;for(;e>=o.packetOffset;){let t=await o.readPacketHeader(e);if(!t)break outer;if(t.pid===l&&t.payloadUnitStartIndicator===1){let t=await o.readSection(e,!1);if(t){let e=_a(t,!1);if(e&&e.pts!==null){_=e;break}}}e-=o.packetStride}}return y(_.sectionStartPos,e=>e.pts<=a)}{let e=p,t=null,r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let i=null,p=e<=f.sectionStartPos,m,h=null;if(p)m=f,h=d;else{let t=await u(e,s.fileSize??1/0,r);m=t?.pesPacketHeader??null,h=t?.section??null}let g=!1,_=0;outer:for(;m&&!(t!==null&&m.sectionStartPos>=t);){if(m.pts<=a){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=m.randomAccessIndicator===1;else{n(h);let t=va(h,!0);n(t);let r=new Ca(this.elementaryStream,t);await r.markNextPacket(),e=r.suppliedPacket?.randomAccessIndicator===1}e&&(i=m)}if(m.pts>a&&(g=!0),g&&(_++,_>v))break;let e=m.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break outer;if(t.pid===l&&t.payloadUnitStartIndicator===1){let t=await o.readSection(e,r);if(t){let e=_a(t,!1);if(e&&e.pts!==null){m=e,h=t,Sa(this.elementaryStream,m);break}}}e+=o.packetStride}}if(i){let e=i;if(_===0)outer:for(let t=0;t<v;t++){let t=e.sectionStartPos-o.packetStride;for(;t>=o.packetOffset;){let n=await o.readPacketHeader(t);if(!n)break outer;if(n.pid===l&&n.payloadUnitStartIndicator===1){let n=await o.readSection(t,r);if(n){let t=_a(n,!1);if(t&&t.pts!==null){e=t;break}}}t-=o.packetStride}}let t=await y(e.sectionStartPos,e=>e.pts<=a&&e.randomAccessIndicator===1);return n(t),t}if(p)return null;t=e,e=Math.max(be(e-f.sectionStartPos-c,o.packetStride)+f.sectionStartPos,f.sectionStartPos)}}}},ba=class extends ya{getType(){return`video`}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},xa=class extends ya{getType(){return`audio`}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return n(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},Sa=(e,t)=>{let n=e.referencePesPackets,r=w(n,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let i=n[r];if(t.pts<=i.pts)return!1;let a=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-i.sectionStartPos<a)return!1;if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<a)return!1}}return n.splice(r+1,0,t),!0},Ca=class{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return n(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=i(this.pesPackets).sectionEndPos;for(n(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=va(n,!1);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,r=n+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(n,r);let i=new Uint8Array(e);i.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),n=e-a;if(n<=t.data.byteLength){i.set(t.data.subarray(0,n),a);break}i.set(t.data,a),a+=t.data.byteLength}return i}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){n(!this.suppliedPacket);let e=this.elementaryStream;if(e.info.type===`video`){let t=e.info.codec,n=1024;if(t!==`avc`&&t!==`hevc`)throw Error(`Unhandled.`);let r=null;for(;;){let e=this.ensureBuffered(n);if(e instanceof Promise&&(e=await e),e===0)break;let i=this.currentPos,a=this.readBytes(e),o=a.byteLength,s=0;for(;s<o;){let e=a.indexOf(0,s);if(e===-1||e>=o)break;s=e;let n=i+s;if(s+4>=o){this.seekTo(n);break}let c=a[s+1],l=a[s+2],u=a[s+3],d=0,f=null;if(c===0&&l===0&&u===1?(d=4,f=a[s+4]):c===0&&l===1&&(d=3,f=u),d===0){s++;continue}let p=n;if(r===null){r=p,s+=d;continue}if(f!==null){let e=t===`avc`?bn(f):Pn(f);if(t===`avc`?e===gn.AUD:e===N.AUD_NUT){let e=p-r;return this.seekTo(r),this.supplyPacket(e,0)}}s+=d}if(e<n)break}if(r!==null){let e=this.endPos-r;return this.seekTo(r),this.supplyPacket(e,0)}}else{let t=e.info.codec;for(;;){let r=this.ensureBuffered(128);r instanceof Promise&&(r=await r);let i=this.currentPos;for(;this.currentPos-i<r;){let r=this.readU8();if(t===`aac`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(9);if(n instanceof Promise&&(n=await n),n<9)return;let i=this.readBytes(9),a=ea(il.tempFromBytes(i));if(a){this.seekTo(t);let n=this.ensureBuffered(a.frameLength);return n instanceof Promise&&(n=await n),this.supplyPacket(n,Math.round(ta*fa/e.info.sampleRate))}this.seekTo(t+1)}else if(t===`mp3`){if(r!==255)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(4);if(n instanceof Promise&&(n=await n),n<4)return;let i=ln(u(this.readBytes(4)).getUint32(0),null);if(i.header){this.seekTo(t);let n=this.ensureBuffered(i.header.totalSize);n instanceof Promise&&(n=await n);let r=i.header.audioSamplesInFrame*fa/e.info.sampleRate;return this.supplyPacket(n,Math.round(r))}this.seekTo(t+1)}else if(t===`ac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,i=this.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=this.readBytes(5);if(a[0]!==11||a[1]!==119){this.seekTo(t+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){this.seekTo(t+1);continue}let c=or[3*s+o];n(c!==void 0),this.seekTo(t),i=this.ensureBuffered(c),i instanceof Promise&&(i=await i);let l=Math.round(sr*fa/e.info.sampleRate);return this.supplyPacket(i,l)}else if(t===`eac3`){if(r!==11)continue;this.skip(-1);let t=this.currentPos,n=this.ensureBuffered(5);if(n instanceof Promise&&(n=await n),n<5)return;let i=this.readBytes(5);if(i[0]!==11||i[1]!==119){this.seekTo(t+1);continue}let a=(((i[2]&7)<<8|i[3])+1)*2,o=ur[i[4]>>6==3?3:i[4]>>4&3];this.seekTo(t),n=this.ensureBuffered(a),n instanceof Promise&&(n=await n);let s=o*256,c=Math.round(s*fa/e.info.sampleRate);return this.supplyPacket(n,c)}else throw Error(`Unhandled.`)}if(r<128)break}}}supplyPacket(e,t){let r=this.getCurrentPesPacket(),i;if(this.lastSuppliedPesPacket===r)n(this.nextPts!==null),i=this.nextPts;else{if(r.pts===null)throw Error(ma);i=r.pts,Sa(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=i+t;let a=r.sectionStartPos,o=a+(this.currentPos-this.currentPesPacketPos),s=this.readBytes(e),c=r.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type===`audio`)c=1;else if(this.elementaryStream.info.decoderConfig){let e=er(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,s)===`key`;c=Number(e)}}this.suppliedPacket={pts:i,data:s,sequenceNumber:o,sectionStartPos:a,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},wa=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),n(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);n(t!==-1);let r;for(t===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(n(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}},Ta=`application/vnd.apple.mpegurl`,Ea=`#EXT-X-STREAM-INF:`,Da=`#EXT-X-I-FRAME-STREAM-INF:`,Oa=`#EXT-X-MEDIA:`,ka=`#EXTINF:`,Aa=`#EXT-X-MAP:`,ja=`#EXT-X-KEY:`,Ma=`#EXT-X-MEDIA-SEQUENCE:`,Na=`#EXT-X-BYTERANGE:`,Pa=`#EXT-X-PROGRAM-DATE-TIME:`,Fa=`#EXT-X-TARGETDURATION:`,Ia=e=>e.length===0||e.startsWith(`#`)&&!e.startsWith(`#EXT`),La=class{constructor(e){this._attributes={};let t=``,n=``,r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];o===`"`?i=!i:o===`=`&&!r&&!i?r=!0:o===`,`&&!i?(t&&(this._attributes[t.trim().toLowerCase()]=n),t=``,n=``,r=!1):r?n+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=n)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(t===null)return null;let n=Number(t);return Number.isFinite(n)?n:null}merge(e){Object.assign(this._attributes,e._attributes)}},Ra=class{constructor(e,t,n){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=n}async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if(t.type===`video`){let n=Je(e,e=>e.getType()===`video`)+1;e.push(new Ba(this,t,n))}else if(t.type===`audio`){let n=Je(e,e=>e.getType()===`audio`)+1;e.push(new Va(this,t,n))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let t=await this.getInputForSegment(this.firstSegment).getTracks();for(let n of t)if(n.type===`video`){let t=Je(e,e=>e.getType()===`video`)+1;e.push(new Ba(this,{id:e.length+1,type:`video`},t))}else if(n.type===`audio`){let t=Je(e,e=>e.getType()===`audio`)+1;e.push(new Va(this,{id:e.length+1,type:`audio`},t))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(t!==void 0)return t;let n=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,n),n}async getMediaOffset(e,t){let n=e.firstSegment??e,r;if(this.firstSegmentFirstTimestamps.has(n))r=this.firstSegmentFirstTimestamps.get(n);else{let e=this.getInputForSegment(n);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(n,r)}if(n===e)return n.timestamp-r;let i=await this.getFirstTimestampForInput(t),a=e.timestamp-n.timestamp,o=i-r-a;return Math.abs(o)<=Math.min(.25,a)?n.timestamp-r:e.timestamp-i}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}},za=class{constructor(e,t,n){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=n}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error(`Missing first segment, can't retrieve track.`);let e=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!e)throw Error(`No matching track found in underlying media data.`);this.firstInputTrack=e})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),n(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,r){n(e.sequenceNumber>=0),n(this.segmentedInput.firstSegment);let i=await this.segmentedInput.getMediaOffset(t,r.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,o=e.clone({timestamp:ye(e.timestamp+i,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(o,{segment:t,track:r,sourcePacket:e}),o}async getFirstPacket(e){await this.hydrate(),n(this.segmentedInput.firstSegment),n(this.firstInputTrack);let t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,n){let r=this.packetInfos.get(e);if(!r)throw Error(`Packet was not created from this track.`);let i=n?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(i)return this.createAdjustedPacket(i,r.segment,r.track);let a=r.segment;for(;;){let e=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!e)return null;let n=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){a=e;continue}let i=await n._backing.getFirstPacket(t);return i?this.createAdjustedPacket(i,e,n):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,n){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){let i=this.segmentedInput.getInputForSegment(r),a=(await i.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!a){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}let o=e-await this.segmentedInput.getMediaOffset(r,i),s=n?await a._backing.getKeyPacket(o,t):await a._backing.getPacket(o,t);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(s,r,a)}return null}},Ba=class extends za{getType(){return`video`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Va=class extends za{getType(){return`audio`}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Ha=e(t(),1);Ke();var Ua=Ha===void 0?void 0:Ha,Wa=1/0,Ga=null;typeof FinalizationRegistry<`u`&&(Ga=new FinalizationRegistry(e=>{e()}));var Ka=class extends ut{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 nl;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e===void 0?(await this._read(0,1,0,Wa),e=this._getFileSize(),n(e!==void 0),e):e})()}async getSize(){if(this._disposed)throw new nl;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError(`offset must be a non-negative integer.`);if(t!==void 0&&(!Number.isInteger(t)||t<0))throw TypeError(`length, when provided, must be a non-negative integer.`);return new lo(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit(`read`,{start:e,end:t})}ref(){return new qa(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}},qa=class{constructor(e){if(this._freed=!1,e._disposed)throw Error(`Cannot ref a disposed source.`);e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error(`Can't get source; ref has already been freed.`);return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error(`Illegal operation: double free on SourceRef.`);let e=this.source;n(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Ja=class extends Ka{constructor(e,t){if(typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`requestHandler must be a function.`);super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),n=e=>{if(!(e instanceof Ka||e instanceof qa))throw TypeError(`requestHandler must return or resolve to a Source or SourceRef.`);let t=e instanceof Ka?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(n):n(t)}},Ya=(e,t)=>e.path===t.path,Xa=class extends Ja{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,i){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{let t=e instanceof Ka?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),n(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,r,i))}return this._root.source._read(e,t,r,i)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},Za=class extends Ka{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError(`buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.`);super(),this._onreadCalled=!1,this._bytes=l(e),this._view=u(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||=(this._dispatchRead(0,this._bytes.byteLength),!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}},Qa=class extends Ka{constructor(e,t={}){if(!(e instanceof Blob))throw TypeError(`blob must be a Blob.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!qe(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(t.useStreamReader!==void 0&&typeof t.useStreamReader!=`boolean`)throw TypeError(`options.useStreamReader, when provided, must be a boolean.`);super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new co({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:so.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,n,r){return this._orchestrator.read(e,t,n,r)}async _runWorker(e){n(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&(t=(`stream`in this._blob)&&!Me()&&this._options.useStreamReader!==!1?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:r}=await t.read();if(n)throw this._orchestrator.onWorkerFinished(e),Error(`Blob reader stopped unexpectedly before all requested data was read.`);if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else{let t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},$a=.5*2**20,eo=((e,t,n)=>{if(t instanceof Error&&(t.message.includes(`Failed to fetch`)||t.message.includes(`Load failed`)||t.message.includes(`NetworkError when attempting to fetch resource`))&&typeof window<`u`){let e=null;try{typeof window<`u`&&window.location!==void 0&&(e=new URL(n instanceof Request?n.url:n,window.location.href).origin)}catch{}if((!(typeof navigator<`u`&&typeof navigator.onLine==`boolean`)||navigator.onLine)&&e!==null&&e!==window.location.origin)return console.warn(`Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option.`),null}return Math.min(2**(e-2),16)}),to=new Set,no=class e extends Ja{constructor(t,n={}){if(typeof t!=`string`&&!(t instanceof URL)&&!(typeof Request<`u`&&t instanceof Request))throw TypeError(`url must be a string, URL or Request.`);if(!n||typeof n!=`object`)throw TypeError(`options must be an object.`);if(n.requestInit!==void 0&&(!n.requestInit||typeof n.requestInit!=`object`))throw TypeError(`options.requestInit, when provided, must be an object.`);if(n.getRetryDelay!==void 0&&typeof n.getRetryDelay!=`function`)throw TypeError(`options.getRetryDelay, when provided, must be a function.`);if(n.maxCacheSize!==void 0&&(!qe(n.maxCacheSize)||n.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(n.parallelism!==void 0&&(!Number.isInteger(n.parallelism)||n.parallelism<1))throw TypeError(`options.parallelism, when provided, must be a positive number.`);if(n.fetchFn!==void 0&&typeof n.fetchFn!=`function`)throw TypeError(`options.fetchFn, when provided, must be a function.`);let r=t instanceof Request?t.url:t instanceof URL?t.href:t;super(r,t=>new e(t.path,this._options)),this._fileSizeDetermined=!1,this._url=t,this._options=n,this._getRetryDelay=n.getRetryDelay??eo,this._orchestrator=new co({maxCacheSize:n.maxCacheSize??64*2**20,maxWorkerCount:n.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:so.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,n,r){return this._orchestrator.read(e,t,n,r)}async _runWorker(e){for(;;){let t=new AbortController,n=await Oe(this._options.fetchFn??fetch,this._url,Ee(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);outer:if(this._orchestrator.fileSize===null){let t=n.headers.get(`Content-Range`);if(t){let e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break outer}}let r=n.headers.get(`Content-Length`);r&&this._orchestrator.supplyFileSize(e.currentPos+Number(r))}if(this._fileSizeDetermined=!0,n.status!==206){if(!this._usedForHls){let e=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<`u`?window.location.href:void 0);e.origin!==`null`&&!(e.pathname.endsWith(`.m3u8`)||e.pathname.endsWith(`.m3u`))&&(to.has(e.origin)||(console.log(this._usedForHls,this._url,e.pathname),console.warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),to.add(e.origin)))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize===null?(e.targetPos=1/0,e.strictTarget=!1):e.targetPos=this._orchestrator.fileSize,this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!n.body)throw Error(`Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.`);let r=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let n;try{n=await r.read()}catch(e){if(this._disposed)throw e;let t=this._getRetryDelay(1,e,this._url);if(t!==null){console.error(`Error while reading response stream. Attempting to resume.`,e),await ct(1e3*t);break}throw e}if(e.aborted)continue;let{done:i,value:a}=n;if(i){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+a.length),this._orchestrator.supplyWorkerData(e,a)}}}_dispose(){this._orchestrator.dispose()}},ro=class e extends Ja{constructor(t,r={}){if(typeof t!=`string`)throw TypeError(`filePath must be a string.`);if(!r||typeof r!=`object`)throw TypeError(`options must be an object.`);if(r.maxCacheSize!==void 0&&(!qe(r.maxCacheSize)||r.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(!Ua.fs)throw Error(`FilePathSource is only available in server-side environments (Node.js, Bun, Deno).`);super(t,t=>new e(t.path,r)),this._fileHandle=null,this._customSource=new io({getSize:async()=>{let e=await Ua.fs.open(t,`r`);return this._fileHandle=e,Ga?.register(this,()=>{e.close()},this),(await e.stat()).size},read:async(e,t)=>{n(this._fileHandle);let r=new Uint8Array(t-e);return await this._fileHandle.read(r,0,t-e,e),r},maxCacheSize:r.maxCacheSize,prefetchProfile:`fileSystem`})}_read(e,t,n,r){return this._customSource._read(e,t,n,r)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Ga?.unregister(this))}},io=class extends Ka{constructor(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(typeof e.getSize!=`function`)throw TypeError(`options.getSize must be a function.`);if(typeof e.read!=`function`)throw TypeError(`options.read must be a function.`);if(e.dispose!==void 0&&typeof e.dispose!=`function`)throw TypeError(`options.dispose, when provided, must be a function.`);if(e.maxCacheSize!==void 0&&(!qe(e.maxCacheSize)||e.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);if(e.prefetchProfile&&![`none`,`fileSystem`,`network`].includes(e.prefetchProfile))throw TypeError(`options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.`);super(),this._options=e,this._orchestrator=new co({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:so[e.prefetchProfile??`none`],runWorker:this._runWorker.bind(this)})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,n,r){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,n,r);let i=this._options.getSize();if(i instanceof Promise)return i.then(i=>{if(!Number.isInteger(i)||i<0)throw TypeError(`options.getSize must return or resolve to a non-negative integer.`);return this._orchestrator.fileSize=i,this._orchestrator.read(e,t,n,r)});if(!Number.isInteger(i)||i<0)throw TypeError(`options.getSize must return or resolve to a non-negative integer.`);return this._orchestrator.fileSize=i,this._orchestrator.read(e,t,n,r)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let t=e.currentPos,n=e.targetPos,r=this._options.read(e.currentPos,n);if(r instanceof Promise&&(r=await r),e.aborted)break;if(r instanceof Uint8Array){if(r=l(r),r.length!==n-e.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${n-e.currentPos} bytes, but got ${r.length}.`);this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else if(r instanceof ReadableStream){let i=r.getReader();for(;e.currentPos<n&&!e.aborted;){let{done:r,value:a}=await i.read();if(r){if(e.currentPos<n)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${n-t} bytes, but got ${e.currentPos-t}`);break}if(!(a instanceof Uint8Array))throw TypeError(`ReadableStream returned by options.read must yield Uint8Array chunks.`);if(e.aborted)break;let o=l(a);this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}else throw TypeError(`options.read must return or resolve to a Uint8Array or a ReadableStream.`)}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}},ao=io,oo=class extends Ka{constructor(e,t={}){if(!(e instanceof ReadableStream))throw TypeError(`stream must be a ReadableStream.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!qe(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=t.maxCacheSize??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let n=w(this._cache,e,e=>e.start),r=n===-1?null:this._cache[n];if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let i=e,a=new Uint8Array(t-e);if(n!==-1)for(let r=n;r<this._cache.length;r++){let n=this._cache[r];if(n.start>=t)break;let o=Math.max(e,n.start);o>i&&this._throwDueToCacheMiss();let s=Math.min(t,n.end);o<s&&(a.set(n.bytes.subarray(o-n.start,s-n.start),o-e),i=s)}if(i===t)return{bytes:a,view:u(a),offset:e};this._currentIndex>i&&this._throwDueToCacheMiss();let{promise:o,resolve:s,reject:c}=T();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:s,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else throw e})),o}_throwDueToCacheMiss(){throw Error(`Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.`)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let n=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(n,r);for(let e=0;e<this._pendingSlices.length;e++){let i=this._pendingSlices[e],a=Math.max(n,i.start),o=Math.min(r,i.end);a<o&&(i.bytes.set(t.subarray(a-n,o-n),a-i.start),o===i.end&&(i.resolve({bytes:i.bytes,view:u(i.bytes),offset:i.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:n,end:r,bytes:t,view:u(t),age:0});this._cache.length>0;){let e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},so={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{let n=2**16;return e=Math.floor((e-n)/n)*n,t=Math.ceil((t+n)/n)*n,{start:e,end:t}},network:(e,t,n)=>{let r=2**16;e=Math.max(0,Math.floor((e-r)/r)*r);for(let r of n){let n=8*2**20,i=Math.max((r.startPos+r.targetPos)/2,r.targetPos-n);if(Be(e,t,i,r.targetPos)){let e=r.targetPos-r.startPos,i=Math.ceil((e+1)/n)*n,a=2**Math.ceil(Math.log2(e+1)),o=Math.min(a,i);t=Math.max(t,r.startPos+o)}}return t=Math.max(t,e+$a),{start:e,end:t}}},co=class{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,r,i){n(!this.disposed);let a=this.options.prefetchProfile(e,t,this.workers),o=Math.max(a.start,r),s=Math.min(a.end,this.fileSize??1/0,i);n(o<=e&&t<=s);let c=null,l=w(this.cache,e,e=>e.start),d=l===-1?null:this.cache[l];d&&d.start<=e&&t<=d.end&&(d.age=this.nextAge++,c={bytes:d.bytes,view:d.view,offset:d.start});let f=w(this.cache,o,e=>e.start),p=c?null:new Uint8Array(t-e),m=0,h=o,g=[];if(f!==-1){for(let r=f;r<this.cache.length;r++){let i=this.cache[r];if(i.start>=s)break;if(i.end<=o)continue;let a=Math.max(o,i.start),c=Math.min(s,i.end);if(n(a<=c),h<a&&g.push({start:h,end:a}),h=c,p){let n=Math.max(e,i.start),r=Math.min(t,i.end);if(n<r){let t=n-e;p.set(i.bytes.subarray(n-i.start,r-i.start),t),t===m&&(m=r-e)}}i.age=this.nextAge++}h<s&&g.push({start:h,end:s})}else g.push({start:o,end:s});if(p&&m>=p.length&&(c={bytes:p,view:u(p),offset:e}),g.length===0)return n(c),c;let{promise:_,resolve:v,reject:y}=T(),b=[];for(let n of g){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?b.push(n):r<i&&b.push({start:r,end:i})}let x=p&&{start:e,bytes:p,holes:b,resolve:v,reject:y};outer:for(let e of g){for(let t of this.workers)if(this.checkHoleAgainstWorker(t,e,x?[x]:[])){this.checkQueuedReadsAgainstWorker(t);continue outer}let t=e.end<s||this.fileSize!==null,n=this.createWorker(e.start,e.end,t);if(n)x&&(n.pendingSlices=[x]),this.runWorker(n);else{let n=w(this.queuedReads,e.start,e=>e.hole.start),r=n===-1?null:this.queuedReads[n];for(r&&e.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,e.end),r.strictTarget&&=t,x&&r.pendingSlices.push(x)):(n++,r={hole:{start:e.start,end:e.end},strictTarget:t,pendingSlices:x?[x]:[],age:this.nextAge++},this.queuedReads.splice(n,0,r));n+1<this.queuedReads.length;){let e=this.queuedReads[n+1];if(e.hole.start>r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&=e.strictTarget,r.age=Math.min(r.age,e.age),this.queuedReads.splice(n+1,1)}}}return c||=(n(p),_.then(t=>t&&{bytes:t,view:u(t),offset:e})),c}checkHoleAgainstWorker(e,t,n){if(Be(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t<n.length;t++){let r=n[t];e.pendingSlices.includes(r)||e.pendingSlices.push(r)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let n=0;n<this.queuedReads.length;n++){let r=this.queuedReads[n];if(this.checkHoleAgainstWorker(e,r.hole,r.pendingSlices))this.queuedReads.splice(n,1),n--,t=!0;else if(t)break}}createWorker(e,t,r){if(this.workers.length>=this.options.maxWorkerCount){let e=null,t=null;for(let n=0;n<this.workers.length;n++){let r=this.workers[n];!r.running&&r.pendingSlices.length===0&&(!e||r.age<e.age)&&(t=n,e=r)}if(e)n(t!==null),n(e.pendingSlices.length===0),this.workers.splice(t,1);else return null}let i={startPos:e,currentPos:e,targetPos:t,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(i),i}runWorker(e){n(!e.running),n(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(e=>e.reject(t)),e.pendingSlices.length=0;else throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let t=1;t<this.queuedReads.length;t++)this.queuedReads[t].age<this.queuedReads[e].age&&(e=t);let t=this.queuedReads[e];this.queuedReads.splice(e,1);let r=this.createWorker(t.hole.start,t.hole.end,t.strictTarget);n(r),r.pendingSlices=t.pendingSlices,this.runWorker(r)}})}consolidateEverythingIntoOneWorker(e){let t=new Set(e.pendingSlices);for(let n=0;n<this.workers.length;n++){let r=this.workers[n];if(r!==e){for(let e of r.pendingSlices)t.add(e);r.aborted=!0,r.pendingSlices.length=0,this.workers.splice(n,1),n--}}for(let e=0;e<this.queuedReads.length;e++){let n=this.queuedReads[e];for(let e of n.pendingSlices)t.add(e)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){n(!e.aborted);let r=e.currentPos,i=r+t.length;this.insertIntoCache({start:r,end:i,bytes:t,view:u(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++){let a=e.pendingSlices[n],o=Math.max(r,a.start),s=Math.min(i,a.start+a.bytes.length);o<s&&a.bytes.set(t.subarray(o-r,s-r),o-a.start);for(let e=0;e<a.holes.length;e++){let t=a.holes[e];r<=t.start&&i>t.start&&(t.start=i),t.end<=t.start&&(a.holes.splice(e,1),e--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(n,1),n--)}for(let t=0;t<this.workers.length;t++){let n=this.workers[t];e===n||n.running||Be(r,i,n.currentPos,n.targetPos)&&(this.workers.splice(t,1),t--)}}supplyFileSize(e){n(this.fileSize===null),this.fileSize=e;for(let t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let n=0;n<t.pendingSlices.length;n++){let r=t.pendingSlices[n];for(let i of r.holes)if(i.end>e){r.resolve(null),t.pendingSlices.splice(n,1),n--;break}}}for(let t=0;t<this.queuedReads.length;t++){let n=this.queuedReads[t];if(n.hole.start>=e){for(let e of n.pendingSlices)e.resolve(null);this.queuedReads.splice(t,1),t--}else if(n.hole.end>e){n.hole.end=e,n.strictTarget=!0;for(let t=0;t<n.pendingSlices.length;t++){let r=n.pendingSlices[t];r.start>=e&&(r.resolve(null),n.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){let t=this.workers.indexOf(e);n(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(let t of e.pendingSlices)t.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=w(this.cache,e.start,e=>e.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let r=new Uint8Array(e.end-n.start);r.set(n.bytes,0),r.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=r,n.view=u(r),n.end=e.end,t--,e=n}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 n=t+1;n<this.cache.length;n++){let t=this.cache[n];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(n,1),this.currentCacheSize-=t.bytes.length,n--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=u(r),e.end=t.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let n=1;n<this.cache.length;n++){let r=this.cache[n];r.age<t.age&&(e=n,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}},lo=class extends Ka{constructor(e,t,n){if(super(),this._ref=null,e._disposed)throw Error(`Cannot create a slice of a disposed source.`);this._baseSource=e,this._offset=t,this._length=n??null}_getFileSize(){let e=this._baseSource._getFileSize();return e===void 0?this._length===null?void 0:this._length:e===null?this._length===null?null:this._length:D(e-this._offset,0,this._length??1/0)}_read(e,t,n,r){if(this._length!==null&&t>this._length)return null;let i=this._baseSource._read(this._offset+e,this._offset+t,this._offset+n,this._offset+r);return i instanceof Promise?i.then(e=>e?(e.offset-=this._offset,e):null):i?(i.offset-=this._offset,i):null}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},uo=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},fo=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r}),po=/^0[xX][0-9a-fA-F]+$/,mo=/^data:.*;base64,/i,ho=class extends Ra{constructor(e,t,n,r){super(e.input,t,n),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await ct(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){let t={stack:[],error:void 0,hasError:!1};try{let r=await new rl(uo(t,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1).source).requestEntireFile();n(r),e=yl(r,r.length,{ignore:Ia})}catch(e){t.error=e,t.hasError=!0}finally{fo(t)}}let t=!1,r=0,a=null,o=null,s=0,c=null,l=null,d=null,f=null,p=null,m=null,h=!1,g=i(this.segments)??null,_=e=>{let t=e.indexOf(`@`),n=Number(t===-1?e:e.slice(0,t));if(!Number.isInteger(n)||n<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(t!==-1&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:n,offset:r}},v=e=>{s=e,g&&(n(g.sequenceNumber!==null),g.sequenceNumber<e&&(r=g.timestamp+g.duration,c=g.firstSegment,l=g.initSegment,p=g.lastProgramDateTimeSeconds,g=null))};for(let n=0;n<e.length;n++){let y=e[n];if(!t){if(y!==`#EXTM3U`)throw Error(`Invalid M3U8 file; expected first line to be #EXTM3U.`);t=!0;continue}if(!y.startsWith(`#`)){if(!g){if(a===null)throw Error(`Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.`);let e=o;if(e&&e.method===`AES-128`&&!e.iv){let t=new Uint8Array(16),n=u(t);n.setUint32(8,Math.floor(s/2**32)),n.setUint32(12,s),e={...e,iv:t}}let t={path:O(this.path,y),offset:f?.offset??0,length:f?.length??null},n={timestamp:r,relativeToUnixEpoch:p!==null,firstSegment:c,sequenceNumber:s,location:t,duration:a,encryption:e,initSegment:l,lastProgramDateTimeSeconds:p};c??=n,r+=a,this.segments.push(n)}a=null,f===null?d=null:f=null,v(s+1)}if(y.startsWith(`#EXTINF:`)){if(g){h=!0;continue}h||=(p===null&&s>0&&m!==null&&(r=s*m),!0);let e=y.slice(ka.length),t=e.indexOf(`,`),n=t===-1?e:e.slice(0,t),i=Number(n);if(!Number.isFinite(i)||i<0)throw Error(`Invalid #EXTINF tag duration '${n}'.`);a=i}else if(y.startsWith(`#EXT-X-MAP:`)){let e=new La(y.slice(Aa.length)),t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-MAP tag; missing URI attribute.`);let n=e.get(`byterange`),i=null;if(n!==null&&(i=_(n)),i&&i.offset===null)throw Error(`Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.`);if(!g){let e={path:O(this.path,t),offset:i?.offset??0,length:i?.length??null};if(o?.method===`AES-128`&&!o.iv)throw Error(`IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.`);l={timestamp:r,relativeToUnixEpoch:p!==null,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:p}}a=null,f===null?d=null:f=null}else if(y.startsWith(`#EXT-X-KEY:`)){let e=new La(y.slice(ja.length)),t=e.get(`method`);if(t===`NONE`)o=null;else if(t===`AES-128`){let t=e.get(`uri`);if(!t)throw Error(`Invalid #EXT-X-KEY: AES-128 requires a URI attribute.`);let n=null,r=e.get(`iv`);if(r){if(!po.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,`0`),n=new Uint8Array(16);for(let t=0;t<16;t++){let r=-32+t;n[t]=parseInt(e.slice(r,r+2),16)}}let i=e.get(`keyformat`)??`identity`;if(i!==`identity`)throw Error(`For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.`);o={method:`AES-128`,keyUri:O(this.path,t),iv:n,keyFormat:i}}else if(t===`SAMPLE-AES`||t===`SAMPLE-AES-CTR`){let n=e.get(`uri`);if(!n)throw Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if((e.get(`keyformat`)??`identity`)===`identity`)throw Error(`For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.`);let r=null;if(mo.test(n)){let e=n.indexOf(`,`),t=Ue(n.slice(e+1));if(t.length>=8&&t[4]===112&&t[5]===115&&t[6]===115&&t[7]===104){let e=u(t).getUint32(0);r=vr(t.subarray(8,Math.min(e,t.length)))}}o={method:t,psshBox:r}}else throw Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`)}else if(y.startsWith(`#EXT-X-MEDIA-SEQUENCE:`)){let e=y.slice(Ma.length),t=Number(e);if(!Number.isInteger(t)||t<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);v(t)}else if(y.startsWith(`#EXT-X-BYTERANGE:`)){let e=_(y.slice(Na.length));if(e.offset===null){if(d===null)throw Error(`Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.`);e.offset=d}f=e,d=e.offset+e.length}else if(y.startsWith(`#EXT-X-PROGRAM-DATE-TIME:`)){if(g)continue;let e=y.slice(Pa.length),t=Date.parse(e);if(!Number.isFinite(t))continue;let n=t/1e3;if(p===n)continue;if(p===null&&this.segments.length>0){let e=i(this.segments),t=n-(e.timestamp+e.duration);for(let e of this.segments)e.timestamp+=t,e.relativeToUnixEpoch=!0;r+=t}p=n,r=n}else if(y===`#EXT-X-DISCONTINUITY`)c=null;else if(y.startsWith(`#EXT-X-TARGETDURATION:`)){let e=y.slice(Fa.length),t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,m=t}else if(y===`#EXT-X-ENDLIST`){this.streamHasEnded=!0;break}else y.startsWith(`#EXT-X-PLAYLIST-TYPE:`)&&y.slice(21).toLowerCase()===`vod`&&(this.streamHasEnded=!0)}if(!t)throw Error(`Invalid M3U8 file; no #EXTM3U header.`)}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let r=w(this.segments,e,e=>e.timestamp);if(r===-1)return null;if(r<this.segments.length-1||this.streamHasEnded||n)return this.segments[r];let i=this.segments[r];if(e<i.timestamp+i.duration)return i;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getNextSegment(e,t){let r=this.segments.indexOf(e);n(r!==-1);let i=r+1,a=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(i<this.segments.length)return this.segments[i];if(this.streamHasEnded||a)return null;await this.runUpdateSegments(),t.skipLiveWait&&(a=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return n(t!==-1),this.segments[t-1]??null}getInputForSegment(e){let t=e,r=this.inputCache.find(e=>e.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let i=null;(t.initSegment||t.firstSegment)&&(i=this.getInputForSegment(t.initSegment??t.firstSegment));let a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||t.encryption.method!==`SAMPLE-AES`&&t.encryption.method!==`SAMPLE-AES-CTR`||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let n=e.psshBoxes,{psshBox:r}=t.encryption;return(r.keyIds===null||r.keyIds.includes(e.keyId))&&!n.some(e=>yr(e,r))&&(n=[...n,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:n})})}},o=new el({source:new Xa(t.location.path,async e=>{n(e.isRoot);let r={...e,isRoot:!1},i,a=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method===`SAMPLE-AES`||t.encryption.method===`SAMPLE-AES-CTR`){if(i=await this.input._getSourceCached(r),a){let e=i.source.slice(t.location.offset,t.location.length??void 0).ref();i.free(),i=e}}else if(t.encryption.method===`AES-128`){let e=t.encryption;n(e.iv);let o=await this.input._getSourceCached(r);if(a){let e=o.source.slice(t.location.offset,t.location.length??void 0).ref();o.free(),o=e}i=new oo(Fr(new rl(o.source),async()=>{let t={stack:[],error:void 0,hasError:!1};try{let n=await new rl(uo(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},2),!1).source).requestSlice(0,16);if(!n)throw Error(`Invalid AES-128 key; expected at least 16 bytes of data.`);return{key:B(n,16),iv:e.iv}}catch(e){t.error=e,t.hasError=!0}finally{fo(t)}},()=>{o.free()})).ref()}else n(!1);return i}),formats:this.input._formats.filter(e=>!(e instanceof Fo)),initInput:i??void 0,formatOptions:a});if(o._onFormatDetermined=e=>{if((t.encryption?.method===`SAMPLE-AES`||t.encryption?.method===`SAMPLE-AES-CTR`)&&!e._isIsobmff)throw Error(`The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.`)},this.inputCache.push({segment:t,input:o,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=Ye(this.inputCache,e=>e.age);n(e!==-1),this.inputCache.splice(e,1)}return o}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}},go=class extends hr{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{n(this.input._rootSource instanceof Ja);let{rootPath:e}=this.input._rootSource,t=await this.input._reader.requestEntireFile();n(t);let r=yl(t,t.length,{ignore:Ia}),i=[],a=[];for(let t=1;t<r.length;t++){let n=r[t];if(n.startsWith(`#EXT-X-STREAM-INF:`)){let a=t,o=r[++t];if(o===void 0)throw Error(`Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.`);let s=O(e,o),c=new La(n.slice(Ea.length));if(c.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);i.push({fullPath:s,attributes:c,lineNumber:a,hasOnlyKeyPackets:!1})}else if(n.startsWith(`#EXT-X-I-FRAME-STREAM-INF:`)){let r=new La(n.slice(Da.length)),a=r.get(`uri`);if(a===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.`);if(r.getAsNumber(`bandwidth`)===null)throw Error(`Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.`);let o=O(e,a);i.push({fullPath:o,attributes:r,lineNumber:t,hasOnlyKeyPackets:!0})}else if(n.startsWith(`#EXT-X-MEDIA:`)){let r=new La(n.slice(Oa.length));if(r.get(`type`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.`);if(r.get(`group-id`)===null)throw Error(`Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.`);let i=null,o=r.get(`uri`);o!==null&&(i=O(e,o)),a.push({fullPath:i,attributes:r,lineNumber:t})}else if(n!==`#EXT-X-I-FRAMES-ONLY`&&n.startsWith(`#EXTINF:`)){let t=new ho(this,e,null,r);this.segmentedInputs=[t],this.hasMasterPlaylist=!1,this.trackBackings=await t.getTrackBackings();return}}let o=[...new Set(a.filter(e=>e.attributes.get(`type`).toLowerCase()===`video`).map(e=>e.attributes.get(`group-id`)))],s=[...new Set(a.filter(e=>e.attributes.get(`type`).toLowerCase()===`audio`).map(e=>e.attributes.get(`group-id`)))],c=await Promise.all(i.map(async(t,r)=>{let i=[],c=t.attributes.get(`codecs`),l;if(c)l=c.split(`,`).map(e=>e.trim());else{let e=await this.getSegmentedInputForPath(t.fullPath).getTrackBackings(),n=await Promise.all(e.map(async e=>({track:e,codec:await e.getCodec()})));l=await Promise.all(n.filter(e=>e.codec!==null).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let u=t.attributes.get(`video`),d=t.attributes.get(`audio`),f=l.some(e=>A.includes(Wt(e))),p=l.some(e=>M.includes(Wt(e)));if(u!==null&&!f){if(!o.includes(u))throw Error(`Invalid M3U8 file; variant stream references video group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);let t=a.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===u&&n.toLowerCase()===`video`});outer:if(t){let r=t.attributes.get(`uri`);if(r===null)break outer;let i=O(e,r),a=(await this.getSegmentedInputForPath(i).getTrackBackings()).find(e=>e.getType()===`video`);if(!a||await a.getCodec()===null)break outer;let o=await a.getDecoderConfig().then(e=>e?.codec??null);n(o!==null),l.push(o)}}if(d!==null&&!p){if(!s.includes(d))throw Error(`Invalid M3U8 file; variant stream references audio group "${d}" which is not defined in any #EXT-X-MEDIA tags.`);let t=a.find(e=>{let t=e.attributes.get(`group-id`),n=e.attributes.get(`type`);return t===d&&n.toLowerCase()===`audio`});outer:if(t){let r=t.attributes.get(`uri`);if(r===null)break outer;let i=O(e,r),a=(await this.getSegmentedInputForPath(i).getTrackBackings()).find(e=>e.getType()===`audio`);if(!a||await a.getCodec()===null)break outer;let o=await a.getDecoderConfig().then(e=>e?.codec??null);n(o!==null),l.push(o)}}l=[...new Set(l)];let m=null,h=null,g=t.attributes.getAsNumber(`bandwidth`);n(g!==null);let _=t.attributes.getAsNumber(`average-bandwidth`),v=t.attributes.get(`name`);for(let e of l){let n=Wt(e);if(n!==null){if(A.includes(n)){if(m!==null)throw Error(`Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.`);m=e;let n=t.attributes.get(`video`);if(n===null){let e=t.attributes.get(`resolution`),n=null,a=null;if(e){let t=e.match(/^(\d+)x(\d+)$/);t&&(n=Number(t[1]),a=Number(t[2]))}i.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(r),peakBitrate:g,averageBitrate:_,name:v,hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:`video`,width:n,height:a}})}else{if(!o.includes(n))throw Error(`Invalid M3U8 file; variant stream references video group "${n}" which is not defined in any #EXT-X-MEDIA tags.`);for(let e of a){let a=e.attributes.get(`group-id`),o=e.attributes.get(`type`);if(a!==n||o.toLowerCase()!==`video`)continue;let s=e.attributes.get(`resolution`)??t.attributes.get(`resolution`),c=null,l=null;if(s){let e=s.match(/^(\d+)x(\d+)$/);e&&(c=Number(e[1]),l=Number(e[2]))}i.push({id:-1,demuxer:this,backingTrack:null,default:bo(e.attributes),autoselect:bo(e.attributes)||xo(e.attributes),languageCode:So(e.attributes.get(`language`)),lineNumber:e.lineNumber,fullPath:e.fullPath??t.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(r),peakBitrate:null,averageBitrate:null,name:e.attributes.get(`name`),hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:`video`,width:c,height:l}})}}}else if(M.includes(n)){if(h!==null)throw Error(`Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.`);h=e;let n=t.attributes.get(`audio`);if(n===null){let e=t.attributes.get(`channels`),n=e===null?null:Number(e.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:`und`,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:h,pairingMask:1n<<BigInt(r),peakBitrate:g,averageBitrate:_,name:v,hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:n!==null&&Number.isInteger(n)&&n>0?n:null}})}else{if(!s.includes(n))throw Error(`Invalid M3U8 file; variant stream references audio group "${n}" which is not defined in any #EXT-X-MEDIA tags.`);for(let e of a){let a=e.attributes.get(`group-id`),o=e.attributes.get(`type`);if(a!==n||o.toLowerCase()!==`audio`)continue;let s=e.attributes.get(`channels`)??t.attributes.get(`channels`),c=s===null?null:Number(s.split(`/`)[0]);i.push({id:-1,demuxer:this,backingTrack:null,default:bo(e.attributes),autoselect:bo(e.attributes)||xo(e.attributes),languageCode:So(e.attributes.get(`language`)),lineNumber:e.lineNumber,fullPath:e.fullPath??t.fullPath,fullCodecString:h,pairingMask:1n<<BigInt(r),peakBitrate:null,averageBitrate:null,name:e.attributes.get(`name`),hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:`audio`,numberOfChannels:c!==null&&Number.isInteger(c)&&c>0?c:null}})}}}}}return i})),l=[],u=e=>{let t=l.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||=e.default,t.autoselect||=e.autoselect,t.lineNumber=Math.min(t.lineNumber,e.lineNumber),e.peakBitrate!==null&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),e.averageBitrate!==null&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===`und`&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(let e of c)for(let t of e)u(t);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(let e of l)e.info.type===`video`?this.trackBackings.push(new vo(e)):this.trackBackings.push(new yo(e));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),n(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let n=null;return this.internalTracks&&(n=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))),t=new ho(this,e,n,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Ta}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},_o=class{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(r.length===1)t=r[0];else if(this instanceof vo){for(let e of r)if(await e.getCodec()===this.getCodec()){t=e;break}}else{n(this instanceof yo);for(let e of r)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw Error(`Could not find matching track in underlying media data.`);this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw Error(`Not implemented on base class.`)}getDisposition(){return{...vt,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){n(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let n of this.internalTrack.demuxer.internalTracks)if(n.info.type===e&&t++,n===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}},vo=class extends _o{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return`video`}getCodec(){return Wt(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}},yo=class extends _o{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return`audio`}getCodec(){return Wt(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels===null?this.delegate(()=>this.backingAudioTrack.getNumberOfChannels()):this.internalTrack.info.numberOfChannels}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}},bo=e=>{let t=e.get(`default`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},xo=e=>{let t=e.get(`autoselect`);if(t===null)return!1;let n=t.toUpperCase();if(n===`YES`)return!0;if(n===`NO`)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},So=e=>e===null?`und`:e.split(`-`)[0]||`und`,Co=class{constructor(){this._isIsobmff=!1}},wo=class extends Co{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);let n=W(t,4);return n!==`ftyp`&&n!==`styp`?null:W(t,4)}_createDemuxer(e){return new Ir(e)}},To=class extends wo{async _canReadInput(e){let t=await this._getMajorBrand(e);if(t!==null)return t!==`qt `;let n=e._reader.requestSlice(4,4);if(n instanceof Promise&&(n=await n),!n)return!1;let r=W(n,4);return r===`moof`||r===`sidx`}get name(){return`MP4`}get mimeType(){return`video/mp4`}},Eo=class extends wo{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},Do=class extends Co{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=di(n);if(r===null||r<1||r>8||R(n,r)!==L.EBML)return!1;let i=hi(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=gi(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case L.EBMLVersion:if(R(a,r)!==1)return!1;break;case L.EBMLReadVersion:if(R(a,r)!==1)return!1;break;case L.DocType:if(_i(a,r)!==t)return!1;break;case L.DocTypeVersion:if(R(a,r)>4)return!1}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new Ai(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},Oo=class extends Do{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},ko=class extends Co{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=wl(n);if(!r)break;t=n.filePos+r.size}let n=await Pi(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=cn(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=U(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await Pi(e._reader,t,t+4);if(!s)return!1;let c=s.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new Fi(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},Ao=class extends Co{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=W(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),W(t,4)===`WAVE`)}_createDemuxer(e){return new Zi(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},jo=class extends Co{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?W(t,4)===`OggS`:!1}_createDemuxer(e){return new Ki(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},Mo=class extends Co{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?W(t,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new ua(e)}},No=class extends Co{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=wl(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(n instanceof Promise&&(n=await n),!n)return!1;let r=ea(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=ea(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new na(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},Po=class extends Co{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let n=B(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71||n[4]===71&&n[196]===71}_createDemuxer(e){return new ga(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},Fo=class extends Co{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||W(t,7)!==`#EXTM3U`)return!1;if(!(e._rootSource instanceof Ja))throw TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new go(e)}get name(){return`HTTP Live Streaming (HLS)`}get mimeType(){return Ta}},Io=new To,Lo=new Eo,Ro=new Do,zo=new Oo,Bo=new ko,Vo=new Ao,Ho=new jo,Uo=new No,Wo=new Mo,Go=new Po,Ko=new Fo,qo=[Ko,Io,Lo,Ro,zo,Vo,Ho,Wo,Bo,Uo,Go],Jo=[Ko,Io,Lo,Bo,Uo,Go],Yo=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(`${t}, when provided, must be an object.`);if(e.isobmff!==void 0){if(!e.isobmff||typeof e.isobmff!=`object`)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(e.isobmff.resolveKeyId!==void 0&&typeof e.isobmff.resolveKeyId!=`function`)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}},Xo=new Map,Zo=new Map,Qo=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.codec!==void 0&&typeof t.codec!=`string`)throw TypeError(`options.codec, when provided, must be a string.`);if(t.codec!==void 0&&Wt(t.codec)!==e)throw TypeError(`options.codec, when provided, must match the specified codec (${e}).`);if(t.codedWidth!==void 0&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw TypeError(`options.codedWidth, when provided, must be a positive integer.`);if(t.codedHeight!==void 0&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw TypeError(`options.codedHeight, when provided, must be a positive integer.`);if(t.displayAspectWidth!==void 0&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw TypeError(`options.displayAspectWidth, when provided, must be a positive integer.`);if(t.displayAspectHeight!==void 0&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw TypeError(`options.displayAspectHeight, when provided, must be a positive integer.`);if(t.description!==void 0&&!S(t.description))throw TypeError(`options.description, when provided, must be a buffer source.`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.optimizeForLatency!==void 0&&typeof t.optimizeForLatency!=`boolean`)throw TypeError(`options.optimizeForLatency, when provided, must be a boolean.`)},$o=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.codec!==void 0&&typeof t.codec!=`string`)throw TypeError(`options.codec, when provided, must be a string.`);if(t.codec!==void 0&&Wt(t.codec)!==e)throw TypeError(`options.codec, when provided, must match the specified codec (${e}).`);if(t.numberOfChannels!==void 0&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw TypeError(`options.numberOfChannels, when provided, must be a positive integer.`);if(t.sampleRate!==void 0&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw TypeError(`options.sampleRate, when provided, must be a positive integer.`);if(t.description!==void 0&&!S(t.description))throw TypeError(`options.description, when provided, must be a buffer source.`)},es=e=>A.includes(e)?ts(e):M.includes(e)?ns(e):!1,ts=async(e,t={})=>{if(!A.includes(e))return!1;Qo(e,t);let n={...t,codedWidth:t.codedWidth??1280,codedHeight:t.codedHeight??720,codec:t.codec??Pt(e,1280,720,1e6)};n.description??=void 0;let r=JSON.stringify(n),i=Xo.get(r);if(i)return i;let a=(async()=>_c.some(t=>t.supports(e,n))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(n)).supported===!0)();return Xo.set(r,a),a},ns=async(e,t={})=>{if(!M.includes(e))return!1;$o(e,t);let n={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??Rt(e,2,48e3)};if(n.description===void 0){let e=Bt(n);if(e===!1)return!1;n.description=e}let r=JSON.stringify(n),i=Zo.get(r);if(i)return i;let a=(async()=>vc.some(t=>t.supports(e,n))||j.includes(e)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(n)).supported===!0)();return Zo.set(r,a),a},rs=async()=>{let[e,t]=await Promise.all([is(),as()]);return[...e,...t]},is=async(e=A,t)=>{let n=await Promise.all(e.map(e=>ts(e,t)));return e.filter((e,t)=>n[t])},as=async(e=M,t)=>{let n=await Promise.all(e.map(e=>ns(e,t)));return e.filter((e,t)=>n[t])},os=function(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t},ss=(function(e){return function(t){function n(n){t.error=t.hasError?new e(n,t.error,`An error was suppressed during disposal.`):n,t.hasError=!0}var r,i=0;function a(){for(;r=t.stack.pop();)try{if(!r.async&&i===1)return i=0,t.stack.push(r),Promise.resolve().then(a);if(r.dispose){var e=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(e).then(a,function(e){return n(e),a()})}else i|=1}catch(e){n(e)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return a()}})(typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r});Ke();var cs=-1/0,ls=-1/0,us=null;typeof FinalizationRegistry<`u`&&(us=new FinalizationRegistry(e=>{let t=performance.now();e.type===`video`?(t-cs>=1e3&&(console.error(`A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them.`),cs=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-ls>=1e3&&(console.error(`An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them.`),ls=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var ds=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},fs=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],ps=new Set(fs),ms=class e{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(t,r){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!r||typeof r!=`object`)throw TypeError(`init must be an object.`);if(r.format===void 0||!ps.has(r.format))throw TypeError(`init.format must be one of: `+fs.join(`, `));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(r.timestamp))throw TypeError(`init.timestamp must be a number.`);if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(r.layout!==void 0){if(!Array.isArray(r.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of r.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(r.visibleRect!==void 0&&Qe(r.visibleRect,`init.visibleRect`),r.displayWidth!==void 0&&(!Number.isInteger(r.displayWidth)||r.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(r.displayHeight!==void 0&&(!Number.isInteger(r.displayHeight)||r.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(r.displayWidth!==void 0!=(r.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this._data=l(t).slice(),this._layout=r.layout??Ts(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0;let e=r.colorSpace??null;e===null&&(e=this.format===`RGBA`||this.format===`RGBX`||this.format===`BGRA`||this.format===`BGRX`?{primaries:`bt709`,transfer:`iec61966-2-1`,matrix:`rgb`,fullRange:!0}:{primaries:`bt709`,transfer:`bt709`,matrix:`bt709`,fullRange:!1}),this.colorSpace=new bs(e),this.visibleRect={left:r.visibleRect?.left??0,top:r.visibleRect?.top??0,width:r.visibleRect?.width??r.codedWidth,height:r.visibleRect?.height??r.codedHeight},r.displayWidth===void 0?(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height):(this.squarePixelWidth=this.rotation%180==0?r.displayWidth:r.displayHeight,this.squarePixelHeight=this.rotation%180==0?r.displayHeight:r.displayWidth)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(r?.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(r?.timestamp!==void 0&&!Number.isFinite(r?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(r?.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);r?.visibleRect!==void 0&&Qe(r.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=r?.rotation??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=r?.timestamp??t.timestamp/1e6,this.duration=r?.duration??(t.duration??0)/1e6,this.colorSpace=new bs(t.colorSpace)}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!r||typeof r!=`object`)throw TypeError(`init must be an object.`);if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(r.timestamp))throw TypeError(`init.timestamp must be a number.`);if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(r.timestamp*Te),duration:Math.trunc((r.duration??0)*Te)||void 0}),r);let i=0,a=0;if(`naturalWidth`in t?(i=t.naturalWidth,a=t.naturalHeight):`videoWidth`in t?(i=t.videoWidth,a=t.videoHeight):`width`in t&&(i=Number(t.width),a=Number(t.height)),!i||!a)throw TypeError(`Could not determine dimensions.`);let o=new OffscreenCanvas(i,a),s=o.getContext(`2d`,{alpha:Pe(),willReadFrequently:!0});n(s),s.drawImage(t,0,0),this._data=o,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:i,height:a},this.squarePixelWidth=i,this.squarePixelHeight=a,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new bs({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else if(t instanceof ds){if(!r||typeof r!=`object`)throw TypeError(`init must be an object.`);if(r.rotation!==void 0&&![0,90,180,270].includes(r.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(r.timestamp))throw TypeError(`init.timestamp must be a number.`);if(r.duration!==void 0&&(!Number.isFinite(r.duration)||r.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(this._data=t,t._referenceCount++,this.format=t.getFormat(),this.format!==null&&!fs.includes(this.format))throw TypeError(`getFormat() must return a VideoSamplePixelFormat or null.`);if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw TypeError(`getCodedWidth() must return a positive integer.`);if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError(`getCodedHeight() must return a positive integer.`);if(this.squarePixelWidth=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError(`getSquarePixelWidth() must return a positive integer.`);if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError(`getSquarePixelHeight() must return a positive integer.`);this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=t.getColorSpace()}else throw TypeError(`Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.`);this.pixelAspectRatio=Ze({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),us?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return n(this._data!==null),this._data instanceof ds?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):xs(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(n(this._layout),new e(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})):new e(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})}close(){this._closed||=(us?.unregister(this),this._data instanceof ds?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):xs(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(ws(e),this._closed)throw Error(`VideoSample is closed.`);if((e.format??this.format)==null)throw Error(`Cannot get allocation size when format is null.`);return xs(this._data)?this._data.allocationSize(e):Ds(this,e).allocationSize}async copyTo(t,r={}){if(!S(t))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(ws(r),this._closed)throw Error(`VideoSample is closed.`);if((r.format??this.format)==null)throw Error(`Cannot copy video sample data when format is null.`);if(n(this._data!==null),xs(this._data))return this._data.copyTo(t,r);if(r.format&&![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(this.format)&&[`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(r.format))if(this._data instanceof ds){let n={stack:[],error:void 0,hasError:!1};try{let i=os(n,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},r.colorSpace??`srgb`),!1);if(!(i instanceof e))throw TypeError(`toRgbSample() must return a VideoSample.`);if(![`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(i.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${i.format}' instead.`);return await i.copyTo(t,r)}catch(e){n.error=e,n.hasError=!0}finally{ss(n)}}else{if(typeof VideoFrame>`u`)throw Error(`For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.`);let e=this.toVideoFrame(),n=await e.copyTo(t,r);return e.close(),n}let i=Ds(this,r);n(this.format);let a=l(t);if(a.byteLength<i.allocationSize)throw TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${a.byteLength}`);let o=Es(this.format),s;if(this._data instanceof ds){let e=this._data.getDataPlanes();if(e instanceof Promise&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw TypeError(`getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.`);s=e}else if(this._data instanceof Uint8Array)n(this._layout),n(this._layout.length===o.length),s=this._layout.map((e,t)=>{let n=Math.ceil(this.codedHeight/o[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*n),stride:e.stride}});else{let e=this._data.getContext(`2d`);n(e),s=[{data:l(e.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}let c=[],u=o.length;for(let e=0;e<u;e++){let t=i.computedLayouts[e],n=s[e].stride,r=s[e].data,o=t.sourceTop*n;o+=t.sourceLeftBytes;let l=t.destinationOffset,u=t.sourceWidthBytes,d={offset:l,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(o+u>r.byteLength)throw Error(`Source buffer OOB read.`);if(l+u>a.byteLength)throw Error(`Destination buffer OOB write.`);let e=r.subarray(o,o+u);a.set(e,l),o+=n,l+=t.destinationStride}c.push(d)}if(r.format!==void 0){let e=this.format.startsWith(`RGB`)!==r.format.startsWith(`RGB`),t=this.format.includes(`X`)&&r.format.includes(`A`);if(e||t)for(let n=0;n<i.allocationSize;n+=4){if(e){let e=a[n],t=a[n+2];a[n]=t,a[n+2]=e}t&&(a[n+3]=255)}}return c}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);if(n(this._data!==null),this._data instanceof ds){if(this.format===null)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.`);let e=this._data.getDataPlanes();if(e instanceof Promise)throw Error(`Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.`);let t=e.reduce((e,t)=>e+t.data.byteLength,0),n=new Uint8Array(t),r=0,i=[];for(let t of e)n.set(t.data,r),i.push(r),r+=t.data.byteLength;return new VideoFrame(n,{format:this.format,layout:e.map((e,t)=>({offset:i[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return xs(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._rotateSourceRegion(l,u,d,f,this.rotation));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);t.crop!==void 0&&Cs(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,[a,o]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&=Ss(s,a,o);let c,l,u,d,{sx:f,sy:p,sWidth:m,sHeight:h}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,i);if(t.fit===`fill`)c=0,l=0,u=n,d=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[a,o],s=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);u=e*s,d=i*s,c=(n-u)/2,l=(r-d)/2}e.save();let g=i%180==0?1:u/d;e.translate(n/2,r/2),e.rotate(i*Math.PI/180),e.scale(1/g,g),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),f,p,m,h,c,l,u,d),e.restore()}_rotateSourceRegion(e,t,n,r,i){return i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(n(this._data!==null),this._data instanceof ds||this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(t){if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when provided, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when provided, must be a positive integer.`);if(t.roundDimensionsTo!==void 0&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw TypeError(`options.roundDimensionsTo, when provided, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotate!==void 0&&![0,90,180,270].includes(t.rotate))throw TypeError(`options.rotate, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&Cs(t.crop,`options.`),t.alpha!==void 0&&![`keep`,`discard`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'keep' or 'discard'.`);let i=r(this.rotation+(t.rotate??0)),[a,o]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],s=t.crop;s&&=Ss(s,a,o);let c=s?s.width:a,l=s?s.height:o,u=c/l,d,f;t.width!==void 0&&t.height===void 0?(d=t.width,f=d/u):t.width===void 0&&t.height!==void 0?(f=t.height,d=f*u):t.width!==void 0&&t.height!==void 0?(d=t.width,f=t.height):(d=c,f=l),d=ve(d,t.roundDimensionsTo??1),f=ve(f,t.roundDimensionsTo??1);let p={width:d,height:f,fit:t.fit??`fill`,rotation:i,crop:s??{left:0,top:0,width:a,height:o},alpha:t.alpha??`keep`};for(let e of hs){let t=e(this,p);if(t instanceof Promise&&(t=await t),t!==null)return t}let m=null,h=!1;for(let e of vs)if(e.canvas.width===p.width&&e.canvas.height===p.height){m=e.canvas,e.age=ys++;break}if(m===null){if(typeof OffscreenCanvas<`u`)m=new OffscreenCanvas(p.width,p.height);else{if(typeof window>`u`||typeof document>`u`)throw Error(`Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().`);m=document.createElement(`canvas`),m.width=p.width,m.height=p.height}h=!0,vs.length>=_s&&vs.splice(Ye(vs,e=>e.age),1),vs.push({canvas:m,age:ys++})}let g=m.getContext(`2d`,{alpha:!0});return n(g),p.alpha===`discard`?(g.fillStyle=`black`,g.fillRect(0,0,p.width,p.height)):h||g.clearRect(0,0,p.width,p.height),this.drawWithFit(g,{fit:p.fit,rotation:p.rotation,crop:p.crop}),new e(m,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}[Symbol.dispose](){this.close()}},hs=[],gs=e=>{hs.includes(e)||hs.push(e)},_s=3,vs=[],ys=0,bs=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(h);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(_);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(y);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw 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}}},xs=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,Ss=(e,t,r)=>{let i=Math.min(e.left,t),a=Math.min(e.top,r),o=Math.min(e.width,t-i),s=Math.min(e.height,r-a);return n(o>=0),n(s>=0),{left:i,top:a,width:o,height:s}},Cs=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},ws=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},Ts=(e,t,n)=>{let r=Es(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},Es=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return t(1,1,2,2,!1);case`I420P10`:case`I420P12`:return t(2,2,2,2,!1);case`I420A`:return t(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return t(2,2,2,2,!0);case`I422`:return t(1,1,2,1,!1);case`I422P10`:case`I422P12`:return t(2,2,2,1,!1);case`I422A`:return t(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return t(2,2,2,1,!0);case`I444`:return t(1,1,1,1,!1);case`I444P10`:case`I444P12`:return t(2,2,1,1,!1);case`I444A`:return t(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return t(2,2,1,1,!0);case`NV12`:return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case`RGBA`:case`RGBX`:case`BGRA`:case`BGRX`:return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:E(e),n(!1)}},Ds=(e,t)=>{let n={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,i=Os(n,r,e.codedWidth,e.codedHeight,e.format),a=t.layout,o;if(!t.format||t.format===e.format)o=e.format;else if([`RGBA`,`RGBX`,`BGRA`,`BGRX`].includes(t.format))o=t.format;else throw Error(`NotSupportedError: Invalid destination format.`);return As(i,o,a)},Os=(e,t,n,r,i)=>{let a={...e};if(t!==void 0){if(t.width===0||t.height===0)throw TypeError(`visibleRect dimensions cannot be zero.`);if((t.x||0)+(t.width||0)>n)throw TypeError(`visibleRect exceeds codedWidth.`);if((t.y||0)+(t.height||0)>r)throw TypeError(`visibleRect exceeds codedHeight.`);a.x=t.x||0,a.y=t.y||0,a.width=t.width||0,a.height=t.height||0}if(!ks(i,a))throw TypeError(`visibleRect alignment is invalid for the format.`);return a},ks=(e,t)=>{if(e===null)return!0;let n=Es(e);for(let e=0;e<n.length;e++){let r=n[e],i=r.widthDivisor,a=r.heightDivisor;if((t.x||0)%i!==0||(t.y||0)%a!==0)return!1}return!0},As=(e,t,n)=>{let r=Es(t),i=r.length;if(n!==void 0&&n.length!==i)throw TypeError(`Layout must have ${i} planes.`);let a=0,o=[],s=[];for(let t=0;t<i;t++){let i=r[t],c=i.sampleBytes,l=i.widthDivisor,u=i.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*c,d.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/l)*c,n!==void 0){let e=n[t];if(e.stride<d.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=a,d.destinationStride=d.sourceWidthBytes;let f=d.destinationStride*d.sourceHeight+d.destinationOffset;if(f>4294967295)throw TypeError(`Allocation size exceeds limit.`);s.push(f),a=Math.max(a,f);for(let e=0;e<t;e++){let n=o[e];if(!(s[t]<=n.destinationOffset||s[e]<=d.destinationOffset))throw TypeError(`Planes overlap.`)}o.push(d)}return{allocationSize:a,computedLayouts:o}},js=new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]),Ms=class{constructor(){this._referenceCount=0}},Ns=class e{get microsecondTimestamp(){return Math.trunc(Te*this.timestamp)}get microsecondDuration(){return Math.trunc(Te*this.duration)}constructor(e){if(this._closed=!1,Rs(e)){if(e.format===null)throw 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 Ms){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!js.has(this.format))throw TypeError(`getFormat() must return an AudioSampleFormat.`);if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw TypeError(`getSampleRate() must return a positive integer.`);if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw TypeError(`getNumberOfFrames() must return a non-negative integer.`);if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw TypeError(`getNumberOfChannels() must return a positive integer.`);if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw TypeError(`getTimestamp() must return a finite number.`);this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!=`object`)throw TypeError(`Invalid AudioDataInit: must be an object.`);if(!js.has(e.format))throw TypeError(`Invalid AudioDataInit: invalid format.`);if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError(`Invalid AudioDataInit: sampleRate must be > 0.`);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw TypeError(`Invalid AudioDataInit: numberOfChannels must be an integer > 0.`);if(!Number.isFinite(e?.timestamp))throw TypeError(`init.timestamp must be a number.`);let t=e.data.byteLength/(Ps(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw 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 n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError(`Invalid AudioDataInit: data is not a BufferSource.`);let r=this.numberOfFrames*this.numberOfChannels*Ps(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=n}us?.register(this,{type:`audio`,data:this._data},this)}allocationSize(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(e.format!==void 0&&!js.has(e.format))throw TypeError(`Invalid format.`);if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw RangeError(`frameOffset out of range`);let r=e.frameCount===void 0?this.numberOfFrames-n:e.frameCount;if(r>this.numberOfFrames-n)throw RangeError(`frameCount out of range`);let i=Ps(t),a=Fs(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&e.planeIndex!==0)throw RangeError(`planeIndex out of range`);return(a?r:r*this.numberOfChannels)*i}copyTo(e,t){if(!S(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(t.format!==void 0&&!js.has(t.format))throw TypeError(`Invalid format.`);if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let{format:n,frameCount:r,frameOffset:i}=t,{planeIndex:a}=t,o=this.format,s=n??this.format;if(!s)throw Error(`Destination format not determined`);let c=this.numberOfFrames,l=this.numberOfChannels,d=i??0;if(d>=c)throw RangeError(`frameOffset out of range`);let f=r===void 0?c-d:r;if(f>c-d)throw RangeError(`frameCount out of range`);let p=Ps(s),m=Fs(s);if(m&&a>=l||!m&&a!==0)throw RangeError(`planeIndex out of range`);let h=(m?f:f*l)*p;if(e.byteLength<h)throw RangeError(`Destination buffer is too small`);let g=u(e),_=Ls(s);if(Rs(this._data))Me()&&l>2&&s!==o?Bs(this._data,g,o,s,l,a,d,f):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:f,format:s});else{let e=Is(o),t=Ps(o),n=Fs(o),r;if(this._data instanceof Ms){let e=e=>{let r=this._data.getDataPlane(e);if(!(r instanceof Uint8Array))throw TypeError(`getDataPlane() must return a Uint8Array.`);let i=c*t*(n?1:l);if(r.byteLength!==i)throw TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${r.byteLength} bytes.`);return r};if(n)if(m)r=e(a),a=0;else{r=new Uint8Array(c*t*l);for(let n=0;n<l;n++){let i=e(n);r.set(i,n*c*t)}}else r=e(0)}else r=this._data;let i=u(r);for(let r=0;r<f;r++)if(m){let o=r*p,s;s=n?(a*c+(r+d))*t:((r+d)*l+a)*t,_(g,o,e(i,s))}else for(let a=0;a<l;a++){let o=(r*l+a)*p,s;s=n?(a*c+(r+d))*t:((r+d)*l+a)*t,_(g,o,e(i,s))}}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(this._data instanceof Ms){let t=new e(this._data);return t.setTimestamp(this.timestamp),t}if(Rs(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}return new e({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||=(us?.unregister(this),this._data instanceof Ms?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Rs(this._data)?this._data.close():this._data=new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);return this._data instanceof Ms?this._createAudioDataFromData():Rs(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(Fs(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{let 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 Error(`AudioSample is closed.`);let 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 n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:`f32-planar`}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a;for(;c>0;){let a=Math.min(o,c),l=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(l.subarray(e*a,(e+1)*a),e,s);yield new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:l}),s+=a,c-=a}}static fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a,l=[];for(;c>0;){let a=Math.min(o,c),u=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(u.subarray(e*a,(e+1)*a),e,s);let d=new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:u});l.push(d),s+=a,c-=a}return l}},Ps=e=>{switch(e){case`u8`:case`u8-planar`:return 1;case`s16`:case`s16-planar`:return 2;case`s32`:case`s32-planar`:return 4;case`f32`:case`f32-planar`:return 4;default:throw Error(`Unknown AudioSampleFormat`)}},Fs=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},Is=e=>{switch(e){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)}},Ls=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,D((n+1)*127.5,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,D(Math.round(n*32767),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,D(Math.round(n*2147483647),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},Rs=e=>typeof AudioData<`u`&&e instanceof AudioData,zs=e=>{switch(e){case`u8-planar`:return`u8`;case`s16-planar`:return`s16`;case`s32-planar`:return`s32`;case`f32-planar`:return`f32`;default:return e}},Bs=(e,t,n,r,i,a,o,s)=>{let c=Is(n),l=Ls(r),d=Ps(n),f=Ps(r),p=Fs(n);if(Fs(r))if(p){let r=new ArrayBuffer(s*d),i=u(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*d;l(t,e*f,c(i,n))}}else{let r=new ArrayBuffer(s*i*d),p=u(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*d;l(t,e*f,c(p,n))}}else if(p){let r=s*d,a=new ArrayBuffer(r),p=u(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*d;l(t,(e*i+r)*f,c(p,n))}}}else{let r=new ArrayBuffer(s*i*d),a=u(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*d;l(t,r*f,c(a,o))}}},Vs=(e,t)=>{let n=e.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(n);return e.copyTo(r,{format:t,planeIndex:0}),new Ns({data:r,format:t,numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,timestamp:e.timestamp,duration:e.duration})},Hs=new Map,Us=new Map,Ws=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!A.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${A.join(`, `)}.`);if(!(e.bitrate instanceof Xs)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.width!==void 0&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError(`config.transform.width, when provided, must be a positive integer.`);if(e.transform.height!==void 0&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError(`config.transform.height, when provided, must be a positive integer.`);if(e.transform.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.transform.fit))throw TypeError(`config.transform.fit, when provided, must be one of "fill", "contain", or "cover".`);if(e.transform.width!==void 0&&e.transform.height!==void 0&&e.transform.fit===void 0&&![`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.`);if(e.transform.fit!==void 0&&[`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw 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(e.transform.rotate!==void 0&&![0,90,180,270].includes(e.transform.rotate))throw TypeError(`config.transform.rotate, when provided, must be 0, 90, 180 or 270.`);if(e.transform.crop!==void 0&&Cs(e.transform.crop,`config.transform.`),e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`);if(e.transform.frameRate!==void 0&&(!Number.isFinite(e.transform.frameRate)||e.transform.frameRate<=0))throw TypeError(`config.transform.frameRate, when provided, must be a finite positive number.`);if(e.transform.force!==void 0&&typeof e.transform.force!=`boolean`)throw TypeError(`config.transform.force, when provided, must be a boolean.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);Gs(e.codec,e)},Gs=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&Wt(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},Ks=e=>{let t=e.bitrate instanceof Xs?e.bitrate._toVideoBitrate(e.codec,e.width,e.height):e.bitrate;return{codec:e.fullCodecString??Pt(e.codec,e.width,e.height,t),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:e.bitrateMode,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...Gt(e.codec)}},qs=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!M.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${M.join(`, `)}.`);if(e.bitrate===void 0&&!(j.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.bitrate must be provided for compressed audio codecs.`);if(e.bitrate!==void 0&&!(e.bitrate instanceof Xs)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.transform!==void 0){if(typeof e.transform!=`object`||!e.transform)throw TypeError(`config.transform, when provided, must be an object.`);if(e.transform.numberOfChannels!==void 0&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError(`config.transform.numberOfChannels, when provided, must be a positive integer.`);if(e.transform.sampleRate!==void 0&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError(`config.transform.sampleRate, when provided, must be a positive integer.`);if(e.transform.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.transform.sampleFormat))throw TypeError(`config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e.transform.process!==void 0&&typeof e.transform.process!=`function`)throw TypeError(`config.transform.process, when provided, must be a function.`)}if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedPacket, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);Js(e.codec,e)},Js=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&Wt(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},Ys=e=>{let t=e.bitrate instanceof Xs?e.bitrate._toAudioBitrate(e.codec):e.bitrate;return{codec:e.fullCodecString??Rt(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:t,bitrateMode:e.bitrateMode,...Kt(e.codec)}},Xs=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){let r=3e6*(t*n/2073600)**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[e]*this._factor;return Math.ceil(r/1e3)*1e3}_toAudioBitrate(e){if(j.includes(e)||e===`flac`)return;let t={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!t)throw Error(`Unhandled codec: ${e}`);let n=t*this._factor;return e===`aac`?n=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e):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((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e)),Math.round(n/1e3)*1e3}},Zs=new Xs(.3),Qs=new Xs(.6),$s=new Xs(1),ec=new Xs(2),tc=new Xs(4),nc=e=>{if(A.includes(e))return rc(e);if(M.includes(e))return ic(e);if(Dt.includes(e))return ac(e);throw TypeError(`Unknown codec '${e}'.`)},rc=async(e,t={})=>{let{width:n=1280,height:r=720,bitrate:i=1e6,...a}=t;if(!A.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(!(i instanceof Xs)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);Gs(e,a);let o=Ks({codec:e,width:n,height:r,bitrate:i,framerate:void 0,...a,alpha:`discard`}),s=JSON.stringify(o),c=Hs.get(s);if(c)return c;let l=(async()=>yc.some(t=>t.supports(e,o))?!0:typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`)||!(await VideoEncoder.isConfigSupported(o)).supported?!1:!Pe()||new Promise(async e=>{try{let t=new VideoEncoder({output:()=>{},error:()=>e(!1)});t.configure(o);let i=new Uint8Array(n*r*4),a=new VideoFrame(i,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});t.encode(a),a.close(),await t.flush(),e(!0)}catch{e(!1)}}))();return Hs.set(s,l),l},ic=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,bitrate:i=128e3,...a}=t;if(!M.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(!(i instanceof Xs)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer.`);Js(e,a);let o=Ys({codec:e,numberOfChannels:n,sampleRate:r,bitrate:i,...a}),s=JSON.stringify(o),c=Us.get(s);if(c)return c;let l=(async()=>bc.some(t=>t.supports(e,o))||j.includes(e)?!0:typeof AudioEncoder>`u`?!1:(await AudioEncoder.isConfigSupported(o)).supported===!0)();return Us.set(s,l),l},ac=async e=>!!Dt.includes(e),oc=async()=>{let[e,t,n]=await Promise.all([sc(),cc(),lc()]);return[...e,...t,...n]},sc=async(e=A,t)=>{let n=await Promise.all(e.map(e=>rc(e,t)));return e.filter((e,t)=>n[t])},cc=async(e=M,t)=>{let n=await Promise.all(e.map(e=>ic(e,t)));return e.filter((e,t)=>n[t])},lc=async(e=Dt)=>{let t=await Promise.all(e.map(ac));return e.filter((e,n)=>t[n])},uc=async(e,t)=>{for(let n of e)if(await rc(n,t))return n;return null},dc=async(e,t)=>{for(let n of e)if(await ic(n,t))return n;return null},fc=async e=>{for(let t of e)if(await ac(t))return t;return null},pc=class{static supports(e,t){return!1}},mc=class{static supports(e,t){return!1}},hc=class{static supports(e,t){return!1}},gc=class{static supports(e,t){return!1}},_c=[],vc=[],yc=[],bc=[],xc=e=>{if(e.prototype instanceof pc){let t=e;if(_c.includes(t)){console.warn(`Video decoder already registered.`);return}_c.push(t),Xo.clear()}else if(e.prototype instanceof mc){let t=e;if(vc.includes(t)){console.warn(`Audio decoder already registered.`);return}vc.push(t),Zo.clear()}else throw TypeError(`Decoder must be a CustomVideoDecoder or CustomAudioDecoder.`)},Sc=e=>{if(e.prototype instanceof hc){let t=e;if(yc.includes(t)){console.warn(`Video encoder already registered.`);return}yc.push(t),Hs.clear()}else if(e.prototype instanceof gc){let t=e;if(bc.includes(t)){console.warn(`Audio encoder already registered.`);return}bc.push(t),Us.clear()}else throw TypeError(`Encoder must be a CustomVideoEncoder or CustomAudioEncoder.`)},Cc=e=>{let t=8191,n=e,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&r)!==r&&a>=5;)r>>=1,a--;return o=n>>a-4&15,~(i|a-5<<4|o)&255},wc=e=>{let t=0,n=0,r=~e;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+5;let i=(1<<n|(r&15)<<n-4|1<<n-5)-33;return t===0?i:-i},Tc=e=>{let t=4095,n=2048,r=0,i=11,a=0,o=e;for(o<0&&(o=-o,r=128),o>t&&(o=t);(o&n)!==n&&i>=5;)n>>=1,i--;return a=o>>(i===4?1:i-4)&15,(r|i-4<<4|a)^85},Ec=e=>{let t=0,n=0,r=e^85;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+4;let i=0;return i=n===4?r<<1|1:1<<n|(r&15)<<n-4|1<<n-5,t===0?i:-i},Dc=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`);if(e.skipLiveWait!==void 0&&typeof e.skipLiveWait!=`boolean`)throw TypeError(`options.skipLiveWait, when defined, must be a boolean.`)},Oc=e=>{if(!qe(e))throw TypeError(`timestamp must be a number.`)},kc=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,Ac=class{constructor(e){if(!(e instanceof Wc))throw TypeError(`track must be an InputTrack.`);this._track=e}async getFirstPacket(e={}){if(Dc(e),this._track.input._disposed)throw new nl;return kc(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Dc(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Oc(e),Dc(t),this._track.input._disposed)throw new nl;return kc(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof F))throw TypeError(`packet must be an EncodedPacket.`);if(Dc(t),this._track.input._disposed)throw new nl;return kc(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Oc(e),Dc(t),this._track.input._disposed)throw new nl;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return r&&(n(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r)}async getNextKeyPacket(e,t={}){if(!(e instanceof F))throw TypeError(`packet must be an EncodedPacket.`);if(Dc(t),this._track.input._disposed)throw new nl;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return r&&(n(r.type===`key`),await this._track.determinePacketType(r)===`delta`?this.getNextKeyPacket(r,t):r)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof F))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof F))throw TypeError(`endPacket must be an EncodedPacket.`);if(Dc(n),this._track.input._disposed)throw new nl;let r=[],{promise:i,resolve:a}=T(),{promise:o,resolve:s}=T(),c=!1,l=!1,u=null,d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>f()){({promise:o,resolve:s}=T()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=T(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{u||(u=e,a())});let p=this._track;return{async next(){for(;;)if(p.input._disposed)throw new nl;else if(l)return{value:void 0,done:!0};else if(u)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},jc=class{constructor(e,t){this.onSample=e,this.onError=t}},Mc=class{mediaSamplesInRange(e=-1/0,t=1/0,n){Oc(e),Oc(t);let r=[],i=!1,a=null,{promise:o,resolve:s}=T(),{promise:c,resolve:l}=T(),u=!1,d=!1,f=!1,p=null,m={...n,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let n=await this._createDecoder(n=>{if(l(),n.timestamp>=t&&(d=!0),d){n.close();return}a&&(n.timestamp>e?(r.push(a),i=!0):a.close()),n.timestamp>=e&&(r.push(n),i=!0),a=i?null:n,r.length>0&&(s(),{promise:o,resolve:s}=T())},e=>{p||(p=e,s())}),h=this._createPacketSink(),g=await h.getKeyPacket(e,m)??await h.getFirstKeyPacket(m),_=g,v=h.packets(g??void 0,void 0,m);for(await v.next();_&&!d&&!this._track.input._disposed;){let e=Nc(r.length);if(r.length+n.getDecodeQueueSize()>e){({promise:c,resolve:l}=T()),await c;continue}n.decode(_);let t=await v.next();if(t.done)break;_=t.value}await v.return(),!f&&!this._track.input._disposed&&await n.flush(),n.close(),!i&&a&&r.push(a),u=!0,s()})().catch(e=>{p||(p=e,s())});let h=this._track,g=()=>{a?.close();for(let e of r)e.close()};return{async next(){for(;;)if(h.input._disposed)throw g(),new nl;else if(f)return{value:void 0,done:!0};else if(p)throw g(),p;else if(r.length>0){let e=r.shift();return l(),{value:e,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}},async return(){return f=!0,d=!0,l(),s(),g(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){ue(e);let r=le(e),i=[],a=[],{promise:o,resolve:s}=T(),{promise:c,resolve:l}=T(),u=!1,d=!1,f=null,p=e=>{a.push(e),s(),{promise:o,resolve:s}=T()},m={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{let e=await this._createDecoder(e=>{if(l(),d){e.close();return}let t=0;for(;i.length>0&&e.timestamp-i[0]>-1e-10;)t++,i.shift();if(t>0)for(let n=0;n<t;n++)p(n<t-1?e.clone():e);else e.close()},e=>{f||(f=e,s())}),t=this._createPacketSink(),o=null,h=null,g=-1,_=async()=>{n(h);let r=h;for(e.decode(r);r.sequenceNumber<g;){let i=Nc(a.length);for(;a.length+e.getDecodeQueueSize()>i&&!d;)({promise:c,resolve:l}=T()),await c;if(d)break;let o=await t.getNextPacket(r,m);n(o),e.decode(o),r=o}g=-1},v=async()=>{await e.flush();for(let e=0;e<i.length;e++)p(null);i.length=0};for await(let e of r){if(Oc(e),d||this._track.input._disposed)break;let n=await t.getPacket(e,m),r=n&&await t.getKeyPacket(e,m);if(!r){g!==-1&&(await _(),await v()),p(null),o=null;continue}o&&(r.sequenceNumber!==h.sequenceNumber||n.timestamp<o.timestamp)&&(await _(),await v()),i.push(n.timestamp),g=Math.max(n.sequenceNumber,g),o=n,h=r}!d&&!this._track.input._disposed&&(g!==-1&&await _(),await v()),e.close(),u=!0,s()})().catch(e=>{f||(f=e,s())});let h=this._track,g=()=>{for(let e of a)e?.close()};return{async next(){for(;;)if(h.input._disposed)throw g(),new nl;else if(d)return{value:void 0,done:!0};else if(f)throw g(),f;else if(a.length>0){let e=a.shift();return n(e!==void 0),l(),{value:e,done:!1}}else if(!u)await o;else return{value:void 0,done:!0}},async return(){return d=!0,l(),s(),g(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Nc=e=>e===0?40:8,Pc=class extends jc{constructor(e,t,r,i,a,o){super(e,t),this.codec=r,this.decoderConfig=i,this.rotation=a,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ae,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new Ae;let s=_c.find(e=>e.supports(r,i));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof ms))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=e=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();n(t!==void 0),await this.mergeAlpha(e,t)}else this.colorQueue.push(e)}).catch(e=>this.onError(e))};if(r===`avc`&&this.decoderConfig.description&&Ie()){let e=On(l(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=An(e.sequenceParameterSets[0]);t&&t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`})}}let t=Error(`Decoding error`).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(n(this.decoder),Me()||ae(this.inputTimestamps,e.timestamp,e=>e),Ie()&&this.currentPacketIndex===0){if(this.codec===`avc`){let t=[];for(let n of yn(e.data,this.decoderConfig)){let r=bn(e.data[n.offset]);r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}e=new F(Tn(t,this.decoderConfig),e.type,e.timestamp,e.duration)}else if(this.codec===`hevc`){let t=Kn(e.data,this.decoderConfig);t&&(e=new F(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||=new Ic,!this.alphaDecoder){let e=e=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){let t=this.colorQueue.shift();n(t!==void 0),await this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();n(e!==void 0),await this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(e=>this.onError(e))},t=Error(`Decoding error`).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=er(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=t===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Nn(e,this.decoderConfig)){let n=Pn(e[t.offset]);if(n===N.RASL_N||n===N.RASL_R)return!0}return!1}sampleHandler(e){if(Me()){if(this.sampleQueue.length>0&&e.timestamp>=i(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ae(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();n(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){let t=new ms(e);this.sampleHandler(t);return}n(this.merger);let r=new ms(await this.merger.update(e,t));this.sampleHandler(r)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Me()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Fc=!1,Ic=class e{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let t=typeof OffscreenCanvas<`u`||typeof document<`u`&&typeof document.createElement==`function`;if(!e.forceCpu&&t&&!Fc)try{this.canvas=typeof OffscreenCanvas<`u`?new OffscreenCanvas(300,150):document.createElement(`canvas`);let e=this.canvas.getContext(`webgl2`,{premultipliedAlpha:!1});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_colorTexture`),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_alphaTexture`),1)}catch(e){this.gl=null,this.canvas=null,Fc=!0,console.warn(`Falling back to CPU for color/alpha merging.`,e)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){n(this.gl);let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2
+ in vec2 a_position;
3
+ in vec2 a_texCoord;
4
+ out vec2 v_texCoord;
5
+
6
+ void main() {
7
+ gl_Position = vec4(a_position, 0.0, 1.0);
8
+ v_texCoord = a_texCoord;
9
+ }
10
+ `),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
11
+ precision highp float;
12
+
13
+ uniform sampler2D u_colorTexture;
14
+ uniform sampler2D u_alphaTexture;
15
+ in vec2 v_texCoord;
16
+ out vec4 fragColor;
17
+
18
+ void main() {
19
+ vec3 color = texture(u_colorTexture, v_texCoord).rgb;
20
+ float alpha = texture(u_alphaTexture, v_texCoord).r;
21
+ fragColor = vec4(color, alpha);
22
+ }
23
+ `),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){n(this.gl);let r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){n(this.gl),n(this.program);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.program,`a_position`),a=this.gl.getAttribLocation(this.program,`a_texCoord`);return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){n(this.gl);let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateGpu(e,t){n(this.gl),n(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let r=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),r}updateCpu(e,t){if(!this.worker){let e=new Blob([`(${Lc.toString()})()`],{type:`application/javascript`}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve(t.frame))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha merge worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let n=this.nextRequestId++,r=T();return this.pendingRequests.set(n,r),this.worker.postMessage({id:n,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){this.gl?.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=Error(`Color/alpha merger closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};Ic.forceCpu=!0;var Lc=()=>{let e=null,t=null,n=Promise.resolve();self.addEventListener(`message`,e=>{let{id:t,color:i,alpha:a}=e.data;n=n.then(async()=>{try{let e=await r(i,a);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{i.close(),a.close()}})});let r=async(e,t)=>{let n=e.format,r=t.format;if(!n||!r)throw Error(`CPU color/alpha merging requires a known VideoFrame format.`);let s=n.includes(`P10`),c=n.includes(`P12`),l=r.includes(`P10`),u=r.includes(`P12`);if(l!==s||u!==c)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${n}', alpha: '${r}').`);let d=e.codedWidth,f=e.codedHeight;if(n===`RGBX`||n===`RGBA`||n===`BGRX`||n===`BGRA`)return await i(e,t,d,f,n);if(n===`I420`||n===`I420P10`||n===`I420P12`||n===`I422`||n===`I422P10`||n===`I422P12`||n===`I444`||n===`I444P10`||n===`I444P12`)return await a(e,t,d,f,n);if(n===`NV12`)return await o(e,t,d,f);throw Error(`CPU color/alpha merging does not support format '${n}'.`)},i=async(e,t,n,r,i)=>{let a=n*r,o=new Uint8Array(a*4);await e.copyTo(o);let c=await s(t,n,r,1);for(let e=0,t=3;e<a;e++,t+=4)o[t]=c[e];let l={format:i===`RGBX`||i===`RGBA`?`RGBA`:`BGRA`,codedWidth:n,codedHeight:r,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,l)},a=async(e,t,n,r,i)=>{let a=i.includes(`P10`),o=i.includes(`P12`),c=a||o?2:1,l,u;i.startsWith(`I420`)?(l=Math.ceil(n/2),u=Math.ceil(r/2)):i.startsWith(`I422`)?(l=Math.ceil(n/2),u=r):(l=n,u=r);let d=n*r,f=l*u,p=d*c,m=f*c,h=d*c,g=p+2*m+h,_=new Uint8Array(g);await e.copyTo(_);let v=await s(t,n,r,c),y=p+2*m;_.set(v,y);let b={format:i.slice(0,4)+`A`+i.slice(4),codedWidth:n,codedHeight:r,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[_.buffer]};return new VideoFrame(_,b)},o=async(e,n,r,i)=>{let a=r*i,o=Math.ceil(r/2)*Math.ceil(i/2),c=e.allocationSize();(!t||t.byteLength!==c)&&(t=new Uint8Array(c)),await e.copyTo(t);let l=new Uint8Array(a+2*o+a);l.set(t.subarray(0,a),0);let u=a,d=a+o,f=a;for(let e=0;e<o;e++)l[u+e]=t[f+e*2],l[d+e]=t[f+e*2+1];let p=await s(n,r,i,1);l.set(p,a+2*o);let m={format:`I420A`,codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,m)},s=async(t,n,r,i)=>{let a=t.allocationSize();(!e||e.byteLength!==a)&&(e=new Uint8Array(a)),await t.copyTo(e);let o=t.format;if(o===`RGBA`||o===`BGRA`||o===`RGBX`||o===`BGRX`){let t=o===`RGBA`||o===`RGBX`?0:2,i=n*r;for(let n=0;n<i;n++)e[n]=e[n*4+t];return e.subarray(0,i)}return e.subarray(0,n*r*i)}},Rc=class extends Mc{constructor(e){if(!(e instanceof Kc))throw TypeError(`videoTrack must be an InputVideoTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This video track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getRotation(),a=await this._track.getDecoderConfig(),o=await this._track.getTimeResolution();return n(r&&a),new Pc(e,t,r,a,i,o)}_createPacketSink(){return new Ac(this._track)}async getSample(e,t={}){Oc(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw Error(`Internal error: Iterator returned nothing.`)}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}},zc=class{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Kc))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&Cs(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??`fill`,this._videoSampleSink=new Rc(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let e=this._options,t=this._videoTrack,n=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),i=await t.getSquarePixelHeight(),[a,o]=n%180==0?[r,i]:[i,r],s=e.crop;s&&=Ss(s,a,o);let[c,l]=s?[s.width,s.height]:[a,o],u=c/l;e.width!==void 0&&e.height===void 0?(c=e.width,l=Math.round(c/u)):e.width===void 0&&e.height!==void 0?(l=e.height,c=Math.round(l*u)):e.width!==void 0&&e.height!==void 0&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=n,this._crop=s})()}_videoSampleToWrappedCanvas(e){let t=this._width,r=this._height,i=this._canvasPool[this._nextCanvasIndex],a=!1;i||(typeof document<`u`?(i=document.createElement(`canvas`),i.width=t,i.height=r):i=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=i),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let o=i.getContext(`2d`,{alpha:this._alpha||Pe()});n(o),o.resetTransform(),a||(!this._alpha&&Pe()?(o.fillStyle=`black`,o.fillRect(0,0,t,r)):o.clearRect(0,0,t,r)),e.drawWithFit(o,{fit:this._fit,rotation:this._rotation,crop:this._crop});let s={canvas:i,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e,t){Oc(e),await this._ensureInit();let n=await this._videoSampleSink.getSample(e,t);return n&&this._videoSampleToWrappedCanvas(n)}async*canvases(e,t,n){await this._ensureInit(),yield*ge(this._videoSampleSink.samples(e,t,n),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*ge(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}},Bc=class extends jc{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Ae,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let i=t=>{let n=t.timestamp;this.expectedFirstTimestamp&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-n),n+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(n-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=n);let i=this.currentTimestamp;if(this.currentTimestamp+=t.duration,t.numberOfFrames===0){t.close();return}let a=r.sampleRate;t.setTimestamp(Math.round(i*a)/a),e(t)},a=vc.find(e=>e.supports(n,r));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Ns))throw TypeError(`The argument passed to onSample must be an AudioSample.`);i(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=Error(`Decoding error`).stack;this.decoder=new AudioDecoder({output:e=>{try{i(new Ns(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(n(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(n(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(n(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(n(this.decoder),this.decoder.close())}},Vc=class extends jc{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,n(j.includes(r.codec)),this.codec=r.codec;let{dataType:i,sampleSize:a,littleEndian:o}=Ut(this.codec);switch(this.inputSampleSize=a,a){case 1:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-2**7:i===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):i===`ulaw`?this.readInputValue=(e,t)=>wc(e.getUint8(t)):i===`alaw`?this.readInputValue=(e,t)=>Ec(e.getUint8(t)):n(!1);break;case 2:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint16(t,o)-2**15:i===`signed`?this.readInputValue=(e,t)=>e.getInt16(t,o):n(!1);break;case 3:i===`unsigned`?this.readInputValue=(e,t)=>de(e,t,o)-2**23:i===`signed`?this.readInputValue=(e,t)=>fe(e,t,o):n(!1);break;case 4:i===`unsigned`?this.readInputValue=(e,t)=>e.getUint32(t,o)-2**31:i===`signed`?this.readInputValue=(e,t)=>e.getInt32(t,o):i===`float`?this.readInputValue=(e,t)=>e.getFloat32(t,o):n(!1);break;case 8:i===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,o):n(!1);break;default:E(a),n(!1)}switch(a){case 1:i===`ulaw`||i===`alaw`?(this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0)):(this.outputSampleSize=1,this.outputFormat=`u8`,this.writeOutputValue=(e,t,n)=>e.setUint8(t,n+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0);break;case 3:this.outputSampleSize=4,this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n<<8,!0);break;case 4:this.outputSampleSize=4,i===`float`?(this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0)):(this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n,!0));break;case 8:this.outputSampleSize=4,this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0);break;default:E(a),n(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=u(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(r),a=new DataView(i);for(let e=0;e<n*this.decoderConfig.numberOfChannels;e++){let n=e*this.inputSampleSize,r=e*this.outputSampleSize,i=this.readInputValue(t,n);this.writeOutputValue(a,r,i)}let o=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);let s=this.currentTimestamp;this.currentTimestamp+=o;let c=new Ns({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:s});this.onSample(c)}async flush(){}close(){}},Hc=class extends Mc{constructor(e){if(!(e instanceof qc))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let r=await this._track.getCodec(),i=await this._track.getDecoderConfig();return n(r&&i),j.includes(i.codec)?new Vc(e,t,i):new Bc(e,t,r,i)}_createPacketSink(){return new Ac(this._track)}async getSample(e,t={}){Oc(e);for await(let n of this.mediaSamplesAtTimestamps([e],t))return n;throw Error(`Internal error: Iterator returned nothing.`)}samples(e,t,n={}){return this.mediaSamplesInRange(e,t,n)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}},Uc=class{constructor(e){if(!(e instanceof qc))throw TypeError(`audioTrack must be an InputAudioTrack.`);this._audioSampleSink=new Hc(e)}_audioSampleToWrappedArrayBuffer(e){let t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Oc(e);let n=await this._audioSampleSink.getSample(e,t);return n&&this._audioSampleToWrappedArrayBuffer(n)}buffers(e,t,n){return ge(this._audioSampleSink.samples(e,t,n),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return ge(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}},Wc=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Kc}isAudioTrack(){return this instanceof qc}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return z(this._backing.getInternalCodecId(),`internalCodecId`,`getInternalCodecId`)}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return z(this._backing.getLanguageCode(),`languageCode`,`getLanguageCode`)}async getName(){return this._backing.getName()}get name(){return z(this._backing.getName(),`name`,`getName`)}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return z(this._backing.getTimeResolution(),`timeResolution`,`getTimeResolution`)}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return z(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){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return ye((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let n=new Ac(this),r=1/0,i=-1/0,a=0,o=0;for await(let s of n.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&s.timestamp>=i)break;r=Math.min(r,s.timestamp),i=Math.max(i,s.timestamp+s.duration),a++,o+=s.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(i-r)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an InputTrack.`);return this.input!==t.input||this===t?!1:(this._backing.getPairingMask()&t._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Qc({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Qc({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Qc({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Qc({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Qc({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Gc(e);let t=await this.input.getTracks();for(let n of t)if(this.canBePairedWith(n)&&(!e||await e(n)))return!0;return!1}hasPairableVideoTrack(e){return e&&=Gc(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Gc(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},z=(e,t,n)=>{if(e instanceof Promise)throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${n}()' instead.`);return e},Gc=e=>{if(e!==void 0&&typeof e!=`function`)throw TypeError(`predicate, when provided, must be a function.`);return e?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`predicate must return or resolve to a boolean value.`);return e},r=e(t);return r instanceof Promise?r.then(n):n(r)}:void 0},Kc=class extends Wc{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 z(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return z(this._backing.getCodedWidth(),`codedWidth`,`getCodedWidth`)}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return z(this._backing.getCodedHeight(),`codedHeight`,`getCodedHeight`)}async getRotation(){return this._backing.getRotation()}get rotation(){return z(this._backing.getRotation(),`rotation`,`getRotation`)}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return z(this._backing.getSquarePixelWidth(),`squarePixelWidth`,`getSquarePixelWidth`)}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return z(this._backing.getSquarePixelHeight(),`squarePixelHeight`,`getSquarePixelHeight`)}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=Ze({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=Ze({num:z(this._backing.getSquarePixelWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)*z(this._backing.getCodedHeight(),`pixelAspectRatio`,`getPixelAspectRatio`),den:z(this._backing.getSquarePixelHeight(),`pixelAspectRatio`,`getPixelAspectRatio`)*z(this._backing.getCodedWidth(),`pixelAspectRatio`,`getPixelAspectRatio`)})}async getDisplayWidth(){return await this._backing.getMetadataDisplayWidth?.()??(await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(e!==void 0){let t=z(e,`displayWidth`,`getDisplayWidth`);if(t!==null)return t}return z(z(this._backing.getRotation(),`displayWidth`,`getDisplayWidth`)%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight(),`displayWidth`,`getDisplayWidth`)}async getDisplayHeight(){return await this._backing.getMetadataDisplayHeight?.()??(await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(e!==void 0){let t=z(e,`displayHeight`,`getDisplayHeight`);if(t!==null)return t}return z(z(this._backing.getRotation(),`displayHeight`,`getDisplayHeight`)%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth(),`displayHeight`,`getDisplayHeight`)}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pg`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return n(t!==null),_c.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof F))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);let t=await this.getCodec();if(t===null)return null;let r=await this.getDecoderConfig();return n(r),er(t,r,e.data)}},qc=class extends Wc{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}async getCodec(){return this._backing.getCodec()}get codec(){return z(this._backing.getCodec(),`codec`,`getCodec`)}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return z(this._backing.getNumberOfChannels(),`numberOfChannels`,`getNumberOfChannels`)}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return z(this._backing.getSampleRate(),`sampleRate`,`getSampleRate`)}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return await this._backing.getMetadataCodecParameterString?.()??(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();return n(t!==null),vc.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof F))throw TypeError(`packet must be an EncodedPacket.`);return await this.getCodec()===null?null:`key`}},Jc=e=>e??1/0,Yc=e=>-(e??-1/0),Xc=e=>-e,Zc=e=>{if(typeof e!=`object`||!e)throw TypeError(`query must be an object.`);if(e.filter!==void 0&&typeof e.filter!=`function`)throw TypeError(`query.filter, when provided, must be a function.`);if(e.sortBy!==void 0&&typeof e.sortBy!=`function`)throw TypeError(`query.sortBy, when provided, must be a function.`);return{filter:e.filter?t=>{let n=e=>{if(typeof e!=`boolean`)throw TypeError(`query.filter must return or resolve to a boolean.`);return e},r=e.filter(t);return r instanceof Promise?r.then(n):n(r)}:void 0,sortBy:e.sortBy?t=>{let n=e=>{if(typeof e!=`number`&&(!Array.isArray(e)||!e.every(e=>typeof e==`number`)))throw TypeError(`query.sortBy must return or resolve to a number or an array of numbers.`);return e},r=e.sortBy(t);return r instanceof Promise?r.then(n):n(r)}:void 0}},Qc=(e,t)=>({filter:e?.filter||t?.filter?n=>{let r=e?.filter?.(n)??!0,i=e=>e===!1?!1:t?.filter?.(n)??!0;return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?n=>{let r=e?.sortBy?.(n)??[],i=t?.sortBy?.(n)??[],a=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return r instanceof Promise||i instanceof Promise?Promise.all([r,i]).then(([e,t])=>a(e,t)):a(r,i)}:void 0}),$c=async(e,t)=>{let n=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){let t=await Promise.all(r);n=e.filter((e,n)=>t[n])}else n=e.filter((e,t)=>r[t])}if(!t?.sortBy)return n;let r=n.map(e=>t.sortBy(e)),i=r.some(e=>e instanceof Promise)?await Promise.all(r):r;return n.map((e,t)=>({track:e,sortValue:i[t]})).sort((e,t)=>{let n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],i=Math.max(n.length,r.length);for(let e=0;e<i;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}).map(e=>e.track)};Ke();var el=class e extends ut{get disposed(){return this._disposed}constructor(t){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,!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof Co)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(t.source instanceof Ka||t.source instanceof qa))throw TypeError(`options.source must be a Source or SourceRef.`);if(t.source instanceof Ka&&t.source._disposed)throw TypeError(`options.source must not be a disposed Source.`);if(t.initInput!==void 0&&!(t.initInput instanceof e))throw TypeError(`options.initInput, when provided, must be an Input.`);t.formatOptions!==void 0&&Yo(t.formatOptions,`formatOptions`),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},this._rootRef=t.source instanceof Ka?t.source.ref():t.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){n(this._rootSource instanceof Ja);let t=await this._rootSource._resolveRequest(e);return this._emit(`source`,{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let r=this._sourceCache.find(n=>n.cacheGroup===t&&Ya(n.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());let i=this._sourceCachePromises.find(n=>n.cacheGroup===t&&Ya(n.request,e));if(i)return i.promise.then(e=>e.sourceRef.source.ref());let a=(async()=>{let r=await this._getSourceUncached(e);if(Je(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1)>=4){let e=Ye(this._sourceCache,e=>e.cacheGroup===t&&e.sourceRef.source._refCount===1?e.age:1/0);n(e!==-1);let r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),oe(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);let i=this._sourceCachePromises.findIndex(t=>t.request===e);return n(i!==-1),this._sourceCachePromises.splice(i,1),{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:a}),a.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new rl(this._rootSource),this._emit(`source`,{source:this._rootSource,request:null,isRoot:!0});for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new tl})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),n(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof tl)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();let t=e.filter(e=>e!==null);if(t.length===0)return 0;let n=await Promise.all(t.map(e=>e.getFirstTimestamp()));return Math.min(...n)}async computeDuration(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null);if(n.length===0)return 0;let r=await Promise.all(n.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();let n=e.filter(e=>e!==null),r=(await Promise.all(n.map(e=>e.getDurationFromMetadata(t)))).filter(e=>e!==null);return r.length===0?null:Math.max(...r)}async getTracks(e){return e&&=Zc(e),$c((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=Zc(e),$c((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=Zc(e),$c((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=Zc(e);let t=Qc(e,{sortBy:async e=>[Xc((await e.getDisposition()).default),Xc(await e.hasPairableAudioTrack()),Xc(!await e.hasOnlyKeyPackets()),Yc(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=Zc(e);let t=await this.getPrimaryVideoTrack(),n=Qc(e,{sortBy:async e=>[Xc(!t||e.canBePairedWith(t)),Xc((await e.getDisposition()).default),Yc(await e.getBitrate())]});return(await this.getAudioTracks(n))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let n=e.getType()===`video`?new Kc(this,e):new qc(this,e);return this._backingToTrack.set(e,n),n}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise?.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}},tl=class extends Error{constructor(e=`Input has an unsupported or unrecognizable format.`){super(e),this.name=`UnsupportedInputFormatError`}},nl=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},rl=class{constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(e===void 0)throw 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 nl;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){let t=new Uint8Array;return new il(t,u(t),0,e,e)}let n=e+t,r=this.source._read(e,n,0,Wa);return r instanceof Promise?r.then(t=>t?new il(t.bytes,t.view,t.offset,e,n):null):r?new il(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new nl;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,D(this.fileSizeNonStrict-e,t,r));{let i=this.requestSlice(e,r),a=i=>i||(n(this.fileSizeNonStrict!==null),this.requestSlice(e,D(this.fileSizeNonStrict-e,t,r)));return i instanceof Promise?i.then(a):a(i)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let e=1024;return(async()=>{let t=[],n=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);let r=t.length*e,i=this.requestSliceRange(r,0,e);if(i instanceof Promise&&(i=await i),!i)break;t.push(B(i,i.length)),n+=i.length}let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.length;return new il(r,u(r),0,0,n)})()}},il=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,u(t),0,0,t.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(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},al=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},B=(e,t)=>{al(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},V=e=>(al(e,1),e.view.getUint8(e.bufferPos++)),ol=(e,t)=>{al(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},H=e=>{al(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},sl=e=>{al(e,3);let t=de(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},cl=e=>{al(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},ll=(e,t)=>{al(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},U=e=>{al(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},ul=e=>{al(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},dl=e=>{al(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},fl=e=>{al(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},pl=(e,t)=>{let n,r;return t?(n=ll(e,!0),r=ll(e,!0)):(r=ll(e,!1),n=ll(e,!1)),r*4294967296+n},ml=e=>{let t=U(e),n=U(e);return t*4294967296+n},hl=e=>{let t=dl(e),n=U(e);return t*4294967296+n},gl=e=>{let t=ul(e);return fl(e)*4294967296+t},_l=e=>{al(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},vl=e=>{al(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},W=(e,t)=>{al(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},yl=(e,t,n)=>d.decode(B(e,t)).split(`
24
+ `).map(e=>e.trim()).filter(e=>e.length>0&&!n?.ignore?.(e)),bl;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(bl||={});var G;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(G||={});var xl=`Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),Sl=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=B(e,125),e.filePos=n;let r=Cl(e,30);r&&(t.title??=r);let i=Cl(e,30);i&&(t.artist??=i);let a=Cl(e,30);a&&(t.album??=a);let o=Cl(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(String(s)));let c=B(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=Cl(e,28),e.skip(2)}else e.skip(-30),l=Cl(e,30);l&&(t.comment??=l);let u=V(e);u<xl.length&&(t.genre??=xl[u])},Cl=(e,t)=>{let n=B(e,t),r=ze(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},wl=e=>{let t=e.filePos,n=W(e,3),r=V(e),i=V(e),a=V(e),o=U(e);return n!==`ID3`||r===255||i===255||o&2155905152?(e.filePos=t,null):{majorVersion:r,revision:i,flags:a,size:dn(o)}},Tl=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new El(t,B(e,t.size));if(t.flags&bl.Footer&&r.removeFooter(),t.flags&bl.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&bl.ExtendedHeader){let e=r.readU32();t.majorVersion===3?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){let e=r.readId3V2Frame();if(!e)break;let i=r.pos,a=r.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&bl.Unsynchronisation)),o){console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=a;continue}if(s){console.warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=a;continue}if(c&&r.ununsynchronizeRegion(r.pos,a),n.raw??={},e.id===`TXXX`){let e=n.raw.TXXX??={},t=r.readId3V2TextEncoding(),i=r.readId3V2Text(t,a),o=r.readId3V2Text(t,a);e[i]??=o}else e.id[0]===`T`?n.raw[e.id]??=r.readId3V2EncodingAndText(a):n.raw[e.id]??=r.readBytes(e.size);switch(r.pos=i,e.id){case`TIT2`:case`TT2`:n.title??=r.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=r.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=r.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=r.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=r.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`TPOS`:case`TPA`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break;case`TCON`:case`TCO`:{let e=r.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(xl[e]!==void 0){n.genre??=xl[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(xl[e]!==void 0){n.genre??=xl[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=r.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=r.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(String(t)))}break;case`USLT`:case`ULT`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.lyrics??=r.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.comment??=r.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=r.readId3V2TextEncoding(),i;if(t.majorVersion===2){let e=r.readAscii(3);i=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else i=r.readId3V2Text(e,a);let o=r.readU8(),s=r.readId3V2Text(e,a).trimEnd(),c=a-r.pos;if(c>=0){let e=r.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:i,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:r.pos+=e.size}r.pos=a}},El=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?dn(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:dn(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case G.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case G.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=ze(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(r[0]===254&&r[1]===255){let e=new TextDecoder(`utf-16be`),t=ze(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{let e=ze(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),d.decode(r.subarray(0,e))}case G.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=ze(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case G.UTF_8:{let e=ze(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),d.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},Dl=class{constructor(e){this.helper=new Uint8Array(8),this.helperView=u(this.helper),this.writer=e}writeId3V2Tag(e){let t=this.writer.getPos();this.writeAscii(`ID3`),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let n=this.writer.getPos(),r=new Set;for(let{key:t,value:n}of Ve(e))switch(t){case`title`:this.writeId3V2TextFrame(`TIT2`,n),r.add(`TIT2`);break;case`description`:this.writeId3V2TextFrame(`TIT3`,n),r.add(`TIT3`);break;case`artist`:this.writeId3V2TextFrame(`TPE1`,n),r.add(`TPE1`);break;case`album`:this.writeId3V2TextFrame(`TALB`,n),r.add(`TALB`);break;case`albumArtist`:this.writeId3V2TextFrame(`TPE2`,n),r.add(`TPE2`);break;case`trackNumber`:{let t=e.tracksTotal===void 0?n.toString():`${n}/${e.tracksTotal}`;this.writeId3V2TextFrame(`TRCK`,t),r.add(`TRCK`)}break;case`discNumber`:{let t=e.discsTotal===void 0?n.toString():`${n}/${e.discsTotal}`;this.writeId3V2TextFrame(`TPOS`,t),r.add(`TPOS`)}break;case`genre`:this.writeId3V2TextFrame(`TCON`,n),r.add(`TCON`);break;case`date`:this.writeId3V2TextFrame(`TDRC`,n.toISOString().slice(0,10)),r.add(`TDRC`);break;case`lyrics`:this.writeId3V2LyricsFrame(n),r.add(`USLT`);break;case`comment`:this.writeId3V2CommentFrame(n),r.add(`COMM`);break;case`images`:{let e={coverFront:3,coverBack:4,unknown:0};for(let t of n){let n=e[t.kind]??0,r=t.description??``;this.writeId3V2ApicFrame(t.mimeType,n,r,t.data)}}break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:E(t)}if(e.raw)for(let t in e.raw){let n=e.raw[t];if(n==null||t.length!==4||r.has(t))continue;let i;if(typeof n==`string`)if(p(n)){i=new Uint8Array(n.length+2),i[0]=G.ISO_8859_1;for(let e=0;e<n.length;e++)i[e+1]=n.charCodeAt(e)}else{let e=f.encode(n);i=new Uint8Array(e.byteLength+2),i[0]=G.UTF_8,i.set(e,1)}else if(n instanceof Uint8Array)i=n;else if(t===`TXXX`&&pt(n)){for(let e in n){let t=n[e],r=p(e)&&p(t),i=r?null:f.encode(e),a=r?null:f.encode(t),o=r?e.length:i.byteLength,s=r?t.length:a.byteLength,c=1+o+1+s+1;this.writeAscii(`TXXX`),this.writeSynchsafeU32(c),this.writeU16(0),this.writeU8(r?G.ISO_8859_1:G.UTF_8),r?(this.writeIsoString(e),this.writeIsoString(t)):(this.writer.write(i),this.writeU8(0),this.writer.write(a),this.writeU8(0))}continue}else continue;this.writeAscii(t),this.writeSynchsafeU32(i.byteLength),this.writeU16(0),this.writer.write(i)}let i=this.writer.getPos(),a=i-n;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(i),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(un(e))}writeIsoString(e){let t=new Uint8Array(e.length+1);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);this.writer.write(t)}writeUtf8String(e){let t=f.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){let n=p(t),r=1+(n?t.length:f.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(r),this.writeU16(0),this.writeU8(n?G.ISO_8859_1:G.UTF_8),n?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){let t=p(e),n=5+e.length+1;this.writeAscii(`USLT`),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?G.ISO_8859_1:G.UTF_8),this.writeAscii(`und`),t?(this.writeIsoString(``),this.writeIsoString(e)):(this.writeUtf8String(``),this.writeUtf8String(e))}writeId3V2CommentFrame(e){let t=p(e),n=5+(t?e.length:f.encode(e).byteLength)+1;this.writeAscii(`COMM`),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?G.ISO_8859_1:G.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(``),this.writeIsoString(e)):(this.writeUtf8String(``),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,n,r){let i=p(e)&&p(n),a=i?n.length:f.encode(n).byteLength,o=1+e.length+1+1+a+1+r.byteLength;this.writeAscii(`APIC`),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(i?G.ISO_8859_1:G.UTF_8),i?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),i?this.writeIsoString(n):this.writeUtf8String(n),this.writer.write(r)}},Ol=class{constructor(e){this.mutex=new C,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,n){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw 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 ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},kl=class extends Ol{constructor(e,t){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),_t(this.output._metadataTags)||new Dl(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return`audio/aac`}async addEncodedVideoPacket(){throw Error(`ADTS does not support video.`)}async addEncodedAudioPacket(e,t,r){let i=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type===`key`),this.inputIsAdts===null){en(r);let e=r?.decoderConfig?.description;if(this.inputIsAdts=!e,!this.inputIsAdts){let t=wt(St(l(e)));this.header=t.header,this.headerBitstream=t.bitstream}}if(this.inputIsAdts){let e=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,e)}else{n(this.header);let e=t.data.byteLength+this.header.byteLength;Tt(this.headerBitstream,e);let r=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){let n=new Uint8Array(e);n.set(this.header,0),n.set(t.data,this.header.byteLength),this.format._options.onFrame(n,r)}}await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw Error(`ADTS does not support subtitles.`)}async finalize(){(await this.mutex.acquire())()}},Al=new Uint8Array([102,76,97,67]),jl=38,Ml=34,Nl=class extends Ol{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(Al),e()}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:r,minimumFrameSize:i,maximumFrameSize:a,sampleRate:o,channels:s,totalSamples:c}){n(this.writer.getPos()===4);let l=!_t(this.output._metadataTags),u=new k(new Uint8Array(4));u.writeBits(1,Number(!l)),u.writeBits(7,tr.STREAMINFO),u.writeBits(24,Ml),this.writer.write(u.bytes);let d=new k(new Uint8Array(18));if(d.writeBits(16,t),d.writeBits(16,r),d.writeBits(24,i),d.writeBits(24,a),d.writeBits(20,o),d.writeBits(3,s-1),d.writeBits(5,e-1),c>=2**32)throw Error(`This muxer only supports writing up to 2 ** 32 samples`);d.writeBits(4,0),d.writeBits(32,c),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let t=32+e.mimeType.length+(e.description?.length??0)+e.data.length,r=new Uint8Array(t),i=0,a=u(r);a.setUint32(i,e.kind===`coverFront`?3:e.kind===`coverBack`?4:0),i+=4,a.setUint32(i,e.mimeType.length),i+=4,r.set(f.encode(e.mimeType),8),i+=e.mimeType.length,a.setUint32(i,e.description?.length??0),i+=4,r.set(f.encode(e.description??``),i),i+=e.description?.length??0,i+=16,a.setUint32(i,e.data.length),i+=4,r.set(e.data,i),i+=e.data.length,n(i===t);let o=new k(new Uint8Array(4));o.writeBits(1,0),o.writeBits(7,tr.PICTURE),o.writeBits(24,t),this.writer.write(o.bytes),this.writer.write(r)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(jl+Al.byteLength),_t(this.output._metadataTags)){this.metadataWritten=!0;return}let e=this.output._metadataTags.images??[];for(let t of e)this.writePictureBlock(t);let t=rr(new Uint8Array,this.output._metadataTags,!1),n=new k(new Uint8Array(4));n.writeBits(1,1),n.writeBits(7,tr.VORBIS_COMMENT),n.writeBits(24,t.length),this.writer.write(n.bytes),this.writer.write(t),this.metadataWritten=!0}async getMimeType(){return`audio/flac`}async addEncodedVideoPacket(){throw Error(`FLAC does not support video.`)}async addEncodedAudioPacket(e,t,r){let i=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type===`key`),this.sampleRate===null){en(r),n(r),n(r.decoderConfig),n(r.decoderConfig.description),this.sampleRate=r.decoderConfig.sampleRate,this.channels=r.decoderConfig.numberOfChannels;let e=new k(l(r.decoderConfig.description));e.skipBits(167);let t=e.readBits(5)+1;this.bitsPerSample=t,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let i=il.tempFromBytes(t.data);i.skip(2);let a=ia(new k(B(i,2)).readBits(4));if(a===null)throw Error(`Invalid FLAC frame: Invalid block size.`);oa(i);let o=sa(i,a);this.format._options.appendOnly||(this.blockSizes.push(o),this.frameSizes.push(t.data.length));let s=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,s),await this.writer.flush()}finally{i()}}addSubtitleCue(){throw Error(`FLAC does not support subtitles.`)}async finalize(){let e=await this.mutex.acquire();if(!this.format._options.appendOnly){let e=1/0,t=0,r=1/0,i=0,a=0;for(let n=0;n<this.blockSizes.length;n++)r=Math.min(r,this.frameSizes[n]),i=Math.max(i,this.frameSizes[n]),t=Math.max(t,this.blockSizes[n]),a+=this.blockSizes[n],n!==this.blockSizes.length-1&&(e=Math.min(e,this.blockSizes[n]));n(this.sampleRate!==null),n(this.channels!==null),n(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:e,maximumBlockSize:t,minimumFrameSize:r,maximumFrameSize:i,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}},Pl=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Fl=/^WEBVTT(.|\n)*?\n{2}/,Il=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Ll=class{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
25
+ `,`
26
+ `).replaceAll(`\r`,`
27
+ `),Pl.lastIndex=0;let t;if(!this.preambleText){if(!Fl.test(e))throw Error(`WebVTT preamble incorrect.`);t=Pl.exec(e);let n=e.slice(0,t?.index??e.length).trimEnd();if(!n)throw Error(`No WebVTT preamble provided.`);this.preambleText=n,t&&(e=e.slice(t.index),Pl.lastIndex=0)}for(;t=Pl.exec(e);){let n=e.slice(0,t.index),r=t[1],i=t.index+t[0].length,a=e.indexOf(`
28
+ `,i)+1,o=e.slice(i,a).trim(),s=e.indexOf(`
29
+
30
+ `,i);s===-1&&(s=e.length);let c=zl(t[2]),l=zl(t[3])-c,u=e.slice(a,s).trim();e=e.slice(s).trimStart(),Pl.lastIndex=0;let d={timestamp:c/1e3,duration:l/1e3,text:u,identifier:r,settings:o,notes:n},f={};this.preambleEmitted||=(f.config={description:this.preambleText},!0),this.options.output(d,f)}}},Rl=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,zl=e=>{let t=Rl.exec(e);if(!t)throw Error(`Expected match.`);return 36e5*Number(t[1]||`0`)+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])},Bl=e=>{let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},Vl=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);n(t!==void 0);let r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},K=new Uint8Array(8),Hl=new DataView(K.buffer),q=e=>[(e%256+256)%256],J=e=>(Hl.setUint16(0,e,!1),[K[0],K[1]]),Ul=e=>(Hl.setInt16(0,e,!1),[K[0],K[1]]),Wl=e=>(Hl.setUint32(0,e,!1),[K[1],K[2],K[3]]),Y=e=>(Hl.setUint32(0,e,!1),[K[0],K[1],K[2],K[3]]),Gl=e=>(Hl.setInt32(0,e,!1),[K[0],K[1],K[2],K[3]]),Kl=e=>(Hl.setUint32(0,Math.floor(e/2**32),!1),Hl.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),ql=e=>(Hl.setInt32(0,Math.floor(e/2**32),!1),Hl.setUint32(4,e,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),Jl=e=>(Hl.setInt16(0,2**8*e,!1),[K[0],K[1]]),Yl=e=>(Hl.setInt32(0,2**16*e,!1),[K[0],K[1],K[2],K[3]]),Xl=e=>(Hl.setInt32(0,2**30*e,!1),[K[0],K[1],K[2],K[3]]),Zl=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},X=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},Ql=e=>{let t=Math.PI/180*e,n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},$l=Ql(0),eu=e=>[Yl(e[0]),Yl(e[1]),Xl(e[2]),Yl(e[3]),Yl(e[4]),Xl(e[5]),Yl(e[6]),Yl(e[7]),Xl(e[8])],Z=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),Q=(e,t,n,r,i)=>Z(e,[q(t),Wl(n),r??[]],i),tu=e=>e.isQuickTime?Z(`ftyp`,[X(`qt `),Y(512),X(`qt `)]):e.fragmented?e.cmaf?Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]):Z(`ftyp`,[X(`iso5`),Y(512),X(`iso5`),X(`iso6`),X(`mp41`)]):Z(`ftyp`,[X(`isom`),Y(512),X(`isom`),e.holdsAvc?X(`avc1`):[],X(`mp41`)]),nu=()=>Z(`styp`,[X(`iso5`),Y(0),X(`iso5`),X(`iso6`),X(`mp41`),X(`cmfc`),X(`dash`)]),ru=(e,t)=>{let n=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(n)||(n=0),Q(`sidx`,1,0,[Y(1),Y(Bd),Kl($(e.minWrittenTimestamp,Bd)),Kl(0),J(0),J(1),Y(t&2147483647),Y($(n,Bd)),Y(0)])},iu=e=>({type:`mdat`,largeSize:e}),au=e=>({type:`free`,size:e}),ou=e=>Z(`moov`,void 0,[su(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>lu(t,e.creationTime)),e.isFragmented?Xu(e.trackDatas):null,dd(e)]),su=(e,t)=>{let n=Math.max(0,...t.map(e=>$(cu(e),Bd)+$(e.startTimestampOffset??0,Bd))),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!a(e)||!a(n),o=i?Kl:Y;return Q(`mvhd`,+i,0,[o(e),o(e),Y(Bd),o(n),Yl(1),Jl(1),Array(10).fill(0),eu($l),Array(24).fill(0),Y(r)])},cu=e=>{if(e.samples.length===0)return 0;let t=1/0,n=-1/0;for(let r=0;r<e.samples.length;r++){let i=e.samples[r];i.timestamp<t&&(t=i.timestamp),i.timestamp+i.duration>n&&(n=i.timestamp+i.duration)}return t===1/0?0:n-t},lu=(e,t)=>{let n=Hd(e),r=e.startTimestampOffset!==null&&e.startTimestampOffset>0;return Z(`trak`,void 0,[uu(e,t),r?du(e,e.startTimestampOffset):null,fu(e,t),n.name===void 0?null:Z(`udta`,void 0,[Z(`name`,[...f.encode(n.name)])])])},uu=(e,t)=>{let n=$(cu(e),Bd)+$(e.startTimestampOffset??0,Bd),r=!a(t)||!a(n),i=r?Kl:Y,o;if(e.type===`video`){let t=e.track.metadata.rotation;o=Ql(t??0)}else o=$l;let s=2;return e.track.metadata.disposition?.default!==!1&&(s|=1),Q(`tkhd`,+r,s,[i(t),i(t),Y(e.track.id),Y(0),i(n),Array(8).fill(0),J(0),J(e.track.id),Jl(+(e.type===`audio`)),J(0),eu(o),Yl(e.type===`video`?e.info.width:0),Yl(e.type===`video`?e.info.height:0)])},du=(e,t)=>{let n=$(t,Bd),r=$(cu(e),Bd),i=!a(n)||!a(r),o=i?Kl:Y,s=i?ql:Gl;return Z(`edts`,void 0,[Q(`elst`,+!!i,0,[Y(2),o(n),s(-1),Yl(1),o(r),s(0),Yl(1)])])},fu=(e,t)=>Z(`mdia`,void 0,[pu(e,t),gu(!0,mu[e.type],hu[e.type]),_u(e)]),pu=(e,t)=>{let n=$(cu(e),e.timescale),r=!a(t)||!a(n),i=r?Kl:Y;return Q(`mdhd`,+r,0,[i(t),i(t),Y(e.timescale),i(n),J(Td(e.track.metadata.languageCode??`und`)),J(0)])},mu={video:`vide`,audio:`soun`,subtitle:`text`},hu={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},gu=(e,t,n,r=`\0\0\0\0`)=>Q(`hdlr`,0,0,[e?X(`mhlr`):Y(0),X(t),X(r),Y(0),Y(0),X(n,!0)]),_u=e=>Z(`minf`,void 0,[vu[e.type](),yu(),Su(e)]),vu={video:()=>Q(`vmhd`,0,1,[J(0),J(0),J(0),J(0)]),audio:()=>Q(`smhd`,0,0,[J(0),J(0)]),subtitle:()=>Q(`nmhd`,0,0)},yu=()=>Z(`dinf`,void 0,[bu()]),bu=()=>Q(`dref`,0,0,[Y(1)],[xu()]),xu=()=>Q(`url `,0,1),Su=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return Z(`stbl`,void 0,[Cu(e),Uu(e),t?Ju(e):null,t?Yu(e):null,Gu(e),Ku(e),qu(e),Wu(e)])},Cu=e=>{let t;if(e.type===`video`)t=wu(yd(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let r=xd(e.track.source._codec,e.muxer.isQuickTime);n(r),t=ju(r,e)}else e.type===`subtitle`&&(t=Vu(Cd[e.track.source._codec],e));return n(t),Q(`stsd`,0,0,[Y(1)],[t])},wu=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1),J(0),J(0),Array(12).fill(0),J(t.info.width),J(t.info.height),Y(4718592),Y(4718592),Y(0),J(1),Array(32).fill(0),J(24),Ul(65535)],[bd[t.track.source._codec](t),Tu(t),x(t.info.decoderConfig.colorSpace)?Eu(t):null]),Tu=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:Z(`pasp`,[Y(e.info.pixelAspectRatio.num),Y(e.info.pixelAspectRatio.den)]),Eu=e=>Z(`colr`,[X(`nclx`),J(h[e.info.decoderConfig.colorSpace.primaries]),J(_[e.info.decoderConfig.colorSpace.transfer]),J(y[e.info.decoderConfig.colorSpace.matrix]),q(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),Du=e=>e.info.decoderConfig&&Z(`avcC`,[...l(e.info.decoderConfig.description)]),Ou=e=>e.info.decoderConfig&&Z(`hvcC`,[...l(e.info.decoderConfig.description)]),ku=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?h[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?_[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?y[t.colorSpace.matrix]:2;return Q(`vpcC`,1,0,[q(r),q(i),q(c),q(l),q(u),q(d),J(0)])},Au=e=>Z(`av1C`,It(e.info.decoderConfig.codec)),ju=(e,t)=>{let n=0,r,i=16,a=j.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=Ut(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),J(1),J(n),J(0),Y(0),J(t.info.numberOfChannels),J(i),J(0),J(0),J(t.info.sampleRate<2**16?t.info.sampleRate:0),J(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),J(1),J(n),J(0),Y(0),J(t.info.numberOfChannels),J(Math.min(i,16)),Ul(e),J(0),J(t.info.sampleRate<2**16?t.info.sampleRate:0),J(0),a?[Y(1),Y(i/8),Y(t.info.numberOfChannels*i/8)]:[Y(0),Y(0),Y(0)],Y(2)]}return Z(e,r,[Sd(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},Mu=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...q(t),...q(21),...Wl(0),...Y(0),...Y(0)];if(e.info.decoderConfig.description){let t=l(e.info.decoderConfig.description);n=[...n,...q(5),...Zl(t.byteLength),...t]}return n=[...J(1),...q(0),...q(4),...Zl(n.length),...n,...q(6),...q(1),...q(2)],n=[...q(3),...Zl(n.length),...n],Q(`esds`,0,0,n)},Nu=e=>Z(`wave`,void 0,[Pu(e),Fu(e),Z(`\0\0\0\0`)]),Pu=e=>Z(`frma`,[X(xd(e.track.source._codec,e.muxer.isQuickTime))]),Fu=e=>{let{littleEndian:t}=Ut(e.track.source._codec);return Z(`enda`,[J(+t)])},Iu=e=>{let t=e.info.numberOfChannels,r=3840,i=e.info.sampleRate,a=0,o=0,s=new Uint8Array,c=e.info.decoderConfig?.description;if(c){n(c.byteLength>=18);let e=Xn(l(c));t=e.outputChannelCount,r=e.preSkip,i=e.inputSampleRate,a=e.outputGain,o=e.channelMappingFamily,e.channelMappingTable&&(s=e.channelMappingTable)}return Z(`dOps`,[q(0),q(t),J(r),Y(i),Ul(a),q(o),...s])},Lu=e=>{let t=e.info.decoderConfig?.description;return n(t),Q(`dfLa`,0,0,[...l(t).subarray(4)])},Ru=e=>{let{littleEndian:t,sampleSize:n}=Ut(e.track.source._codec);return Q(`pcmC`,0,0,[q(+t),q(8*n)])},zu=e=>{let t=ar(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new k(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),Z(`dac3`,[...n])},Bu=e=>{let t=dr(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new k(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return Z(`dec3`,[...i])},Vu=(e,t)=>Z(e,[[,,,,,,].fill(0),J(1)],[wd[t.track.source._codec](t)]),Hu=e=>Z(`vttC`,[...f.encode(e.info.config.description)]),Uu=e=>Q(`stts`,0,0,[Y(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Y(e.sampleCount),Y(e.sampleDelta)])]),Wu=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return Q(`stss`,0,0,[Y(t.length),t.map(([e])=>Y(e+1))])},Gu=e=>Q(`stsc`,0,0,[Y(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Y(e.firstChunk),Y(e.samplesPerChunk),Y(1)])]),Ku=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=Ut(e.track.source._codec);return Q(`stsz`,0,0,[Y(t*e.info.numberOfChannels),Y(e.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0))])}return Q(`stsz`,0,0,[Y(0),Y(e.samples.length),e.samples.map(e=>Y(e.size))])},qu=e=>e.finalizedChunks.length>0&&i(e.finalizedChunks).offset>=2**32?Q(`co64`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Kl(e.offset))]):Q(`stco`,0,0,[Y(e.finalizedChunks.length),e.finalizedChunks.map(e=>Y(e.offset))]),Ju=e=>Q(`ctts`,1,0,[Y(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Y(e.sampleCount),Gl(e.sampleCompositionTimeOffset)])]),Yu=e=>{let t=1/0,r=-1/0,i=1/0,a=-1/0;n(e.compositionTimeOffsetTable.length>0),n(e.samples.length>0);for(let n=0;n<e.compositionTimeOffsetTable.length;n++){let i=e.compositionTimeOffsetTable[n];t=Math.min(t,i.sampleCompositionTimeOffset),r=Math.max(r,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];i=Math.min(i,$(n.timestamp,e.timescale)),a=Math.max(a,$(n.timestamp+n.duration,e.timescale))}let o=Math.max(-t,0);return a>=2**31?null:Q(`cslg`,0,0,[Gl(o),Gl(t),Gl(r),Gl(i),Gl(a)])},Xu=e=>Z(`mvex`,void 0,e.map(Zu)),Zu=e=>Q(`trex`,0,0,[Y(e.track.id),Y(1),Y(0),Y(0),Y(0)]),Qu=(e,t)=>Z(`moof`,void 0,[$u(e),...t.map(td)]),$u=e=>Q(`mfhd`,0,0,[Y(e)]),ed=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,t|=r?1:2,t<<24|n<<16|0},td=e=>Z(`traf`,void 0,[nd(e),rd(e),id(e)]),nd=e=>{n(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let r=e.currentChunk.samples[1]??e.currentChunk.samples[0],i={duration:r.timescaleUnitsToNextSample,size:r.size,flags:ed(r)};return Q(`tfhd`,0,t,[Y(e.track.id),Y(i.duration),Y(i.size),Y(i.flags)])},rd=e=>(n(e.currentChunk),Q(`tfdt`,1,0,[Kl($(e.currentChunk.startTimestamp,e.timescale))])),id=e=>{n(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),r=e.currentChunk.samples.map(e=>e.size),i=e.currentChunk.samples.map(ed),a=e.currentChunk.samples.map(t=>$(t.timestamp-t.decodeTimestamp,e.timescale)),o=new Set(t),s=new Set(r),c=new Set(i),l=new Set(a),u=c.size===2&&i[0]!==i[1],d=o.size>1,f=s.size>1,p=!u&&c.size>1,m=l.size>1||[...l].some(e=>e!==0),h=0;return h|=1,h|=4*u,h|=256*d,h|=512*f,h|=1024*p,h|=2048*m,Q(`trun`,1,h,[Y(e.currentChunk.samples.length),Y(e.currentChunk.offset-e.currentChunk.moofOffset||0),u?Y(i[0]):[],e.currentChunk.samples.map((e,n)=>[d?Y(t[n]):[],f?Y(r[n]):[],p?Y(i[n]):[],m?Gl(a[n]):[]])])},ad=e=>Z(`mfra`,void 0,[...e.map(od),sd()]),od=(e,t)=>Q(`tfra`,1,0,[Y(e.track.id),Y(63),Y(e.finalizedChunks.length),e.finalizedChunks.map(n=>[Kl($(n.samples[0].timestamp,e.timescale)),Kl(n.moofOffset),Y(t+1),Y(1),Y(1)])]),sd=()=>Q(`mfro`,0,0,[Y(0)]),cd=()=>Z(`vtte`),ld=(e,t,n,r,i)=>Z(`vttc`,void 0,[i===null?null:Z(`vsid`,[Gl(i)]),n===null?null:Z(`iden`,[...f.encode(n)]),t===null?null:Z(`ctim`,[...f.encode(Bl(t))]),r===null?null:Z(`sttg`,[...f.encode(r)]),Z(`payl`,[...f.encode(e)])]),ud=e=>Z(`vtta`,[...f.encode(e)]),dd=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=gd(r);e&&t.push(e)}else if(n===`mdta`){let e=_d(r);e&&t.push(e)}else(n===`udta`||n===`auto`&&e.isQuickTime)&&fd(t,e.output._metadataTags);return t.length===0?null:Z(`udta`,void 0,t)},fd=(e,t)=>{for(let{key:n,value:r}of Ve(t))switch(n){case`title`:e.push(pd(`©nam`,r));break;case`description`:e.push(pd(`©des`,r));break;case`artist`:e.push(pd(`©ART`,r));break;case`album`:e.push(pd(`©alb`,r));break;case`albumArtist`:e.push(pd(`albr`,r));break;case`genre`:e.push(pd(`©gen`,r));break;case`date`:e.push(pd(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(pd(`©cmt`,r));break;case`lyrics`:e.push(pd(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:E(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(pd(n,r)):r instanceof Uint8Array&&e.push(Z(n,Array.from(r))))}},pd=(e,t)=>{let n=f.encode(t);return Z(e,[J(n.length),J(Td(`und`)),Array.from(n)])},md={"image/jpeg":13,"image/png":14,"image/bmp":27},hd=(e,t)=>{let n=[];for(let{key:r,value:i}of Ve(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:vd(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:vd(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:vd(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:vd(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:vd(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:vd(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:vd(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:vd(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:vd(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:Z(`data`,[Y(md[e.mimeType]??0),Y(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:vd(t)})}else n.push({key:`trkn`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.tracksTotal??0),J(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:Z(`data`,[Y(0),Y(0),J(0),J(i),J(e.discsTotal??0),J(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:E(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:vd(i)}):i instanceof Uint8Array?n.push({key:r,value:Z(`data`,[Y(0),Y(0),Array.from(i)])}):i instanceof mt&&n.push({key:r,value:Z(`data`,[Y(md[i.mimeType]??0),Y(0),Array.from(i.data)])}))}return n},gd=e=>{let t=hd(e,!1);return t.length===0?null:Q(`meta`,0,0,void 0,[gu(!1,`mdir`,``,`appl`),Z(`ilst`,void 0,t.map(e=>Z(e.key,void 0,[e.value])))])},_d=e=>{let t=hd(e,!0);return t.length===0?null:Z(`meta`,void 0,[gu(!1,`mdta`,``),Q(`keys`,0,0,[Y(t.length)],t.map(e=>Z(`mdta`,[...f.encode(e.key)]))),Z(`ilst`,void 0,t.map((e,t)=>Z(String.fromCharCode(...Y(t+1)),void 0,[e.value])))])},vd=e=>Z(`data`,[Y(1),Y(0),...f.encode(e)]),yd=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`}},bd={avc:Du,hevc:Ou,vp8:ku,vp9:ku,av1:Au},xd=(e,t)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`}if(t)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},Sd=(e,t)=>{switch(e){case`aac`:return Mu;case`mp3`:return Mu;case`opus`:return Iu;case`vorbis`:return Mu;case`flac`:return Lu;case`ac3`:return zu;case`eac3`:return Bu}if(t)switch(e){case`pcm-s24`:return Nu;case`pcm-s24be`:return Nu;case`pcm-s32`:return Nu;case`pcm-s32be`:return Nu;case`pcm-f32`:return Nu;case`pcm-f32be`:return Nu;case`pcm-f64`:return Nu;case`pcm-f64be`:return Nu}else switch(e){case`pcm-s16`:return Ru;case`pcm-s16be`:return Ru;case`pcm-s24`:return Ru;case`pcm-s24be`:return Ru;case`pcm-s32`:return Ru;case`pcm-s32be`:return Ru;case`pcm-f32`:return Ru;case`pcm-f32be`:return Ru;case`pcm-f64`:return Ru;case`pcm-f64be`:return Ru}return null},Cd={webvtt:`wvtt`},wd={webvtt:Hu},Td=e=>{n(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},Ed=class{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 Error(`Can't have multiple Writers for the same Target.`);this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){n(!this.started),this.target._start(),this.started=!0}write(e){n(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 n(this.started&&!this.finalized),this.target._flush()}async finalize(){n(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}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}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 Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},Dd=Ha===void 0?void 0:Ha,Od=class extends ut{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 TypeError(`offset must be a non-negative integer.`);return new Rd(this,e)}},kd=2**16,Ad=2**32,jd=class extends Od{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!=`object`)throw TypeError(`BufferTarget options, when provided, must be an object.`);if(e.onFinalize!==void 0&&typeof e.onFinalize!=`function`)throw 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(kd,{maxByteLength:Ad})}catch{this._buffer=new ArrayBuffer(kd),this._supportsResize=!1}else this._buffer=new ArrayBuffer(kd);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>Ad)throw Error(`ArrayBuffer exceeded maximum size of ${Ad} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this._bytes,0),this._buffer=e,this._bytes=n}}}_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)}},Md=2**24,Nd=2,Pd=class extends Od{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw TypeError(`StreamTarget requires a WritableStream instance.`);if(t!=null&&typeof t!=`object`)throw TypeError(`StreamTarget options, when provided, must be an object.`);if(t.chunked!==void 0&&typeof t.chunked!=`boolean`)throw TypeError(`options.chunked, when provided, must be a boolean.`);if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw TypeError(`options.chunkSize, when provided, must be an integer and not smaller than 1024.`);this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??Md}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){let e=t-this._lastWriteEnd;this._write(new Uint8Array(e),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(n(this._streamWriter),this._sections.length===0)return;let e=[],t=[...this._sections].sort((e,t)=>e.start-t.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let n=1;n<t.length;n++){let r=e[e.length-1],i=t[n];i.start<=r.start+r.size?r.size=Math.max(r.size,i.start+i.data.byteLength-r.start):e.push({start:i.start,size:i.data.byteLength})}for(let t of e){t.data=new Uint8Array(t.size);for(let e of this._sections)t.start<=e.start&&e.start<t.start+t.size&&t.data.set(e.data,e.start-t.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(t.data,t.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&t.start!==this._lastFlushEnd)throw Error(`Internal error: Monotonicity violation.`);this._streamWriter.write({type:`write`,data:t.data,position:t.start}).catch(e=>{this._writeError??=e}),this._lastFlushEnd=t.start+t.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let n=this._chunks.findIndex(e=>e.start<=t&&t<e.start+this._chunkSize);n===-1&&(n=this._createChunk(t));let r=this._chunks[n],i=t-r.start,a=e.subarray(0,Math.min(this._chunkSize-i,e.byteLength));r.data.set(a,i);let o={start:i,end:i+a.byteLength};if(this._insertSectionIntoChunk(r,o),r.written[0].start===0&&r.written[0].end===this._chunkSize&&(r.shouldFlush=!0),this._chunks.length>Nd){for(let e=0;e<this._chunks.length-1;e++)this._chunks[e].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let n=0,r=e.written.length-1,i=-1;for(;n<=r;){let a=Math.floor(n+(r-n+1)/2);e.written[a].start<=t.start?(n=a+1,i=a):r=a-1}for(e.written.splice(i+1,0,t),(i===-1||e.written[i].end<t.start)&&i++;i<e.written.length-1&&e.written[i].end>=e.written[i+1].start;)e.written[i].end=Math.max(e.written[i].end,e.written[i+1].end),e.written.splice(i+1,1)}_createChunk(e){let t={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(t),this._chunks.sort((e,t)=>e.start-t.start),this._chunks.indexOf(t)}_tryToFlushChunks(e=!1){n(this._streamWriter);for(let t=0;t<this._chunks.length;t++){let n=this._chunks[t];if(!(!n.shouldFlush&&!e)){for(let e of n.written){let t=n.start+e.start;if(this._monotonicity===!0&&t!==this._lastFlushEnd)throw Error(`Internal error: Monotonicity violation.`);this._streamWriter.write({type:`write`,data:n.data.subarray(e.start,e.end),position:t}).catch(e=>{this._writeError??=e}),this._lastFlushEnd=n.start+e.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;n(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit(`finalized`)}async _close(){return this._streamWriter?.close()}},Fd=class extends Od{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new Pd(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:e=>{if(this._monotonicity!==!0)throw Error(`AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.`);return n(e.position===this._nextWritePos),this._nextWritePos+=e.data.byteLength,n(this._writer),this._writer.write(e.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Id=class extends Od{constructor(e,t={}){if(typeof e!=`string`)throw TypeError(`filePath must be a string.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Dd.fs)throw Error(`FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).`);super(),this._fileHandle=null;let r=new WritableStream({start:async()=>{this._fileHandle=await Dd.fs.open(e,`w`)},write:async e=>{n(this._fileHandle),await this._fileHandle.write(e.data,0,e.data.byteLength,e.position)},close:async()=>{this._fileHandle&&=(await this._fileHandle.close(),null)}});this._streamTarget=new Pd(r,{chunked:!0,...t})}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit(`finalized`)}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}},Ld=class extends Od{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit(`finalized`)}async _close(){}},Rd=class extends Od{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)}},zd=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!=`string`)throw TypeError(`rootPath must be a string.`);if(typeof t!=`function`)throw TypeError(`getTarget must be a function.`)}},Bd=57600,Vd=2082844800,Hd=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},$=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},Ud=class extends Ol{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new jd,this.auxWriter=new Ed(this.auxTarget,!1),this.auxBoxWriter=new Vl(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=T(),this.creationTime=Math.floor(Date.now()/1e3)+Vd,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof $f,this.isCmaf=t instanceof Qf,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof Qf?1/0:1)}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart=`fragmented`,this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>this.format._options.fastStart===void 0?e instanceof jd:this.format._options.fastStart===`fragmented`),this.boxWriter=new Vl(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof jd&&`in-memory`),this.isFragmented=this.fastStart===`fragmented`),this.isCmaf){if(!this.output._hasInitTarget())throw Error(`CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.`);let e=new Ed(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Vl(e)}let t=this.output._tracks.some(e=>e.isVideoTrack()&&e.source._codec===`avc`);{let e=this.initBoxWriter??this.boxWriter;if(n(e),this.format._options.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(tu({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onFtyp(t,n)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output._tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(n(this.writer),n(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=iu(!0),this.boxWriter.writeBox(this.mdat));await this.writer?.flush(),e()}allTracksAreKnown(){for(let 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;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return _r({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;Qt(r),n(r),n(r.decoderConfig);let a={...r.decoderConfig};n(a.codedWidth!==void 0),n(a.codedHeight!==void 0);let o=!1;if(e.source._codec===`avc`&&!a.description){let e=En(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);a.description=Dn(e),o=!0}else if(e.source._codec===`hevc`&&!a.description){let e=In(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);a.description=Wn(e),o=!0}let s=ke(1/(e.metadata.frameRate??57600),1e6).den,c=a.displayAspectWidth,l=a.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}:Ze({num:c*a.codedHeight,den:l*a.codedWidth}),d={muxer:this,track:e,type:`video`,info:{width:a.codedWidth,height:a.codedHeight,pixelAspectRatio:u,decoderConfig:a,requiresAnnexBTransformation:o},timescale:s,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;en(r),n(r),n(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){let e=ea(il.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=bt[e.samplingFrequencyIndex],r=xt[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);a.description=Ct({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),o=!0}let s={muxer:this,track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresPcmTransformation:!this.isFragmented&&j.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:o,firstPacket:t},timescale:a.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;tn(t),n(t),n(t.config);let i={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[..._n(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=wn(e,4)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=this.createSampleForTrack(r,i,t.timestamp,t.duration,t.type);await this.registerSample(r,a)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=ea(il.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let a=t.timestamp,o=t.duration;if(r.info.requiresPcmTransformation){let e=Ut(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(o=i.byteLength/e/r.info.sampleRate,r.info.expectedNextPcmPacketTimestamp!==null){let e=a-r.info.expectedNextPcmPacketTimestamp;if(e<.01)a=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);a=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=a+o}let s=this.createSampleForTrack(r,i,a,o,t.type);await this.registerSample(r,s)}finally{r()}}async padWithSilence(e,t,n){let r=$(n,e.timescale);if(n=r/e.timescale,r>0){let{sampleSize:i,silentValue:a}=Ut(e.info.decoderConfig.codec),o=r*e.info.numberOfChannels,s=new Uint8Array(i*o).fill(a),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),t,n,`key`);await this.registerSample(e,c)}return n}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let r=new Set([]);for(let i of e.cueQueue)n(i.timestamp<=t),n(e.lastCueEndTimestamp<=i.timestamp+i.duration),r.add(Math.max(i.timestamp,e.lastCueEndTimestamp)),r.add(i.timestamp+i.duration);let i=[...r].sort((e,t)=>e-t),a=i[0],o=i[1]??a;if(t<o)break;if(e.lastCueEndTimestamp<a){this.auxWriter.seek(0);let t=cd();this.auxBoxWriter.writeBox(t);let n=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,a-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=a}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=o)break;Il.lastIndex=0;let r=Il.test(n.text),i=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&o<i&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=ud(n.notes);this.auxBoxWriter.writeBox(e)}let c=ld(n.text,r?a:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),i===o&&e.cueQueue.splice(t--,1)}let s=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,s,a,o-a,`key`);await this.registerSample(e,c),e.lastCueEndTimestamp=o}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:$(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=$(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=i(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=r[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let a=e.timestampProcessingQueue[t];a.decodeTimestamp=r[t];let o=$(a.timestamp-a.decodeTimestamp,e.timescale),s=$(a.duration,e.timescale);if(e.lastTimescaleUnits!==null){n(e.lastSample);let t=$(a.decodeTimestamp,e.timescale,!1),r=Math.round(t-e.lastTimescaleUnits);if(n(r>=0),e.lastTimescaleUnits+=r,e.lastSample.timescaleUnitsToNextSample=r,!this.isFragmented){let t=i(e.timeToSampleTable);if(n(t),t.sampleCount===1){t.sampleDelta=r;let n=e.timeToSampleTable[e.timeToSampleTable.length-2];n&&n.sampleDelta===r&&(n.sampleCount++,e.timeToSampleTable.pop(),t=n)}else t.sampleDelta!==r&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:r}));t.sampleDelta===s?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:s});let a=i(e.compositionTimeOffsetTable);n(a),a.sampleCompositionTimeOffset===o?a.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=$(a.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:s}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=a}if(e.timestampProcessingQueue.length=0,n(e.lastSample),n(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){n(t.type===`key`);let r=$(t.timestamp,e.timescale,!1),i=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=i}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(n(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(!e.currentChunk)r=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.closed});n>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=n>=.5}r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),n(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(n(!this.isFragmented),n(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+$(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||i(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)n(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(n(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){n(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){let e=this.initBoxWriter??this.boxWriter;n(e),this.format._options.onMoov&&e.writer.startTrackingWrites();let t=ou(this);if(e.writeBox(t),this.format._options.onMoov){let{data:t,start:n}=e.writer.stopTrackingWrites();this.format._options.onMoov(t,n)}if(this.isCmaf){n(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Vl(this.writer);let e=this.boxWriter.measureBox(nu()),t=this.boxWriter.measureBox(ru(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}n(this.writer),n(this.boxWriter);let r=this.trackDatas.filter(e=>e.currentChunk),i=Qu(t,r),a=this.writer.getPos(),o=a+this.boxWriter.measureBox(i),s=o+8,c=1/0;for(let e of r){e.currentChunk.offset=s,e.currentChunk.moofOffset=a;for(let t of e.currentChunk.samples)s+=t.size;c=Math.min(c,e.currentChunk.startTimestamp)}let l=s-o,u=l>=2**32;if(u)for(let e of r)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();let d=Qu(t,r);if(this.boxWriter.writeBox(d),this.format._options.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,c)}n(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();let f=iu(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(o+(u?16:8));for(let e of r)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(let e of r)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(n(this.writer),n(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){let e=ou(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;n(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=iu(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){n(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let r=t.track.metadata.maximumPacketCount;n(r!==void 0),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0,e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas){await this.finalizeCurrentChunk(e),n(e.startTimestampOffset!==null);for(let t=0;t<e.samples.length;t++){let n=e.samples[t];n.timestamp-=e.startTimestampOffset,n.decodeTimestamp-=e.startTimestampOffset}}if(n(this.writer),n(this.boxWriter),this.fastStart===`in-memory`){this.mdat=iu(!1);let e;for(let t=0;t<2;t++){let t=ou(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let i=this.writer.getPos()+r+e;for(let t of this.finalizedChunks){t.offset=i;for(let{data:r}of t.samples)n(r),i+=r.byteLength,e+=r.byteLength}if(i<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let t=ou(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)n(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){let e=this.segmentHeaderSize===null?0:this.writer.getPos()-this.segmentHeaderSize;this.writer.seek(0),this.boxWriter.writeBox(nu()),this.boxWriter.writeBox(ru(this,e))}else{let e=this.writer.getPos(),t=ad(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{n(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);n(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}let r=ou(this);if(this.fastStart===`reserve`){n(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(au(e))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}e()}},Wd=-(2**15),Gd=2**15-1,Kd=`Mediabunny`,qd=6,Jd=5,Yd={video:1,audio:2,subtitle:17},Xd=class extends Ol{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=T(),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.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new ui(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:L.EBML,data:[{id:L.EBMLVersion,data:1},{id:L.EBMLReadVersion,data:1},{id:L.EBMLMaxIDLength,data:4},{id:L.EBMLMaxSizeLength,data:8},{id:L.DocType,data:this.format instanceof tp?`webm`:`matroska`},{id:L.DocTypeVersion,data:2},{id:L.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let t=new Uint8Array([28,83,187,107]),n=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),i=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:L.SeekHead,data:[{id:L.Seek,data:[{id:L.SeekID,data:t},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:L.Seek,data:[{id:L.SeekID,data:n},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:L.Seek,data:[{id:L.SeekID,data:r},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:L.Seek,data:[{id:L.SeekID,data:i},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:L.Seek,data:[{id:L.SeekID,data:a},{id:L.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){let e={id:L.Duration,data:new ei(0)};this.segmentDuration=e;let t={id:L.Info,data:[{id:L.TimestampScale,data:1e6},{id:L.MuxingApp,data:Kd},{id:L.WritingApp,data:Kd},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){let e={id:L.Tracks,data:[]};this.tracksElement=e;for(let t of this.trackDatas){let r=Si[t.track.source._codec];n(r);let i=0;if(t.type===`audio`&&t.track.source._codec===`opus`){i=8e7;let e=t.info.decoderConfig.description;if(e){let t=Xn(l(e));i=Math.round(1e9*(t.preSkip/Vt))}}e.data.push({id:L.TrackEntry,data:[{id:L.TrackNumber,data:t.track.id},{id:L.TrackUID,data:t.track.id},{id:L.TrackType,data:Yd[t.type]},t.track.metadata.disposition?.default===!1?{id:L.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:L.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:L.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:L.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:L.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:L.FlagCommentary,data:1}:null,{id:L.FlagLacing,data:0},{id:L.Language,data:t.track.metadata.languageCode??`und`},{id:L.CodecID,data:r},{id:L.CodecDelay,data:0},{id:L.SeekPreRoll,data:i},t.track.metadata.name===void 0?null:{id:L.Name,data:new ni(t.track.metadata.name)},t.type===`video`?this.videoSpecificTrackInfo(t):null,t.type===`audio`?this.audioSpecificTrackInfo(t):null,t.type===`subtitle`?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){let{frameRate:t,rotation:n}=e.track.metadata,i=[e.info.decoderConfig.description?{id:L.CodecPrivate,data:l(e.info.decoderConfig.description)}:null,t?{id:L.DefaultDuration,data:1e9/t}:null],a=n?r(-n):0,o=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,s=e.info.decoderConfig.colorSpace,c={id:L.Video,data:[{id:L.PixelWidth,data:e.info.width},{id:L.PixelHeight,data:e.info.height},o?{id:L.DisplayWidth,data:e.info.aspectRatio.num}:null,o?{id:L.DisplayHeight,data:e.info.aspectRatio.den}:null,o?{id:L.DisplayUnit,data:3}:null,e.info.alphaMode?{id:L.AlphaMode,data:1}:null,x(s)?{id:L.Colour,data:[{id:L.MatrixCoefficients,data:y[s.matrix]},{id:L.TransferCharacteristics,data:_[s.transfer]},{id:L.Primaries,data:h[s.primaries]},{id:L.Range,data:s.fullRange?2:1}]}:null,a?{id:L.Projection,data:[{id:L.ProjectionType,data:0},{id:L.ProjectionPoseRoll,data:new $r((a+180)%360-180)}]}:null]};return i.push(c),i}audioSpecificTrackInfo(e){let t=j.includes(e.track.source._codec)?Ut(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:L.CodecPrivate,data:l(e.info.decoderConfig.description)}:null,{id:L.Audio,data:[{id:L.SamplingFrequency,data:new $r(e.info.sampleRate)},{id:L.Channels,data:e.info.numberOfChannels},t?{id:L.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:L.CodecPrivate,data:f.encode(e.info.config.description)}]}maybeCreateTags(){let e=[],t=(t,n)=>{e.push({id:L.SimpleTag,data:[{id:L.TagName,data:new ni(t)},typeof n==`string`?{id:L.TagString,data:new ni(n)}:{id:L.TagBinary,data:n}]})},n=this.output._metadataTags,r=new Set;for(let{key:e,value:i}of Ve(n))switch(e){case`title`:t(`TITLE`,i),r.add(`TITLE`);break;case`description`:t(`DESCRIPTION`,i),r.add(`DESCRIPTION`);break;case`artist`:t(`ARTIST`,i),r.add(`ARTIST`);break;case`album`:t(`ALBUM`,i),r.add(`ALBUM`);break;case`albumArtist`:t(`ALBUM_ARTIST`,i),r.add(`ALBUM_ARTIST`);break;case`genre`:t(`GENRE`,i),r.add(`GENRE`);break;case`comment`:t(`COMMENT`,i),r.add(`COMMENT`);break;case`lyrics`:t(`LYRICS`,i),r.add(`LYRICS`);break;case`date`:t(`DATE`,i.toISOString().slice(0,10)),r.add(`DATE`);break;case`trackNumber`:t(`PART_NUMBER`,n.tracksTotal===void 0?i.toString():`${i}/${n.tracksTotal}`),r.add(`PART_NUMBER`);break;case`discNumber`:t(`DISC`,n.discsTotal===void 0?i.toString():`${i}/${n.discsTotal}`),r.add(`DISC`);break;case`tracksTotal`:case`discsTotal`:break;case`images`:case`raw`:break;default:E(e)}if(n.raw)for(let e in n.raw){let i=n.raw[e];i==null||r.has(e)||(typeof i==`string`||i instanceof Uint8Array)&&t(e,i)}e.length!==0&&(this.tagsElement={id:L.Tags,data:[{id:L.Tag,data:[{id:L.Targets,data:[{id:L.TargetTypeValue,data:50},{id:L.TargetType,data:`MOVIE`}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,t=[],n=new Set,r=e.images??[];for(let e of r){let r=e.name;r===void 0&&(r=(e.kind===`coverFront`?`cover`:e.kind===`coverBack`?`back`:`image`)+(He(e.mimeType)??``));let i;for(;;){i=0n;for(let e=0;e<8;e++)i<<=8n,i|=BigInt(Math.floor(Math.random()*256));if(i!==0n&&!n.has(i))break}n.add(i),t.push({id:L.AttachedFile,data:[e.description===void 0?null:{id:L.FileDescription,data:new ni(e.description)},{id:L.FileName,data:new ni(r)},{id:L.FileMediaType,data:e.mimeType},{id:L.FileData,data:e.data},{id:L.FileUID,data:i}]})}for(let[n,i]of Object.entries(e.raw??{}))i instanceof ht&&/^\d+$/.test(n)&&(r.find(e=>e.mimeType===i.mimeType&&Ge(e.data,i.data))||t.push({id:L.AttachedFile,data:[i.description===void 0?null:{id:L.FileDescription,data:new ni(i.description)},{id:L.FileName,data:new ni(i.name??``)},{id:L.FileMediaType,data:i.mimeType??``},{id:L.FileData,data:i.data},{id:L.FileUID,data:BigInt(n)}]}));t.length!==0&&(this.attachmentsElement={id:L.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:L.Segment,size:this.format._options.appendOnly?-1:qd,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:L.Cues,data:[]}}get segmentDataOffset(){return n(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let 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;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return wi({isWebM:this.format instanceof tp,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;Qt(r),n(r),n(r.decoderConfig),n(r.decoderConfig.codedWidth!==void 0),n(r.decoderConfig.codedHeight!==void 0);let a=r.decoderConfig.displayAspectWidth,o=r.decoderConfig.displayAspectHeight,s=a===void 0||o===void 0?null:Ze({num:a,den:o}),c={track:e,type:`video`,info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,aspectRatio:s,decoderConfig:r.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return e.source._codec===`vp9`?c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(Ft(c.info.decoderConfig.codec))}:e.source._codec===`av1`&&(c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(It(c.info.decoderConfig.codec))}),this.trackDatas.push(c),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,r){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;en(r),n(r),n(r.decoderConfig);let a={...r.decoderConfig},o=!1;if(e.source._codec===`aac`&&!a.description){let e=ea(il.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=bt[e.samplingFrequencyIndex],r=xt[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);a.description=Ct({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),o=!0}let s={track:e,type:`audio`,info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:a,requiresAdtsStripping:o},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getSubtitleTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;tn(t),n(t),n(t.config);let i={track:e,type:`subtitle`,info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(i),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),i}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,i);let a=t.timestamp,o=t.duration;e.metadata.frameRate!==void 0&&(a=ye(a,e.metadata.frameRate),o=ye(o,e.metadata.frameRate));let s=r.info.alphaMode?t.sideData.alpha??null:null,c=this.createInternalChunk(t.data,a,o,t.type,s);e.source._codec===`vp9`&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=ea(il.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}let a=t.type===`key`;this.validateTimestamp(r.track,t.timestamp,a);let o=this.createInternalChunk(i,t.timestamp,t.duration,t.type);r.chunkQueue.push(o),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,!0);let i=t.text,a=Math.round(t.timestamp*1e3);Il.lastIndex=0,i=i.replace(Il,e=>`<${Bl(zl(e.slice(1,-1))-a)}>`);let o=f.encode(i),s=`${t.settings??``}\n${t.identifier??``}\n${t.notes??``}`,c=this.createInternalChunk(o,t.timestamp,t.duration,`key`,s.trim()?f.encode(s):null);r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.chunkQueue.length===0&&!r.closed)break outer;r.chunkQueue.length>0&&r.chunkQueue[0].timestamp<n&&(t=r,n=r.chunkQueue[0].timestamp)}if(!t)break;let r=t.chunkQueue.shift();this.writeBlock(t,r)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!==`key`||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let n=new k(t.data);n.skipBits(2);let r=n.readBits(1),i=(n.readBits(1)<<1)+r;if(i===3&&n.skipBits(1),n.readBits(1)||n.readBits(1)!==0||(n.skipBits(2),n.readBits(24)!==4817730))return;i>=2&&n.skipBits(1);let a={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];c(t.data,n.pos,n.pos+3,a)}createInternalChunk(e,t,n,r,i=null){return{data:e,type:r,timestamp:t,duration:n,additions:i}}writeBlock(e,t){this.segment||this.createSegment();let r=Math.round(1e3*t.timestamp),i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.chunkQueue[0];return r?r.type===`key`:n.closed}),a=!1;if(!this.currentCluster)a=!0;else{n(this.currentClusterStartMsTimestamp!==null),n(this.currentClusterMaxMsTimestamp!==null);let e=r-this.currentClusterStartMsTimestamp;a=i&&r>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>Gd}a&&this.createNewCluster(r);let o=r-this.currentClusterStartMsTimestamp;if(o<Wd)return;let s=new Uint8Array(4),c=new DataView(s.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,o,!1);let l=Math.round(1e3*t.duration);if(t.additions){let n={id:L.BlockGroup,data:[{id:L.Block,data:[s,t.data]},t.type===`delta`?{id:L.ReferenceBlock,data:new ti(e.lastWrittenMsTimestamp-r)}:null,t.additions?{id:L.BlockAdditions,data:[{id:L.BlockMore,data:[{id:L.BlockAddID,data:1},{id:L.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:L.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(n)}else{c.setUint8(3,Number(t.type===`key`)<<7);let e={id:L.SimpleBlock,data:[s,t.data]};this.ebmlWriter.writeEBML(e)}this.startTimestamp=Math.min(this.startTimestamp,r),this.endTimestamp=Math.max(this.endTimestamp,r+l),e.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:L.Cluster,size:this.format._options.appendOnly?-1:Jd,data:[{id:L.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(n(this.currentCluster),!this.format._options.appendOnly){let e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,Jd),this.writer.seek(t)}if(this.format._options.onCluster){n(this.currentClusterStartMsTimestamp!==null);let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(let[e,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(e);let r=[...t.entries()].sort((e,t)=>e[0]-t[0]);for(let[t,i]of r)n(this.cues),this.cues.data.push({id:L.CuePoint,data:[{id:L.CueTime,data:t},...i.map(t=>({id:L.CueTrackPositions,data:[{id:L.CueTrack,data:t.track.id},{id:L.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),n(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let e=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(e,qd);let t=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new ei(t),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),n(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}},Zd=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let t=this.writer.getPos(),n=224|e.mpegVersionId<<3|e.layer<<1,r;r=e.mpegVersionId&2&&e.mpegVersionId&1?0:1;let i=-1,a=r*16*4+e.layer*16;for(let t=0;t<16;t++){let n=rn[a+t];if(on(r,e.layer,1e3*n,e.sampleRate,0)>=155){i=t;break}}if(i===-1)throw Error(`No suitable bitrate found.`);let o=i<<4|e.frequencyIndex<<2|0,s=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=255,this.helper[1]=n,this.helper[2]=o,this.helper[3]=s,this.writer.write(this.helper.subarray(0,4));let c=cn(e.mpegVersionId,e.channel);this.writer.seek(t+c),this.writeU32(an);let l=0;e.frameCount!==null&&(l|=fn.FrameCount),e.fileSize!==null&&(l|=fn.FileSize),e.toc!==null&&(l|=fn.Toc),this.writeU32(l),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));let u=rn[a+i],d=on(r,e.layer,1e3*u,e.sampleRate,0);this.writer.seek(t+d)}},Qd=class extends Ol{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(this.format._options.xingHeader===!1),this.mp3Writer=new Zd(this.writer),_t(this.output._metadataTags)||new Dl(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return`audio/mpeg`}async addEncodedVideoPacket(){throw Error(`MP3 does not support video.`)}async addEncodedAudioPacket(e,t){let n=await this.mutex.acquire();try{let n=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&n){let e=u(t.data);if(e.byteLength<4)throw Error(`Invalid MP3 header in sample.`);let n=ln(e.getUint32(0,!1),null).header;if(!n)throw Error(`Invalid MP3 header in sample.`);let r=cn(n.mpegVersionId,n.channel);if(e.byteLength>=r+4){let t=e.getUint32(r,!1);if(t===1483304551||t===1231971951)return}this.xingFrameData={mpegVersionId:n.mpegVersionId,layer:n.layer,frequencyIndex:n.frequencyIndex,sampleRate:n.sampleRate,channel:n.channel,modeExtension:n.modeExtension,copyright:n.copyright,original:n.original,emphasis:n.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,t.timestamp,t.type===`key`),n&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw Error(`MP3 does not support subtitles.`)}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;let e=await this.mutex.acquire(),t=this.writer.getPos()-this.xingFramePos;this.writer.seek(this.xingFramePos);let n=new Uint8Array(100);for(let e=0;e<100;e++){let r=Math.floor(this.framePositions.length*(e/100)),i=this.framePositions[r]-this.xingFramePos;n[e]=i/t*256}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=t,this.xingFrameData.toc=n,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(e,t)}e()}},$d=8192,ef=class extends Ol{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=T(),this.pageBytes=new Uint8Array(Ui),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,Hi({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw Error(`Video tracks are not supported.`)}getTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;let i;do i=Math.floor(2**32*Math.random());while(this.trackDatas.some(e=>e.serialNumber===i));n(e.source._codec===`vorbis`||e.source._codec===`opus`),en(t),n(t),n(t.decoderConfig);let a={track:e,serialNumber:i,internalSampleRate:e.source._codec===`opus`?Vt:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(a,t),this.trackDatas.push(a),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}queueHeaderPackets(e,t){if(n(t.decoderConfig),e.track.source._codec===`vorbis`){n(t.decoderConfig.description);let r=l(t.decoderConfig.description);if(r[0]!==2)throw TypeError(`First byte of Vorbis decoder description must be 2.`);let i=1,a=()=>{let e=0;for(;;){let t=r[i++];if(t===void 0)throw TypeError(`Vorbis decoder description is too short.`);if(e+=t,t<255)return e}},o=a(),s=a();if(r.length-i<=0)throw TypeError(`Vorbis decoder description is too short.`);let c=r.subarray(i,i+=o);i+=s;let d=r.subarray(i),f=new Uint8Array(7);f[0]=3,f[1]=118,f[2]=111,f[3]=114,f[4]=98,f[5]=105,f[6]=115;let p=rr(f,this.output._metadataTags,!0);e.packetQueue.push({data:c,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:p,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:d,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});let m=u(c).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(m&15),1<<(m>>4)],modeBlockflags:$n(d).modeBlockflags}}else if(e.track.source._codec===`opus`){if(!t.decoderConfig.description)throw TypeError(`For Ogg, Opus decoder description is required.`);let n=l(t.decoderConfig.description),r=new Uint8Array(8),i=u(r);i.setUint32(0,1332770163,!1),i.setUint32(4,1415669619,!1);let a=rr(r,this.output._metadataTags,!0);e.packetQueue.push({data:n,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Xn(n).preSkip}}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let i=r.currentTimestampInSamples,{durationInSamples:a,vorbisBlockSize:o}=Vi(t.data,r.codecInfo,r.vorbisLastBlocksize);r.currentTimestampInSamples+=a,r.vorbisLastBlocksize=o,r.packetQueue.push({data:t.data,timestampInSamples:i,durationInSamples:a,forcePageFlush:!1}),await this.interleavePages()}finally{r()}}addSubtitleCue(){throw Error(`Subtitle tracks are not supported.`)}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let e of this.trackDatas)for(;e.packetQueue.length>0;){let t=e.packetQueue.shift();if(this.writePacket(e,t,!1),t.forcePageFlush)break}this.bosPagesWritten=!0}outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.packetQueue.length<=1&&!r.closed)break outer;r.packetQueue.length>0&&r.packetQueue[0].timestampInSamples<n&&(t=r,n=r.packetQueue[0].timestampInSamples)}if(!t)break;let r=t.packetQueue.shift(),i=t.packetQueue.length===0;this.writePacket(t,r,i)}e||await this.writer.flush()}writePacket(e,t,n){let r=t.timestampInSamples+t.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){let t=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&r-e.currentPageStartTimestampInSamples>t&&this.writePage(e,!1)}let i=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);let r=Math.min(255,i);e.currentLacingValues.push(r),e.currentPageSize++,o+=r;let s=i<255;if(e.currentLacingValues.length===255){let r=t.data.subarray(a,o);if(a=o,e.currentPageData.push(r),e.currentPageSize+=r.length,this.writePage(e,n&&s),s)return}if(s)break;i-=255}let s=t.data.subarray(a);e.currentPageData.push(s),e.currentPageSize+=s.length,e.currentGranulePosition=r,(e.currentPageSize>=$d||t.forcePageFlush)&&this.writePage(e,n)}writePage(e,t){this.pageView.setUint32(0,Li,!0),this.pageView.setUint8(4,0);let n=0;e.currentPageStartsWithFreshPacket||(n|=1),e.pagesWritten===0&&(n|=2),t&&(n|=4),this.pageView.setUint8(5,n);let r=e.currentLacingValues.every(e=>e===255)?-1:e.currentGranulePosition;he(this.pageView,6,r,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let i=27+e.currentLacingValues.length;for(let t of e.currentPageData)this.pageBytes.set(t,i),i+=t.length;let a=this.pageBytes.subarray(0,i),o=Bi(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){let{data:t,start:n}=this.writer.stopTrackingWrites();this.format._options.onPage(t,n,e.track.source)}}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0;await this.interleavePages(!0);for(let e of this.trackDatas)e.currentLacingValues.length>0&&this.writePage(e,!0);e()}},tf=0,nf=4096,rf=256,af=224,of=192,sf=new Uint8Array([9,240]),cf=new Uint8Array([70,1]),lf=class extends Ol{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(188),this.packetView=u(this.packetBuffer),this.allTracksKnown=T(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,pa(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;Qt(t),n(t?.decoderConfig);let i=e.source._codec;n(i===`avc`||i===`hevc`);let a=i===`avc`?27:36,o={track:e,pid:rf+this.trackDatas.length,streamType:a,streamId:af+this.videoTrackIndex++,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(o),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getAudioTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;en(t),n(t?.decoderConfig);let i=e.source._codec;n(i===`aac`||i===`mp3`||i===`ac3`||i===`eac3`);let a,o;switch(i){case`aac`:a=15,o=of+this.audioTrackIndex++;break;case`mp3`:a=3,o=of+this.audioTrackIndex++;break;case`ac3`:a=129,o=189;break;case`eac3`:a=135,o=189}let s={track:e,pid:rf+this.trackDatas.length,streamType:a,streamId:o,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let i=this.prepareVideoPacket(r,t,n);t.type===`key`&&await this.flushTimestampQueue(r),r.timestampProcessingQueue.push({data:i,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type===`key`})}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,n);this.validateTimestamp(r.track,t.timestamp,t.type===`key`);let i=this.prepareAudioPacket(r,t,n);t.type===`key`&&await this.flushTimestampQueue(r),r.timestampProcessingQueue.push({data:i,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type===`key`})}finally{r()}}async addSubtitleCue(){throw Error(`MPEG-TS does not support subtitles.`)}prepareVideoPacket(e,t,n){let r=e.track.source._codec;if(e.inputIsAnnexB===null){let t=n?.decoderConfig?.description;if(e.inputIsAnnexB=!t,!e.inputIsAnnexB){let n=l(t);r===`avc`?e.avcDecoderConfig=On(n):e.hevcDecoderConfig=Gn(n)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,r):this.prepareLengthPrefixedVideoPacket(e,t,r)}prepareAnnexBVideoPacket(e,t){let n=[];for(let r of _n(e)){let i=e.subarray(r.offset,r.offset+r.length);(t===`avc`?bn(i[0])===gn.AUD:Pn(i[0])===N.AUD_NUT)||n.push(i)}let r=t===`avc`?sf:cf;return n.unshift(r),Cn(n)}prepareLengthPrefixedVideoPacket(e,t,n){let r=t.data,i=n===`avc`?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(let e of vn(r,i)){let t=r.subarray(e.offset,e.offset+e.length);(n===`avc`?bn(t[0])===gn.AUD:Pn(t[0])===N.AUD_NUT)||a.push(t)}if(t.type===`key`)if(n===`avc`){let t=e.avcDecoderConfig;for(let e of t.pictureParameterSets)a.unshift(e);for(let e of t.sequenceParameterSets)a.unshift(e)}else{let t=e.hevcDecoderConfig;for(let e of t.arrays)if(e.nalUnitType===N.PPS_NUT)for(let t of e.nalUnits)a.unshift(t);for(let e of t.arrays)if(e.nalUnitType===N.SPS_NUT)for(let t of e.nalUnits)a.unshift(t);for(let e of t.arrays)if(e.nalUnitType===N.VPS_NUT)for(let t of e.nalUnits)a.unshift(t)}let o=n===`avc`?sf:cf;return a.unshift(o),Cn(a)}prepareAudioPacket(e,t,r){let i=e.track.source._codec;if(i===`mp3`||i===`ac3`||i===`eac3`)return t.data;if(e.inputIsAdts===null){let t=r?.decoderConfig?.description;if(e.inputIsAdts=!t,!e.inputIsAdts){let n=wt(St(l(t)));e.adtsHeader=n.header,e.adtsHeaderBitstream=n.bitstream}}if(e.inputIsAdts)return t.data;n(e.adtsHeader),n(e.adtsHeaderBitstream);let a=e.adtsHeader,o=t.data.byteLength+a.byteLength;Tt(e.adtsHeaderBitstream,o);let s=new Uint8Array(o);return s.set(a,0),s.set(t.data,a.byteLength),s}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async flushTimestampQueue(e,t=!0){if(e.timestampProcessingQueue.length===0)return;let n=e.timestampProcessingQueue.map(e=>e.presentationTimestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t],e.packetQueue.push(r)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.packetQueue.length===0&&!r.closed)break outer;r.packetQueue.length>0&&r.packetQueue[0].presentationTimestamp<n&&(t=r,n=r.packetQueue[0].presentationTimestamp)}if(!t)break;let r=t.packetQueue.shift();this.writePesPacket(t,r)}e||await this.writer.flush()}writeTables(){n(!this.tablesWritten),this.writePsiSection(tf,pf),this.writePsiSection(nf,mf(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let n=0,r=!0;for(;n<t.length;){let i=184-!!r,a=t.length-n,o=Math.min(i,a),s;r?(s=this.payloadBuffer.subarray(0,1+o),s[0]=0,s.set(t.subarray(n,n+o),1)):s=t.subarray(n,n+o),this.writeTsPacket(e,r,null,s),n+=o,r=!1}}writePesPacket(e,t){let r=e.track.type===`video`,i=r?10:5,a=new Uint8Array(9+i),o=u(a),s=new k(a.subarray(9));pe(o,0,1,!1),a[3]=e.streamId;let c=e.track.type===`video`?0:Math.min(8+t.data.length,65535);o.setUint16(4,c,!1),o.setUint8(6,132),o.setUint8(7,r?192:128),o.setUint8(8,i);let l=Math.round(t.presentationTimestamp*fa);if(s.pos=0,s.writeBits(4,r?3:2),s.writeBits(3,l>>>30&7),s.writeBits(1,1),s.writeBits(15,l>>>15&32767),s.writeBits(1,1),s.writeBits(15,l&32767),s.writeBits(1,1),r){n(t.decodeTimestamp!==null);let e=Math.round(t.decodeTimestamp*fa);s.writeBits(4,1),s.writeBits(3,e>>>30&7),s.writeBits(1,1),s.writeBits(15,e>>>15&32767),s.writeBits(1,1),s.writeBits(15,e&32767),s.writeBits(1,1)}let d=a.length+t.data.length,f=0,p=!0;for(;f<d;){let n=p,r=d-f,i=p&&t.isKeyframe,o=p&&!e.firstPacketWritten,s=Math.max(0,184-r),c;c=i||o?Math.max(2,s):s;let l=null;if(c>0){let e=this.adaptationFieldBuffer;c===1?e[0]=0:(e[0]=c-1,e[1]=Number(o)<<7|Number(i)<<6,e.fill(255,2,c)),l=e.subarray(0,c)}let u=Math.min(184-c,r),m=this.payloadBuffer.subarray(0,u),h=0;if(f<a.length){let e=Math.min(a.length-f,u);m.set(a.subarray(f,f+e),0),h=e}let g=Math.max(0,f-a.length),_=g+(u-h);h<u&&m.set(t.data.subarray(g,_),h),this.writeTsPacket(e.pid,n,l,m),f+=u,p=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,n,r){let i=this.continuityCounters.get(e)??0,a=r.length>0,o=n?a?3:2:+!!a;this.packetBuffer[0]=71,this.packetView.setUint16(1,(t?16384:0)|e&8191,!1),this.packetBuffer[3]=o<<4|i&15,a&&this.continuityCounters.set(e,i+1&15);let s=4;n&&(this.packetBuffer.set(n,s),s+=n.length),this.packetBuffer.set(r,s),s+=r.length,s<188&&this.packetBuffer.fill(255,s);let c=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),c)}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.closed=!0,await this.flushTimestampQueue(n,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.closed=!0,await this.flushTimestampQueue(e,!1);await this.interleavePackets(!0),e()}},uf=79764919,df=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^uf:t<<1;df[e]=t>>>0&4294967295}var ff=e=>{let t=4294967295;for(let n=0;n<e.length;n++){let r=e[n];t=(t<<8^df[t>>>24^r])>>>0}return t},pf=new Uint8Array(16);{let e=u(pf);pf[0]=0,e.setUint16(1,45069,!1),e.setUint16(3,1,!1),pf[5]=193,pf[6]=0,pf[7]=0,e.setUint16(8,1,!1),e.setUint16(10,61440,!1),e.setUint32(12,ff(pf.subarray(0,12)),!1)}var mf=e=>{let t=0;for(let n of e)t+=5,n.streamType===129?t+=cr.length:n.streamType===135&&(t+=lr.length);let n=9+t+4,r=new Uint8Array(3+n-4),i=u(r);r[0]=2,i.setUint16(1,45056|n&4095,!1),i.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,i.setUint16(8,65535,!1),i.setUint16(10,61440,!1);let a=12;for(let t of e)r[a++]=t.streamType,i.setUint16(a,57344|t.pid&8191,!1),a+=2,t.streamType===129?(i.setUint16(a,61440|cr.length,!1),a+=2,r.set(cr,a),a+=cr.length):t.streamType===135?(i.setUint16(a,61440|lr.length,!1),a+=2,r.set(lr,a),a+=lr.length):(i.setUint16(a,61440,!1),a+=2);let o=ff(r),s=new Uint8Array(r.length+4);return s.set(r,0),u(s).setUint32(r.length,o,!1),s},hf=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}},gf=class extends Ol{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new hf(this.writer),e()}async getMimeType(){return`audio/wav`}async addEncodedVideoPacket(){throw Error(`WAVE does not support video.`)}async addEncodedAudioPacket(e,t,r){let i=await this.mutex.acquire();try{if(this.headerWritten||=(en(r),n(r),n(r.decoderConfig),this.writeHeader(e,r.decoderConfig),this.sampleRate=r.decoderConfig.sampleRate,!0),this.validateTimestamp(e,t.timestamp,t.type===`key`),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw Error(`WAVE does not support subtitles.`)}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let n,r=e.source._codec,i=Ut(r);n=i.dataType===`ulaw`?Xi.MULAW:i.dataType===`alaw`?Xi.ALAW:i.dataType===`float`?Xi.IEEE_FLOAT:Xi.PCM;let a=t.numberOfChannels,o=t.sampleRate,s=i.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?`RF64`:`RIFF`),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii(`WAVE`),this.isRf64&&(this.riffWriter.writeAscii(`ds64`),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii(`fmt `),this.riffWriter.writeU32(16),this.riffWriter.writeU16(n),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*s),this.riffWriter.writeU16(s),this.riffWriter.writeU16(8*i.sampleSize),!_t(this.output._metadataTags)){let e=this.format._options.metadataFormat??`info`;e===`info`?this.writeInfoChunk(this.output._metadataTags):e===`id3`?this.writeId3Chunk(this.output._metadataTags):E(e)}if(this.riffWriter.writeAscii(`data`),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onHeader(e,t)}}writeInfoChunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii(`LIST`),this.riffWriter.writeU32(0),this.riffWriter.writeAscii(`INFO`);let n=new Set,r=(e,t)=>{if(!p(t)){console.warn(`Didn't write tag '${e}' because '${t}' is not ISO 8859-1-compatible.`);return}let r=t.length+1,i=new Uint8Array(r);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);this.riffWriter.writeAscii(e),this.riffWriter.writeU32(r),this.writer.write(i),r&1&&this.writer.write(new Uint8Array(1)),n.add(e)};for(let{key:t,value:i}of Ve(e))switch(t){case`title`:r(`INAM`,i),n.add(`INAM`);break;case`artist`:r(`IART`,i),n.add(`IART`);break;case`album`:r(`IPRD`,i),n.add(`IPRD`);break;case`trackNumber`:r(`ITRK`,e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`),n.add(`ITRK`);break;case`genre`:r(`IGNR`,i),n.add(`IGNR`);break;case`date`:r(`ICRD`,i.toISOString().slice(0,10)),n.add(`ICRD`);break;case`comment`:r(`ICMT`,i),n.add(`ICMT`);break;case`albumArtist`:case`discNumber`:case`tracksTotal`:case`discsTotal`:case`description`:case`lyrics`:case`images`:break;case`raw`:break;default:E(t)}if(e.raw)for(let t in e.raw){let i=e.raw[t];i==null||t.length!==4||n.has(t)||typeof i==`string`&&r(t,i)}let i=this.writer.getPos(),a=i-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(i),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii(`ID3 `),this.riffWriter.writeU32(0);let n=new Dl(this.writer).writeId3V2Tag(e),r=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(n),this.writer.seek(r),n&1&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire(),t=this.writer.getPos();this.isRf64?(n(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),n(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),n(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(n(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),n(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}},_f=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=Math.floor(e.startTime*this.targetSampleRate),this.timestampOffset=e.startTime-this.bufferStartFrame/this.targetSampleRate}doChannelMixerSetup(){n(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=e===1&&t===2?(t,n)=>t[n*e]:e===1&&t===4?(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let r=e.allocationSize({planeIndex:0,format:`f32`}),i=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(i,{planeIndex:0,format:`f32`});let a=e.timestamp,o=Math.min(e.timestamp+e.duration,this.endTime),s=Math.floor(a*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let r=t-this.bufferStartFrame;n(r<this.bufferSizeInFrames);let o=(t/this.targetSampleRate-a)*this.sourceSampleRate,s=Math.floor(o),c=Math.ceil(o),l=o-s;for(let t=0;t<this.targetNumberOfChannels;t++){let n=0,a=0;s>=0&&s<e.numberOfFrames&&(n=this.channelMixer(i,s,t)),c>=0&&c<e.numberOfFrames&&(a=this.channelMixer(i,c,t));let o=n+l*(a-n),u=r*this.targetNumberOfChannels+t;this.outputBuffer[u]+=o}this.maxWrittenFrame=this.maxWrittenFrame===null?r:Math.max(this.maxWrittenFrame,r)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new Ns({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n+this.timestampOffset,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}},vf=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw 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})()}},yf=class extends vf{constructor(e){if(super(),this._connectedTrack=null,!A.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${A.join(`, `)}.`);this._codec=e}},bf=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&t.type!==`key`)throw Error(`Cannot add non-key packets to a hasOnlyKeyPackets video track.`)},xf=class extends yf{constructor(e){super(e)}add(e,t){if(!(e instanceof F))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),bf(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Sf=class{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 Ae,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t,r){let i=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let a=this.encodingConfig,o=a.sizeChangeBehavior??`deny`,s=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(s=!0,o===`deny`))throw 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(a.transform?.width!==void 0||a.transform?.height!==void 0||a.transform?.rotate!==void 0||a.transform?.crop!==void 0||a.transform?.force===!0||s&&o!==`passThrough`){let r=a.transform?.width,i=a.transform?.height,c=a.transform?.fit??`fill`;s&&o!==`passThrough`&&(n(this.outputWidth),n(this.outputHeight),n(o!==`deny`),r=this.outputWidth,i=this.outputHeight,c=o);let l=await e.transform({width:r,height:i,roundDimensionsTo:2,crop:a.transform?.crop,rotate:a.transform?.rotate,fit:c,alpha:a.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=l.displayWidth,this.outputHeight=l.displayHeight),t&&e.close(),e=l,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let c=a.transform?.frameRate;if(c!==void 0){let n=e.timestamp+e.duration,a=xe(e.timestamp,c);if(this.frameRateLastSample!==null)if(a<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=n;return}else await this.padFrameRate(a,r);e===i&&(e=e.clone(),t=!0),e.setTimestamp(a),e.setDuration(1/c),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=a,this.frameRateLastEndTimestamp=n}await this.processAndEncode(e,r)}finally{t&&e.close()}}async processAndEncode(e,t){let r=this.encodingConfig,i;if(r.transform?.process){let t=r.transform.process(e);if(t instanceof Promise&&(t=await t),t===null)return;Array.isArray(t)||(t=[t]),i=t.map(t=>t instanceof ms?t:typeof VideoFrame<`u`&&t instanceof VideoFrame?new ms(t):new ms(t,{timestamp:e.timestamp,duration:e.duration}))}else i=[e];try{for(let e of i){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),n(this.encoderInitialized);let r=this.encodingConfig.keyFrameInterval??2,i=Math.floor(e.timestamp/r),a={...t,keyFrame:t?.keyFrame||r===0||i!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=i,this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n}else{n(this.encoder);let t=e.toVideoFrame(),r=w(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),i=r===-1?null:this.preciseTimings[r];if(i&&i.microsecondTimestamp===t.timestamp?(i.timestamp!==e.timestamp&&(i.timestampIsValid=!1),i.duration!==e.duration&&(i.durationIsValid=!1)):(this.preciseTimings.splice(r+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(t,a),t.close();else if(t.format&&!t.format.includes(`A`)||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(t,a),t.close();else{let e=t.displayWidth,n=t.displayHeight;this.splitter||=new wf(e,n);let{colorFrame:r,alphaFrame:i}=await this.splitter.update(t);this.alphaFrameQueue.push(i),this.encoder.encode(r,a),r.close()}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of i)t!==e&&t.close()}}async padFrameRate(e,t){let r=this.encodingConfig.transform.frameRate;n(this.frameRateLastSample);let i=Math.round((e-this.frameRateLastTimestamp)*r);for(let e=1;e<i;e++){let n=this.frameRateLastSample.clone();n.setTimestamp(this.frameRateLastTimestamp+e/r),n.setDuration(1/r),await this.processAndEncode(n,t),n.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=Ks({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let r=yc.find(e=>e.supports(this.encodingConfig.codec,t));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof F))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);bf(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if(typeof VideoEncoder>`u`)throw Error(`VideoEncoder is not supported by this browser.`);if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.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.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??`no-preference`}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let e=[],r=[],i=0,a=0,o=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=F.fromEncodedChunk(e,r),a=w(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),o=a===-1?null:this.preciseTimings[a],s=null;this.emittedEncoderPackets===0&&i.type===`delta`&&n?.decoderConfig&&(s=er(this.encodingConfig.codec,n.decoderConfig,i.data)),(o&&o.microsecondTimestamp===e.timestamp||s!==null)&&(i=i.clone({timestamp:o?.timestampIsValid?o.timestamp:void 0,duration:o?.durationIsValid?o.duration:void 0,type:s??void 0})),bf(this.source._connectedTrack,i),this.encodingConfig.onEncodedPacket?.(i,n),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.error??=e}),this.emittedEncoderPackets++},s=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(t,s)=>{if(!this.alphaEncoder){o(t,null,s);return}let c=this.alphaFrameQueue.shift();n(c!==void 0),c?(this.alphaEncoder.encode(c,{keyFrame:t.type===`key`}),a++,c.close(),e.push({chunk:t,meta:s})):a===0?o(t,null,s):(r.push(i+a),e.push({chunk:t,meta:s}))},error:e=>{e.stack=s,this.error??=e}}),this.encoder.configure(t),this.encodingConfig.alpha===`keep`){let s=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(t,s)=>{a--;let c=e.shift();for(n(c!==void 0),o(c.chunk,t,c.meta),i++;r.length>0&&r[0]===i;){r.shift();let t=e.shift();n(t!==void 0),o(t.chunk,null,t.meta)}},error:e=>{e.stack=s,this.error??=e}}),this.alphaEncoder.configure(t)}}n(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){let e=this.encodingConfig.transform.frameRate,t=xe(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},Cf=!1,wf=class e{constructor(t,n){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;let r=typeof OffscreenCanvas<`u`||typeof document<`u`&&typeof document.createElement==`function`;if(!e.forceCpu&&r&&!Cf)try{typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(t,n):(this.canvas=document.createElement(`canvas`),this.canvas.width=t,this.canvas.height=n);let e=this.canvas.getContext(`webgl2`,{alpha:!0});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,`u_resolution`),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,`u_sourceTexture`),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,`u_sourceTexture`),0)}catch(e){this.gl=null,this.canvas=null,Cf=!0,console.warn(`Falling back to CPU for color/alpha splitting.`,e)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){n(this.gl),n(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);let t=this.runColorProgram(e),r=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:r}}createVertexShader(){return n(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
31
+ in vec2 a_position;
32
+ in vec2 a_texCoord;
33
+ out vec2 v_texCoord;
34
+
35
+ void main() {
36
+ gl_Position = vec4(a_position, 0.0, 1.0);
37
+ v_texCoord = a_texCoord;
38
+ }
39
+ `)}createColorProgram(){n(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
40
+ precision highp float;
41
+
42
+ uniform sampler2D u_sourceTexture;
43
+ in vec2 v_texCoord;
44
+ out vec4 fragColor;
45
+
46
+ void main() {
47
+ vec4 source = texture(u_sourceTexture, v_texCoord);
48
+ fragColor = vec4(source.rgb, 1.0);
49
+ }
50
+ `),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createAlphaProgram(){n(this.gl);let e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
51
+ precision highp float;
52
+
53
+ uniform sampler2D u_sourceTexture;
54
+ uniform vec2 u_resolution; // The width and height of the canvas
55
+ in vec2 v_texCoord;
56
+ out vec4 fragColor;
57
+
58
+ // This function determines the value for a single byte in the YUV stream
59
+ float getByteValue(float byteOffset) {
60
+ float width = u_resolution.x;
61
+ float height = u_resolution.y;
62
+
63
+ float yPlaneSize = width * height;
64
+
65
+ if (byteOffset < yPlaneSize) {
66
+ // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
67
+ float y = floor(byteOffset / width);
68
+ float x = mod(byteOffset, width);
69
+
70
+ // Add 0.5 to sample the center of the texel
71
+ vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
72
+
73
+ // The luma value is the alpha from the source texture
74
+ return texture(u_sourceTexture, sampleCoord).a;
75
+ } else {
76
+ // Write a fixed value for chroma and beyond
77
+ return 128.0 / 255.0;
78
+ }
79
+ }
80
+
81
+ void main() {
82
+ // Each fragment writes 4 bytes (R, G, B, A)
83
+ float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
84
+ float baseByteOffset = pixelIndex * 4.0;
85
+
86
+ vec4 result;
87
+ for (int i = 0; i < 4; i++) {
88
+ float currentByteOffset = baseByteOffset + float(i);
89
+ result[i] = getByteValue(currentByteOffset);
90
+ }
91
+
92
+ fragColor = result;
93
+ }
94
+ `),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){n(this.gl);let r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS)||console.error(`Shader compile error:`,this.gl.getShaderInfoLog(r)),r}createVAO(){n(this.gl),n(this.colorProgram);let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let i=this.gl.getAttribLocation(this.colorProgram,`a_position`),a=this.gl.getAttribLocation(this.colorProgram,`a_texCoord`);return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){n(this.gl);let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}runColorProgram(e){return n(this.gl),n(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:`discard`})}runAlphaProgram(e){n(this.gl),n(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:t,height:r}=this.canvas,i=Math.ceil(t/2)*Math.ceil(r/2),a=t*r+i*2,o=Math.ceil(a/(t*4)),s=new Uint8Array(4*t*o);this.gl.readPixels(0,0,t,o,this.gl.RGBA,this.gl.UNSIGNED_BYTE,s),s=s.subarray(0,a),n(s[t*r]===128),n(s[s.length-1]===128);let c={format:`I420`,codedWidth:t,codedHeight:r,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[s.buffer]};return new VideoFrame(s,c)}updateCpu(e){if(!this.worker){let e=new Blob([`(${Tf.toString()})()`],{type:`application/javascript`}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.addEventListener(`message`,e=>{let t=e.data,n=this.pendingRequests.get(t.id);n&&(this.pendingRequests.delete(t.id),`error`in t?n.reject(Error(t.error)):n.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener(`error`,e=>{let t=Error(e.message||`Color/alpha splitter worker error.`);for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,n=T();return this.pendingRequests.set(t,n),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),n.promise}close(){this.gl?.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;let e=Error(`Color/alpha splitter closed.`);for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};wf.forceCpu=!0;var Tf=()=>{let e=null,t=Promise.resolve();self.addEventListener(`message`,e=>{let{id:r,sourceFrame:i}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await n(i);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{i.close()}})});let n=async t=>{let n=t.format;if(!n)throw Error(`CPU color/alpha splitting requires a known VideoFrame format.`);let a=t.codedWidth,o=t.codedHeight,s=t.allocationSize();if((!e||e.byteLength!==s)&&(e=new Uint8Array(s)),await t.copyTo(e),n===`RGBA`||n===`BGRA`)return r(e,a,o,n,t);if(n===`I420A`||n===`I420AP10`||n===`I420AP12`||n===`I422A`||n===`I422AP10`||n===`I422AP12`||n===`I444A`||n===`I444AP10`||n===`I444AP12`)return i(e,a,o,n,t);throw Error(`CPU color/alpha splitting does not support format '${n}'.`)},r=(e,t,n,r,i)=>{let a=t*n,o=a+Math.ceil(t/2)*Math.ceil(n/2)*2,s=new Uint8Array(o);for(let t=0,n=3;t<a;t++,n+=4)s[t]=e[n];s.fill(128,a);let c=new VideoFrame(e,{format:r===`RGBA`?`RGBX`:`BGRX`,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),l={format:`I420`,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[s.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(s,l)}},i=(e,t,n,r,i)=>{let a=r.includes(`P10`),o=r.includes(`P12`),s=a||o?2:1,c,l;r.startsWith(`I420`)?(c=Math.ceil(t/2),l=Math.ceil(n/2)):r.startsWith(`I422`)?(c=Math.ceil(t/2),l=n):(c=t,l=n);let u=t*n,d=c*l,f=u*s,p=d*s,m=u*s,h=f+p*2,g=r.replace(`A`,``),_=Math.ceil(t/2)*Math.ceil(n/2),v=m+_*s*2,y=new Uint8Array(v),b=h;y.set(e.subarray(b,b+m),0);let x=m,S=a?512:o?2048:128;s===1?y.fill(S,x):new Uint16Array(y.buffer,x,2*_).fill(S);let C=a?`I420P10`:o?`I420P12`:`I420`,ee=new VideoFrame(e.subarray(0,h),{format:g,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),te={format:C,codedWidth:t,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[y.buffer]};return{colorFrame:ee,alphaFrame:new VideoFrame(y,te)}}},Ef=class extends yf{constructor(e){Ws(e),super(e.codec),this._encoder=new Sf(this,e)}add(e,t){if(!(e instanceof ms))throw TypeError(`videoSample must be a VideoSample.`);return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Df=class extends yf{constructor(e,t){if(!(typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas))throw TypeError(`canvas must be an HTMLCanvasElement or OffscreenCanvas.`);Ws(t),super(t.codec),this._encoder=new Sf(this,t),this._canvas=e}add(e,t=0,n){if(!Number.isFinite(e)||e<0)throw TypeError(`timestamp must be a non-negative number.`);if(!Number.isFinite(t)||t<0)throw TypeError(`duration must be a non-negative number.`);let r=new ms(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,n)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Of=class extends yf{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!==`video`)throw TypeError(`track must be a video MediaStreamTrack.`);if(Ws(t),typeof n!=`object`||!n)throw TypeError(`options must be an object.`);if(n.frameRate!=null&&(typeof n.frameRate!=`number`||n.frameRate<=0))throw TypeError(`options.frameRate, when provided, must be either a positive number or null.`);if(n.timestampBase!==void 0&&n.timestampBase!==`synced-zero`&&n.timestampBase!==`zero`&&n.timestampBase!==`unix`)throw TypeError(`options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.`);t={...t,latencyMode:`realtime`},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=T(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=n,this._encoder=new Sf(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=this._options.frameRate===void 0?this._track.getSettings().frameRate??null:this._options.frameRate;this._abortController=new AbortController;let t=null,r=null,i=0,a=!1,o=null,s=0,c=()=>{if(n(e!==null),!this._lastVideoFrame)return;n(r!==null),n(t!==null);let a=performance.now();for(;a-r>1e3/e;){r+=1e3/e;let n=t+i/e,o=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*n,duration:1e6/e});u(o,a)}};e!==null&&(this._timerHandle=ot(c,4));let l=t=>{if(e===null)u(t);else{let e=performance.now();this._lastVideoFrame?(c(),this._lastVideoFrame?.close(),this._lastVideoFrame=t):(u(t.clone(),e),r=e,this._lastVideoFrame=t)}},u=(e,n=performance.now())=>{if(a){e.close();return}i++;let r=e.timestamp/1e6;if(this._paused){if(t!==null){if(o!==null&&this._options.timestampBase!==`unix`){let e=r-o;s-=e}o=r}e.close();return}if(t===null){t=r;let e,i=this._options.timestampBase??`synced-zero`;if(i===`unix`)e=Date.now()/1e3;else if(i===`zero`)e=0;else{let t=this._connectedTrack.output;t._firstMediaStreamTimestamp===null?(t._firstMediaStreamTimestamp=n/1e3,e=0):e=n/1e3-t._firstMediaStreamTimestamp}s=e-t}if(o=r,this._encoder.getQueueSize()>=8){e.close();return}let c=new ms(e,{timestamp:r+s});this._encoder.add(c,!0).catch(e=>{a=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._workerTrackId!==null&&Vf({type:`stopTrack`,trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<`u`){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:l});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||this._promiseWithResolvers.reject(e)})}else if(await Bf())this._workerTrackId=If++,Vf({type:`videoTrack`,trackId:this._workerTrackId,track:this._track}),this._workerListener=e=>{let t=e.data;t.type===`videoFrame`&&t.trackId===this._workerTrackId?l(t.videoFrame):t.type===`error`&&t.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(t.error)},Lf.addEventListener(`message`,this._workerListener);else if(e!==null){let e=document.createElement(`video`);e.style.position=`fixed`,e.style.left=`-10000px`,e.style.top=`-10000px`,e.style.width=`1px`,e.style.height=`1px`,e.style.opacity=`0`,e.style.pointerEvents=`none`,e.muted=!0,e.srcObject=new MediaStream([this._track]),document.body.appendChild(e),this._videoElement=e,e.addEventListener(`loadeddata`,()=>{if(a||!this._videoElement)return;let t=new VideoFrame(e,{timestamp:1e3*performance.now()});l(t),t.close()},{once:!0}),e.play().catch(e=>{a=!0,this._promiseWithResolvers.reject(e)})}else throw Error(`When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not supported by this browser.`)}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&=(this._abortController.abort(),null),this._timerHandle&&st(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&=(this._videoElement.srcObject=null,this._videoElement.remove(),null),this._workerTrackId!==null&&(n(this._workerListener),Vf({type:`stopTrack`,trackId:this._workerTrackId}),await new Promise(e=>{let t=r=>{let i=r.data;i.type===`trackStopped`&&i.trackId===this._workerTrackId&&(n(this._workerListener),Lf.removeEventListener(`message`,this._workerListener),Lf.removeEventListener(`message`,t),e())};Lf.addEventListener(`message`,t)})),await this._encoder.flushAndClose(e)}},kf=class extends vf{constructor(e){if(super(),this._connectedTrack=null,!M.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${M.join(`, `)}.`);this._codec=e}},Af=class extends kf{constructor(e){super(e)}add(e,t){if(!(e instanceof F))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},jf=class{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 Ae,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve()}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 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;let n=this.encodingConfig;n.transform?.numberOfChannels!==void 0||n.transform?.sampleRate!==void 0?(this.resampler||=new _f({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,startTime:e.timestamp,endTime:1/0,onSample:async e=>{await this.processAndEncode(e,!0)}}),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let n=this.encodingConfig;if(n.transform?.sampleFormat!==void 0&&zs(e.format)!==n.transform.sampleFormat){let r=Vs(e,n.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(n.transform?.process){let r=n.transform.process(e);if(r instanceof Promise&&(r=await r),r===null)return;Array.isArray(r)||(r=[r]);for(let e of r){if(!(e instanceof Ns))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);await this.encodeSample(e,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),n(this.encoderInitialized);{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new Ns({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(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{n(this.encoder);let r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){n(this.outputSampleSize),n(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:i,sampleRate:a,timestamp:o}=e,s=2048,c=[];for(let t=0;t<i;t+=s){let n=Math.min(s,e.numberOfFrames-t),i=n*r*this.outputSampleSize,a=new ArrayBuffer(i),o=new DataView(a);c.push({frameCount:n,view:o})}let l=e.allocationSize({planeIndex:0,format:`f32-planar`}),u=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<r;t++){e.copyTo(u,{planeIndex:t,format:`f32-planar`});for(let e=0;e<c.length;e++){let{frameCount:n,view:i}=c[e];for(let a=0;a<n;a++)this.writeOutputValue(i,(a*r+t)*this.outputSampleSize,u[e*s+a])}}t&&e.close();let d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:a}};for(let e=0;e<c.length;e++){let{frameCount:t,view:n}=c[e],r=n.buffer,i=e*s,l=new F(new Uint8Array(r),`key`,o+i/a,t/a);this.encodingConfig.onEncodedPacket?.(l,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:r}=e,a=Ys({numberOfChannels:t,sampleRate:r,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(a);let o=bc.find(e=>e.supports(this.encodingConfig.codec,a));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof F))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else if(j.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(`AudioEncoder is not supported by this browser.`);if(!(await AudioEncoder.isConfigSupported(a)).supported)throw Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let e=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||St(l(t.decoderConfig.description)).objectType===0,e){let e=Number(i(a.codec.split(`.`)));t.decoderConfig.description=Ct({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let n=F.fromEncodedChunk(e);n=n.clone({timestamp:ye(n.timestamp,a.sampleRate),duration:e.duration==null?void 0:ye(n.duration,a.sampleRate)}),this.encodingConfig.onEncodedPacket?.(n,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.error??=e})},error:t=>{t.stack=e,this.error??=t}}),this.encoder.configure(a)}n(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:i}=Ut(e);switch(this.outputSampleSize=r,r){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,D((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,D(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=D(Math.floor(n*32767),-32768,32767);e.setUint8(t,Cc(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=D(Math.floor(n*32767),-32768,32767);e.setUint8(t,Tc(r))}:n(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,D((n+1)*32767.5,0,65535),i):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,D(Math.round(n*32767),-32768,32767),i):n(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>pe(e,t,D((n+1)*8388607.5,0,16777215),i):t===`signed`?this.writeOutputValue=(e,t,n)=>me(e,t,D(Math.round(n*8388607),-8388608,8388607),i):n(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,D((n+1)*2147483647.5,0,4294967295),i):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,D(Math.round(n*2147483647),-2147483648,2147483647),i):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,i):n(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,i):n(!1);break;default:E(r),n(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),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.error)throw this.error}},Mf=class extends kf{constructor(e){qs(e),super(e.codec),this._encoder=new jf(this,e)}add(e){if(!(e instanceof Ns))throw TypeError(`audioSample must be an AudioSample.`);return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Nf=class extends kf{constructor(e){qs(e),super(e.codec),this._accumulatedTime=0,this._encoder=new jf(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let t=Ns._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(let e of t)await this._encoder.add(e,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Pf=class extends kf{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,n={}){if(!(e instanceof MediaStreamTrack)||e.kind!==`audio`)throw TypeError(`track must be an audio MediaStreamTrack.`);if(qs(t),typeof n!=`object`||!n)throw TypeError(`options must be an object.`);if(n.timestampBase!==void 0&&n.timestampBase!==`synced-zero`&&n.timestampBase!==`zero`&&n.timestampBase!==`unix`)throw TypeError(`options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.`);super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=T(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=n,this._encoder=new jf(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,n=null,r=0,i=i=>{if(t){i.close();return}let a=i.timestamp;if(this._paused){if(e!==null){if(n!==null&&this._options.timestampBase!==`unix`){let e=a-n;r-=e}n=a}i.close();return}if(e===null){e=i.timestamp;let t,n=this._options.timestampBase??`synced-zero`;if(n===`unix`)t=Date.now()/1e3;else if(n===`zero`)t=0;else{let e=this._connectedTrack.output;e._firstMediaStreamTimestamp===null?(e._firstMediaStreamTimestamp=performance.now()/1e3,t=0):t=performance.now()/1e3-e._firstMediaStreamTimestamp}r=t-e}if(n=a,this._encoder.getQueueSize()>=8){i.close();return}i.setTimestamp(a+r),this._encoder.add(i,!0).catch(e=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<`u`){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:e=>i(new Ns(e))});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&e.name===`AbortError`||this._promiseWithResolvers.reject(e)})}else{let e=window.AudioContext||window.webkitAudioContext;this._audioContext=new e({sampleRate:this._track.getSettings().sampleRate});let t=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state===`suspended`&&await this._audioContext.resume(),t.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let n=0;this._scriptProcessorNode.onaudioprocess=e=>{let t=Ns._fromAudioBuffer(e.inputBuffer,n);n+=e.inputBuffer.duration;for(let e of t)i(e)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&=(this._abortController.abort(),null),this._audioContext&&(n(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}},Ff=()=>{let e=(e,t)=>{t?self.postMessage(e,{transfer:t}):self.postMessage(e)};e({type:`support`,supported:typeof MediaStreamTrackProcessor<`u`});let t=new Map,n=new Map;self.addEventListener(`message`,r=>{let i=r.data;switch(i.type){case`videoTrack`:{n.set(i.trackId,i.track);let r=new MediaStreamTrackProcessor({track:i.track}),a=new WritableStream({write:t=>{if(!n.has(i.trackId)){t.close();return}e({type:`videoFrame`,trackId:i.trackId,videoFrame:t},[t])}}),o=new AbortController;t.set(i.trackId,o),r.readable.pipeTo(a,{signal:o.signal}).catch(t=>{t instanceof DOMException&&t.name===`AbortError`||e({type:`error`,trackId:i.trackId,error:t})})}break;case`stopTrack`:{let r=t.get(i.trackId);r&&(r.abort(),t.delete(i.trackId)),n.get(i.trackId)?.stop(),n.delete(i.trackId),e({type:`trackStopped`,trackId:i.trackId})}break;default:E(i)}})},If=0,Lf=null,Rf=()=>{let e=new Blob([`(${Ff.toString()})()`],{type:`application/javascript`}),t=URL.createObjectURL(e);Lf=new Worker(t)},zf=null,Bf=async()=>zf===null?(Lf||Rf(),new Promise(e=>{n(Lf);let t=n=>{let r=n.data;r.type===`support`&&(zf=r.supported,Lf.removeEventListener(`message`,t),e(r.supported))};Lf.addEventListener(`message`,t)})):zf,Vf=(e,t)=>{n(Lf),t?Lf.postMessage(e,t):Lf.postMessage(e)},Hf=class extends vf{constructor(e){if(super(),this._connectedTrack=null,!Dt.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Dt.join(`, `)}.`);this._codec=e}},Uf=class extends Hf{constructor(e){super(e),this._error=null,this._lastMuxerPromise=Promise.resolve(),this._parser=new Ll({codec:e,output:(e,t)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,e,t).catch(e=>{this._error??=e})}})}add(e){if(typeof e!=`string`)throw TypeError(`text must be a string.`);return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose(e){e||this._checkForError()}},Wf=class extends Ol{constructor(e,t){if(!(e._target instanceof zd))throw TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=t._options.getPlaylistPath??(({n:e})=>`playlist-${e}.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(e=>e.isSingleFile?`segments-${e.playlist.n}${e.format.fileExtension}`:`segment-${e.playlist.n}-${e.n}${e.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(e=>`init-${e.n}${e.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),t=this.output._tracks.some(e=>e.metadata.isRelativeToUnixEpoch),r=this.output._tracks.some(e=>!e.metadata.isRelativeToUnixEpoch);if(t&&r)throw Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;let i=new Map,a=[],o=!1,s=!1,c=!1;for(let e of this.output._tracks){e.type===`video`&&(o=!0);let t=new Map;for(let n of this.output._tracks){if(e===n||!e.canBePairedWith(n))continue;if(e.type===n.type){s||=(console.warn(`Illegal pairing of two ${e.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),!0);continue}if(e.isVideoTrack()&&e.metadata.hasOnlyKeyPackets||n.isVideoTrack()&&n.metadata.hasOnlyKeyPackets){c||=(console.warn(`A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired.`),!0);continue}let r=t.get(n.source._codec);r||t.set(n.source._codec,r=[]),r.push(n)}for(let[,n]of t){let t=n.map(e=>e.id).join(`-`);a.find(e=>e.key===t)||a.push({name:n[0].type+`-`+(a.length+1),key:t,tracks:n,needsEmit:!1,firstNoUri:!1});let r=i.get(e);r||i.set(e,r=[]),r.push(t)}}let l=o?`video`:`audio`,u=[],d=[],f=[];for(let e of this.output._tracks){let t=i.get(e);if(t){if(n(t.length>0),e.type!==l)continue;for(let r of t){let o=a.find(e=>e.key===r);if(n(o),t.length===1&&o.tracks.length===1){let t=i.get(o.tracks[0]);if(n(t!==void 0),t.length===1){let r=a.find(e=>e.key===t[0]);if(r.tracks.length===1){n(r.tracks[0]===e),u.push({tracks:[e,o.tracks[0]],linkedGroup:null});continue}}}u.push({tracks:[e],linkedGroup:o}),o.needsEmit=!0}}else e.type===`video`?d.push(e):e.type===`audio`&&f.push(e)}let p=({metadata:e})=>{let t=``;return t+=`${e.languageCode??`und`}-`,t+=`${e.name??``}-`,t+=`${e.disposition?.default??!0}-`,t+=`${e.disposition?.primary??!1}-`,t+=`${e.disposition?.forced??!1}-`,t};if(d.length>0)if(new Set(d.map(p)).size>1){let e={key:d.map(e=>e.id).join(`-`),name:`video-`+(a.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};a.push(e),u.push({tracks:[d[0]],linkedGroup:e})}else for(let e of d)u.push({tracks:[e],linkedGroup:null});if(f.length>0)if(new Set(f.map(p)).size>1){let e={key:f.map(e=>e.id).join(`-`),name:`audio-`+(a.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};a.push(e),u.push({tracks:[f[0]],linkedGroup:e})}else for(let e of f)u.push({tracks:[e],linkedGroup:null});let m=e=>{let t=[],r=0,i=0,a=!1,o=null,s=-1/0;for(let n of e)n.isVideoTrack()?(r++,a||=(n.metadata.rotation??0)!==0):n.isAudioTrack()&&i++,t.push(n.source._codec);for(let e of lt(this.format._options.segmentFormat)){let n=e.getSupportedCodecs(),c=e.getSupportedTrackCounts();if(t.some(e=>!n.includes(e))||r<c.video.min||r>c.video.max||i<c.audio.min||i>c.audio.max)continue;let l=0;a&&e.supportsVideoRotationMetadata&&l++,l>s&&(o=e,s=l)}return n(o),o},h=async e=>{if(e.some(e=>this.playlists.some(t=>t.tracks.includes(e))))throw Error(`Internal error: track is already registered in a playlist.`);let t=m(e),n=this.playlists.length+1,r=await this.getPlaylistPath({n,tracks:e,segmentFormat:t});Gf(r);let i={id:this.playlists.length+1,path:r,tracks:e,segmentFormat:t,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new C};return this.playlists.push(i),i};for(let e of a)if(e.needsEmit)for(let t=0;t<e.tracks.length;t++){let n=e.tracks[t],r=this.playlists.find(e=>e.tracks[0].id===n.id);r??=await h([n]),this.playlistDeclarations.push({playlist:r,groupId:e.name,noUri:e.firstNoUri&&t===0,references:[]})}for(let e of u){let t=this.playlists.find(t=>t.tracks[0].id===e.tracks[0].id);t??=await h(e.tracks),this.playlistDeclarations.push({playlist:t,groupId:null,noUri:!1,references:e.linkedGroup?this.playlistDeclarations.filter(t=>t.groupId===e.linkedGroup.name):[]})}e()}async getMimeType(){return Ta}allTracksAreKnown(e){for(let t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async onTrackClose(e){let t=this.trackDatas.find(t=>t.track===e);t&&(t.closed=!0);let r=this.playlists.find(t=>t.tracks.includes(e));n(r);let i=await r.mutex.acquire();try{await this.advancePlaylist(r)}finally{i()}}getVideoTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;Qt(t),n(t),n(t?.decoderConfig);let i=this.playlists.filter(t=>t.tracks.includes(e));return n(i.length===1),r={track:e,packets:[],playlist:i[0],closed:!1,info:{type:`video`,decoderConfig:t.decoderConfig}},this.trackDatas.push(r),r}getAudioTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;en(t),n(t),n(t?.decoderConfig);let i=this.playlists.filter(t=>t.tracks.includes(e));return n(i.length===1),r={track:e,packets:[],playlist:i[0],closed:!1,info:{type:`audio`,decoderConfig:t.decoderConfig}},this.trackDatas.push(r),r}async addEncodedVideoPacket(e,t,n){let r=this.getVideoTrackData(e,n),i=r.playlist,a=await i.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type===`key`),r.packets.push(t),i.currentSegmentStartTimestamp===null?i.currentSegmentStartTimestamp=t.timestamp:i.currentSegmentStartTimestampIsFixed||(i.currentSegmentStartTimestamp=Math.min(i.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(i)}finally{a()}}async addEncodedAudioPacket(e,t,n){let r=this.getAudioTrackData(e,n),i=r.playlist,a=await i.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type===`key`),r.packets.push(t),i.currentSegmentStartTimestamp===null?i.currentSegmentStartTimestamp=t.timestamp:i.currentSegmentStartTimestampIsFixed||(i.currentSegmentStartTimestamp=Math.min(i.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(i)}finally{a()}}async addSubtitleCue(e,t,n){throw Error(`Unreachable.`)}async advancePlaylist(e){if(n(!e.done),!this.allTracksAreKnown(e))return;if(e.currentSegmentStartTimestamp===null){await this.onPlaylistDone(e);return}let t=this.trackDatas.filter(t=>e.tracks.includes(t.track)),r=t.find(e=>e.info.type===`video`),i=t.find(e=>e.info.type===`audio`);for(;;){let a=e.currentSegmentStartTimestamp+this.targetSegmentDuration,o=0,s=0;if(r&&(!r.closed||r.packets.length>0)){let e=r.packets.every(e=>e.timestamp<a),t=null,c=null;if(e){if(!r.closed)return}else for(let e=0;e<r.packets.length;e++){let n=r.packets[e];if(t!==null&&n.timestamp>a)break;e>0&&n.type===`key`&&(t=n,c=e)}if(c!==null){if(o=c,i){let e=i.packets.findIndex(e=>e.timestamp>=t.timestamp);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}}else{if(!r.closed)return;o=r.packets.length;let e=Xe(r.packets,e=>e.timestamp),t=r.packets[e];if(n(t),i)if(t.timestamp<a){let e=i.packets.findIndex(e=>e.timestamp>=a);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}else{let e=i.packets.findIndex(e=>e.timestamp>t.timestamp);if(e!==-1)s=e;else if(i.closed)s=i.packets.length;else return}}}else if(i&&(!i.closed||i.packets.length>0))if(i.packets.every(e=>e.timestamp<a))if(i.closed)s=i.packets.length;else return;else{let e=ce(i.packets,e=>e.timestamp<=a);s=Math.max(e,1)}if(o===0&&s===0){t.every(e=>e.closed)&&await this.onPlaylistDone(e);return}let c=null,l,u;n(this.output._target instanceof zd);let d=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){let t={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Jf(e)};l=await this.getSegmentPath(t),Kf(l),u=O(O(d.rootPath,e.path),l);let n=await this.output._getTarget({path:u,isRoot:!1,mimeType:e.segmentFormat.mimeType});n._start(),e.singleFile={target:n,path:l,nextOffset:0,info:t}}else l=e.singleFile.path,u=O(O(d.rootPath,e.path),l);else c={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Jf(e)},l=await this.getSegmentPath(c),Kf(l),u=O(O(d.rootPath,e.path),l),e.nextSegmentId++;let f=0,p=null,m=new gp({format:e.segmentFormat,target:new zd(u,async t=>{let n={...t,isRoot:!1};if(t.isRoot)if(e.singleFile){let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on(`write`,({end:e})=>f=Math.max(f,e)),t}else{let e=await this.output._getTarget(n);return p=e,e.on(`write`,({end:e})=>f=Math.max(f,e)),e}return this.output._getTarget(n)}),initTarget:async()=>{if(e.initSegment)return new Ld;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on(`write`,({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),t.on(`finalized`,()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),t}{let t=Jf(e),n=await this.getInitPath(t);qf(n),e.initSegment={path:n,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let r=O(O(d.rootPath,e.path),n),i=await this.output._getTarget({path:r,isRoot:!1,mimeType:e.segmentFormat.mimeType});return i.on(`write`,({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),i.on(`finalized`,()=>{this.format._options.onInit?.(i,t)}),i}}}),h=-1/0;try{let e=null,t=null;if(r&&(e=new xf(r.track.source._codec),m.addVideoTrack(e,r.track.metadata)),i&&(t=new Af(i.track.source._codec),m.addAudioTrack(t,i.track.metadata)),await m.start(),r){n(e);let t={decoderConfig:r.info.decoderConfig};for(let n=0;n<o;n++){let i=r.packets[n];await e.add(i,t),h=Math.max(h,i.timestamp+i.duration)}}if(i){n(t);let e={decoderConfig:i.info.decoderConfig};for(let n=0;n<s;n++){let r=i.packets[n];await t.add(r,e),h=Math.max(h,r.timestamp+r.duration)}}await m.finalize()}catch(e){throw await m.cancel(),e}c&&(n(p),this.format._options.onSegment?.(p,c)),o>0&&(n(r),r.packets.splice(0,o)),s>0&&(n(i),i.packets.splice(0,s));let g=1/0;r&&r.packets.length>0&&(g=r.packets[0].timestamp),i&&i.packets.length>0&&(g=Math.min(g,i.packets[0].timestamp));let _=g<1/0?g:h;n(Number.isFinite(_));let v=_-e.currentSegmentStartTimestamp;if(n(v>=0),e.writtenSegments.push({path:l,duration:v,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:c??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,v),e.currentSegmentStartTimestamp=_,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let t=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(n(t.info),this.format._options.onSegmentPopped?.(t.path,t.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){n(!e.done),e.done=!0,e.singleFile&&(await e.singleFile.target._flush(),await e.singleFile.target._finalize(),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let t=e.writtenSegments,n=0,r=0,i=0;for(let e=0;e<t.length;e++){i+=t[e].duration;let r=0,a=0;for(let i=e;i<t.length&&(r+=t[i].byteSize,a+=t[i].duration,a>=.5*this.globalTargetDuration&&a<=1.5*this.globalTargetDuration&&(n=Math.max(n,8*r/a)),!(a>1.5*this.globalTargetDuration));i++);}if(n===0)for(let e of t){let t=e.duration||1;n=Math.max(n,8*e.byteSize/t)}for(let e of t)r+=8*e.byteSize;e.peakBitrate=n,e.averageBitrate=r/(i||1)}async writePlaylist(e){n(this.output._target instanceof zd);let t=this.output._target;this.updatePlaylistBitrates(e);let r=!1;for(let t of e.writtenSegments)r||=t.byteOffset!==null;let i=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,a=3;(i||r)&&(a=4),e.initSegment&&(a=5),e.initSegment&&!i&&(a=6);let o=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,s=O(t.rootPath,e.path),c=`#EXTM3U
95
+ #EXT-X-VERSION:${a}\n`+(this.isLive?``:`#EXT-X-PLAYLIST-TYPE:VOD
96
+ `)+`#EXT-X-TARGETDURATION:${Math.ceil(o)}\n`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}\n`:``)+`#EXT-X-INDEPENDENT-SEGMENTS
97
+ `+(i?`#EXT-X-I-FRAMES-ONLY
98
+ `:``)+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset===null?``:`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`)+`
99
+ `:``)+`
100
+ `+e.writtenSegments.map(e=>`#EXTINF:${+e.duration.toFixed(12)},\n`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*e.timestamp).toISOString()}\n`:``)+(e.byteOffset===null?``:`#EXT-X-BYTERANGE:${e.byteSize}@${e.byteOffset}\n`)+`${e.path}\n`).join(``)+(e.done?(e.writtenSegments.length>0?`
101
+ `:``)+`#EXT-X-ENDLIST
102
+ `:``);this.format._options.onPlaylist?.(c,Jf(e));let l=new Ed(await this.output._getTarget({path:s,isRoot:!1,mimeType:Ta}),!0);l.start(),l.write(f.encode(c)),await l.flush(),await l.finalize()}async writeMasterPlaylist(){n(this.output._target instanceof zd);let e=this.output._target,t=`#EXTM3U
103
+ `,r=!1,i=null,a=0,o=!1;for(let e of this.playlistDeclarations)if(e.groupId===null){let i=e.playlist.tracks[0].isVideoTrack()&&e.playlist.tracks[0].metadata.hasOnlyKeyPackets,a=[];for(let t of e.playlist.tracks){let e=this.trackDatas.find(e=>e.track===t)?.info.decoderConfig.codec??t.source._codec;a.push(e)}let o=0,s=0;if(e.references.length>0){let t=e.references[0].playlist.tracks[0],r=this.trackDatas.find(e=>e.track===t)?.info.decoderConfig.codec??t.source._codec;a.push(r);for(let t of e.references)n(t.playlist.peakBitrate!==null),o=Math.max(o,t.playlist.peakBitrate),s=Math.max(s,t.playlist.averageBitrate??0)}n(e.playlist.peakBitrate!==null);let c=e.playlist.peakBitrate+o,l=(e.playlist.averageBitrate??0)+s;r||=(t+=`
104
+ `,!0),t+=i?`#EXT-X-I-FRAME-STREAM-INF:`:`#EXT-X-STREAM-INF:`,t+=`BANDWIDTH=${Math.ceil(c)}`,l>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(l)}`),t+=`,CODECS="${a.join(`,`)}"`;let u=e.playlist.tracks.find(e=>e.isVideoTrack());if(u?.isVideoTrack()){let e=this.trackDatas.find(e=>e.track===u)?.info.decoderConfig;if(e){let n=e.displayAspectWidth??e.codedWidth,r=e.displayAspectHeight??e.codedHeight;n!==void 0&&r!==void 0&&(u.metadata.rotation!==void 0&&u.metadata.rotation%180==90&&([n,r]=[r,n]),t+=`,RESOLUTION=${n}x${r}`)}!i&&u.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+u.metadata.frameRate.toFixed(3)}`)}if(!i){let r=new Map;for(let t of e.references){n(t.groupId!==null);let e=t.playlist.tracks[0].type;r.set(e,t.groupId)}for(let[e,n]of r)t+=`,${e.toUpperCase()}="${n}"`}i?(t+=`,URI="${e.playlist.path}"`,t+=`
105
+ `):(t+=`
106
+ `,t+=`${e.playlist.path}\n`)}else{n(e.playlist.tracks.length===1);let r=e.playlist.tracks[0],s=r.type,c=r.metadata.name??null,l=r.metadata.languageCode,u=r.metadata.disposition;(i===null||e.groupId!==i)&&(a=0,t+=`
107
+ `,o=!1),i=e.groupId,a++,t+=`#EXT-X-MEDIA:TYPE=${s.toUpperCase()},GROUP-ID="${e.groupId}"`,c!==null&&/[\n\r"]/.test(c)&&(console.warn(`Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes.`),c=null),c??=`${l??e.groupId}-${a}`,t+=`,NAME="${c}"`,l!==void 0&&(t+=`,LANGUAGE="${l}"`);let d=u?.primary??!1,f=u?.default??!0,p=u?.forced??!1;if(d&&!o&&(t+=`,DEFAULT=YES`,o=!0),(d||f)&&(t+=`,AUTOSELECT=YES`),p&&(t+=`,FORCED=YES`),s===`audio`){let e=this.trackDatas.find(e=>e.track===r)?.info.decoderConfig;e&&(t+=`,CHANNELS="${e.numberOfChannels}"`)}e.noUri||(t+=`,URI="${e.playlist.path}"`),t+=`
108
+ `}this.format._options.onMaster?.(t);let s=await this.mutex.acquire();try{let n;this.numWrittenMasterPlaylists===0?n=await this.output._getRootWriter(!0):(n=new Ed(await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:Ta}),!0),n.start()),n.write(f.encode(t)),await n.flush(),await n.finalize(),this.numWrittenMasterPlaylists++}finally{s()}}async tryWriteMasterPlaylist(){n(this.isLive);for(let e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(e=>e.mutex.acquire()))).forEach(e=>e());for(let e of this.trackDatas)e.closed=!0;await Promise.all(this.playlists.map(e=>e.done?Promise.resolve():this.advancePlaylist(e))),this.isLive||await this.writeMasterPlaylist()}},Gf=e=>{if(typeof e!=`string`)throw TypeError(`options.getPlaylistPath must return or resolve to a string`);if(/[\n\r"]/.test(e))throw TypeError(`Playlist paths cannot contain line feed, carriage return, or double quote characters.`)},Kf=e=>{if(typeof e!=`string`)throw TypeError(`options.getSegmentPath must return or resolve to a string`);if(/[\n\r"]/.test(e))throw TypeError(`Segment paths cannot contain line feed or carriage return characters.`)},qf=e=>{if(typeof e!=`string`)throw TypeError(`options.getInitPath must return or resolve to a string`);if(/[\n\r"]/.test(e))throw TypeError(`Init paths cannot contain line feed, carriage return, or double quote characters.`)},Jf=e=>({n:e.id,tracks:e.tracks,segmentFormat:e.segmentFormat}),Yf=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>A.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>M.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Dt.includes(e))}_codecUnsupportedHint(e){return``}},Xf=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:1,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new Ud(e,this)}},Zf=class extends Xf{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...A,...Et,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Dt]}_codecUnsupportedHint(e){return new $f().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},Qf=class extends Xf{constructor(e){super(e)}get _name(){return`CMAF`}get fileExtension(){return`.m4s`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...A,...Et,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...Dt]}},$f=class extends Xf{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...A,...M]}_codecUnsupportedHint(e){return new Zf().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},ep=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.appendOnly!==void 0&&typeof e.appendOnly!=`boolean`)throw TypeError(`options.appendOnly, when provided, must be a boolean.`);if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw TypeError(`options.minimumClusterDuration, when provided, must be a non-negative number.`);if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!=`function`)throw TypeError(`options.onEbmlHeader, when provided, must be a function.`);if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!=`function`)throw TypeError(`options.onHeader, when provided, must be a function.`);if(e.onCluster!==void 0&&typeof e.onCluster!=`function`)throw TypeError(`options.onCluster, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Xd(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:1,max:127}}}get fileExtension(){return`.mkv`}get mimeType(){return`video/x-matroska`}getSupportedCodecs(){return[...A,...Et,...j.filter(e=>![`pcm-s8`,`pcm-f32be`,`pcm-f64be`,`ulaw`,`alaw`].includes(e)),...Dt]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},tp=class extends ep{constructor(e){super(e)}getSupportedCodecs(){return[...A.filter(e=>[`vp8`,`vp9`,`av1`].includes(e)),...M.filter(e=>[`opus`,`vorbis`].includes(e)),...Dt]}get _name(){return`WebM`}get fileExtension(){return`.webm`}get mimeType(){return`video/webm`}_codecUnsupportedHint(e){return new ep().getSupportedCodecs().includes(e)?` Switching to MKV will grant support for this codec.`:``}},np=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.xingHeader!==void 0&&typeof e.xingHeader!=`boolean`)throw TypeError(`options.xingHeader, when provided, must be a boolean.`);if(e.onXingFrame!==void 0&&typeof e.onXingFrame!=`function`)throw TypeError(`options.onXingFrame, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Qd(e,this)}get _name(){return`MP3`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.mp3`}get mimeType(){return`audio/mpeg`}getSupportedCodecs(){return[`mp3`]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},rp=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.large!==void 0&&typeof e.large!=`boolean`)throw TypeError(`options.large, when provided, must be a boolean.`);if(e.metadataFormat!==void 0&&![`info`,`id3`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'info' or 'id3'.`);if(e.onHeader!==void 0&&typeof e.onHeader!=`function`)throw TypeError(`options.onHeader, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new gf(e,this)}get _name(){return`WAVE`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.wav`}get mimeType(){return`audio/wav`}getSupportedCodecs(){return[...j.filter(e=>[`pcm-s16`,`pcm-s24`,`pcm-s32`,`pcm-f32`,`pcm-u8`,`ulaw`,`alaw`].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},ip=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.maximumPageDuration!==void 0&&(!Number.isFinite(e.maximumPageDuration)||e.maximumPageDuration<=0))throw TypeError(`options.maximumPageDuration, when provided, must be a positive number.`);if(e.onPage!==void 0&&typeof e.onPage!=`function`)throw TypeError(`options.onPage, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new ef(e,this)}get _name(){return`Ogg`}getSupportedTrackCounts(){let e=2**32;return{video:{min:0,max:0},audio:{min:0,max:e},subtitle:{min:0,max:0},total:{min:1,max:e}}}get fileExtension(){return`.ogg`}get mimeType(){return`application/ogg`}getSupportedCodecs(){return[...M.filter(e=>[`vorbis`,`opus`].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},ap=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.onFrame!==void 0&&typeof e.onFrame!=`function`)throw TypeError(`options.onFrame, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new kl(e,this)}get _name(){return`ADTS`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.aac`}get mimeType(){return`audio/aac`}getSupportedCodecs(){return[`aac`]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},op=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.appendOnly!==void 0&&typeof e.appendOnly!=`boolean`)throw TypeError(`options.appendOnly, when provided, must be a boolean.`);super(),this._options=e}_createMuxer(e){return new Nl(e,this)}get _name(){return`FLAC`}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return`.flac`}get mimeType(){return`audio/flac`}getSupportedCodecs(){return[`flac`]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}},sp=class extends Yf{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.onPacket!==void 0&&typeof e.onPacket!=`function`)throw TypeError(`options.onPacket, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new lf(e,this)}get _name(){return`MPEG-TS`}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:1,max:48}}}get fileExtension(){return`.ts`}get mimeType(){return`video/MP2T`}getSupportedCodecs(){return[...A.filter(e=>[`avc`,`hevc`].includes(e)),...M.filter(e=>[`aac`,`mp3`,`ac3`,`eac3`].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}},cp=class extends Yf{constructor(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.segmentFormat instanceof Yf)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(e=>e instanceof Yf)))throw TypeError(`options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.`);if(e.targetDuration!==void 0&&(typeof e.targetDuration!=`number`||e.targetDuration<=0))throw TypeError(`options.targetDuration, when provided, must be a positive number.`);if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!=`boolean`)throw TypeError(`options.singleFilePerPlaylist, when provided, must be a boolean.`);if(e.live!==void 0&&typeof e.live!=`boolean`)throw TypeError(`options.live, when provided, must be a boolean.`);if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!=`number`||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw TypeError(`options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.`);if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!=`function`)throw TypeError(`options.getPlaylistPath, when provided, must be a function.`);if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!=`function`)throw TypeError(`options.getSegmentPath, when provided, must be a function.`);if(e.getInitPath!==void 0&&typeof e.getInitPath!=`function`)throw TypeError(`options.getInitPath, when provided, must be a function.`);if(e.onMaster!==void 0&&typeof e.onMaster!=`function`)throw TypeError(`options.onMaster, when provided, must be a function.`);if(e.onPlaylist!==void 0&&typeof e.onPlaylist!=`function`)throw TypeError(`options.onPlaylist, when provided, must be a function.`);if(e.onSegment!==void 0&&typeof e.onSegment!=`function`)throw TypeError(`options.onSegment, when provided, must be a function.`);if(e.onInit!==void 0&&typeof e.onInit!=`function`)throw TypeError(`options.onInit, when provided, must be a function.`);if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!=`function`)throw TypeError(`options.onSegmentPopped, when provided, must be a function.`);super(),this._options=e}_createMuxer(e){return new Wf(e,this)}get _name(){return`HTTP Live Streaming (HLS)`}get fileExtension(){return`.m3u8`}get mimeType(){return Ta}getSupportedCodecs(){return[...new Set(lt(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,n=!1;for(let r of lt(this._options.segmentFormat)){let i=r.getSupportedTrackCounts();e||=i.video.max>0,t||=i.audio.max>0,n||=i.subtitle.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:1,max:1/0}}}get supportsVideoRotationMetadata(){return lt(this._options.segmentFormat).some(e=>e.supportsVideoRotationMetadata)}get supportsTimestampedMediaData(){return!0}_codecUnsupportedHint(e){return` Using different segment formats may grant support for this codec.`}},lp=[`video`,`audio`,`subtitle`],up=class e{constructor(e,t,n,r,i){this.id=e,this.output=t,this.type=n,this.source=r,this.metadata=i}isVideoTrack(){return this.type===`video`}isAudioTrack(){return this.type===`audio`}isSubtitleTrack(){return this.type===`subtitle`}canBePairedWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrack.`);if(this===t)return!1;let n=lt(this.metadata.group),r=lt(t.metadata.group);for(let e of n)if(this.type!==t.type&&r.some(t=>e===t)||r.some(t=>e._pairedGroups.has(t)))return!0;return!1}},dp=class extends up{constructor(e,t,n,r){super(e,t,`video`,n,r)}},fp=class extends up{constructor(e,t,n,r){super(e,t,`audio`,n,r)}},pp=class extends up{constructor(e,t,n,r){super(e,t,`subtitle`,n,r)}},mp=class e{constructor(){this._pairedGroups=new Set}pairWith(t){if(!(t instanceof e))throw TypeError(`other must be an OutputTrackGroup.`);if(this===t)throw TypeError(`Cannot pair a group with itself.`);this._pairedGroups.add(t),t._pairedGroups.add(this)}},hp=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!we(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&yt(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`);if(e.group!==void 0&&!(e.group instanceof mp)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof mp))))throw TypeError(`metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.`)},gp=class extends ut{get target(){let e=`Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.`;if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw TypeError(e);return t}constructor(e){if(super(),this.state=`pending`,this.defaultTrackGroup=new mp,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new C,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof Yf))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof Od||e.target instanceof zd))throw TypeError(`options.target must be a Target or a PathedTarget.`);if(e.target instanceof Od&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Od)&&typeof e.initTarget!=`function`)throw 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 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 Od&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){n(this._target instanceof zd);let t=this._target.getTarget(e),r=e=>{if(!(e instanceof Od))throw TypeError(`getTarget must return a Target.`);return e};return t instanceof Promise?t.then(r):r(t)}async _getTarget(e){n(this._target instanceof zd);let 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(n(this._initTarget!==null),this._initTarget instanceof Od)return this._initTarget;let e=await this._initTarget();return this.state===`canceled`?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Od)return this._emit(`target`,{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),n=t=>(this.state===`canceled`?t._close():this._rememberTarget(t),this._emit(`target`,{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(n):n(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),n=new Ed(t,typeof e==`boolean`?e:e(t));return n.start(),n})()}addVideoTrack(e,t={}){if(!(e instanceof yf))throw TypeError(`source must be a VideoSource.`);if(hp(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new dp(this._tracks.length+1,this,e,n))}addAudioTrack(e,t={}){if(!(e instanceof kf))throw TypeError(`source must be an AudioSource.`);hp(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new fp(this._tracks.length+1,this,e,n))}addSubtitleTrack(e,t={}){if(!(e instanceof Hf))throw TypeError(`source must be a SubtitleSource.`);hp(t);let n={...t};return n.group??=this.defaultTrackGroup,this._addTrack(new pp(this._tracks.length+1,this,e,n))}setMetadataTags(e){if(gt(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(e.source._connectedTrack)throw Error(`Source is already used for a track.`);let t=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((t,n)=>t+ +(n.type===e.type),0),r=t[e.type].max;if(n===r)throw Error(r===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${r===1?``:`s`}.`);let i=t.total.max;if(this._tracks.length===i)throw Error(`${this.format._name} does not support more than ${i} tracks${i===1?``:`s`} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(t.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(t.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(t.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){let e=this.format.getSupportedTrackCounts();for(let t of lp){let n=this._tracks.reduce((e,n)=>e+ +(n.type===t),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this._tracks.length<t)throw 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 Error(`Output has been canceled.`);return this._startPromise?(console.warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`;let e=await this._mutex.acquire();try{await this._muxer.start();let e=this._tracks.map(e=>e.source._start());await Promise.all(e)}finally{e()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){this.state===`finalized`&&console.warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire();try{let e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(console.warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire();try{let e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state=`finalized`}finally{e()}})()}},_p=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.video, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.video.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.video.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!A.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${A.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof Xs)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.video.bitrate, when provided, must be a positive integer or a quality.`);if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError(`options.video.width, when provided, must be a positive integer.`);if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError(`options.video.height, when provided, must be a positive integer.`);if(e?.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.fit))throw TypeError(`options.video.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 TypeError(`When both options.video.width and options.video.height are provided, options.video.fit must also be provided.`);if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError(`options.video.rotate, when provided, must be 0, 90, 180 or 270.`);if(e?.allowRotationMetadata!==void 0&&typeof e.allowRotationMetadata!=`boolean`)throw TypeError(`options.video.allowRotationMetadata, when provided, must be a boolean.`);if(e?.crop!==void 0&&Cs(e.crop,`options.video.`),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError(`options.video.frameRate, when provided, must be a finite positive number.`);if(e?.alpha!==void 0&&![`discard`,`keep`].includes(e.alpha))throw TypeError(`options.video.alpha, when provided, must be either 'discard' or 'keep'.`);if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`options.video.keyFrameInterval, when provided, must be a non-negative number.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.video.process, when provided, must be a function.`);if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError(`options.video.processedWidth, when provided, must be a positive integer.`);if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError(`options.video.processedHeight, when provided, must be a positive integer.`);if(e?.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(e?.group!==void 0&&!(e.group instanceof mp||Array.isArray(e.group)&&e.group.every(e=>e instanceof mp)))throw TypeError(`options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`)},vp=e=>{if(!e||typeof e!=`object`)throw TypeError(`options.audio, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.audio.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.audio.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!M.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${M.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof Xs)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.audio.bitrate, when provided, must be a positive integer or a quality.`);if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError(`options.audio.numberOfChannels, when provided, must be a positive integer.`);if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError(`options.audio.sampleRate, when provided, must be a positive integer.`);if(e?.sampleFormat!==void 0&&![`u8`,`s16`,`s32`,`f32`].includes(e.sampleFormat))throw TypeError(`options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.audio.process, when provided, must be a function.`);if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError(`options.audio.processedNumberOfChannels, when provided, must be a positive integer.`);if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError(`options.audio.processedSampleRate, when provided, must be a positive integer.`);if(e?.group!==void 0&&!(e.group instanceof mp||Array.isArray(e.group)&&e.group.every(e=>e instanceof mp)))throw TypeError(`options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.`)},yp=2,bp=48e3,xp=class e{static async init(t){let n=new e(t);return await n._init(),n}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPromises=[],this._executed=!1,this._synchronizer=new wp,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.input instanceof el))throw TypeError(`options.input must be an Input.`);if(!(e.output instanceof gp))throw TypeError(`options.output must be an Output.`);if(e.tracks!==void 0&&e.tracks!==`all`&&e.tracks!==`primary`)throw TypeError(`options.tracks, when provided, must be either 'all' or 'primary'.`);if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!==`pending`)throw TypeError(`options.output must be fresh: no tracks or metadata tags added and not started.`);if(e.video!==void 0&&typeof e.video!=`function`)if(Array.isArray(e.video))for(let t of e.video)_p(t);else _p(e.video);if(e.audio!==void 0&&typeof e.audio!=`function`)if(Array.isArray(e.audio))for(let t of e.audio)vp(t);else vp(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!=`object`))throw TypeError(`options.trim, when provided, must be an object.`);if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError(`options.trim.start, when provided, must be a finite number.`);if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw TypeError(`options.trim.end, when provided, must be a finite number.`);if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw TypeError(`options.trim.start must be less than options.trim.end.`);if(e.tags!==void 0&&(typeof e.tags!=`object`||!e.tags)&&typeof e.tags!=`function`)throw TypeError(`options.tags, when provided, must be an object or a function.`);if(typeof e.tags==`object`&&gt(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!=`boolean`)throw TypeError(`options.showWarnings, when provided, must be a boolean.`);this._options=e,this.input=e.input,this.output=e.output;let{promise:t,resolve:n}=T();this._started=t,this._start=n}async _init(){let e=await this.input.getFormat(),t,r=this._options.tracks;r===void 0&&(r=e.name.includes(`(HLS)`)?`primary`:`all`),r===`all`?t=await this.input.getTracks():r===`primary`?t=[await this.input.getPrimaryVideoTrack(),await this.input.getPrimaryAudioTrack()].filter(e=>e!==null):(E(r),n(!1));let i=this.output.format.getSupportedTrackCounts(),a=1,o=1,s=[],c=[];for(let e of t){let t;if(e.isVideoTrack())if(this._options.video)if(typeof this._options.video==`function`){let n=await this._options.video(e,a)??{};if(Array.isArray(n))for(let e of n)_p(e);else _p(n);t=Array.isArray(n)?n:[n],a++}else t=Array.isArray(this._options.video)?this._options.video:[this._options.video];else t=[{}];else if(e.isAudioTrack())if(this._options.audio)if(typeof this._options.audio==`function`){let n=await this._options.audio(e,o)??{};if(Array.isArray(n))for(let e of n)vp(e);else vp(n);t=Array.isArray(n)?n:[n],o++}else t=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else t=[{}];else n(!1);let r=t.filter(e=>e.discard);for(let t of r)this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:t});if(t.length===r.length){t.length===0&&this.discardedTracks.push({track:e,reason:`discarded_by_user`,trackOptions:{}});continue}let i=t.filter(e=>!e.discard);s.push(e),c.push(i)}this._startTimestamp=this._options.trim?.start===void 0?Math.max(await this.input.getFirstTimestamp(s),0):this._options.trim.start,this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);for(let e=0;e<s.length;e++){let t=s[e],r=c[e];for(let e of r){if(this._totalTrackCount===i.total.max){this.discardedTracks.push({track:t,reason:`max_track_count_reached`,trackOptions:e});continue}if(this._addedCounts[t.type]===i[t.type].max){this.discardedTracks.push({track:t,reason:`max_track_count_of_type_reached`,trackOptions:e});continue}let r=this._nextOutputTrackId++;t.isVideoTrack()?await this._processVideoTrack(t,e,r):t.isAudioTrack()?await this._processAudioTrack(t,e,r):n(!1)}}for(let e=0;e<this.utilizedTracks.length-1;e++)for(let t=e+1;t<this.utilizedTracks.length;t++){let r=this.utilizedTracks[e],i=this.utilizedTracks[t],a=this._outputOwnTrackGroups[e],o=this._outputOwnTrackGroups[t];n(a!==void 0),n(o!==void 0),a&&o&&r.canBePairedWith(i)&&a.pairWith(o)}let l=await this.input.getMetadataTags(),u;if(this._options.tags){let e=typeof this._options.tags==`function`?await this._options.tags(l):this._options.tags;gt(e),u=e}else u=l;let d=e.mimeType===this.output.format.mimeType,f=l.raw===u.raw;if(l.raw&&f&&!d&&delete u.raw,this.output.setMetadataTags(u),this.isValid=this._totalTrackCount>=i.total.min&&this._addedCounts.video>=i.video.min&&this._addedCounts.audio>=i.audio.min&&this._addedCounts.subtitle>=i.subtitle.min,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>e.reason!==`discarded_by_user`);t.length>0&&e.push(`Some tracks had to be discarded from the conversion:`,t),this.isValid||(e.length>0&&e.push(`
109
+
110
+ `),e.push(this._getInvalidityExplanation().join(``))),e.length>0&&console.warn(...e)}}_getInvalidityExplanation(){let e=[];if(this.discardedTracks.length===0)e.push(`Due to missing tracks, this conversion cannot be executed.`);else{let t=this.discardedTracks.every(e=>e.reason===`discarded_by_user`||e.reason===`no_encodable_target_codec`)&&this.discardedTracks.some(e=>e.reason===`no_encodable_target_codec`);if(e.push(`Due to discarded tracks, this conversion cannot be executed.`),t){let t=this.discardedTracks.flatMap(e=>e.reason===`discarded_by_user`?[]:e.track.type===`video`?this.output.format.getSupportedVideoCodecs():e.track.type===`audio`?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs()),n=[...new Set(t)];n.length===1?e.push(`\nTracks were discarded because your environment is not able to encode '${n[0]}'.`):e.push(`
111
+ Tracks were discarded because your environment is not able to encode any of the following codecs: ${n.map(e=>`'${e}'`).join(`, `)}.`),n.includes(`mp3`)&&e.push(`
112
+ The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),n.includes(`aac`)&&e.push(`
113
+ The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(n.includes(`ac3`)||n.includes(`eac3`))&&e.push(`
114
+ The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes(`flac`)&&e.push(`
115
+ The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
116
+ Check the discardedTracks field for more info.`)}return e}async execute(){if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
117
+ `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);this._executed=!0;for(let e of this._outputTrackIds)this._synchronizer.declareTrack(e);if(this.onProgress){let e=[...new Set(this.utilizedTracks)].map(async e=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this._outputTrackIds)this._maxTimestamps.set(e,0);this.onProgress?.(0,0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new Sp;if(await this.output.finalize(),this._computeProgress){let e=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,e)}}async cancel(){if(this.output.state!==`finalizing`&&this.output.state!==`finalized`){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t,i){let a=await e.getCodec();if(!a){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}let o,s=await e.getRotation(),c=r(s+(t.rotate??0)),l=c,u=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),d=await e.getSquarePixelWidth(),f=await e.getSquarePixelHeight(),[p,m]=c%180==0?[d,f]:[f,d],h=t.crop;h&&=Ss(h,p,m);let[g,_]=h?[h.width,h.height]:[p,m],v=g,y=_,b=v/y;t.width!==void 0&&t.height===void 0?(v=dt(t.width),y=dt(Math.round(v/b))):t.width===void 0&&t.height!==void 0?(y=dt(t.height),v=dt(Math.round(y*b))):t.width!==void 0&&t.height!==void 0&&(v=dt(t.width),y=dt(t.height));let x=await e.getFirstTimestamp(),S=this.output.format.getSupportedVideoCodecs(),C=!!t.forceTranscode||x<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!S.includes(a)||t.codec&&t.codec!==a||v!==g||y!==_||c!==0&&!u||!!h,ee=t.alpha??`discard`;if(C){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}t.codec&&(S=S.filter(e=>e===t.codec));let a=t.bitrate??ec,p=await uc(S,{width:t.process&&t.processedWidth?t.processedWidth:v,height:t.process&&t.processedHeight?t.processedHeight:y,bitrate:a});if(!p){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}let m={codec:p,bitrate:a,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:ee,hardwareAcceleration:t.hardwareAcceleration,transform:{}};n(m.transform);let b=v!==g||y!==_||c!==0&&(!u||t.process!==void 0)||!!h||d!==await e.getCodedWidth()||f!==await e.getCodedHeight();if(!b){let t=new gp({format:new Zf,target:new Ld}),n=new Ef(m);t.addVideoTrack(n),await t.start();let r=await new Rc(e).getSample(x);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),b=!0,t.cancel()}else await t.cancel()}t.frameRate&&(m.transform.frameRate=t.frameRate),b&&(l=0,m.transform.width=v,m.transform.height=y,m.transform.fit=t.fit??`fill`,m.transform.rotate=r(c-s),m.transform.crop=h,m.transform.alpha=ee);let C=new Ef(m);o=C,this._trackPromises.push((async()=>{await this._started;let n=new Rc(e);for await(let e of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){e.close();return}let n=Math.max(e.timestamp-this._startTimestamp,0);e.setTimestamp(n),await this._registerVideoSample(t,i,C,e),e.close()}C.close(),this._synchronizer.closeTrack(i)})())}else{let t=new xf(a);o=t,this._trackPromises.push((async()=>{await this._started;let r=new Ac(e),a={decoderConfig:await e.getDecoderConfig()??void 0};for await(let e of r.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this._canceled)return;if(e.timestamp>=this._endTimestamp)break;let r=e.clone({timestamp:e.timestamp-this._startTimestamp,sideData:ee===`discard`?{}:e.sideData});n(r.timestamp>=0),this._reportProgress(i,r.timestamp+r.duration),await t.add(r,a),this._synchronizer.shouldWait(i,r.timestamp)&&await this._synchronizer.wait(r.timestamp)}t.close(),this._synchronizer.closeTrack(i)})())}let te=null;t.group||(te=new mp);let ne=await e.getLanguageCode();this.output.addVideoTrack(o,{frameRate:t.frameRate,languageCode:we(ne)?ne:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:l,group:te??t.group}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(te)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(t,r.timestamp+r.duration);let i;if(!e.process)i=[r];else{let t=e.process(r);t instanceof Promise&&(t=await t),Array.isArray(t)||(t=t===null?[]:[t]),i=t.map(e=>e instanceof ms?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new ms(e):new ms(e,{timestamp:r.timestamp,duration:r.duration}))}try{for(let e of i){if(this._canceled)break;await n.add(e),this._synchronizer.shouldWait(t,e.timestamp)&&await this._synchronizer.wait(e.timestamp)}}finally{for(let e of i)e!==r&&e.close()}}async _processAudioTrack(e,t,r){let i=await e.getCodec();if(!i){this.discardedTracks.push({track:e,reason:`unknown_source_codec`,trackOptions:t});return}let a,o=await e.getNumberOfChannels(),s=await e.getSampleRate(),c=await e.getFirstTimestamp(),l=t.numberOfChannels??o,u=t.sampleRate??s,d=l!==o||u!==s||c<this._startTimestamp||c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,f=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!d&&f.includes(i)&&(!t.codec||t.codec===i)&&!t.process&&t.sampleFormat===void 0){let t=new Af(i);a=t,this._trackPromises.push((async()=>{await this._started;let i=new Ac(e),a={decoderConfig:await e.getDecoderConfig()??void 0};for await(let e of i.packets()){if(this._canceled)return;if(e.timestamp>=this._endTimestamp)break;let i=e.clone({timestamp:e.timestamp-this._startTimestamp});n(i.timestamp>=0),this._reportProgress(r,i.timestamp+i.duration),await t.add(i,a),this._synchronizer.shouldWait(r,i.timestamp)&&await this._synchronizer.wait(i.timestamp)}t.close(),this._synchronizer.closeTrack(r)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`,trackOptions:t});return}let n=null;t.codec&&(f=f.filter(e=>e===t.codec));let i=t.bitrate??ec,o=await cc(f,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:l,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:u,bitrate:i});if(!o.some(e=>Et.includes(e))&&f.some(e=>Et.includes(e))&&(l!==yp||u!==bp)){let e=(await cc(f,{numberOfChannels:yp,sampleRate:bp,bitrate:i})).find(e=>Et.includes(e));e&&(d=!0,n=e,l=yp,u=bp)}else n=o[0]??null;if(n===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`,trackOptions:t});return}if(d)a=this._resampleAudio(e,t,r,n,l,u,i);else{let o=new Mf({codec:n,bitrate:i});a=o,this._trackPromises.push((async()=>{await this._started;let n=new Hc(e);for await(let e of n.samples(void 0,this._endTimestamp)){if(this._canceled){e.close();return}e.setTimestamp(e.timestamp-this._startTimestamp),await this._registerAudioSample(t,r,o,e),e.close()}o.close(),this._synchronizer.closeTrack(r)})())}}let p=null;t.group||(p=new mp);let m=await e.getLanguageCode();this.output.addAudioTrack(a,{languageCode:we(m)?m:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:p??t.group}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(p)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;let i=r;e.sampleFormat!==void 0&&zs(i.format)!==e.sampleFormat&&(i=Vs(i,e.sampleFormat)),this._reportProgress(t,i.timestamp+i.duration);let a;if(!e.process)a=[i];else{let t=e.process(i);if(t instanceof Promise&&(t=await t),Array.isArray(t)||(t=t===null?[]:[t]),!t.every(e=>e instanceof Ns))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);a=t}try{for(let e of a){if(this._canceled)break;await n.add(e),this._synchronizer.shouldWait(t,e.timestamp)&&await this._synchronizer.wait(e.timestamp)}}finally{i!==r&&i.close();for(let e of a)e!==r&&e.close()}}_resampleAudio(e,t,r,i,a,o,s){let c=new Mf({codec:i,bitrate:s});return this._trackPromises.push((async()=>{await this._started;let i=new _f({targetNumberOfChannels:a,targetSampleRate:o,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async e=>{n(e.timestamp>=this._startTimestamp),e.setTimestamp(e.timestamp-this._startTimestamp),await this._registerAudioSample(t,r,c,e),e.close()}}),s=new Hc(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of s){if(this._canceled){e.close();return}await i.add(e),e.close()}await i.finalize(),c.close(),this._synchronizer.closeTrack(r)})()),c}_reportProgress(e,t){if(!this._computeProgress)return;n(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let r=Math.min(...this._maxTimestamps.values()),i=D(r/this._totalDuration,0,1);i!==this._lastProgress&&(this._lastProgress=i,this.onProgress?.(i,r))}},Sp=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},Cp=1,wp=class{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){let r=this.maxTimestamps.get(e);return n(r!==void 0),this.maxTimestamps.set(e,Math.max(t,r)),t-this.computeMinAndMaybeResolve()>Cp}wait(e){let{promise:t,resolve:n}=T();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<Cp&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}};export{Uo as ADTS,qo as ALL_FORMATS,lp as ALL_TRACK_TYPES,M as AUDIO_CODECS,No as AdtsInputFormat,ap as AdtsOutputFormat,Fd as AppendOnlyStreamTarget,ht as AttachedFile,Uc as AudioBufferSink,Nf as AudioBufferSource,Ns as AudioSample,Ms as AudioSampleResource,Hc as AudioSampleSink,Mf as AudioSampleSource,kf as AudioSource,Mc as BaseMediaSampleSink,Qa as BlobSource,Za as BufferSource,jd as BufferTarget,zc as CanvasSink,Df as CanvasSource,Qf as CmafOutputFormat,ft as ConcurrentRunner,xp as Conversion,Sp as ConversionCanceledError,mc as CustomAudioDecoder,gc as CustomAudioEncoder,Xa as CustomPathedSource,io as CustomSource,pc as CustomVideoDecoder,hc as CustomVideoEncoder,Af as EncodedAudioPacketSource,F as EncodedPacket,Ac as EncodedPacketSink,xf as EncodedVideoPacketSource,ut as EventEmitter,Wo as FLAC,ro as FilePathSource,Id as FilePathTarget,Mo as FlacInputFormat,op as FlacOutputFormat,Ko as HLS,Jo as HLS_FORMATS,Fo as HlsInputFormat,cp as HlsOutputFormat,el as Input,qc as InputAudioTrack,nl as InputDisposedError,Co as InputFormat,Wc as InputTrack,Kc as InputVideoTrack,wo as IsobmffInputFormat,Xf as IsobmffOutputFormat,Ro as MATROSKA,Bo as MP3,Io as MP4,Go as MPEG_TS,Do as MatroskaInputFormat,vf as MediaSource,Pf as MediaStreamAudioTrackSource,Of as MediaStreamVideoTrackSource,ep as MkvOutputFormat,$f as MovOutputFormat,ko as Mp3InputFormat,np as Mp3OutputFormat,To as Mp4InputFormat,Zf as Mp4OutputFormat,Po as MpegTsInputFormat,sp as MpegTsOutputFormat,Et as NON_PCM_AUDIO_CODECS,Ld as NullTarget,Ho as OGG,jo as OggInputFormat,ip as OggOutputFormat,gp as Output,fp as OutputAudioTrack,Yf as OutputFormat,pp as OutputSubtitleTrack,up as OutputTrack,mp as OutputTrackGroup,dp as OutputVideoTrack,j as PCM_AUDIO_CODECS,Ja as PathedSource,zd as PathedTarget,Lo as QTFF,ec as QUALITY_HIGH,Qs as QUALITY_LOW,$s as QUALITY_MEDIUM,tc as QUALITY_VERY_HIGH,Zs as QUALITY_VERY_LOW,Xs as Quality,Eo as QuickTimeInputFormat,lo as RangedSource,Rd as RangedTarget,oo as ReadableStreamSource,mt as RichImageData,Dt as SUBTITLE_CODECS,Ka as Source,qa as SourceRef,ao as StreamSource,Pd as StreamTarget,Hf as SubtitleSource,Od as Target,Uf as TextSubtitleSource,tl as UnsupportedInputFormatError,no as UrlSource,A as VIDEO_CODECS,fs as VIDEO_SAMPLE_PIXEL_FORMATS,ms as VideoSample,bs as VideoSampleColorSpace,ds as VideoSampleResource,Rc as VideoSampleSink,Ef as VideoSampleSource,yf as VideoSource,Vo as WAVE,zo as WEBM,rp as WavOutputFormat,Ao as WaveInputFormat,Oo as WebMInputFormat,tp as WebMOutputFormat,Jc as asc,es as canDecode,ns as canDecodeAudio,ts as canDecodeVideo,nc as canEncode,ic as canEncodeAudio,ac as canEncodeSubtitles,rc as canEncodeVideo,Yc as desc,as as getDecodableAudioCodecs,rs as getDecodableCodecs,is as getDecodableVideoCodecs,cc as getEncodableAudioCodecs,oc as getEncodableCodecs,lc as getEncodableSubtitleCodecs,sc as getEncodableVideoCodecs,dc as getFirstEncodableAudioCodec,fc as getFirstEncodableSubtitleCodec,uc as getFirstEncodableVideoCodec,Xc as prefer,xc as registerDecoder,Sc as registerEncoder,gs as registerVideoSampleTransformer};