@kenzuya/mediabunny 1.28.6 → 1.28.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 (227) hide show
  1. package/dist/bundles/mediabunny.node.js +26704 -0
  2. package/dist/bundles/mediabunny.node.min.js +490 -0
  3. package/dist/index.d.ts.map +1 -0
  4. package/dist/packages/eac3/build/eac3.d.ts +3 -0
  5. package/dist/packages/eac3/build/eac3.d.ts.map +1 -0
  6. package/dist/packages/eac3/mediabunny-eac3.node.js +1058 -0
  7. package/dist/packages/eac3/mediabunny-eac3.node.min.js +44 -0
  8. package/dist/packages/eac3/src/decode.worker.d.ts +9 -0
  9. package/dist/packages/eac3/src/decode.worker.d.ts.map +1 -0
  10. package/dist/packages/eac3/src/eac3-loader.d.ts +12 -0
  11. package/dist/packages/eac3/src/eac3-loader.d.ts.map +1 -0
  12. package/dist/packages/eac3/src/encode.worker.d.ts +9 -0
  13. package/dist/packages/eac3/src/encode.worker.d.ts.map +1 -0
  14. package/dist/packages/eac3/src/index.d.ts +26 -0
  15. package/dist/packages/eac3/src/index.d.ts.map +1 -0
  16. package/dist/packages/eac3/src/shared.d.ts +67 -0
  17. package/dist/packages/eac3/src/shared.d.ts.map +1 -0
  18. package/dist/packages/mp3-encoder/build/lame.d.ts +3 -0
  19. package/dist/packages/mp3-encoder/build/lame.d.ts.map +1 -0
  20. package/dist/packages/mp3-encoder/mediabunny-mp3-encoder.node.js +689 -0
  21. package/dist/packages/mp3-encoder/mediabunny-mp3-encoder.node.min.js +58 -0
  22. package/dist/packages/mp3-encoder/src/encode.worker.d.ts +9 -0
  23. package/dist/packages/mp3-encoder/src/encode.worker.d.ts.map +1 -0
  24. package/dist/packages/mp3-encoder/src/index.d.ts +27 -0
  25. package/dist/packages/mp3-encoder/src/index.d.ts.map +1 -0
  26. package/dist/packages/mp3-encoder/src/shared.d.ts +40 -0
  27. package/dist/packages/mp3-encoder/src/shared.d.ts.map +1 -0
  28. package/dist/packages/mpeg4/build/xvid.d.ts +3 -0
  29. package/dist/packages/mpeg4/build/xvid.d.ts.map +1 -0
  30. package/dist/packages/mpeg4/mediabunny-mpeg4.node.js +1198 -0
  31. package/dist/packages/mpeg4/mediabunny-mpeg4.node.min.js +44 -0
  32. package/dist/packages/mpeg4/src/decode.worker.d.ts +9 -0
  33. package/dist/packages/mpeg4/src/decode.worker.d.ts.map +1 -0
  34. package/dist/packages/mpeg4/src/encode.worker.d.ts +9 -0
  35. package/dist/packages/mpeg4/src/encode.worker.d.ts.map +1 -0
  36. package/dist/packages/mpeg4/src/index.d.ts +49 -0
  37. package/dist/packages/mpeg4/src/index.d.ts.map +1 -0
  38. package/dist/packages/mpeg4/src/shared.d.ts +39 -0
  39. package/dist/packages/mpeg4/src/shared.d.ts.map +1 -0
  40. package/dist/packages/mpeg4/src/xvid-loader.d.ts +12 -0
  41. package/dist/packages/mpeg4/src/xvid-loader.d.ts.map +1 -0
  42. package/dist/shared/mp3-misc.d.ts.map +1 -0
  43. package/dist/src/adts/adts-demuxer.d.ts.map +1 -0
  44. package/dist/src/adts/adts-muxer.d.ts.map +1 -0
  45. package/dist/src/adts/adts-reader.d.ts.map +1 -0
  46. package/dist/src/avi/avi-demuxer.d.ts.map +1 -0
  47. package/dist/src/avi/avi-misc.d.ts.map +1 -0
  48. package/dist/src/avi/avi-muxer.d.ts.map +1 -0
  49. package/dist/src/avi/riff-writer.d.ts.map +1 -0
  50. package/dist/src/codec-data.d.ts.map +1 -0
  51. package/dist/src/codec.d.ts.map +1 -0
  52. package/dist/src/conversion.d.ts.map +1 -0
  53. package/dist/src/custom-coder.d.ts.map +1 -0
  54. package/dist/src/demuxer.d.ts.map +1 -0
  55. package/dist/src/encode.d.ts.map +1 -0
  56. package/dist/src/flac/flac-demuxer.d.ts.map +1 -0
  57. package/dist/src/flac/flac-misc.d.ts.map +1 -0
  58. package/dist/src/flac/flac-muxer.d.ts.map +1 -0
  59. package/dist/src/id3.d.ts.map +1 -0
  60. package/dist/src/index.d.ts +30 -0
  61. package/dist/src/index.d.ts.map +1 -0
  62. package/dist/src/input-format.d.ts.map +1 -0
  63. package/dist/src/input-track.d.ts.map +1 -0
  64. package/dist/src/input.d.ts.map +1 -0
  65. package/dist/src/isobmff/isobmff-boxes.d.ts.map +1 -0
  66. package/dist/src/isobmff/isobmff-demuxer.d.ts.map +1 -0
  67. package/dist/src/isobmff/isobmff-misc.d.ts.map +1 -0
  68. package/dist/src/isobmff/isobmff-muxer.d.ts.map +1 -0
  69. package/dist/src/isobmff/isobmff-reader.d.ts.map +1 -0
  70. package/dist/src/matroska/ebml.d.ts.map +1 -0
  71. package/dist/src/matroska/matroska-demuxer.d.ts.map +1 -0
  72. package/dist/src/matroska/matroska-input.d.ts.map +1 -0
  73. package/dist/src/matroska/matroska-misc.d.ts.map +1 -0
  74. package/dist/src/matroska/matroska-muxer.d.ts.map +1 -0
  75. package/dist/src/media-sink.d.ts.map +1 -0
  76. package/dist/src/media-source.d.ts.map +1 -0
  77. package/dist/src/metadata.d.ts.map +1 -0
  78. package/dist/src/misc.d.ts.map +1 -0
  79. package/dist/src/mp3/mp3-demuxer.d.ts.map +1 -0
  80. package/dist/src/mp3/mp3-muxer.d.ts.map +1 -0
  81. package/dist/src/mp3/mp3-reader.d.ts.map +1 -0
  82. package/dist/src/mp3/mp3-writer.d.ts.map +1 -0
  83. package/dist/src/muxer.d.ts.map +1 -0
  84. package/dist/src/ogg/ogg-demuxer.d.ts.map +1 -0
  85. package/dist/src/ogg/ogg-misc.d.ts.map +1 -0
  86. package/dist/src/ogg/ogg-muxer.d.ts.map +1 -0
  87. package/dist/src/ogg/ogg-reader.d.ts.map +1 -0
  88. package/dist/src/output-format.d.ts.map +1 -0
  89. package/dist/src/output.d.ts.map +1 -0
  90. package/dist/src/packet.d.ts.map +1 -0
  91. package/dist/src/pcm.d.ts.map +1 -0
  92. package/dist/src/reader.d.ts.map +1 -0
  93. package/dist/src/sample.d.ts.map +1 -0
  94. package/dist/src/source.d.ts.map +1 -0
  95. package/dist/src/subtitles.d.ts.map +1 -0
  96. package/dist/src/target.d.ts.map +1 -0
  97. package/dist/src/tsconfig.tsbuildinfo +1 -0
  98. package/dist/src/wave/riff-writer.d.ts.map +1 -0
  99. package/dist/src/wave/wave-demuxer.d.ts.map +1 -0
  100. package/dist/src/wave/wave-muxer.d.ts.map +1 -0
  101. package/dist/src/writer.d.ts.map +1 -0
  102. package/package.json +44 -8
  103. package/dist/modules/shared/mp3-misc.d.ts.map +0 -1
  104. package/dist/modules/src/adts/adts-demuxer.d.ts.map +0 -1
  105. package/dist/modules/src/adts/adts-muxer.d.ts.map +0 -1
  106. package/dist/modules/src/adts/adts-reader.d.ts.map +0 -1
  107. package/dist/modules/src/avi/avi-demuxer.d.ts.map +0 -1
  108. package/dist/modules/src/avi/avi-misc.d.ts.map +0 -1
  109. package/dist/modules/src/avi/avi-muxer.d.ts.map +0 -1
  110. package/dist/modules/src/avi/riff-writer.d.ts.map +0 -1
  111. package/dist/modules/src/codec-data.d.ts.map +0 -1
  112. package/dist/modules/src/codec.d.ts.map +0 -1
  113. package/dist/modules/src/conversion.d.ts.map +0 -1
  114. package/dist/modules/src/custom-coder.d.ts.map +0 -1
  115. package/dist/modules/src/demuxer.d.ts.map +0 -1
  116. package/dist/modules/src/encode.d.ts.map +0 -1
  117. package/dist/modules/src/flac/flac-demuxer.d.ts.map +0 -1
  118. package/dist/modules/src/flac/flac-misc.d.ts.map +0 -1
  119. package/dist/modules/src/flac/flac-muxer.d.ts.map +0 -1
  120. package/dist/modules/src/id3.d.ts.map +0 -1
  121. package/dist/modules/src/index.d.ts.map +0 -1
  122. package/dist/modules/src/input-format.d.ts.map +0 -1
  123. package/dist/modules/src/input-track.d.ts.map +0 -1
  124. package/dist/modules/src/input.d.ts.map +0 -1
  125. package/dist/modules/src/isobmff/isobmff-boxes.d.ts.map +0 -1
  126. package/dist/modules/src/isobmff/isobmff-demuxer.d.ts.map +0 -1
  127. package/dist/modules/src/isobmff/isobmff-misc.d.ts.map +0 -1
  128. package/dist/modules/src/isobmff/isobmff-muxer.d.ts.map +0 -1
  129. package/dist/modules/src/isobmff/isobmff-reader.d.ts.map +0 -1
  130. package/dist/modules/src/matroska/ebml.d.ts.map +0 -1
  131. package/dist/modules/src/matroska/matroska-demuxer.d.ts.map +0 -1
  132. package/dist/modules/src/matroska/matroska-input.d.ts.map +0 -1
  133. package/dist/modules/src/matroska/matroska-misc.d.ts.map +0 -1
  134. package/dist/modules/src/matroska/matroska-muxer.d.ts.map +0 -1
  135. package/dist/modules/src/media-sink.d.ts.map +0 -1
  136. package/dist/modules/src/media-source.d.ts.map +0 -1
  137. package/dist/modules/src/metadata.d.ts.map +0 -1
  138. package/dist/modules/src/misc.d.ts.map +0 -1
  139. package/dist/modules/src/mp3/mp3-demuxer.d.ts.map +0 -1
  140. package/dist/modules/src/mp3/mp3-muxer.d.ts.map +0 -1
  141. package/dist/modules/src/mp3/mp3-reader.d.ts.map +0 -1
  142. package/dist/modules/src/mp3/mp3-writer.d.ts.map +0 -1
  143. package/dist/modules/src/muxer.d.ts.map +0 -1
  144. package/dist/modules/src/ogg/ogg-demuxer.d.ts.map +0 -1
  145. package/dist/modules/src/ogg/ogg-misc.d.ts.map +0 -1
  146. package/dist/modules/src/ogg/ogg-muxer.d.ts.map +0 -1
  147. package/dist/modules/src/ogg/ogg-reader.d.ts.map +0 -1
  148. package/dist/modules/src/output-format.d.ts.map +0 -1
  149. package/dist/modules/src/output.d.ts.map +0 -1
  150. package/dist/modules/src/packet.d.ts.map +0 -1
  151. package/dist/modules/src/pcm.d.ts.map +0 -1
  152. package/dist/modules/src/reader.d.ts.map +0 -1
  153. package/dist/modules/src/sample.d.ts.map +0 -1
  154. package/dist/modules/src/source.d.ts.map +0 -1
  155. package/dist/modules/src/subtitles.d.ts.map +0 -1
  156. package/dist/modules/src/target.d.ts.map +0 -1
  157. package/dist/modules/src/tsconfig.tsbuildinfo +0 -1
  158. package/dist/modules/src/wave/riff-writer.d.ts.map +0 -1
  159. package/dist/modules/src/wave/wave-demuxer.d.ts.map +0 -1
  160. package/dist/modules/src/wave/wave-muxer.d.ts.map +0 -1
  161. package/dist/modules/src/writer.d.ts.map +0 -1
  162. /package/dist/bundles/{mediabunny.js → mediabunny.browser.js} +0 -0
  163. /package/dist/bundles/{mediabunny.min.js → mediabunny.browser.min.js} +0 -0
  164. /package/dist/{modules/src/index.d.ts → index.d.ts} +0 -0
  165. /package/dist/packages/eac3/{mediabunny-eac3.js → mediabunny-eac3.browser.js} +0 -0
  166. /package/dist/packages/eac3/{mediabunny-eac3.min.js → mediabunny-eac3.browser.min.js} +0 -0
  167. /package/dist/packages/mp3-encoder/{mediabunny-mp3-encoder.js → mediabunny-mp3-encoder.browser.js} +0 -0
  168. /package/dist/packages/mp3-encoder/{mediabunny-mp3-encoder.min.js → mediabunny-mp3-encoder.browser.min.js} +0 -0
  169. /package/dist/packages/mpeg4/{mediabunny-mpeg4.js → mediabunny-mpeg4.browser.js} +0 -0
  170. /package/dist/packages/mpeg4/{mediabunny-mpeg4.min.js → mediabunny-mpeg4.browser.min.js} +0 -0
  171. /package/dist/{modules/shared → shared}/mp3-misc.d.ts +0 -0
  172. /package/dist/{modules/src → src}/adts/adts-demuxer.d.ts +0 -0
  173. /package/dist/{modules/src → src}/adts/adts-muxer.d.ts +0 -0
  174. /package/dist/{modules/src → src}/adts/adts-reader.d.ts +0 -0
  175. /package/dist/{modules/src → src}/avi/avi-demuxer.d.ts +0 -0
  176. /package/dist/{modules/src → src}/avi/avi-misc.d.ts +0 -0
  177. /package/dist/{modules/src → src}/avi/avi-muxer.d.ts +0 -0
  178. /package/dist/{modules/src → src}/avi/riff-writer.d.ts +0 -0
  179. /package/dist/{modules/src → src}/codec-data.d.ts +0 -0
  180. /package/dist/{modules/src → src}/codec.d.ts +0 -0
  181. /package/dist/{modules/src → src}/conversion.d.ts +0 -0
  182. /package/dist/{modules/src → src}/custom-coder.d.ts +0 -0
  183. /package/dist/{modules/src → src}/demuxer.d.ts +0 -0
  184. /package/dist/{modules/src → src}/encode.d.ts +0 -0
  185. /package/dist/{modules/src → src}/flac/flac-demuxer.d.ts +0 -0
  186. /package/dist/{modules/src → src}/flac/flac-misc.d.ts +0 -0
  187. /package/dist/{modules/src → src}/flac/flac-muxer.d.ts +0 -0
  188. /package/dist/{modules/src → src}/id3.d.ts +0 -0
  189. /package/dist/{modules/src → src}/input-format.d.ts +0 -0
  190. /package/dist/{modules/src → src}/input-track.d.ts +0 -0
  191. /package/dist/{modules/src → src}/input.d.ts +0 -0
  192. /package/dist/{modules/src → src}/isobmff/isobmff-boxes.d.ts +0 -0
  193. /package/dist/{modules/src → src}/isobmff/isobmff-demuxer.d.ts +0 -0
  194. /package/dist/{modules/src → src}/isobmff/isobmff-misc.d.ts +0 -0
  195. /package/dist/{modules/src → src}/isobmff/isobmff-muxer.d.ts +0 -0
  196. /package/dist/{modules/src → src}/isobmff/isobmff-reader.d.ts +0 -0
  197. /package/dist/{modules/src → src}/matroska/ebml.d.ts +0 -0
  198. /package/dist/{modules/src → src}/matroska/matroska-demuxer.d.ts +0 -0
  199. /package/dist/{modules/src → src}/matroska/matroska-input.d.ts +0 -0
  200. /package/dist/{modules/src → src}/matroska/matroska-misc.d.ts +0 -0
  201. /package/dist/{modules/src → src}/matroska/matroska-muxer.d.ts +0 -0
  202. /package/dist/{modules/src → src}/media-sink.d.ts +0 -0
  203. /package/dist/{modules/src → src}/media-source.d.ts +0 -0
  204. /package/dist/{modules/src → src}/metadata.d.ts +0 -0
  205. /package/dist/{modules/src → src}/misc.d.ts +0 -0
  206. /package/dist/{modules/src → src}/mp3/mp3-demuxer.d.ts +0 -0
  207. /package/dist/{modules/src → src}/mp3/mp3-muxer.d.ts +0 -0
  208. /package/dist/{modules/src → src}/mp3/mp3-reader.d.ts +0 -0
  209. /package/dist/{modules/src → src}/mp3/mp3-writer.d.ts +0 -0
  210. /package/dist/{modules/src → src}/muxer.d.ts +0 -0
  211. /package/dist/{modules/src → src}/ogg/ogg-demuxer.d.ts +0 -0
  212. /package/dist/{modules/src → src}/ogg/ogg-misc.d.ts +0 -0
  213. /package/dist/{modules/src → src}/ogg/ogg-muxer.d.ts +0 -0
  214. /package/dist/{modules/src → src}/ogg/ogg-reader.d.ts +0 -0
  215. /package/dist/{modules/src → src}/output-format.d.ts +0 -0
  216. /package/dist/{modules/src → src}/output.d.ts +0 -0
  217. /package/dist/{modules/src → src}/packet.d.ts +0 -0
  218. /package/dist/{modules/src → src}/pcm.d.ts +0 -0
  219. /package/dist/{modules/src → src}/reader.d.ts +0 -0
  220. /package/dist/{modules/src → src}/sample.d.ts +0 -0
  221. /package/dist/{modules/src → src}/source.d.ts +0 -0
  222. /package/dist/{modules/src → src}/subtitles.d.ts +0 -0
  223. /package/dist/{modules/src → src}/target.d.ts +0 -0
  224. /package/dist/{modules/src → src}/wave/riff-writer.d.ts +0 -0
  225. /package/dist/{modules/src → src}/wave/wave-demuxer.d.ts +0 -0
  226. /package/dist/{modules/src → src}/wave/wave-muxer.d.ts +0 -0
  227. /package/dist/{modules/src → src}/writer.d.ts +0 -0
@@ -0,0 +1,490 @@
1
+ /*!
2
+ * Copyright (c) 2025-present, Vanilagy and contributors
3
+ *
4
+ * This Source Code Form is subject to the terms of the Mozilla Public
5
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
6
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7
+ */
8
+ var G7=Object.defineProperty;var K7=($,J)=>{for(var Y in J)G7($,Y,{get:J[Y],enumerable:!0,configurable:!0,set:(j)=>J[Y]=()=>j})};var Q7=($,J)=>()=>($&&(J=$($=0)),J);var S8={};K7(S8,{splitSrtIntoCues:()=>$$,splitAssIntoCues:()=>J$,parseSubtitleTimestamp:()=>I8,parseSrtTimestamp:()=>p6,parseAssTimestamp:()=>m6,inlineTimestampRegex:()=>u1,formatSubtitleTimestamp:()=>k1,formatSrtTimestamp:()=>l6,formatCuesToWebVTT:()=>o6,formatCuesToSrt:()=>n6,formatCuesToAss:()=>r6,formatAssTimestamp:()=>d6,convertDialogueLineToMkvFormat:()=>Y$,SubtitleParser:()=>c6});class c6{options;preambleText=null;preambleEmitted=!1;constructor($){this.options=$}parse($){if(this.options.codec==="srt")this.parseSrt($);else if(this.options.codec==="ass"||this.options.codec==="ssa")this.parseAss($);else if(this.options.codec==="tx3g")this.parseTx3g($);else if(this.options.codec==="ttml")this.parseTtml($);else this.parseWebVTT($)}parseSrt($){let J=$$($);for(let Y=0;Y<J.length;Y++){let j={};if(Y===0)j.config={description:""};this.options.output(J[Y],j)}}parseAss($){let{header:J,cues:Y}=J$($);for(let j=0;j<Y.length;j++){let X={};if(j===0&&J)X.config={description:J};this.options.output(Y[j],X)}}parseWebVTT($){$=$.replaceAll(`\r
9
+ `,`
10
+ `).replaceAll("\r",`
11
+ `),x8.lastIndex=0;let J;if(!this.preambleText){if(!p7.test($))throw Error("WebVTT preamble incorrect.");J=x8.exec($);let Y=$.slice(0,J?.index??$.length).trimEnd();if(!Y)throw Error("No WebVTT preamble provided.");if(this.preambleText=Y,J)$=$.slice(J.index),x8.lastIndex=0}while(J=x8.exec($)){let Y=$.slice(0,J.index),j=J[1],X=J.index+J[0].length,Z=$.indexOf(`
12
+ `,X)+1,G=$.slice(X,Z).trim(),K=$.indexOf(`
13
+
14
+ `,X);if(K===-1)K=$.length;let Q=I8(J[2]),U=I8(J[3])-Q,W=$.slice(Z,K).trim();$=$.slice(K).trimStart(),x8.lastIndex=0;let V={timestamp:Q/1000,duration:U/1000,text:W,identifier:j,settings:G,notes:Y},N={};if(!this.preambleEmitted)N.config={description:this.preambleText},this.preambleEmitted=!0;this.options.output(V,N)}}parseTx3g($){let J={config:{description:""}},Y={timestamp:0,duration:0,text:$.trim()};this.options.output(Y,J)}parseTtml($){let J=/<p[^>]*>(.*?)<\/p>/gs,Y=[...$.matchAll(J)];for(let j=0;j<Y.length;j++){let Z=Y[j][1]?.replace(/<[^>]+>/g,"")||"",G={};if(j===0)G.config={description:""};let K={timestamp:0,duration:0,text:Z.trim()};this.options.output(K,G)}}}var x8,p7,u1,l7,I8=($)=>{let J=l7.exec($);if(!J)throw Error("Expected match.");return 3600000*Number(J[1]||"0")+60000*Number(J[2])+1000*Number(J[3])+Number(J[4])},k1=($)=>{let J=Math.floor($/3600000),Y=Math.floor($%3600000/60000),j=Math.floor($%60000/1000),X=$%1000;return J.toString().padStart(2,"0")+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+"."+X.toString().padStart(3,"0")},m7,p6=($)=>{let J=m7.exec($);if(!J)throw Error("Invalid SRT timestamp format");let Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=Number(J[4]);return Y*3600+j*60+X+Z/1000},l6=($)=>{let J=Math.floor($/3600),Y=Math.floor($%3600/60),j=Math.floor($%60),X=Math.round($%1*1000);return J.toString().padStart(2,"0")+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+","+X.toString().padStart(3,"0")},$$=($)=>{$=$.replaceAll(`\r
15
+ `,`
16
+ `).replaceAll("\r",`
17
+ `);let J=[],Y=/(\d+)\n(\d{2}:\d{2}:\d{2},\d{3})\s+-->\s+(\d{2}:\d{2}:\d{2},\d{3})\n([\s\S]*?)(?=\n\n\d+\n|\n*$)/g,j;while(j=Y.exec($)){let X=p6(j[2]),Z=p6(j[3]),G=j[4].trim();J.push({timestamp:X,duration:Z-X,text:G,identifier:j[1]})}return J},q5=($)=>{if($.startsWith("Dialogue:")||$.startsWith("Comment:")){let Y=$.indexOf(":");if(Y===-1)return $;let X=$.substring(Y+1).split(",");if(X.length>=10)return X.slice(9).join(",")}let J=$.split(",");if(J.length>=8){let Y=J[0]?.trim(),j=J[1]?.trim();if(Y&&!Number.isNaN(Number.parseInt(Y,10))){if(j&&!Number.isNaN(Number.parseInt(j,10))&&J.length>=9)return J.slice(8).join(",");if(J.length>=8)return J.slice(7).join(",")}}return $},n6=($)=>{return $.map((J,Y)=>{let j=Y+1,X=l6(J.timestamp),Z=l6(J.timestamp+J.duration),G=q5(J.text);return`${j}
18
+ ${X} --> ${Z}
19
+ ${G}
20
+ `}).join(`
21
+ `)},o6=($,J)=>{let Y=J||`WEBVTT
22
+ `;if(!Y.endsWith(`
23
+
24
+ `))Y+=`
25
+ `;let j=$.map((X)=>{let Z=k1(X.timestamp*1000),G=k1((X.timestamp+X.duration)*1000),K=q5(X.text);return`${Z} --> ${G}
26
+ ${K}`});return Y+j.join(`
27
+
28
+ `)},d7,m6=($)=>{let J=d7.exec($);if(!J)throw Error("Invalid ASS timestamp format");let Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=Number(J[4]);return Y*3600+j*60+X+Z/100},d6=($)=>{let J=Math.floor($/3600),Y=Math.floor($%3600/60),j=Math.floor($%60),X=Math.floor($%1*100);return J.toString()+":"+Y.toString().padStart(2,"0")+":"+j.toString().padStart(2,"0")+"."+X.toString().padStart(2,"0")},J$=($)=>{$=$.replaceAll(`\r
29
+ `,`
30
+ `).replaceAll("\r",`
31
+ `);let J=$.split(`
32
+ `);if(J.findIndex((W)=>W.trim()==="[Events]")===-1)return{header:$,cues:[]};let j=[],X=[],Z=[],G=[],K=j,Q=!1;for(let W=0;W<J.length;W++){let V=J[W];if(V?.startsWith("[")&&V.endsWith("]")){if(V.trim()==="[Events]"){Q=!0,X.push(V);continue}if(Q)K=G,Q=!1;K.push(V);continue}if(Q){if(!V)continue;if(V.startsWith("Format:"))X.push(V);else if(V.startsWith("Dialogue:"))Z.push(V);else if(V.startsWith("Comment:"))X.push(V)}else if(V!==void 0)K.push(V)}let q=[...j,...X,...G].join(`
33
+ `),U=[];for(let W of Z){let V=W.indexOf(":");if(V===-1)continue;let N=W.substring(V+1).split(",");if(N.length<10)continue;try{let A=m6(N[1].trim()),R=m6(N[2].trim());U.push({timestamp:A,duration:R-A,text:W})}catch{}}return{header:q,cues:U}},c7=($)=>{let J=$.substring($.indexOf(":")+1).split(",").map((j)=>j.trim()),Y=new Map;return J.forEach((j,X)=>{Y.set(j,X)}),Y},Y$=($)=>{let J=/^(Dialogue|Comment):\s*(\d+),\d+:\d{2}:\d{2}\.\d{2},\d+:\d{2}:\d{2}\.\d{2},(.*)$/.exec($);if(J){let Y=J[2],j=J[3];return`${Y},${j}`}if($.startsWith("Dialogue:")||$.startsWith("Comment:"))return $.substring($.indexOf(":")+1).trim();return $},r6=($,J)=>{if(!J||J.trim()==="")J=`[Script Info]
34
+ Title: Default
35
+ ScriptType: v4.00+
36
+
37
+ [V4+ Styles]
38
+ Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
39
+ Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
40
+
41
+ [Events]
42
+ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text`;let Y=J.split(`
43
+ `),j=Y.findIndex((V)=>V.trim()==="[Events]");if(j===-1)return J+`
44
+
45
+ [Events]
46
+ Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
47
+ `+$.map((V)=>V.text).join(`
48
+ `);let X=-1,Z="";for(let V=j+1;V<Y.length;V++){let N=Y[V];if(N?.trim().startsWith("Format:")){X=V,Z=N;break}if(N?.startsWith("[")&&N.endsWith("]"))break}let G=Z?c7(Z):null,K=$.map((V)=>{if(V.text.startsWith("Dialogue:")||V.text.startsWith("Comment:")){if(/^(Dialogue|Comment):\s*\d+,\d+:\d{2}:\d{2}\.\d{2},\d+:\d{2}:\d{2}\.\d{2},/.test(V.text))return V.text}let N=V.text,R=N.startsWith("Comment:")?"Comment:":"Dialogue:";if(N.startsWith("Dialogue:")||N.startsWith("Comment:"))N=N.substring(N.indexOf(":")+1).trim();let z=N.split(","),_=d6(V.timestamp),L=d6(V.timestamp+V.duration),M,B,F=z.length>=9&&!Number.isNaN(Number.parseInt(z[0],10))&&!Number.isNaN(Number.parseInt(z[1],10)),C=z.length>=8&&!Number.isNaN(Number.parseInt(z[0],10));if(F)M=z[1]||"0",B=z.slice(2);else if(C)M=z[0]||"0",B=z.slice(1);else return`${R} 0,${_},${L},Default,,0,0,0,,${V.text}`;return`${R} ${M},${_},${L},${B.join(",")}`});if(X===-1)return`${J}
49
+ ${K.join(`
50
+ `)}`;let Q=[],q=Y.length;for(let V=X+1;V<Y.length;V++){let N=Y[V];if(N?.startsWith("Comment:"))Q.push(N);if(N?.startsWith("[")&&N.endsWith("]")){q=V;break}}let U=Y.slice(0,X+1),W=Y.slice(q);return[...U,...K,...Q,...W].join(`
51
+ `)};var x0=Q7(()=>{/*!
52
+ * Copyright (c) 2025-present, Vanilagy and contributors
53
+ *
54
+ * This Source Code Form is subject to the terms of the Mozilla Public
55
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
56
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
57
+ */x8=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,p7=/^WEBVTT(.|\n)*?\n{2}/,u1=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;l7=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,m7=/(\d{2}):(\d{2}):(\d{2}),(\d{3})/,d7=/(\d+):(\d{2}):(\d{2})\.(\d{2})/});/*!
58
+ * Copyright (c) 2025-present, Vanilagy and contributors
59
+ *
60
+ * This Source Code Form is subject to the terms of the Mozilla Public
61
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
62
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
63
+ */function H($){if(!$)throw Error("Assertion failed.")}var N1=($)=>{let J=($%360+360)%360;if(J===0||J===90||J===180||J===270)return J;throw Error(`Invalid rotation ${$}.`)},n=($)=>{return $&&$[$.length-1]},E1=($)=>{return $>=0&&$<4294967296};class f{bytes;pos=0;constructor($){this.bytes=$}seekToByte($){this.pos=8*$}readBit(){let $=Math.floor(this.pos/8),J=this.bytes[$]??0,Y=7-(this.pos&7),j=(J&1<<Y)>>Y;return this.pos++,j}readBits($){if($===1)return this.readBit();let J=0;for(let Y=0;Y<$;Y++)J<<=1,J|=this.readBit();return J}writeBits($,J){let Y=this.pos+$;for(let j=this.pos;j<Y;j++){let X=Math.floor(j/8),Z=this.bytes[X],G=7-(j&7);Z&=~(1<<G),Z|=(J&1<<Y-j-1)>>Y-j-1<<G,this.bytes[X]=Z}this.pos=Y}readAlignedByte(){if(this.pos%8!==0)throw Error("Bitstream is not byte-aligned.");let $=this.pos/8,J=this.bytes[$]??0;return this.pos+=8,J}skipBits($){this.pos+=$}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let $=new f(this.bytes);return $.pos=this.pos,$}}var E=($)=>{let J=0;while($.readBits(1)===0&&J<32)J++;if(J>=32)throw Error("Invalid exponential-Golomb code.");return(1<<J)-1+$.readBits(J)},m0=($)=>{let J=E($);return(J&1)===0?-(J>>1):J+1>>1},WJ=($,J,Y,j)=>{for(let X=J;X<Y;X++){let Z=Math.floor(X/8),G=$[Z],K=7-(X&7);G&=~(1<<K),G|=(j&1<<Y-X-1)>>Y-X-1<<K,$[Z]=G}},l=($)=>{if($.constructor===Uint8Array)return $;if(ArrayBuffer.isView($))return new Uint8Array($.buffer,$.byteOffset,$.byteLength);if(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)return new Uint8Array($);return new Uint8Array($)},h=($)=>{if($.constructor===DataView)return $;if(ArrayBuffer.isView($))return new DataView($.buffer,$.byteOffset,$.byteLength);if(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)return new DataView($);return new DataView($)},Y0=new TextDecoder,m=new TextEncoder,A1=($)=>{for(let J=0;J<$.length;J++)if($.charCodeAt(J)>255)return!1;return!0},I2=($)=>{return Object.fromEntries(Object.entries($).map(([J,Y])=>[Y,J]))},e0={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},X6=I2(e0),$1={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Z6=I2($1),J1={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},G6=I2(J1),K6=($)=>{return!!$&&!!$.primaries&&!!$.transfer&&!!$.matrix&&$.fullRange!==void 0},i1=($)=>{return $ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)};class w0{currentPromise=Promise.resolve();async acquire(){let $,J=new Promise((j)=>{$=j}),Y=this.currentPromise;return this.currentPromise=J,await Y,$}}var S2=($)=>{return[...$].map((J)=>J.toString(16).padStart(2,"0")).join("")},h2=($)=>{return $=$>>1&1431655765|($&1431655765)<<1,$=$>>2&858993459|($&858993459)<<2,$=$>>4&252645135|($&252645135)<<4,$=$>>8&16711935|($&16711935)<<8,$=$>>16&65535|($&65535)<<16,$>>>0},Y1=($,J,Y)=>{let j=0,X=$.length-1,Z=-1;while(j<=X){let G=j+X>>1,K=Y($[G]);if(K===J)Z=G,X=G-1;else if(K<J)j=G+1;else X=G-1}return Z},u=($,J,Y)=>{let j=0,X=$.length-1,Z=-1;while(j<=X){let G=j+(X-j+1)/2|0;if(Y($[G])<=J)Z=G,j=G+1;else X=G-1}return Z},f2=($,J,Y)=>{let j=u($,Y(J),Y);$.splice(j+1,0,J)},c=()=>{let $,J;return{promise:new Promise((j,X)=>{$=j,J=X}),resolve:$,reject:J}};var g2=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return $[Y];return},Q6=($,J)=>{for(let Y=$.length-1;Y>=0;Y--)if(J($[Y]))return Y;return-1},VJ=async function*($){if(Symbol.iterator in $)yield*$[Symbol.iterator]();else yield*$[Symbol.asyncIterator]()},HJ=($)=>{if(!(Symbol.iterator in $)&&!(Symbol.asyncIterator in $))throw TypeError("Argument must be an iterable or async iterable.")},i=($)=>{throw Error(`Unexpected value: ${$}`)},T1=($,J,Y)=>{let j=$.getUint8(J),X=$.getUint8(J+1),Z=$.getUint8(J+2);if(Y)return j|X<<8|Z<<16;return j<<16|X<<8|Z},NJ=($,J,Y)=>{return T1($,J,Y)<<8>>8},L8=($,J,Y,j)=>{if(Y=Y>>>0,Y=Y&16777215,j)$.setUint8(J,Y&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y>>>16&255);else $.setUint8(J,Y>>>16&255),$.setUint8(J+1,Y>>>8&255),$.setUint8(J+2,Y&255)},AJ=($,J,Y,j)=>{if(Y=$0(Y,-8388608,8388607),Y<0)Y=Y+16777216&16777215;L8($,J,Y,j)},RJ=($,J,Y,j)=>{if(j)$.setUint32(J+0,Y,!0),$.setInt32(J+4,Math.floor(Y/4294967296),!0);else $.setInt32(J+0,Math.floor(Y/4294967296),!0),$.setUint32(J+4,Y,!0)},M8=($,J)=>{return{async next(){let Y=await $.next();if(Y.done)return{value:void 0,done:!0};return{value:J(Y.value),done:!1}},return(){return $.return()},throw(Y){return $.throw(Y)},[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){await $.return()}}},$0=($,J,Y)=>{return Math.max(J,Math.min(Y,$))},a="und",y1=($)=>{let J=Math.round($);if(Math.abs($/J-1)<10*Number.EPSILON)return J;return $},F8=($,J)=>{return Math.round($/J)*J},zJ=($)=>{let J=0;while($)J++,$>>=1;return J},q7=/^[a-z]{3}$/,d0=($)=>{return q7.test($)},c0=1e6*(1+Number.EPSILON),k2=($,J)=>{let Y={...$,...J};if($.headers||J.headers){let j=$.headers?UJ($.headers):{},X=J.headers?UJ(J.headers):{},Z={...j};Object.entries(X).forEach(([G,K])=>{let Q=Object.keys(Z).find((q)=>q.toLowerCase()===G.toLowerCase());if(Q)delete Z[Q];Z[G]=K}),Y.headers=Z}return Y},UJ=($)=>{if($ instanceof Headers){let J={};return $.forEach((Y,j)=>{J[j]=Y}),J}if(Array.isArray($)){let J={};return $.forEach(([Y,j])=>{J[Y]=j}),J}return $},u2=async($,J,Y,j,X)=>{let Z=0;while(!0)try{return await $(J,Y)}catch(G){if(X())throw G;Z++;let K=j(Z,G,J);if(K===null)throw G;if(console.error("Retrying failed fetch. Error:",G),!Number.isFinite(K)||K<0)throw TypeError("Retry delay must be a non-negative finite number.");if(K>0)await new Promise((Q)=>setTimeout(Q,1000*K));if(X())throw G}},_J=($,J)=>{let Y=$<0?-1:1;$=Math.abs($);let j=0,X=1,Z=1,G=0,K=$;while(!0){let Q=Math.floor(K),q=Q*Z+j,U=Q*G+X;if(U>J)return{numerator:Y*Z,denominator:G};if(j=Z,X=G,Z=q,G=U,K=1/(K-Q),!isFinite(K))break}return{numerator:Y*Z,denominator:G}};class v1{currentPromise=Promise.resolve();call($){return this.currentPromise=this.currentPromise.then($)}}var y2=null,s1=()=>{if(y2!==null)return y2;return y2=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))},v2=null,n0=()=>{if(v2!==null)return v2;return v2=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox")},b2=null,B8=()=>{if(b2!==null)return b2;return b2=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))},x2=null,LJ=()=>{if(x2!==null)return x2;if(typeof navigator>"u")return null;let $=/\bChrome\/(\d+)/.exec(navigator.userAgent);if(!$)return null;return x2=Number($[1])},b1=($,J)=>{return $!==-1?$:J},q6=($,J,Y,j)=>{return $<=j&&Y<=J},v0=function*($){for(let J in $){let Y=$[J];if(Y===void 0)continue;yield{key:J,value:Y}}},MJ=($)=>{switch($.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}},FJ=($)=>{let J=atob($),Y=new Uint8Array(J.length);for(let j=0;j<J.length;j++)Y[j]=J.charCodeAt(j);return Y},BJ=($)=>{let J="";for(let Y=0;Y<$.length;Y++)J+=String.fromCharCode($[Y]);return btoa(J)},wJ=($,J)=>{if($.length!==J.length)return!1;for(let Y=0;Y<$.length;Y++)if($[Y]!==J[Y])return!1;return!0},U6=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},R1=($)=>{return typeof $==="number"&&!Number.isNaN($)};/*!
64
+ * Copyright (c) 2025-present, Vanilagy and contributors
65
+ *
66
+ * This Source Code Form is subject to the terms of the Mozilla Public
67
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
68
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
69
+ */var j0=["avc","hevc","vp9","av1","vp8","mpeg4"],o=["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"],X1=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Z0=[...X1,...o],z0=["webvtt","tx3g","ttml","srt","ass","ssa"],OJ=[{maxMacroblocks:99,maxBitrate:64000,level:10},{maxMacroblocks:396,maxBitrate:192000,level:11},{maxMacroblocks:396,maxBitrate:384000,level:12},{maxMacroblocks:396,maxBitrate:768000,level:13},{maxMacroblocks:396,maxBitrate:2000000,level:20},{maxMacroblocks:792,maxBitrate:4000000,level:21},{maxMacroblocks:1620,maxBitrate:4000000,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14000000,level:31},{maxMacroblocks:5120,maxBitrate:20000000,level:32},{maxMacroblocks:8192,maxBitrate:20000000,level:40},{maxMacroblocks:8192,maxBitrate:50000000,level:41},{maxMacroblocks:8704,maxBitrate:50000000,level:42},{maxMacroblocks:22080,maxBitrate:135000000,level:50},{maxMacroblocks:36864,maxBitrate:240000000,level:51},{maxMacroblocks:36864,maxBitrate:240000000,level:52},{maxMacroblocks:139264,maxBitrate:240000000,level:60},{maxMacroblocks:139264,maxBitrate:480000000,level:61},{maxMacroblocks:139264,maxBitrate:800000000,level:62}],PJ=[{maxPictureSize:36864,maxBitrate:128000,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:1500000,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3000000,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6000000,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12000000,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:30000000,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:20000000,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:50000000,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25000000,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:40000000,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:160000000,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:60000000,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:240000000,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:60000000,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:120000000,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:480000000,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:240000000,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:186}],j1=[{maxPictureSize:36864,maxBitrate:200000,level:10},{maxPictureSize:73728,maxBitrate:800000,level:11},{maxPictureSize:122880,maxBitrate:1800000,level:20},{maxPictureSize:245760,maxBitrate:3600000,level:21},{maxPictureSize:552960,maxBitrate:7200000,level:30},{maxPictureSize:983040,maxBitrate:12000000,level:31},{maxPictureSize:2228224,maxBitrate:18000000,level:40},{maxPictureSize:2228224,maxBitrate:30000000,level:41},{maxPictureSize:8912896,maxBitrate:60000000,level:50},{maxPictureSize:8912896,maxBitrate:120000000,level:51},{maxPictureSize:8912896,maxBitrate:180000000,level:52},{maxPictureSize:35651584,maxBitrate:180000000,level:60},{maxPictureSize:35651584,maxBitrate:240000000,level:61},{maxPictureSize:35651584,maxBitrate:480000000,level:62}],CJ=[{maxPictureSize:147456,maxBitrate:1500000,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3000000,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6000000,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12000000,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:30000000,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:20000000,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:50000000,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:30000000,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:40000000,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:160000000,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:60000000,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:240000000,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:60000000,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:60000000,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:240000000,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:480000000,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:160000000,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:160000000,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:800000000,tier:"H",level:19}],DJ=".01.01.01.01.00",EJ=".0.110.01.01.01.0",TJ=($,J,Y,j)=>{if($==="avc"){let Z=Math.ceil(J/16)*Math.ceil(Y/16),G=OJ.find((W)=>Z<=W.maxMacroblocks&&j<=W.maxBitrate)??n(OJ),K=G?G.level:0,Q=100 .toString(16).padStart(2,"0"),q="00",U=K.toString(16).padStart(2,"0");return`avc1.${Q}00${U}`}if($==="hevc"){let K=J*Y,Q=PJ.find((U)=>K<=U.maxPictureSize&&j<=U.maxBitrate)??n(PJ),q="B0";return`hev1.1.6.${Q.tier}${Q.level}.B0`}if($==="vp8")return"vp8";if($==="vp9"){let Z=J*Y,G=j1.find((Q)=>Z<=Q.maxPictureSize&&j<=Q.maxBitrate)??n(j1),K="08";return`vp09.00.${G.level.toString().padStart(2,"0")}.08`}if($==="av1"){let Z=J*Y,G=CJ.find((q)=>Z<=q.maxPictureSize&&j<=q.maxBitrate)??n(CJ),K=G.level.toString().padStart(2,"0"),Q="08";return`av01.0.${K}${G.tier}.08`}if($==="mpeg4")return"mp4v.20.9";throw TypeError(`Unhandled codec '${$}'.`)},yJ=($)=>{let J=$.split("."),Y=Number(J[1]),j=Number(J[2]),X=Number(J[3]),Z=J[4]?Number(J[4]):1;return[1,1,Y,2,1,j,3,1,X,4,1,Z]},W6=($)=>{let J=$.split("."),Y=1,j=1,X=129,Z=Number(J[1]),G=J[2],K=Number(G.slice(0,-1)),Q=(Z<<5)+K,q=G.slice(-1)==="H"?1:0,W=Number(J[3])===8?0:1,V=0,N=J[4]?Number(J[4]):0,A=J[5]?Number(J[5][0]):1,R=J[5]?Number(J[5][1]):1,z=J[5]?Number(J[5][2]):0,_=(q<<7)+(W<<6)+0+(N<<4)+(A<<3)+(R<<2)+z,L=0,M=0;return[129,Q,_,0]},V6=($)=>{let{codec:J,codecDescription:Y,colorSpace:j,avcCodecInfo:X,hevcCodecInfo:Z,vp9CodecInfo:G,av1CodecInfo:K}=$;if(J==="avc"){if(H($.avcType!==null),X){let Q=new Uint8Array([X.avcProfileIndication,X.profileCompatibility,X.avcLevelIndication]);return`avc${$.avcType}.${S2(Q)}`}if(!Y||Y.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${$.avcType}.${S2(Y.subarray(1,4))}`}if(J==="hevc"){let Q,q,U,W,V,N;if(Z)Q=Z.generalProfileSpace,q=Z.generalProfileIdc,U=h2(Z.generalProfileCompatibilityFlags),W=Z.generalTierFlag,V=Z.generalLevelIdc,N=[...Z.generalConstraintIndicatorFlags];else{if(!Y||Y.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let R=h(Y),z=R.getUint8(1);Q=z>>6&3,q=z&31,U=h2(R.getUint32(2)),W=z>>5&1,V=R.getUint8(12),N=[];for(let _=0;_<6;_++)N.push(R.getUint8(6+_))}let A="hev1.";A+=["","A","B","C"][Q]+q,A+=".",A+=U.toString(16).toUpperCase(),A+=".",A+=W===0?"L":"H",A+=V;while(N.length>0&&N[N.length-1]===0)N.pop();if(N.length>0)A+=".",A+=N.map((R)=>R.toString(16).toUpperCase()).join(".");return A}if(J==="vp8")return"vp8";if(J==="vp9"){if(!G){let _=$.width*$.height,L=n(j1).level;for(let M of j1)if(_<=M.maxPictureSize){L=M.level;break}return`vp09.00.${L.toString().padStart(2,"0")}.08`}let Q=G.profile.toString().padStart(2,"0"),q=G.level.toString().padStart(2,"0"),U=G.bitDepth.toString().padStart(2,"0"),W=G.chromaSubsampling.toString().padStart(2,"0"),V=G.colourPrimaries.toString().padStart(2,"0"),N=G.transferCharacteristics.toString().padStart(2,"0"),A=G.matrixCoefficients.toString().padStart(2,"0"),R=G.videoFullRangeFlag.toString().padStart(2,"0"),z=`vp09.${Q}.${q}.${U}.${W}`;if(z+=`.${V}.${N}.${A}.${R}`,z.endsWith(DJ))z=z.slice(0,-DJ.length);return z}if(J==="av1"){if(!K){let M=$.width*$.height,B=n(j1).level;for(let F of j1)if(M<=F.maxPictureSize){B=F.level;break}return`av01.0.${B.toString().padStart(2,"0")}M.08`}let Q=K.profile,q=K.level.toString().padStart(2,"0"),U=K.tier?"H":"M",W=K.bitDepth.toString().padStart(2,"0"),V=K.monochrome?"1":"0",N=100*K.chromaSubsamplingX+10*K.chromaSubsamplingY+1*(K.chromaSubsamplingX&&K.chromaSubsamplingY?K.chromaSamplePosition:0),A=j?.primaries?e0[j.primaries]:1,R=j?.transfer?$1[j.transfer]:1,z=j?.matrix?J1[j.matrix]:1,_=j?.fullRange?1:0,L=`av01.${Q}.${q}${U}.${W}`;if(L+=`.${V}.${N.toString().padStart(3,"0")}`,L+=`.${A.toString().padStart(2,"0")}`,L+=`.${R.toString().padStart(2,"0")}`,L+=`.${z.toString().padStart(2,"0")}`,L+=`.${_}`,L.endsWith(EJ))L=L.slice(0,-EJ.length);return L}if(J==="mpeg4")return"mp4v";throw TypeError(`Unhandled codec '${J}'.`)},vJ=($,J,Y)=>{if($==="aac"){if(J>=2&&Y<=24000)return"mp4a.40.29";if(Y<=24000)return"mp4a.40.5";return"mp4a.40.2"}if($==="mp3")return"mp3";if($==="opus")return"opus";if($==="vorbis")return"vorbis";if($==="flac")return"flac";if($==="ac3")return"ac-3";if($==="eac3")return"ec-3";if(o.includes($))return $;throw TypeError(`Unhandled codec '${$}'.`)},H6=($)=>{let{codec:J,codecDescription:Y,aacCodecInfo:j}=$;if(J==="aac"){if(!j)throw TypeError("AAC codec info must be provided.");if(j.isMpeg2)return"mp4a.67";return`mp4a.40.${x1(Y).objectType}`}if(J==="mp3")return"mp3";if(J==="opus")return"opus";if(J==="vorbis")return"vorbis";if(J==="flac")return"flac";if(J==="ac3")return"ac3";if(J==="eac3")return"ec-3";if(J&&o.includes(J))return J;throw TypeError(`Unhandled codec '${J}'.`)},a1=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],N6=[-1,1,2,3,4,5,6,8],x1=($)=>{if(!$||$.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let J=new f($),Y=J.readBits(5);if(Y===31)Y=32+J.readBits(6);let j=J.readBits(4),X=null;if(j===15)X=J.readBits(24);else if(j<a1.length)X=a1[j];let Z=J.readBits(4),G=null;if(Z>=1&&Z<=7)G=N6[Z];return{objectType:Y,frequencyIndex:j,sampleRate:X,channelConfiguration:Z,numberOfChannels:G}},bJ=($)=>{let J=a1.indexOf($.sampleRate),Y=null;if(J===-1)J=15,Y=$.sampleRate;let j=N6.indexOf($.numberOfChannels);if(j===-1)throw TypeError(`Unsupported number of channels: ${$.numberOfChannels}`);let X=13;if($.objectType>=32)X+=6;if(J===15)X+=24;let Z=Math.ceil(X/8),G=new Uint8Array(Z),K=new f(G);if($.objectType<32)K.writeBits(5,$.objectType);else K.writeBits(5,31),K.writeBits(6,$.objectType-32);if(K.writeBits(4,J),J===15)K.writeBits(24,Y);return K.writeBits(4,j),G},b0=48000,xJ=/^pcm-([usf])(\d+)+(be)?$/,U0=($)=>{if(H(o.includes($)),$==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if($==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let J=xJ.exec($);H(J);let Y;if(J[1]==="u")Y="unsigned";else if(J[1]==="s")Y="signed";else Y="float";let j=Number(J[2])/8,X=J[3]!=="be";return{dataType:Y,sampleSize:j,littleEndian:X,silentValue:$==="pcm-u8"?128:0}},p2=($)=>{if($.startsWith("avc1")||$.startsWith("avc3"))return"avc";if($.startsWith("hev1")||$.startsWith("hvc1"))return"hevc";if($==="vp8")return"vp8";if($.startsWith("vp09"))return"vp9";if($.startsWith("av01"))return"av1";if($==="mp4v"||$.startsWith("mp4v."))return"mpeg4";if($.startsWith("mp4a.40")||$==="mp4a.67")return"aac";if($==="mp3"||$==="mp4a.69"||$==="mp4a.6B"||$==="mp4a.6b")return"mp3";if($==="opus")return"opus";if($==="vorbis")return"vorbis";if($==="flac")return"flac";if($==="ac-3"||$==="ac3")return"ac3";if($==="ec-3"||$==="eac3")return"eac3";if($==="ulaw")return"ulaw";if($==="alaw")return"alaw";if(xJ.test($))return $;if($==="webvtt")return"webvtt";if($==="srt")return"srt";if($==="ass")return"ass";if($==="ssa")return"ssa";return null},IJ=($)=>{if($==="avc")return{avc:{format:"avc"}};if($==="hevc")return{hevc:{format:"hevc"}};return{}},SJ=($)=>{if($==="aac")return{aac:{format:"aac"}};if($==="opus")return{opus:{format:"opus"}};return{}},U7=["avc1","avc3","hev1","hvc1","vp8","vp09","av01","mp4v"],W7=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,V7=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,H7=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,N7=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,t1=($)=>{if(!$)throw TypeError("Video chunk metadata must be provided.");if(typeof $!=="object")throw TypeError("Video chunk metadata must be an object.");if(!$.decoderConfig)throw TypeError("Video chunk metadata must include a decoder configuration.");if(typeof $.decoderConfig!=="object")throw TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof $.decoderConfig.codec!=="string")throw TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!U7.some((J)=>$.decoderConfig.codec.startsWith(J)))throw TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger($.decoderConfig.codedWidth)||$.decoderConfig.codedWidth<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger($.decoderConfig.codedHeight)||$.decoderConfig.codedHeight<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if($.decoderConfig.description!==void 0){if(!i1($.decoderConfig.description))throw TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.")}if($.decoderConfig.colorSpace!==void 0){let{colorSpace:J}=$.decoderConfig;if(typeof J!=="object")throw TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let Y=Object.keys(e0);if(J.primaries!=null&&!Y.includes(J.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${Y.join(", ")}.`);let j=Object.keys($1);if(J.transfer!=null&&!j.includes(J.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${j.join(", ")}.`);let X=Object.keys(J1);if(J.matrix!=null&&!X.includes(J.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${X.join(", ")}.`);if(J.fullRange!=null&&typeof J.fullRange!=="boolean")throw TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if($.decoderConfig.codec.startsWith("avc1")||$.decoderConfig.codec.startsWith("avc3")){if(!W7.test($.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($.decoderConfig.codec.startsWith("hev1")||$.decoderConfig.codec.startsWith("hvc1")){if(!V7.test($.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($.decoderConfig.codec.startsWith("vp8")){if($.decoderConfig.codec!=="vp8")throw TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if($.decoderConfig.codec.startsWith("vp09")){if(!H7.test($.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($.decoderConfig.codec.startsWith("av01")){if(!N7.test($.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/.')}else if($.decoderConfig.codec==="mp4v"||$.decoderConfig.codec.startsWith("mp4v.")){if($.decoderConfig.codec!=="mp4v")throw TypeError('Video chunk metadata decoder configuration codec string for MPEG-4 must be "mp4v".')}},A7=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],_0=($)=>{if(!$)throw TypeError("Audio chunk metadata must be provided.");if(typeof $!=="object")throw TypeError("Audio chunk metadata must be an object.");if(!$.decoderConfig)throw TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof $.decoderConfig!=="object")throw TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof $.decoderConfig.codec!=="string")throw TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!A7.some((J)=>$.decoderConfig.codec.startsWith(J)))throw TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger($.decoderConfig.sampleRate)||$.decoderConfig.sampleRate<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger($.decoderConfig.numberOfChannels)||$.decoderConfig.numberOfChannels<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if($.decoderConfig.description!==void 0){if(!i1($.decoderConfig.description))throw TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.")}if($.decoderConfig.codec.startsWith("mp4a")&&$.decoderConfig.codec!=="mp4a.69"&&$.decoderConfig.codec!=="mp4a.6B"&&$.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes($.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/.");if(!$.decoderConfig.description)throw TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if($.decoderConfig.codec.startsWith("mp3")||$.decoderConfig.codec.startsWith("mp4a")){if($.decoderConfig.codec!=="mp3"&&$.decoderConfig.codec!=="mp4a.69"&&$.decoderConfig.codec!=="mp4a.6B"&&$.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($.decoderConfig.codec.startsWith("opus")){if($.decoderConfig.codec!=="opus")throw TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if($.decoderConfig.description&&$.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($.decoderConfig.codec.startsWith("vorbis")){if($.decoderConfig.codec!=="vorbis")throw TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!$.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($.decoderConfig.codec.startsWith("flac")){if($.decoderConfig.codec!=="flac")throw TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');let J=42;if(!$.decoderConfig.description||$.decoderConfig.description.byteLength<J)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($.decoderConfig.codec==="ac-3"||$.decoderConfig.codec==="ac3"){if($.decoderConfig.codec!=="ac-3")throw TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if($.decoderConfig.codec==="ec-3"||$.decoderConfig.codec==="eac3"){if($.decoderConfig.codec!=="ec-3")throw TypeError('Audio chunk metadata decoder configuration codec string for E-AC-3 must be "ec-3".')}else if($.decoderConfig.codec.startsWith("pcm")||$.decoderConfig.codec.startsWith("ulaw")||$.decoderConfig.codec.startsWith("alaw")){if(!o.includes($.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${o.join(", ")}).`)}},A6=($)=>{if(!$)throw TypeError("Subtitle metadata must be provided.");if(typeof $!=="object")throw TypeError("Subtitle metadata must be an object.");if(!$.config)throw TypeError("Subtitle metadata must include a config object.");if(typeof $.config!=="object")throw TypeError("Subtitle metadata config must be an object.");if(typeof $.config.description!=="string")throw TypeError("Subtitle metadata config description must be a string.")};/*!
70
+ * Copyright (c) 2025-present, Vanilagy and contributors
71
+ *
72
+ * This Source Code Form is subject to the terms of the Mozilla Public
73
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
74
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
75
+ */class l2{codec;config;onSample;static supports($,J){return!1}}class m2{codec;config;onSample;static supports($,J){return!1}}class d2{codec;config;onPacket;static supports($,J){return!1}}class c2{codec;config;onPacket;static supports($,J){return!1}}var e1=[],$8=[],I1=[],S1=[],R7=($)=>{if($.prototype instanceof l2){let J=$;if(e1.includes(J)){console.warn("Video decoder already registered.");return}e1.push(J)}else if($.prototype instanceof m2){let J=$;if($8.includes(J)){console.warn("Audio decoder already registered.");return}$8.push(J)}else throw TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},z7=($)=>{if($.prototype instanceof d2){let J=$;if(I1.includes(J)){console.warn("Video encoder already registered.");return}I1.push(J)}else if($.prototype instanceof c2){let J=$;if(S1.includes(J)){console.warn("Audio encoder already registered.");return}S1.push(J)}else throw TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};/*!
76
+ * Copyright (c) 2025-present, Vanilagy and contributors
77
+ *
78
+ * This Source Code Form is subject to the terms of the Mozilla Public
79
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
80
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
81
+ */var _6=($)=>{if(!$||typeof $!=="object")throw TypeError("Encoding config must be an object.");if(!j0.includes($.codec))throw TypeError(`Invalid video codec '${$.codec}'. Must be one of: ${j0.join(", ")}.`);if(!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("config.bitrate must be a positive integer or a quality.");if($.keyFrameInterval!==void 0&&(!Number.isFinite($.keyFrameInterval)||$.keyFrameInterval<0))throw TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if($.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes($.sizeChangeBehavior))throw TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if($.onEncodedPacket!==void 0&&typeof $.onEncodedPacket!=="function")throw TypeError("config.onEncodedChunk, when provided, must be a function.");if($.onEncoderConfig!==void 0&&typeof $.onEncoderConfig!=="function")throw TypeError("config.onEncoderConfig, when provided, must be a function.");hJ($.codec,$)},hJ=($,J)=>{if(!J||typeof J!=="object")throw TypeError("Encoding options must be an object.");if(J.alpha!==void 0&&!["discard","keep"].includes(J.alpha))throw TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(J.bitrateMode!==void 0&&!["constant","variable"].includes(J.bitrateMode))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(J.latencyMode!==void 0&&!["quality","realtime"].includes(J.latencyMode))throw TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(J.fullCodecString!==void 0&&typeof J.fullCodecString!=="string")throw TypeError("fullCodecString, when provided, must be a string.");if(J.fullCodecString!==void 0&&p2(J.fullCodecString)!==$)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${$}).`);if(J.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(J.hardwareAcceleration))throw TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(J.scalabilityMode!==void 0&&typeof J.scalabilityMode!=="string")throw TypeError("scalabilityMode, when provided, must be a string.");if(J.contentHint!==void 0&&typeof J.contentHint!=="string")throw TypeError("contentHint, when provided, must be a string.")},R6=($)=>{let J=$.bitrate instanceof N0?$.bitrate._toVideoBitrate($.codec,$.width,$.height):$.bitrate;return{codec:$.fullCodecString??TJ($.codec,$.width,$.height,J),width:$.width,height:$.height,bitrate:J,bitrateMode:$.bitrateMode,alpha:$.alpha??"discard",framerate:$.framerate,latencyMode:$.latencyMode,hardwareAcceleration:$.hardwareAcceleration,scalabilityMode:$.scalabilityMode,contentHint:$.contentHint,...IJ($.codec)}},L6=($)=>{if(!$||typeof $!=="object")throw TypeError("Encoding config must be an object.");if(!Z0.includes($.codec))throw TypeError(`Invalid audio codec '${$.codec}'. Must be one of: ${Z0.join(", ")}.`);if($.bitrate===void 0&&(!o.includes($.codec)||$.codec==="flac"))throw TypeError("config.bitrate must be provided for compressed audio codecs.");if($.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if($.onEncodedPacket!==void 0&&typeof $.onEncodedPacket!=="function")throw TypeError("config.onEncodedChunk, when provided, must be a function.");if($.onEncoderConfig!==void 0&&typeof $.onEncoderConfig!=="function")throw TypeError("config.onEncoderConfig, when provided, must be a function.");fJ($.codec,$)},fJ=($,J)=>{if(!J||typeof J!=="object")throw TypeError("Encoding options must be an object.");if(J.bitrateMode!==void 0&&!["constant","variable"].includes(J.bitrateMode))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(J.fullCodecString!==void 0&&typeof J.fullCodecString!=="string")throw TypeError("fullCodecString, when provided, must be a string.");if(J.fullCodecString!==void 0&&p2(J.fullCodecString)!==$)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${$}).`)},z6=($)=>{let J=$.bitrate instanceof N0?$.bitrate._toAudioBitrate($.codec):$.bitrate;return{codec:$.fullCodecString??vJ($.codec,$.numberOfChannels,$.sampleRate),numberOfChannels:$.numberOfChannels,sampleRate:$.sampleRate,bitrate:J,bitrateMode:$.bitrateMode,...SJ($.codec)}};class N0{_factor;constructor($){this._factor=$}_toVideoBitrate($,J,Y){let j=J*Y,X={avc:1,hevc:0.6,vp9:0.6,av1:0.4,vp8:1.2,mpeg4:1.5},Z=2073600,G=3000000,U=3000000*(j/2073600)**0.95*X[$]*this._factor;return Math.ceil(U/1000)*1000}_toAudioBitrate($){if(o.includes($)||$==="flac")return;let Y={aac:128000,opus:64000,mp3:160000,vorbis:64000,ac3:640000,eac3:256000}[$];if(!Y)throw Error(`Unhandled codec: ${$}`);let j=Y*this._factor;if($==="aac")j=[96000,128000,160000,192000].reduce((Z,G)=>Math.abs(G-j)<Math.abs(Z-j)?G:Z);else if($==="opus"||$==="vorbis")j=Math.max(6000,j);else if($==="mp3")j=[8000,16000,24000,32000,40000,48000,64000,80000,96000,112000,128000,160000,192000,224000,256000,320000].reduce((Z,G)=>Math.abs(G-j)<Math.abs(Z-j)?G:Z);return Math.round(j/1000)*1000}}var _7=new N0(0.3),L7=new N0(0.6),M7=new N0(1),M6=new N0(2),F7=new N0(4),B7=($)=>{if(j0.includes($))return F6($);if(Z0.includes($))return B6($);if(z0.includes($))return w6($);throw TypeError(`Unknown codec '${$}'.`)},F6=async($,J={})=>{let{width:Y=1280,height:j=720,bitrate:X=1e6,...Z}=J;if(!j0.includes($))return!1;if(!Number.isInteger(Y)||Y<=0)throw TypeError("width must be a positive integer.");if(!Number.isInteger(j)||j<=0)throw TypeError("height must be a positive integer.");if(!(X instanceof N0)&&(!Number.isInteger(X)||X<=0))throw TypeError("bitrate must be a positive integer or a quality.");hJ($,Z);let G=null;if(I1.length>0){if(G??=R6({codec:$,width:Y,height:j,bitrate:X,framerate:void 0,...Z}),I1.some((q)=>q.supports($,G)))return!0}if(typeof VideoEncoder>"u")return!1;if((Y%2===1||j%2===1)&&($==="avc"||$==="hevc"))return!1;if(G??=R6({codec:$,width:Y,height:j,bitrate:X,framerate:void 0,...Z,alpha:"discard"}),!(await VideoEncoder.isConfigSupported(G)).supported)return!1;if(n0())return new Promise(async(q)=>{try{let U=new VideoEncoder({output:()=>{},error:()=>q(!1)});U.configure(G);let W=new Uint8Array(Y*j*4),V=new VideoFrame(W,{format:"RGBA",codedWidth:Y,codedHeight:j,timestamp:0});U.encode(V),V.close(),await U.flush(),q(!0)}catch{q(!1)}});else return!0},B6=async($,J={})=>{let{numberOfChannels:Y=2,sampleRate:j=48000,bitrate:X=128000,...Z}=J;if(!Z0.includes($))return!1;if(!Number.isInteger(Y)||Y<=0)throw TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(j)||j<=0)throw TypeError("sampleRate must be a positive integer.");if(!(X instanceof N0)&&(!Number.isInteger(X)||X<=0))throw TypeError("bitrate must be a positive integer.");fJ($,Z);let G=null;if(S1.length>0){if(G??=z6({codec:$,numberOfChannels:Y,sampleRate:j,bitrate:X,...Z}),S1.some((Q)=>Q.supports($,G)))return!0}if(o.includes($))return!0;if(typeof AudioEncoder>"u")return!1;return G??=z6({codec:$,numberOfChannels:Y,sampleRate:j,bitrate:X,...Z}),(await AudioEncoder.isConfigSupported(G)).supported===!0},w6=async($)=>{if(!z0.includes($))return!1;return!0},w7=async()=>{let[$,J,Y]=await Promise.all([gJ(),w8(),kJ()]);return[...$,...J,...Y]},gJ=async($=j0,J)=>{let Y=await Promise.all($.map((j)=>F6(j,J)));return $.filter((j,X)=>Y[X])},w8=async($=Z0,J)=>{let Y=await Promise.all($.map((j)=>B6(j,J)));return $.filter((j,X)=>Y[X])},kJ=async($=z0)=>{let J=await Promise.all($.map(w6));return $.filter((Y,j)=>J[j])},n2=async($,J)=>{for(let Y of $)if(await F6(Y,J))return Y;return null},O7=async($,J)=>{for(let Y of $)if(await B6(Y,J))return Y;return null},P7=async($)=>{for(let J of $)if(await w6(J))return J;return null};/*!
82
+ * Copyright (c) 2025-present, Vanilagy and contributors
83
+ *
84
+ * This Source Code Form is subject to the terms of the Mozilla Public
85
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
86
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
87
+ */var O6=4,C7=[44100,48000,32000],P6=[-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],J8=1483304551,C6=1231971951,D6=($,J,Y,j,X)=>{if(J===0)return 0;if(J===1)return Math.floor(144*Y/(j<<$))+X;if(J===2)return Math.floor(144*Y/j)+X;return(Math.floor(12*Y/j)+X)*4},Y8=($,J)=>{return $===3?J===3?21:36:J===3?13:21},E6=($,J)=>{let Y=$>>>24,j=$>>>16&255,X=$>>>8&255,Z=$&255;if(Y!==255&&j!==255&&X!==255&&Z!==255)return{header:null,bytesAdvanced:4};if(Y!==255)return{header:null,bytesAdvanced:1};if((j&224)!==224)return{header:null,bytesAdvanced:1};let G=0,K=0;if(j&16)G=j&8?0:1;else G=1,K=1;let Q=j>>3&3,q=j>>1&3,U=X>>4&15,W=(X>>2&3)%3,V=X>>1&1,N=Z>>6&3,A=Z>>4&3,R=Z>>3&1,z=Z>>2&1,_=Z&3,L=P6[G*16*4+q*16+U];if(L===-1)return{header:null,bytesAdvanced:1};let M=L*1000,B=C7[W]>>G+K,F=D6(G,q,M,B,V);if(J!==null&&J<F)return{header:null,bytesAdvanced:1};let C;if(Q===3)C=q===3?384:1152;else if(q===3)C=384;else if(q===2)C=1152;else C=576;return{header:{totalSize:F,mpegVersionId:Q,layer:q,bitrate:M,frequencyIndex:W,sampleRate:B,channel:N,modeExtension:A,copyright:R,original:z,emphasis:_,audioSamplesInFrame:C},bytesAdvanced:1}},uJ=($)=>{let J=127,Y=0,j=$;while((J^2147483647)!==0)Y=j&~J,Y<<=1,Y|=j&J,J=(J+1<<8)-1,j=Y;return Y},T6=($)=>{let J=2130706432,Y=0;while(J!==0)Y>>=1,Y|=$&J,J>>=8;return Y};/*!
88
+ * Copyright (c) 2025-present, Vanilagy and contributors
89
+ *
90
+ * This Source Code Form is subject to the terms of the Mozilla Public
91
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
92
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
93
+ */class W0{input;constructor($){this.input=$}}/*!
94
+ * Copyright (c) 2025-present, Vanilagy and contributors
95
+ *
96
+ * This Source Code Form is subject to the terms of the Mozilla Public
97
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
98
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
99
+ */var O8=($)=>{let J=[],Y=0;while(Y<$.length){let j=-1,X=0;for(let Z=Y;Z<$.length-3;Z++){if($[Z]===0&&$[Z+1]===0&&$[Z+2]===1){j=Z,X=3;break}if(Z<$.length-4&&$[Z]===0&&$[Z+1]===0&&$[Z+2]===0&&$[Z+3]===1){j=Z,X=4;break}}if(j===-1)break;if(Y>0&&j>Y){let Z=$.subarray(Y,j);if(Z.length>0)J.push(Z)}Y=j+X}if(Y<$.length){let j=$.subarray(Y);if(j.length>0)J.push(j)}return J},lJ=($,J)=>{let Y=[],j=0,X=new DataView($.buffer,$.byteOffset,$.byteLength);while(j+J<=$.length){let Z;if(J===1)Z=X.getUint8(j);else if(J===2)Z=X.getUint16(j,!1);else if(J===3)Z=T1(X,j,!1);else if(J===4)Z=X.getUint32(j,!1);else i(J),H(!1);j+=J;let G=$.subarray(j,j+Z);Y.push(G),j+=Z}return Y},y6=($)=>{let J=[],Y=$.length;for(let j=0;j<Y;j++)if(j+2<Y&&$[j]===0&&$[j+1]===0&&$[j+2]===3)J.push(0,0),j+=2;else J.push($[j]);return new Uint8Array(J)},o2=new Uint8Array([0,0,0,1]),D7=($)=>{let J=$.reduce((X,Z)=>X+o2.byteLength+Z.byteLength,0),Y=new Uint8Array(J),j=0;for(let X of $)Y.set(o2,j),j+=o2.byteLength,Y.set(X,j),j+=X.byteLength;return Y},mJ=($,J)=>{let Y=$.reduce((Z,G)=>Z+J+G.byteLength,0),j=new Uint8Array(Y),X=0;for(let Z of $){let G=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(J){case 1:G.setUint8(X,Z.byteLength);break;case 2:G.setUint16(X,Z.byteLength,!1);break;case 3:L8(G,X,Z.byteLength,!1);break;case 4:G.setUint32(X,Z.byteLength,!1);break}X+=J,j.set(Z,X),X+=Z.byteLength}return j},dJ=($)=>{let J=O8($);if(J.length===0)return null;return mJ(J,4)},r2=($,J)=>{if(J.description){let X=(l(J.description)[4]&3)+1;return lJ($,X)}return O8($)},cJ=($,J)=>{if(J.description){let X=(l(J.description)[4]&3)+1;return mJ($,X)}else return D7($)},h1=($)=>{return $[0]&31},v6=($)=>{try{let J=O8($),Y=J.filter((Q)=>h1(Q)===7),j=J.filter((Q)=>h1(Q)===8),X=J.filter((Q)=>h1(Q)===13);if(Y.length===0)return null;if(j.length===0)return null;let Z=Y[0],G=i2(Z);H(G!==null);let K=G.profileIdc===100||G.profileIdc===110||G.profileIdc===122||G.profileIdc===144;return{configurationVersion:1,avcProfileIndication:G.profileIdc,profileCompatibility:G.constraintFlags,avcLevelIndication:G.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:Y,pictureParameterSets:j,chromaFormat:K?G.chromaFormatIdc:null,bitDepthLumaMinus8:K?G.bitDepthLumaMinus8:null,bitDepthChromaMinus8:K?G.bitDepthChromaMinus8:null,sequenceParameterSetExt:K?X:null}}catch(J){return console.error("Error building AVC Decoder Configuration Record:",J),null}},nJ=($)=>{let J=[];J.push($.configurationVersion),J.push($.avcProfileIndication),J.push($.profileCompatibility),J.push($.avcLevelIndication),J.push(252|$.lengthSizeMinusOne&3),J.push(224|$.sequenceParameterSets.length&31);for(let Y of $.sequenceParameterSets){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}J.push($.pictureParameterSets.length);for(let Y of $.pictureParameterSets){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}if($.avcProfileIndication===100||$.avcProfileIndication===110||$.avcProfileIndication===122||$.avcProfileIndication===144){H($.chromaFormat!==null),H($.bitDepthLumaMinus8!==null),H($.bitDepthChromaMinus8!==null),H($.sequenceParameterSetExt!==null),J.push(252|$.chromaFormat&3),J.push(248|$.bitDepthLumaMinus8&7),J.push(248|$.bitDepthChromaMinus8&7),J.push($.sequenceParameterSetExt.length);for(let Y of $.sequenceParameterSetExt){let j=Y.byteLength;J.push(j>>8),J.push(j&255);for(let X=0;X<j;X++)J.push(Y[X])}}return new Uint8Array(J)},oJ=($)=>{try{let J=h($),Y=0,j=J.getUint8(Y++),X=J.getUint8(Y++),Z=J.getUint8(Y++),G=J.getUint8(Y++),K=J.getUint8(Y++)&3,Q=J.getUint8(Y++)&31,q=[];for(let N=0;N<Q;N++){let A=J.getUint16(Y,!1);Y+=2,q.push($.subarray(Y,Y+A)),Y+=A}let U=J.getUint8(Y++),W=[];for(let N=0;N<U;N++){let A=J.getUint16(Y,!1);Y+=2,W.push($.subarray(Y,Y+A)),Y+=A}let V={configurationVersion:j,avcProfileIndication:X,profileCompatibility:Z,avcLevelIndication:G,lengthSizeMinusOne:K,sequenceParameterSets:q,pictureParameterSets:W,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((X===100||X===110||X===122||X===144)&&Y+4<=$.length){let N=J.getUint8(Y++)&3,A=J.getUint8(Y++)&7,R=J.getUint8(Y++)&7,z=J.getUint8(Y++);V.chromaFormat=N,V.bitDepthLumaMinus8=A,V.bitDepthChromaMinus8=R;let _=[];for(let L=0;L<z;L++){let M=J.getUint16(Y,!1);Y+=2,_.push($.subarray(Y,Y+M)),Y+=M}V.sequenceParameterSetExt=_}return V}catch(J){return console.error("Error deserializing AVC Decoder Configuration Record:",J),null}},i2=($)=>{try{let J=new f(y6($));if(J.skipBits(1),J.skipBits(2),J.readBits(5)!==7)return null;let j=J.readAlignedByte(),X=J.readAlignedByte(),Z=J.readAlignedByte();E(J);let G=null,K=null,Q=null;if(j===100||j===110||j===122||j===244||j===44||j===83||j===86||j===118||j===128){if(G=E(J),G===3)J.skipBits(1);if(K=E(J),Q=E(J),J.skipBits(1),J.readBits(1)){for(let V=0;V<(G!==3?8:12);V++)if(J.readBits(1)){let A=V<6?16:64,R=8,z=8;for(let _=0;_<A;_++){if(z!==0){let L=m0(J);z=(R+L+256)%256}R=z===0?R:z}}}}E(J);let q=E(J);if(q===0)E(J);else if(q===1){J.skipBits(1),m0(J),m0(J);let W=E(J);for(let V=0;V<W;V++)m0(J)}E(J),J.skipBits(1),E(J),E(J);let U=J.readBits(1);return{profileIdc:j,constraintFlags:X,levelIdc:Z,frameMbsOnlyFlag:U,chromaFormatIdc:G,bitDepthLumaMinus8:K,bitDepthChromaMinus8:Q}}catch(J){return console.error("Error parsing AVC SPS:",J),null}},s2=($,J)=>{if(J.description){let X=(l(J.description)[21]&3)+1;return lJ($,X)}return O8($)},Z1=($)=>{return $[0]>>1&63},b6=($)=>{try{let J=O8($),Y=J.filter((S)=>Z1(S)===32),j=J.filter((S)=>Z1(S)===33),X=J.filter((S)=>Z1(S)===34),Z=J.filter((S)=>Z1(S)===39||Z1(S)===40);if(j.length===0||X.length===0)return null;let G=j[0],K=new f(y6(G));K.skipBits(16),K.readBits(4);let Q=K.readBits(3),q=K.readBits(1),{general_profile_space:U,general_tier_flag:W,general_profile_idc:V,general_profile_compatibility_flags:N,general_constraint_indicator_flags:A,general_level_idc:R}=E7(K,Q);E(K);let z=E(K);if(z===3)K.skipBits(1);if(E(K),E(K),K.readBits(1))E(K),E(K),E(K),E(K);let _=E(K),L=E(K);E(K);let B=K.readBits(1)?0:Q;for(let S=B;S<=Q;S++)E(K),E(K),E(K);if(E(K),E(K),E(K),E(K),E(K),E(K),K.readBits(1)){if(K.readBits(1))T7(K)}if(K.skipBits(1),K.skipBits(1),K.readBits(1))K.skipBits(4),K.skipBits(4),E(K),E(K),K.skipBits(1);let F=E(K);if(y7(K,F),K.readBits(1)){let S=E(K);for(let T=0;T<S;T++)E(K),K.skipBits(1)}K.skipBits(1),K.skipBits(1);let C=0;if(K.readBits(1))C=b7(K,Q);let w=0;if(X.length>0){let S=X[0],T=new f(y6(S));if(T.skipBits(16),E(T),E(T),T.skipBits(1),T.skipBits(1),T.skipBits(3),T.skipBits(1),T.skipBits(1),E(T),E(T),m0(T),T.skipBits(1),T.skipBits(1),T.readBits(1))E(T);m0(T),m0(T),T.skipBits(1),T.skipBits(1),T.skipBits(1),T.skipBits(1);let r=T.readBits(1),H0=T.readBits(1);if(!r&&!H0)w=0;else if(r&&!H0)w=2;else if(!r&&H0)w=3;else w=0}let v=[...Y.length?[{arrayCompleteness:1,nalUnitType:32,nalUnits:Y}]:[],...j.length?[{arrayCompleteness:1,nalUnitType:33,nalUnits:j}]:[],...X.length?[{arrayCompleteness:1,nalUnitType:34,nalUnits:X}]:[],...Z.length?[{arrayCompleteness:1,nalUnitType:Z1(Z[0]),nalUnits:Z}]:[]];return{configurationVersion:1,generalProfileSpace:U,generalTierFlag:W,generalProfileIdc:V,generalProfileCompatibilityFlags:N,generalConstraintIndicatorFlags:A,generalLevelIdc:R,minSpatialSegmentationIdc:C,parallelismType:w,chromaFormatIdc:z,bitDepthLumaMinus8:_,bitDepthChromaMinus8:L,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:Q+1,temporalIdNested:q,lengthSizeMinusOne:3,arrays:v}}catch(J){return console.error("Error building HEVC Decoder Configuration Record:",J),null}},E7=($,J)=>{let Y=$.readBits(2),j=$.readBits(1),X=$.readBits(5),Z=0;for(let U=0;U<32;U++)Z=Z<<1|$.readBits(1);let G=new Uint8Array(6);for(let U=0;U<6;U++)G[U]=$.readBits(8);let K=$.readBits(8),Q=[],q=[];for(let U=0;U<J;U++)Q.push($.readBits(1)),q.push($.readBits(1));if(J>0)for(let U=J;U<8;U++)$.skipBits(2);for(let U=0;U<J;U++){if(Q[U])$.skipBits(88);if(q[U])$.skipBits(8)}return{general_profile_space:Y,general_tier_flag:j,general_profile_idc:X,general_profile_compatibility_flags:Z,general_constraint_indicator_flags:G,general_level_idc:K}},T7=($)=>{for(let J=0;J<4;J++)for(let Y=0;Y<(J===3?2:6);Y++)if(!$.readBits(1))E($);else{let X=Math.min(64,1<<4+(J<<1));if(J>1)m0($);for(let Z=0;Z<X;Z++)m0($)}},y7=($,J)=>{let Y=[];for(let j=0;j<J;j++)Y[j]=v7($,j,J,Y)},v7=($,J,Y,j)=>{let X=0,Z=0,G=0;if(J!==0)Z=$.readBits(1);if(Z){if(J===Y){let Q=E($);G=J-(Q+1)}else G=J-1;$.readBits(1),E($);let K=j[G]??0;for(let Q=0;Q<=K;Q++)if(!$.readBits(1))$.readBits(1);X=j[G]}else{let K=E($),Q=E($);for(let q=0;q<K;q++)E($),$.readBits(1);for(let q=0;q<Q;q++)E($),$.readBits(1);X=K+Q}return X},b7=($,J)=>{if($.readBits(1)){if($.readBits(8)===255)$.readBits(16),$.readBits(16)}if($.readBits(1))$.readBits(1);if($.readBits(1)){if($.readBits(3),$.readBits(1),$.readBits(1))$.readBits(8),$.readBits(8),$.readBits(8)}if($.readBits(1))E($),E($);if($.readBits(1),$.readBits(1),$.readBits(1),$.readBits(1))E($),E($),E($),E($);if($.readBits(1)){if($.readBits(32),$.readBits(32),$.readBits(1))E($);if($.readBits(1))x7($,!0,J)}if($.readBits(1)){$.readBits(1),$.readBits(1),$.readBits(1);let Y=E($);return E($),E($),E($),E($),Y}return 0},x7=($,J,Y)=>{let j=!1,X=!1,Z=!1;if(J){if(j=$.readBits(1)===1,X=$.readBits(1)===1,j||X){if(Z=$.readBits(1)===1,Z)$.readBits(8),$.readBits(5),$.readBits(1),$.readBits(5);if($.readBits(4),$.readBits(4),Z)$.readBits(4);$.readBits(5),$.readBits(5),$.readBits(5)}}for(let G=0;G<=Y;G++){let K=$.readBits(1)===1,Q=!0;if(!K)Q=$.readBits(1)===1;let q=!1;if(Q)E($);else q=$.readBits(1)===1;let U=1;if(!q)U=E($)+1;if(j)pJ($,U,Z);if(X)pJ($,U,Z)}},pJ=($,J,Y)=>{for(let j=0;j<J;j++){if(E($),E($),Y)E($),E($);$.readBits(1)}},rJ=($)=>{let J=[];J.push($.configurationVersion),J.push(($.generalProfileSpace&3)<<6|($.generalTierFlag&1)<<5|$.generalProfileIdc&31),J.push($.generalProfileCompatibilityFlags>>>24&255),J.push($.generalProfileCompatibilityFlags>>>16&255),J.push($.generalProfileCompatibilityFlags>>>8&255),J.push($.generalProfileCompatibilityFlags&255),J.push(...$.generalConstraintIndicatorFlags),J.push($.generalLevelIdc&255),J.push(240|$.minSpatialSegmentationIdc>>8&15),J.push($.minSpatialSegmentationIdc&255),J.push(252|$.parallelismType&3),J.push(252|$.chromaFormatIdc&3),J.push(248|$.bitDepthLumaMinus8&7),J.push(248|$.bitDepthChromaMinus8&7),J.push($.avgFrameRate>>8&255),J.push($.avgFrameRate&255),J.push(($.constantFrameRate&3)<<6|($.numTemporalLayers&7)<<3|($.temporalIdNested&1)<<2|$.lengthSizeMinusOne&3),J.push($.arrays.length&255);for(let Y of $.arrays){J.push((Y.arrayCompleteness&1)<<7|0|Y.nalUnitType&63),J.push(Y.nalUnits.length>>8&255),J.push(Y.nalUnits.length&255);for(let j of Y.nalUnits){J.push(j.length>>8&255),J.push(j.length&255);for(let X=0;X<j.length;X++)J.push(j[X])}}return new Uint8Array(J)},x6=($)=>{let J=new f($);if(J.readBits(2)!==2)return null;let j=J.readBits(1),Z=(J.readBits(1)<<1)+j;if(Z===3)J.skipBits(1);if(J.readBits(1)===1)return null;if(J.readBits(1)!==0)return null;if(J.skipBits(2),J.readBits(24)!==4817730)return null;let q=8;if(Z>=2)q=J.readBits(1)?12:10;let U=J.readBits(3),W=0,V=0;if(U!==7)if(V=J.readBits(1),Z===1||Z===3){let w=J.readBits(1),v=J.readBits(1);W=!w&&!v?3:w&&!v?2:1,J.skipBits(1)}else W=1;else W=3,V=1;let N=J.readBits(16),A=J.readBits(16),R=N+1,z=A+1,_=R*z,L=n(j1).level;for(let C of j1)if(_<=C.maxPictureSize){L=C.level;break}return{profile:Z,level:L,bitDepth:q,chromaSubsampling:W,videoFullRangeFlag:V,colourPrimaries:U===2?1:U===1?6:2,transferCharacteristics:U===2?1:U===1?6:2,matrixCoefficients:U===7?0:U===2?1:U===1?6:2}},iJ=function*($){let J=new f($),Y=()=>{let j=0;for(let X=0;X<8;X++){let Z=J.readAlignedByte();if(j|=(Z&127)<<X*7,!(Z&128))break;if(X===7&&Z&128)return null}if(j>=4294967295)return null;return j};while(J.getBitsLeft()>=8){J.skipBits(1);let j=J.readBits(4),X=J.readBits(1),Z=J.readBits(1);if(J.skipBits(1),X)J.skipBits(8);let G;if(Z){let K=Y();if(K===null)return;G=K}else G=Math.floor(J.getBitsLeft()/8);H(J.pos%8===0),yield{type:j,data:$.subarray(J.pos/8,J.pos/8+G)},J.skipBits(G*8)}},I6=($)=>{for(let{type:J,data:Y}of iJ($)){if(J!==1)continue;let j=new f(Y),X=j.readBits(3),Z=j.readBits(1),G=j.readBits(1),K=0,Q=0,q=0;if(G)K=j.readBits(5);else{if(j.readBits(1)){if(j.skipBits(32),j.skipBits(32),j.readBits(1))return null}let C=j.readBits(1);if(C)q=j.readBits(5),j.skipBits(32),j.skipBits(5),j.skipBits(5);let w=j.readBits(5);for(let v=0;v<=w;v++){j.skipBits(12);let k=j.readBits(5);if(v===0)K=k;if(k>7){let T=j.readBits(1);if(v===0)Q=T}if(C){if(j.readBits(1)){let r=q+1;j.skipBits(r),j.skipBits(r),j.skipBits(1)}}if(j.readBits(1))j.skipBits(4)}}let U=j.readBits(4),W=j.readBits(4),V=U+1;j.skipBits(V);let N=W+1;j.skipBits(N);let A=0;if(G)A=0;else A=j.readBits(1);if(A)j.skipBits(4),j.skipBits(3);if(j.skipBits(1),j.skipBits(1),j.skipBits(1),!G){j.skipBits(1),j.skipBits(1),j.skipBits(1),j.skipBits(1);let F=j.readBits(1);if(F)j.skipBits(1),j.skipBits(1);let C=j.readBits(1),w=0;if(C)w=2;else w=j.readBits(1);if(w>0){if(!j.readBits(1))j.skipBits(1)}if(F)j.skipBits(3)}j.skipBits(1),j.skipBits(1),j.skipBits(1);let R=j.readBits(1),z=8;if(X===2&&R)z=j.readBits(1)?12:10;else if(X<=2)z=R?10:8;let _=0;if(X!==1)_=j.readBits(1);let L=1,M=1,B=0;if(!_){if(X===0)L=1,M=1;else if(X===1)L=0,M=0;else if(z===12){if(L=j.readBits(1),L)M=j.readBits(1)}if(L&&M)B=j.readBits(2)}return{profile:X,level:K,tier:Q,bitDepth:z,monochrome:_,chromaSubsamplingX:L,chromaSubsamplingY:M,chromaSamplePosition:B}}return null},z1=($)=>{let J=h($),Y=J.getUint8(9),j=J.getUint16(10,!0),X=J.getUint32(12,!0),Z=J.getInt16(16,!0),G=J.getUint8(18),K=null;if(G)K=$.subarray(19,21+Y);return{outputChannelCount:Y,preSkip:j,inputSampleRate:X,outputGain:Z,channelMappingFamily:G,channelMappingTable:K}},I7=[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],sJ=($)=>{let J=$[0]>>3;return{durationInSamples:I7[J]}},S6=($)=>{if($.length<7)throw Error("Setup header is too short.");if($[0]!==5)throw Error("Wrong packet type in Setup header.");if(String.fromCharCode(...$.slice(1,7))!=="vorbis")throw Error("Invalid packet signature in Setup header.");let Y=$.length,j=new Uint8Array(Y);for(let W=0;W<Y;W++)j[W]=$[Y-1-W];let X=new f(j),Z=0;while(X.getBitsLeft()>97)if(X.readBits(1)===1){Z=X.pos;break}if(Z===0)throw Error("Invalid Setup header: framing bit not found.");let G=0,K=!1,Q=0;while(X.getBitsLeft()>=97){let W=X.pos,V=X.readBits(8),N=X.readBits(16),A=X.readBits(16);if(V>63||N!==0||A!==0){X.pos=W;break}if(X.skipBits(1),G++,G>64)break;if(X.clone().readBits(6)+1===G)K=!0,Q=G}if(!K)throw Error("Invalid Setup header: mode header not found.");if(Q>63)throw Error(`Unsupported mode count: ${Q}.`);let q=Q;X.pos=0,X.skipBits(Z);let U=Array(q).fill(0);for(let W=q-1;W>=0;W--)X.skipBits(40),U[W]=X.readBits(1);return{modeBlockflags:U}},h6=($,J,Y)=>{switch($){case"avc":{let j=r2(Y,J),X=j.some((Z)=>h1(Z)===5);if(!X&&(!B8()||LJ()>=144))for(let Z of j){if(h1(Z)!==6)continue;let K=y6(Z),Q=1;do{let q=0;while(!0){let V=K[Q++];if(V===void 0)break;if(q+=V,V<255)break}let U=0;while(!0){let V=K[Q++];if(V===void 0)break;if(U+=V,V<255)break}if(q===6){let V=new f(K);V.pos=8*Q;let N=E(V),A=V.readBits(1);if(N===0&&A===1){X=!0;break}}Q+=U}while(Q<K.length-1)}return X?"key":"delta"}case"hevc":return s2(Y,J).some((Z)=>{let G=Z1(Z);return 16<=G&&G<=23})?"key":"delta";case"vp8":return(Y[0]&1)===0?"key":"delta";case"vp9":{let j=new f(Y);if(j.readBits(2)!==2)return null;let X=j.readBits(1);if((j.readBits(1)<<1)+X===3)j.skipBits(1);if(j.readBits(1))return null;return j.readBits(1)===0?"key":"delta"}case"av1":{let j=!1;for(let{type:X,data:Z}of iJ(Y))if(X===1){let G=new f(Z);G.skipBits(4),j=!!G.readBits(1)}else if(X===3||X===6||X===7){if(j)return"key";let G=new f(Z);if(G.readBits(1))return null;return G.readBits(2)===0?"key":"delta"}return null}case"mpeg4":{for(let j=0;j<Y.length-4;j++)if(Y[j]===0&&Y[j+1]===0&&Y[j+2]===1&&Y[j+3]===182)return(Y[j+4]>>6&3)===0?"key":"delta";return null}default:i($),H(!1)}};var P8=($,J)=>{let Y=h($),j=0,X=Y.getUint32(j,!0);j+=4;let Z=Y0.decode($.subarray(j,j+X));if(j+=X,X>0)J.raw??={},J.raw.vendor??=Z;let G=Y.getUint32(j,!0);j+=4;for(let K=0;K<G;K++){let Q=Y.getUint32(j,!0);j+=4;let q=Y0.decode($.subarray(j,j+Q));j+=Q;let U=q.indexOf("=");if(U===-1)continue;let W=q.slice(0,U).toUpperCase(),V=q.slice(U+1);switch(J.raw??={},J.raw[W]??=V,W){case"TITLE":J.title??=V;break;case"DESCRIPTION":J.description??=V;break;case"ARTIST":J.artist??=V;break;case"ALBUM":J.album??=V;break;case"ALBUMARTIST":J.albumArtist??=V;break;case"COMMENT":J.comment??=V;break;case"LYRICS":J.lyrics??=V;break;case"TRACKNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.trackNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.tracksTotal??=R}break;case"TRACKTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.tracksTotal??=N}break;case"DISCNUMBER":{let N=V.split("/"),A=Number.parseInt(N[0],10),R=N[1]&&Number.parseInt(N[1],10);if(Number.isInteger(A)&&A>0)J.discNumber??=A;if(R&&Number.isInteger(R)&&R>0)J.discsTotal??=R}break;case"DISCTOTAL":{let N=Number.parseInt(V,10);if(Number.isInteger(N)&&N>0)J.discsTotal??=N}break;case"DATE":{let N=new Date(V);if(!Number.isNaN(N.getTime()))J.date??=N}break;case"GENRE":J.genre??=V;break;case"METADATA_BLOCK_PICTURE":{let N=FJ(V),A=h(N),R=A.getUint32(0,!1),z=A.getUint32(4,!1),_=String.fromCharCode(...N.subarray(8,8+z)),L=A.getUint32(8+z,!1),M=Y0.decode(N.subarray(12+z,12+z+L)),B=A.getUint32(z+L+28),F=N.subarray(z+L+32,z+L+32+B);J.images??=[],J.images.push({data:F,mimeType:_,kind:R===3?"coverFront":R===4?"coverBack":"unknown",name:void 0,description:M||void 0})}break}}},C8=($,J,Y)=>{let j=[$],X="Mediabunny",Z=m.encode("Mediabunny"),G=new Uint8Array(4+Z.length),K=new DataView(G.buffer);K.setUint32(0,Z.length,!0),G.set(Z,4),j.push(G);let Q=new Set,q=(A,R)=>{let z=`${A}=${R}`,_=m.encode(z);G=new Uint8Array(4+_.length),K=new DataView(G.buffer),K.setUint32(0,_.length,!0),G.set(_,4),j.push(G),Q.add(A)};for(let{key:A,value:R}of v0(J))switch(A){case"title":q("TITLE",R);break;case"description":q("DESCRIPTION",R);break;case"artist":q("ARTIST",R);break;case"album":q("ALBUM",R);break;case"albumArtist":q("ALBUMARTIST",R);break;case"genre":q("GENRE",R);break;case"date":{let z=J.raw?.DATE??J.raw?.date;if(z&&typeof z==="string")q("DATE",z);else q("DATE",R.toISOString().slice(0,10))}break;case"comment":q("COMMENT",R);break;case"lyrics":q("LYRICS",R);break;case"trackNumber":q("TRACKNUMBER",R.toString());break;case"tracksTotal":q("TRACKTOTAL",R.toString());break;case"discNumber":q("DISCNUMBER",R.toString());break;case"discsTotal":q("DISCTOTAL",R.toString());break;case"images":{if(!Y)break;for(let z of R){let _=z.kind==="coverFront"?3:z.kind==="coverBack"?4:0,L=new Uint8Array(z.mimeType.length);for(let w=0;w<z.mimeType.length;w++)L[w]=z.mimeType.charCodeAt(w);let M=m.encode(z.description??""),B=new Uint8Array(8+L.length+4+M.length+16+4+z.data.length),F=h(B);F.setUint32(0,_,!1),F.setUint32(4,L.length,!1),B.set(L,8),F.setUint32(8+L.length,M.length,!1),B.set(M,12+L.length),F.setUint32(28+L.length+M.length,z.data.length,!1),B.set(z.data,32+L.length+M.length);let C=BJ(B);q("METADATA_BLOCK_PICTURE",C)}}break;case"raw":break;default:i(A)}if(J.raw)for(let A in J.raw){let R=J.raw[A]??J.raw[A.toLowerCase()];if(A==="vendor"||R==null||Q.has(A))continue;if(typeof R==="string")q(A,R)}let U=new Uint8Array(4);h(U).setUint32(0,Q.size,!0),j.splice(2,0,U);let W=j.reduce((A,R)=>A+R.length,0),V=new Uint8Array(W),N=0;for(let A of j)V.set(A,N),N+=A.length;return V};/*!
100
+ * Copyright (c) 2025-present, Vanilagy and contributors
101
+ *
102
+ * This Source Code Form is subject to the terms of the Mozilla Public
103
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
104
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
105
+ */var G0=new Uint8Array(0);class I{data;type;timestamp;duration;sequenceNumber;byteLength;sideData;constructor($,J,Y,j,X=-1,Z,G){this.data=$;this.type=J;this.timestamp=Y;this.duration=j;this.sequenceNumber=X;if($===G0&&Z===void 0)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(Z===void 0)Z=$.byteLength;if(!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(J!=="key"&&J!=="delta")throw TypeError('type must be either "key" or "delta".');if(!Number.isFinite(Y))throw TypeError("timestamp must be a number.");if(!Number.isFinite(j)||j<0)throw TypeError("duration must be a non-negative number.");if(!Number.isFinite(X))throw TypeError("sequenceNumber must be a number.");if(!Number.isInteger(Z)||Z<0)throw TypeError("byteLength must be a non-negative integer.");if(G!==void 0&&(typeof G!=="object"||!G))throw TypeError("sideData, when provided, must be an object.");if(G?.alpha!==void 0&&!(G.alpha instanceof Uint8Array))throw TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(G?.alphaByteLength!==void 0&&(!Number.isInteger(G.alphaByteLength)||G.alphaByteLength<0))throw TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");if(this.byteLength=Z,this.sideData=G??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0)this.sideData.alphaByteLength=this.sideData.alpha.byteLength}get isMetadataOnly(){return this.data===G0}get microsecondTimestamp(){return Math.trunc(c0*this.timestamp)}get microsecondDuration(){return Math.trunc(c0*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk($=this.type){if(!this.sideData.alpha)throw TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:$,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk($,J){if(!($ instanceof EncodedVideoChunk||$ instanceof EncodedAudioChunk))throw TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let Y=new Uint8Array($.byteLength);return $.copyTo(Y),new I(Y,$.type,$.timestamp/1e6,($.duration??0)/1e6,void 0,void 0,J)}clone($){if($!==void 0&&(typeof $!=="object"||$===null))throw TypeError("options, when provided, must be an object.");if($?.timestamp!==void 0&&!Number.isFinite($.timestamp))throw TypeError("options.timestamp, when provided, must be a number.");if($?.duration!==void 0&&!Number.isFinite($.duration))throw TypeError("options.duration, when provided, must be a number.");return new I(this.data,this.type,$?.timestamp??this.timestamp,$?.duration??this.duration,this.sequenceNumber,this.byteLength)}}/*!
106
+ * Copyright (c) 2025-present, Vanilagy and contributors
107
+ *
108
+ * This Source Code Form is subject to the terms of the Mozilla Public
109
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
110
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
111
+ */var aJ=($)=>{let j=$,X=4096,Z=0,G=12,K=0;if(j<0)j=-j,Z=128;if(j+=33,j>8191)j=8191;while((j&X)!==X&&G>=5)X>>=1,G--;return K=j>>G-4&15,~(Z|G-5<<4|K)&255},tJ=($)=>{let Y=0,j=0,X=~$;if(X&128)X&=-129,Y=-1;j=((X&240)>>4)+5;let Z=(1<<j|(X&15)<<j-4|1<<j-5)-33;return Y===0?Z:-Z},eJ=($)=>{let Y=2048,j=0,X=11,Z=0,G=$;if(G<0)G=-G,j=128;if(G>4095)G=4095;while((G&Y)!==Y&&X>=5)Y>>=1,X--;return Z=G>>(X===4?1:X-4)&15,(j|X-4<<4|Z)^85},$5=($)=>{let J=0,Y=0,j=$^85;if(j&128)j&=-129,J=-1;Y=((j&240)>>4)+4;let X=0;if(Y!==4)X=1<<Y|(j&15)<<Y-4|1<<Y-5;else X=j<<1|1;return J===0?X:-X};/*!
112
+ * Copyright (c) 2025-present, Vanilagy and contributors
113
+ *
114
+ * This Source Code Form is subject to the terms of the Mozilla Public
115
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
116
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
117
+ */U6();var J5=-1/0,Y5=-1/0,y8=null;if(typeof FinalizationRegistry<"u")y8=new FinalizationRegistry(($)=>{let J=Date.now();if($.type==="video"){if(J-J5>=1000)console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),J5=J;if(typeof VideoFrame<"u"&&$.data instanceof VideoFrame)$.data.close()}else{if(J-Y5>=1000)console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Y5=J;if(typeof AudioData<"u"&&$.data instanceof AudioData)$.data.close()}});var t2=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],S7=new Set(t2);class J0{_data;_layout;_closed=!1;format;codedWidth;codedHeight;rotation;timestamp;duration;colorSpace;get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(c0*this.timestamp)}get microsecondDuration(){return Math.trunc(c0*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor($,J){if($ instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer||ArrayBuffer.isView($)){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.format===void 0||!S7.has(J.format))throw TypeError("init.format must be one of: "+t2.join(", "));if(!Number.isInteger(J.codedWidth)||J.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(J.codedHeight)||J.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=l($).slice(),this._layout=J.layout??f7(J.format,J.codedWidth,J.codedHeight),this.format=J.format,this.codedWidth=J.codedWidth,this.codedHeight=J.codedHeight,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new T8(J.colorSpace)}else if(typeof VideoFrame<"u"&&$ instanceof VideoFrame){if(J?.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(J?.timestamp!==void 0&&!Number.isFinite(J?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(J?.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");this._data=$,this._layout=null,this.format=$.format,this.codedWidth=$.displayWidth,this.codedHeight=$.displayHeight,this.rotation=J?.rotation??0,this.timestamp=J?.timestamp??$.timestamp/1e6,this.duration=J?.duration??($.duration??0)/1e6,this.colorSpace=new T8($.colorSpace)}else if(typeof HTMLImageElement<"u"&&$ instanceof HTMLImageElement||typeof SVGImageElement<"u"&&$ instanceof SVGImageElement||typeof ImageBitmap<"u"&&$ instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&$ instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas){if(!J||typeof J!=="object")throw TypeError("init must be an object.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(J.timestamp))throw TypeError("init.timestamp must be a number.");if(J.duration!==void 0&&(!Number.isFinite(J.duration)||J.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new J0(new VideoFrame($,{timestamp:Math.trunc(J.timestamp*c0),duration:Math.trunc((J.duration??0)*c0)||void 0}),J);let Y=0,j=0;if("naturalWidth"in $)Y=$.naturalWidth,j=$.naturalHeight;else if("videoWidth"in $)Y=$.videoWidth,j=$.videoHeight;else if("width"in $)Y=Number($.width),j=Number($.height);if(!Y||!j)throw TypeError("Could not determine dimensions.");let X=new OffscreenCanvas(Y,j),Z=X.getContext("2d",{alpha:n0(),willReadFrequently:!0});H(Z),Z.drawImage($,0,0),this._data=X,this._layout=null,this.format="RGBX",this.codedWidth=Y,this.codedHeight=j,this.rotation=J.rotation??0,this.timestamp=J.timestamp,this.duration=J.duration??0,this.colorSpace=new T8({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");y8?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),f1(this._data))return new J0(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation});if(this._data instanceof Uint8Array)return H(this._layout),new J0(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});return new J0(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){if(this._closed)return;if(y8?.unregister(this),f1(this._data))this._data.close();else this._data=null;this._closed=!0}allocationSize($={}){if(h7($),this._closed)throw Error("VideoSample is closed.");if(($.format??this.format)===null)throw Error("Cannot get allocation size when format is null. Please manually provide an RGB pixel format in the options instead.");if(H(this._data!==null),!f1(this._data)){if($.colorSpace||$.format&&$.format!==this.format||$.layout||$.rect){let J=this.toVideoFrame(),Y=J.allocationSize($);return J.close(),Y}}if(f1(this._data))return this._data.allocationSize($);if(this._data instanceof Uint8Array)return this._data.byteLength;return this.codedWidth*this.codedHeight*4}async copyTo($,J={}){if(!i1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw Error("VideoSample is closed.");if((J.format??this.format)===null)throw Error("Cannot copy video sample data when format is null. Please manually provide an RGB pixel format in the options instead.");if(H(this._data!==null),!f1(this._data)){if(J.colorSpace||J.format&&J.format!==this.format||J.layout||J.rect){let Y=this.toVideoFrame(),j=await Y.copyTo($,J);return Y.close(),j}}if(f1(this._data))return this._data.copyTo($,J);else if(this._data instanceof Uint8Array)return H(this._layout),l($).set(this._data),this._layout;else{let j=this._data.getContext("2d");H(j);let X=j.getImageData(0,0,this.codedWidth,this.codedHeight);return l($).set(X.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),f1(this._data))return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0});if(this._data instanceof Uint8Array)return new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace});return new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw($,J,Y,j,X,Z,G,K,Q){let q=0,U=0,W=this.displayWidth,V=this.displayHeight,N=0,A=0,R=this.displayWidth,z=this.displayHeight;if(Z!==void 0)if(q=J,U=Y,W=j,V=X,N=Z,A=G,K!==void 0)R=K,z=Q;else R=W,z=V;else if(N=J,A=Y,j!==void 0)R=j,z=X;if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(q))throw TypeError("sx must be a number.");if(!Number.isFinite(U))throw TypeError("sy must be a number.");if(!Number.isFinite(W)||W<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(V)||V<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(N))throw TypeError("dx must be a number.");if(!Number.isFinite(A))throw TypeError("dy must be a number.");if(!Number.isFinite(R)||R<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(z)||z<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:q,sy:U,sWidth:W,sHeight:V}=this._rotateSourceRegion(q,U,W,V,this.rotation));let _=this.toCanvasImageSource();$.save();let L=N+R/2,M=A+z/2;$.translate(L,M),$.rotate(this.rotation*Math.PI/180);let B=this.rotation%180===0?1:R/z;$.scale(1/B,B),$.drawImage(_,q,U,W,V,-R/2,-z/2,R,z),$.restore()}drawWithFit($,J){if(!(typeof CanvasRenderingContext2D<"u"&&$ instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&$ instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(J.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");if(J.crop!==void 0)b8(J.crop,"options.");let Y=$.canvas.width,j=$.canvas.height,X=J.rotation??this.rotation,[Z,G]=X%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];if(J.crop)v8(J.crop,Z,G);let K,Q,q,U,{sx:W,sy:V,sWidth:N,sHeight:A}=this._rotateSourceRegion(J.crop?.left??0,J.crop?.top??0,J.crop?.width??Z,J.crop?.height??G,X);if(J.fit==="fill")K=0,Q=0,q=Y,U=j;else{let[z,_]=J.crop?[J.crop.width,J.crop.height]:[Z,G],L=J.fit==="contain"?Math.min(Y/z,j/_):Math.max(Y/z,j/_);q=z*L,U=_*L,K=(Y-q)/2,Q=(j-U)/2}$.save();let R=X%180===0?1:q/U;$.translate(Y/2,j/2),$.rotate(X*Math.PI/180),$.scale(1/R,R),$.translate(-Y/2,-j/2),$.drawImage(this.toCanvasImageSource(),W,V,N,A,K,Q,q,U),$.restore()}_rotateSourceRegion($,J,Y,j,X){if(X===90)[$,J,Y,j]=[J,this.codedHeight-$-Y,j,Y];else if(X===180)[$,J]=[this.codedWidth-$-Y,this.codedHeight-J-j];else if(X===270)[$,J,Y,j]=[this.codedWidth-J-j,$,j,Y];return{sx:$,sy:J,sWidth:Y,sHeight:j}}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(H(this._data!==null),this._data instanceof Uint8Array){let $=this.toVideoFrame();return queueMicrotask(()=>$.close()),$}return this._data}setRotation($){if(![0,90,180,270].includes($))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=$}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}setDuration($){if(!Number.isFinite($)||$<0)throw TypeError("newDuration must be a non-negative number.");this.duration=$}[Symbol.dispose](){this.close()}}class T8{primaries;transfer;matrix;fullRange;constructor($){this.primaries=$?.primaries??null,this.transfer=$?.transfer??null,this.matrix=$?.matrix??null,this.fullRange=$?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}var f1=($)=>{return typeof VideoFrame<"u"&&$ instanceof VideoFrame},v8=($,J,Y)=>{$.left=Math.min($.left,J),$.top=Math.min($.top,Y),$.width=Math.min($.width,J-$.left),$.height=Math.min($.height,Y-$.top),H($.width>=0),H($.height>=0)},b8=($,J)=>{if(!$||typeof $!=="object")throw TypeError(J+"crop, when provided, must be an object.");if(!Number.isInteger($.left)||$.left<0)throw TypeError(J+"crop.left must be a non-negative integer.");if(!Number.isInteger($.top)||$.top<0)throw TypeError(J+"crop.top must be a non-negative integer.");if(!Number.isInteger($.width)||$.width<0)throw TypeError(J+"crop.width must be a non-negative integer.");if(!Number.isInteger($.height)||$.height<0)throw TypeError(J+"crop.height must be a non-negative integer.")},h7=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.colorSpace!==void 0&&!["display-p3","srgb"].includes($.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if($.format!==void 0&&typeof $.format!=="string")throw TypeError("options.format, when provided, must be a string.");if($.layout!==void 0){if(!Array.isArray($.layout))throw TypeError("options.layout, when provided, must be an array.");for(let J of $.layout){if(!J||typeof J!=="object")throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(J.offset)||J.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(J.stride)||J.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if($.rect!==void 0){if(!$.rect||typeof $.rect!=="object")throw TypeError("options.rect, when provided, must be an object.");if($.rect.x!==void 0&&(!Number.isInteger($.rect.x)||$.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if($.rect.y!==void 0&&(!Number.isInteger($.rect.y)||$.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if($.rect.width!==void 0&&(!Number.isInteger($.rect.width)||$.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if($.rect.height!==void 0&&(!Number.isInteger($.rect.height)||$.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},f7=($,J,Y)=>{let j=g7($),X=[],Z=0;for(let G of j){let K=Math.ceil(J/G.widthDivisor),Q=Math.ceil(Y/G.heightDivisor),q=K*G.sampleBytes,U=q*Q;X.push({offset:Z,stride:q}),Z+=U}return X},g7=($)=>{let J=(Y,j,X,Z,G)=>{let K=[{sampleBytes:Y,widthDivisor:1,heightDivisor:1},{sampleBytes:j,widthDivisor:X,heightDivisor:Z},{sampleBytes:j,widthDivisor:X,heightDivisor:Z}];if(G)K.push({sampleBytes:Y,widthDivisor:1,heightDivisor:1});return K};switch($){case"I420":return J(1,1,2,2,!1);case"I420P10":case"I420P12":return J(2,2,2,2,!1);case"I420A":return J(1,1,2,2,!0);case"I420AP10":case"I420AP12":return J(2,2,2,2,!0);case"I422":return J(1,1,2,1,!1);case"I422P10":case"I422P12":return J(2,2,2,1,!1);case"I422A":return J(1,1,2,1,!0);case"I422AP10":case"I422AP12":return J(2,2,2,1,!0);case"I444":return J(1,1,1,1,!1);case"I444P10":case"I444P12":return J(2,2,1,1,!1);case"I444A":return J(1,1,1,1,!0);case"I444AP10":case"I444AP12":return J(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:i($),H(!1)}},a2=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class K0{_data;_closed=!1;format;sampleRate;numberOfFrames;numberOfChannels;duration;timestamp;get microsecondTimestamp(){return Math.trunc(c0*this.timestamp)}get microsecondDuration(){return Math.trunc(c0*this.duration)}constructor($){if(E8($)){if($.format===null)throw TypeError("AudioData with null format is not supported.");this._data=$,this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=$.numberOfFrames,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp/1e6,this.duration=$.numberOfFrames/$.sampleRate}else{if(!$||typeof $!=="object")throw TypeError("Invalid AudioDataInit: must be an object.");if(!a2.has($.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite($.sampleRate)||$.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger($.numberOfChannels)||$.numberOfChannels===0)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite($?.timestamp))throw TypeError("init.timestamp must be a number.");let J=$.data.byteLength/(D8($.format)*$.numberOfChannels);if(!Number.isInteger(J))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=$.format,this.sampleRate=$.sampleRate,this.numberOfFrames=J,this.numberOfChannels=$.numberOfChannels,this.timestamp=$.timestamp,this.duration=J/$.sampleRate;let Y;if($.data instanceof ArrayBuffer)Y=new Uint8Array($.data);else if(ArrayBuffer.isView($.data))Y=new Uint8Array($.data.buffer,$.data.byteOffset,$.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let j=this.numberOfFrames*this.numberOfChannels*D8(this.format);if(Y.byteLength<j)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=Y}y8?.register(this,{type:"audio",data:this._data},this)}allocationSize($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Number.isInteger($.planeIndex)||$.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if($.format!==void 0&&!a2.has($.format))throw TypeError("Invalid format.");if($.frameOffset!==void 0&&(!Number.isInteger($.frameOffset)||$.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if($.frameCount!==void 0&&(!Number.isInteger($.frameCount)||$.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let J=$.format??this.format,Y=$.frameOffset??0;if(Y>=this.numberOfFrames)throw RangeError("frameOffset out of range");let j=$.frameCount!==void 0?$.frameCount:this.numberOfFrames-Y;if(j>this.numberOfFrames-Y)throw RangeError("frameCount out of range");let X=D8(J),Z=f6(J);if(Z&&$.planeIndex>=this.numberOfChannels)throw RangeError("planeIndex out of range");if(!Z&&$.planeIndex!==0)throw RangeError("planeIndex out of range");return(Z?j:j*this.numberOfChannels)*X}copyTo($,J){if(!i1($))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(!Number.isInteger(J.planeIndex)||J.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(J.format!==void 0&&!a2.has(J.format))throw TypeError("Invalid format.");if(J.frameOffset!==void 0&&(!Number.isInteger(J.frameOffset)||J.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(J.frameCount!==void 0&&(!Number.isInteger(J.frameCount)||J.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{planeIndex:Y,format:j,frameCount:X,frameOffset:Z}=J,G=j??this.format;if(!G)throw Error("Destination format not determined");let K=this.numberOfFrames,Q=this.numberOfChannels,q=Z??0;if(q>=K)throw RangeError("frameOffset out of range");let U=X!==void 0?X:K-q;if(U>K-q)throw RangeError("frameCount out of range");let W=D8(G),V=f6(G);if(V&&Y>=Q)throw RangeError("planeIndex out of range");if(!V&&Y!==0)throw RangeError("planeIndex out of range");let A=(V?U:U*Q)*W;if($.byteLength<A)throw RangeError("Destination buffer is too small");let R=h($),z=u7(G);if(E8(this._data))if(V)if(G==="f32-planar")this._data.copyTo($,{planeIndex:Y,frameOffset:q,frameCount:U,format:"f32-planar"});else{let _=new ArrayBuffer(U*4),L=new Float32Array(_);this._data.copyTo(L,{planeIndex:Y,frameOffset:q,frameCount:U,format:"f32-planar"});let M=new DataView(_);for(let B=0;B<U;B++){let F=B*W,C=M.getFloat32(B*4,!0);z(R,F,C)}}else{let _=Q,L=new Float32Array(U);for(let M=0;M<_;M++){this._data.copyTo(L,{planeIndex:M,frameOffset:q,frameCount:U,format:"f32-planar"});for(let B=0;B<U;B++){let C=(B*_+M)*W;z(R,C,L[B])}}}else{let _=this._data,L=h(_),M=this.format,B=k7(M),F=D8(M),C=f6(M);for(let w=0;w<U;w++)if(V){let v=w*W,k;if(C)k=(Y*K+(w+q))*F;else k=((w+q)*Q+Y)*F;let S=B(L,k);z(R,v,S)}else for(let v=0;v<Q;v++){let S=(w*Q+v)*W,T;if(C)T=(v*K+(w+q))*F;else T=((w+q)*Q+v)*F;let r=B(L,T);z(R,S,r)}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(E8(this._data)){let $=new K0(this._data.clone());return $.setTimestamp(this.timestamp),$}return new K0({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){if(this._closed)return;if(y8?.unregister(this),E8(this._data))this._data.close();else this._data=new Uint8Array(0);this._closed=!0}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");if(E8(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(f6(this.format)){let J=this.allocationSize({planeIndex:0,format:this.format}),Y=new ArrayBuffer(J*this.numberOfChannels);for(let j=0;j<this.numberOfChannels;j++)this.copyTo(new Uint8Array(Y,j*J,J),{planeIndex:j,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:Y})}let $=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo($,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:$})}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw Error("AudioSample is closed.");let $=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),J=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let Y=0;Y<this.numberOfChannels;Y++)this.copyTo(J,{planeIndex:Y,format:"f32-planar"}),$.copyToChannel(J,Y);return $}setTimestamp($){if(!Number.isFinite($))throw TypeError("newTimestamp must be a number.");this.timestamp=$}[Symbol.dispose](){this.close()}static*_fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,j=$.numberOfChannels,X=$.sampleRate,Z=$.length,G=Math.floor(Y/j),K=0,Q=Z;while(Q>0){let q=Math.min(G,Q),U=new Float32Array(j*q);for(let W=0;W<j;W++)$.copyFromChannel(U.subarray(W*q,(W+1)*q),W,K);yield new K0({format:"f32-planar",sampleRate:X,numberOfFrames:q,numberOfChannels:j,timestamp:J+K/X,data:U}),K+=q,Q-=q}}static fromAudioBuffer($,J){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let Y=240000,j=$.numberOfChannels,X=$.sampleRate,Z=$.length,G=Math.floor(Y/j),K=0,Q=Z,q=[];while(Q>0){let U=Math.min(G,Q),W=new Float32Array(j*U);for(let N=0;N<j;N++)$.copyFromChannel(W.subarray(N*U,(N+1)*U),N,K);let V=new K0({format:"f32-planar",sampleRate:X,numberOfFrames:U,numberOfChannels:j,timestamp:J+K/X,data:W});q.push(V),K+=U,Q-=U}return q}}var D8=($)=>{switch($){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},f6=($)=>{switch($){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},k7=($)=>{switch($){case"u8":case"u8-planar":return(J,Y)=>(J.getUint8(Y)-128)/128;case"s16":case"s16-planar":return(J,Y)=>J.getInt16(Y,!0)/32768;case"s32":case"s32-planar":return(J,Y)=>J.getInt32(Y,!0)/2147483648;case"f32":case"f32-planar":return(J,Y)=>J.getFloat32(Y,!0)}},u7=($)=>{switch($){case"u8":case"u8-planar":return(J,Y,j)=>J.setUint8(Y,$0((j+1)*127.5,0,255));case"s16":case"s16-planar":return(J,Y,j)=>J.setInt16(Y,$0(Math.round(j*32767),-32768,32767),!0);case"s32":case"s32-planar":return(J,Y,j)=>J.setInt32(Y,$0(Math.round(j*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(J,Y,j)=>J.setFloat32(Y,j,!0)}},E8=($)=>{return typeof AudioData<"u"&&$ instanceof AudioData};/*!
118
+ * Copyright (c) 2025-present, Vanilagy and contributors
119
+ *
120
+ * This Source Code Form is subject to the terms of the Mozilla Public
121
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
122
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
123
+ */var j8=($)=>{if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.metadataOnly!==void 0&&typeof $.metadataOnly!=="boolean")throw TypeError("options.metadataOnly, when defined, must be a boolean.");if($.verifyKeyPackets!==void 0&&typeof $.verifyKeyPackets!=="boolean")throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if($.verifyKeyPackets&&$.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.")},G1=($)=>{if(!R1($))throw TypeError("timestamp must be a number.")},e2=($,J,Y)=>{if(Y.verifyKeyPackets)return J.then(async(j)=>{if(!j||j.type==="delta")return j;let X=await $.determinePacketType(j);if(X)j.type=X;return j});return J};class K1{_track;constructor($){if(!($ instanceof g1))throw TypeError("track must be an InputTrack.");this._track=$}getFirstPacket($={}){if(j8($),this._track.input._disposed)throw new q0;return e2(this._track,this._track._backing.getFirstPacket($),$)}getPacket($,J={}){if(G1($),j8(J),this._track.input._disposed)throw new q0;return e2(this._track,this._track._backing.getPacket($,J),J)}getNextPacket($,J={}){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if(j8(J),this._track.input._disposed)throw new q0;return e2(this._track,this._track._backing.getNextPacket($,J),J)}async getKeyPacket($,J={}){if(G1($),j8(J),this._track.input._disposed)throw new q0;if(!J.verifyKeyPackets)return this._track._backing.getKeyPacket($,J);let Y=await this._track._backing.getKeyPacket($,J);if(!Y)return Y;if(H(Y.type==="key"),await this._track.determinePacketType(Y)==="delta")return this.getKeyPacket(Y.timestamp-1/this._track.timeResolution,J);return Y}async getNextKeyPacket($,J={}){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if(j8(J),this._track.input._disposed)throw new q0;if(!J.verifyKeyPackets)return this._track._backing.getNextKeyPacket($,J);let Y=await this._track._backing.getNextKeyPacket($,J);if(!Y)return Y;if(H(Y.type==="key"),await this._track.determinePacketType(Y)==="delta")return this.getNextKeyPacket(Y,J);return Y}packets($,J,Y={}){if($!==void 0&&!($ instanceof I))throw TypeError("startPacket must be an EncodedPacket.");if($!==void 0&&$.isMetadataOnly&&!Y?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(J!==void 0&&!(J instanceof I))throw TypeError("endPacket must be an EncodedPacket.");if(j8(Y),this._track.input._disposed)throw new q0;let j=[],{promise:X,resolve:Z}=c(),{promise:G,resolve:K}=c(),Q=!1,q=!1,U=null,W=[],V=()=>Math.max(2,W.length);(async()=>{let A=$??await this.getFirstPacket(Y);while(A&&!q&&!this._track.input._disposed){if(J&&A.sequenceNumber>=J?.sequenceNumber)break;if(j.length>V()){({promise:G,resolve:K}=c()),await G;continue}j.push(A),Z(),{promise:X,resolve:Z}=c(),A=await this.getNextPacket(A,Y)}Q=!0,Z()})().catch((A)=>{if(!U)U=A,Z()});let N=this._track;return{async next(){while(!0){if(N.input._disposed)throw new q0;if(q)return{value:void 0,done:!0};if(U)throw U;if(j.length>0){let A=j.shift(),R=performance.now();W.push(R);while(W.length>0&&R-W[0]>=1000)W.shift();return K(),{value:A,done:!1}}if(Q)return{value:void 0,done:!0};await X}},async return(){return q=!0,K(),Z(),{value:void 0,done:!0}},async throw(A){throw A},[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){q=!0,K(),Z()}}}}class g6{onSample;onError;constructor($,J){this.onSample=$;this.onError=J}}class k6{mediaSamplesInRange($=0,J=Number.POSITIVE_INFINITY){G1($),G1(J);let Y=[],j=!1,X=null,{promise:Z,resolve:G}=c(),{promise:K,resolve:Q}=c(),q=!1,U=!1,W=!1,V=null;(async()=>{let R=await this._createDecoder((F)=>{if(Q(),F.timestamp>=J)U=!0;if(U){F.close();return}if(X)if(F.timestamp>$)Y.push(X),j=!0;else X.close();if(F.timestamp>=$)Y.push(F),j=!0;if(X=j?null:F,Y.length>0)G(),{promise:Z,resolve:G}=c()},(F)=>{if(!V)V=F,G()}),z=this._createPacketSink(),_=await z.getKeyPacket($,{verifyKeyPackets:!0})??await z.getFirstPacket(),L=_,M;if(J<Number.POSITIVE_INFINITY){let F=await z.getPacket(J),C=!F?null:F.type==="key"&&F.timestamp===J?F:await z.getNextKeyPacket(F,{verifyKeyPackets:!0});if(C)M=C}let B=z.packets(_??void 0,M);await B.next();while(L&&!U&&!this._track.input._disposed){let F=j5(Y.length);if(Y.length+R.getDecodeQueueSize()>F){({promise:K,resolve:Q}=c()),await K;continue}R.decode(L);let C=await B.next();if(C.done)break;L=C.value}if(await B.return(),!W&&!this._track.input._disposed)await R.flush();if(R.close(),!j&&X)Y.push(X);q=!0,G()})().catch((R)=>{if(!V)V=R,G()});let N=this._track,A=()=>{X?.close();for(let R of Y)R.close()};return{async next(){while(!0){if(N.input._disposed)throw A(),new q0;if(W)return{value:void 0,done:!0};if(V)throw A(),V;if(Y.length>0){let R=Y.shift();return Q(),{value:R,done:!1}}if(!q)await Z;else return{value:void 0,done:!0}}},async return(){return W=!0,U=!0,Q(),G(),A(),{value:void 0,done:!0}},async throw(R){throw R},[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){W=!0,U=!0,Q(),G(),A()}}}mediaSamplesAtTimestamps($){HJ($);let J=VJ($),Y=[],j=[],{promise:X,resolve:Z}=c(),{promise:G,resolve:K}=c(),Q=!1,q=!1,U=null,W=(A)=>{j.push(A),Z(),{promise:X,resolve:Z}=c()};(async()=>{let A=await this._createDecoder((F)=>{if(K(),q){F.close();return}let C=0;while(Y.length>0&&F.timestamp-Y[0]>-0.0000000001)C++,Y.shift();if(C>0)for(let w=0;w<C;w++)W(w<C-1?F.clone():F);else F.close()},(F)=>{if(!U)U=F,Z()}),R=this._createPacketSink(),z=null,_=null,L=-1,M=async()=>{H(_);let F=_;A.decode(F);while(F.sequenceNumber<L){let C=j5(j.length);while(j.length+A.getDecodeQueueSize()>C&&!q)({promise:G,resolve:K}=c()),await G;if(q)break;let w=await R.getNextPacket(F);H(w),A.decode(w),F=w}L=-1},B=async()=>{await A.flush();for(let F=0;F<Y.length;F++)W(null);Y.length=0};for await(let F of J){if(G1(F),q||this._track.input._disposed)break;let C=await R.getPacket(F),w=C&&await R.getKeyPacket(F,{verifyKeyPackets:!0});if(!w){if(L!==-1)await M(),await B();W(null),z=null;continue}if(z&&(w.sequenceNumber!==_.sequenceNumber||C.timestamp<z.timestamp))await M(),await B();Y.push(C.timestamp),L=Math.max(C.sequenceNumber,L),z=C,_=w}if(!q&&!this._track.input._disposed){if(L!==-1)await M();await B()}A.close(),Q=!0,Z()})().catch((A)=>{if(!U)U=A,Z()});let V=this._track,N=()=>{for(let A of j)A?.close()};return{async next(){while(!0){if(V.input._disposed)throw N(),new q0;if(q)return{value:void 0,done:!0};if(U)throw N(),U;if(j.length>0){let A=j.shift();return H(A!==void 0),K(),{value:A,done:!1}}if(!Q)await X;else return{value:void 0,done:!0}}},async return(){return q=!0,K(),Z(),N(),{value:void 0,done:!0}},async throw(A){throw A},[Symbol.asyncIterator](){return this},async[Symbol.asyncDispose](){q=!0,K(),Z(),N()}}}}var j5=($)=>{return $===0?40:8};class X5 extends g6{codec;decoderConfig;rotation;timeResolution;decoder=null;customDecoder=null;customDecoderCallSerializer=new v1;customDecoderQueueSize=0;inputTimestamps=[];sampleQueue=[];currentPacketIndex=0;raslSkipped=!1;alphaDecoder=null;alphaHadKeyframe=!1;colorQueue=[];alphaQueue=[];merger=null;mergerCreationFailed=!1;decodedAlphaChunkCount=0;alphaDecoderQueueSize=0;nullAlphaFrameQueue=[];currentAlphaPacketIndex=0;alphaRaslSkipped=!1;constructor($,J,Y,j,X,Z){super($,J);this.codec=Y;this.decoderConfig=j;this.rotation=X;this.timeResolution=Z;let G=e1.find((K)=>K.supports(Y,j));if(G)this.customDecoder=new G,this.customDecoder.codec=Y,this.customDecoder.config=j,this.customDecoder.onSample=(K)=>{if(!(K instanceof J0))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(K)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let K=(q)=>{if(this.alphaQueue.length>0){let U=this.alphaQueue.shift();H(U!==void 0),this.mergeAlpha(q,U)}else this.colorQueue.push(q)};if(Y==="avc"&&this.decoderConfig.description&&B8()){let q=oJ(l(this.decoderConfig.description));if(q&&q.sequenceParameterSets.length>0){let U=i2(q.sequenceParameterSets[0]);if(U&&U.frameMbsOnlyFlag===0)this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}}}let Q=Error("Decoding error").stack;this.decoder=new VideoDecoder({output:(q)=>{try{K(q)}catch(U){this.onError(U)}},error:(q)=>{q.stack=Q,this.onError(q)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;return H(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0)}decode($){if(this.codec==="hevc"&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture($.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).then(()=>this.customDecoderQueueSize--);else{if(H(this.decoder),!s1())f2(this.inputTimestamps,$.timestamp,(J)=>J);if(B8()&&this.currentPacketIndex===0&&this.codec==="avc"){let Y=r2($.data,this.decoderConfig).filter((X)=>{let Z=h1(X);return!(Z>=20&&Z<=31)}),j=cJ(Y,this.decoderConfig);$=new I(j,$.type,$.timestamp,$.duration)}this.decoder.decode($.toEncodedVideoChunk()),this.decodeAlphaData($)}this.currentPacketIndex++}decodeAlphaData($){if(!$.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new Z5}catch(Y){console.error("Due to an error, only color data will be decoded.",Y),this.mergerCreationFailed=!0,this.decodeAlphaData($);return}if(!this.alphaDecoder){let Y=(X)=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let Z=this.colorQueue.shift();H(Z!==void 0),this.mergeAlpha(Z,X)}else this.alphaQueue.push(X);this.decodedAlphaChunkCount++;while(this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let Z=this.colorQueue.shift();H(Z!==void 0),this.mergeAlpha(Z,null)}else this.alphaQueue.push(null)},j=Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:(X)=>{try{Y(X)}catch(Z){this.onError(Z)}},error:(X)=>{X.stack=j,this.onError(X)}}),this.alphaDecoder.configure(this.decoderConfig)}let J=h6(this.codec,this.decoderConfig,$.sideData.alpha);if(!this.alphaHadKeyframe)this.alphaHadKeyframe=J==="key";if(this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture($.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode($.alphaToEncodedVideoChunk(J??$.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){if(this.alphaDecoderQueueSize===0)this.alphaQueue.push(null);else this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture($){return s2($,this.decoderConfig).some((Y)=>{let j=Z1(Y);return j===8||j===9})}sampleHandler($){if(s1()){if(this.sampleQueue.length>0&&$.timestamp>=n(this.sampleQueue).timestamp){for(let J of this.sampleQueue)this.finalizeAndEmitSample(J);this.sampleQueue.length=0}f2(this.sampleQueue,$,(J)=>J.timestamp)}else{let J=this.inputTimestamps.shift();H(J!==void 0),$.setTimestamp(J),this.finalizeAndEmitSample($)}}finalizeAndEmitSample($){$.setTimestamp(Math.round($.timestamp*this.timeResolution)/this.timeResolution),$.setDuration(Math.round($.duration*this.timeResolution)/this.timeResolution),$.setRotation(this.rotation),this.onSample($)}mergeAlpha($,J){if(!J){let X=new J0($);this.sampleHandler(X);return}H(this.merger),this.merger.update($,J),$.close(),J.close();let Y=new VideoFrame(this.merger.canvas,{timestamp:$.timestamp,duration:$.duration??void 0}),j=new J0(Y);this.sampleHandler(j)}async flush(){if(this.customDecoder)await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());else H(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;if(s1()){for(let $ of this.sampleQueue)this.finalizeAndEmitSample($);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else H(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(($)=>$.close()),this.colorQueue.length=0,this.alphaQueue.forEach(($)=>$?.close()),this.alphaQueue.length=0,this.merger?.close();for(let $ of this.sampleQueue)$.close();this.sampleQueue.length=0}}class Z5{canvas;gl;program;vao;colorTexture;alphaTexture;constructor(){if(typeof OffscreenCanvas<"u")this.canvas=new OffscreenCanvas(300,150);else this.canvas=document.createElement("canvas");let $=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!$)throw Error("Couldn't acquire WebGL 2 context.");this.gl=$,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)}createProgram(){let $=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
124
+ in vec2 a_position;
125
+ in vec2 a_texCoord;
126
+ out vec2 v_texCoord;
127
+
128
+ void main() {
129
+ gl_Position = vec4(a_position, 0.0, 1.0);
130
+ v_texCoord = a_texCoord;
131
+ }
132
+ `),J=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
133
+ precision highp float;
134
+
135
+ uniform sampler2D u_colorTexture;
136
+ uniform sampler2D u_alphaTexture;
137
+ in vec2 v_texCoord;
138
+ out vec4 fragColor;
139
+
140
+ void main() {
141
+ vec3 color = texture(u_colorTexture, v_texCoord).rgb;
142
+ float alpha = texture(u_alphaTexture, v_texCoord).r;
143
+ fragColor = vec4(color, alpha);
144
+ }
145
+ `),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createShader($,J){let Y=this.gl.createShader($);return this.gl.shaderSource(Y,J),this.gl.compileShader(Y),Y}createVAO(){let $=this.gl.createVertexArray();this.gl.bindVertexArray($);let J=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),Y=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,Y),this.gl.bufferData(this.gl.ARRAY_BUFFER,J,this.gl.STATIC_DRAW);let j=this.gl.getAttribLocation(this.program,"a_position"),X=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(j),this.gl.vertexAttribPointer(j,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(X),this.gl.vertexAttribPointer(X,2,this.gl.FLOAT,!1,16,8),$}createTexture(){let $=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,$),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),$}update($,J){if($.displayWidth!==this.canvas.width||$.displayHeight!==this.canvas.height)this.canvas.width=$.displayWidth,this.canvas.height=$.displayHeight;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,$),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,J),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class X8 extends k6{_track;constructor($){if(!($ instanceof D0))throw TypeError("videoTrack must be an InputVideoTrack.");super();this._track=$}async _createDecoder($,J){if(!await this._track.canDecode())throw Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let Y=this._track.codec,j=this._track.rotation,X=await this._track.getDecoderConfig(),Z=this._track.timeResolution;return H(Y&&X),new X5($,J,Y,X,j,Z)}_createPacketSink(){return new K1(this._track)}async getSample($){G1($);for await(let J of this.mediaSamplesAtTimestamps([$]))return J;throw Error("Internal error: Iterator returned nothing.")}samples($=0,J=Number.POSITIVE_INFINITY){return this.mediaSamplesInRange($,J)}samplesAtTimestamps($){return this.mediaSamplesAtTimestamps($)}}class u6{_videoTrack;_alpha;_width;_height;_fit;_rotation;_crop;_videoSampleSink;_canvasPool;_nextCanvasIndex=0;constructor($,J={}){if(!($ instanceof D0))throw TypeError("videoTrack must be an InputVideoTrack.");if(J&&typeof J!=="object")throw TypeError("options must be an object.");if(J.alpha!==void 0&&typeof J.alpha!=="boolean")throw TypeError("options.alpha, when provided, must be a boolean.");if(J.width!==void 0&&(!Number.isInteger(J.width)||J.width<=0))throw TypeError("options.width, when defined, must be a positive integer.");if(J.height!==void 0&&(!Number.isInteger(J.height)||J.height<=0))throw TypeError("options.height, when defined, must be a positive integer.");if(J.fit!==void 0&&!["fill","contain","cover"].includes(J.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(J.width!==void 0&&J.height!==void 0&&J.fit===void 0)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(J.crop!==void 0)b8(J.crop,"options.");if(J.poolSize!==void 0&&(typeof J.poolSize!=="number"||!Number.isInteger(J.poolSize)||J.poolSize<0))throw TypeError("poolSize must be a non-negative integer.");let Y=J.rotation??$.rotation,[j,X]=Y%180===0?[$.codedWidth,$.codedHeight]:[$.codedHeight,$.codedWidth],Z=J.crop;if(Z)v8(Z,j,X);let[G,K]=Z?[Z.width,Z.height]:[j,X],Q=G/K;if(J.width!==void 0&&J.height===void 0)G=J.width,K=Math.round(G/Q);else if(J.width===void 0&&J.height!==void 0)K=J.height,G=Math.round(K*Q);else if(J.width!==void 0&&J.height!==void 0)G=J.width,K=J.height;this._videoTrack=$,this._alpha=J.alpha??!1,this._width=G,this._height=K,this._rotation=Y,this._crop=Z,this._fit=J.fit??"fill",this._videoSampleSink=new X8($),this._canvasPool=Array.from({length:J.poolSize??0},()=>null)}_videoSampleToWrappedCanvas($){let J=this._canvasPool[this._nextCanvasIndex],Y=!1;if(!J){if(typeof document<"u")J=document.createElement("canvas"),J.width=this._width,J.height=this._height;else J=new OffscreenCanvas(this._width,this._height);if(this._canvasPool.length>0)this._canvasPool[this._nextCanvasIndex]=J;Y=!0}if(this._canvasPool.length>0)this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length;let j=J.getContext("2d",{alpha:this._alpha||n0()});if(H(j),j.resetTransform(),!Y)if(!this._alpha&&n0())j.fillStyle="black",j.fillRect(0,0,this._width,this._height);else j.clearRect(0,0,this._width,this._height);$.drawWithFit(j,{fit:this._fit,rotation:this._rotation,crop:this._crop});let X={canvas:J,timestamp:$.timestamp,duration:$.duration};return $.close(),X}async getCanvas($){G1($);let J=await this._videoSampleSink.getSample($);return J&&this._videoSampleToWrappedCanvas(J)}canvases($=0,J=Number.POSITIVE_INFINITY){return M8(this._videoSampleSink.samples($,J),(Y)=>this._videoSampleToWrappedCanvas(Y))}canvasesAtTimestamps($){return M8(this._videoSampleSink.samplesAtTimestamps($),(J)=>J&&this._videoSampleToWrappedCanvas(J))}}class G5 extends g6{decoder=null;customDecoder=null;customDecoderCallSerializer=new v1;customDecoderQueueSize=0;currentTimestamp=null;constructor($,J,Y,j){super($,J);let X=(G)=>{if(this.currentTimestamp===null||Math.abs(G.timestamp-this.currentTimestamp)>=G.duration)this.currentTimestamp=G.timestamp;let K=this.currentTimestamp;if(this.currentTimestamp+=G.duration,G.numberOfFrames===0){G.close();return}let Q=j.sampleRate;G.setTimestamp(Math.round(K*Q)/Q),$(G)},Z=$8.find((G)=>G.supports(Y,j));if(Z)this.customDecoder=new Z,this.customDecoder.codec=Y,this.customDecoder.config=j,this.customDecoder.onSample=(G)=>{if(!(G instanceof K0))throw TypeError("The argument passed to onSample must be an AudioSample.");X(G)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let G=Error("Decoding error").stack;this.decoder=new AudioDecoder({output:(K)=>{try{X(new K0(K))}catch(Q){this.onError(Q)}},error:(K)=>{K.stack=G,this.onError(K)}}),this.decoder.configure(j)}}getDecodeQueueSize(){if(this.customDecoder)return this.customDecoderQueueSize;return H(this.decoder),this.decoder.decodeQueueSize}decode($){if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode($)).then(()=>this.customDecoderQueueSize--);else H(this.decoder),this.decoder.decode($.toEncodedAudioChunk())}flush(){if(this.customDecoder)return this.customDecoderCallSerializer.call(()=>this.customDecoder.flush());return H(this.decoder),this.decoder.flush()}close(){if(this.customDecoder)this.customDecoderCallSerializer.call(()=>this.customDecoder.close());else H(this.decoder),this.decoder.close()}}class K5 extends g6{decoderConfig;codec;inputSampleSize;readInputValue;outputSampleSize;outputFormat;writeOutputValue;currentTimestamp=null;constructor($,J,Y){super($,J);this.decoderConfig=Y;H(o.includes(Y.codec)),this.codec=Y.codec;let{dataType:j,sampleSize:X,littleEndian:Z}=U0(this.codec);switch(this.inputSampleSize=X,X){case 1:if(j==="unsigned")this.readInputValue=(G,K)=>G.getUint8(K)-128;else if(j==="signed")this.readInputValue=(G,K)=>G.getInt8(K);else if(j==="ulaw")this.readInputValue=(G,K)=>tJ(G.getUint8(K));else if(j==="alaw")this.readInputValue=(G,K)=>$5(G.getUint8(K));else H(!1);break;case 2:if(j==="unsigned")this.readInputValue=(G,K)=>G.getUint16(K,Z)-32768;else if(j==="signed")this.readInputValue=(G,K)=>G.getInt16(K,Z);else H(!1);break;case 3:if(j==="unsigned")this.readInputValue=(G,K)=>T1(G,K,Z)-8388608;else if(j==="signed")this.readInputValue=(G,K)=>NJ(G,K,Z);else H(!1);break;case 4:if(j==="unsigned")this.readInputValue=(G,K)=>G.getUint32(K,Z)-2147483648;else if(j==="signed")this.readInputValue=(G,K)=>G.getInt32(K,Z);else if(j==="float")this.readInputValue=(G,K)=>G.getFloat32(K,Z);else H(!1);break;case 8:if(j==="float")this.readInputValue=(G,K)=>G.getFloat64(K,Z);else H(!1);break;default:i(X),H(!1)}switch(X){case 1:if(j==="ulaw"||j==="alaw")this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(G,K,Q)=>G.setInt16(K,Q,!0);else this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(G,K,Q)=>G.setUint8(K,Q+128);break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(G,K,Q)=>G.setInt16(K,Q,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(G,K,Q)=>G.setInt32(K,Q<<8,!0);break;case 4:if(this.outputSampleSize=4,j==="float")this.outputFormat="f32",this.writeOutputValue=(G,K,Q)=>G.setFloat32(K,Q,!0);else this.outputFormat="s32",this.writeOutputValue=(G,K,Q)=>G.setInt32(K,Q,!0);break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(G,K,Q)=>G.setFloat32(K,Q,!0);break;default:i(X),H(!1)}}getDecodeQueueSize(){return 0}decode($){let J=h($.data),Y=$.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,j=Y*this.decoderConfig.numberOfChannels*this.outputSampleSize,X=new ArrayBuffer(j),Z=new DataView(X);for(let q=0;q<Y*this.decoderConfig.numberOfChannels;q++){let U=q*this.inputSampleSize,W=q*this.outputSampleSize,V=this.readInputValue(J,U);this.writeOutputValue(Z,W,V)}let G=Y/this.decoderConfig.sampleRate;if(this.currentTimestamp===null||Math.abs($.timestamp-this.currentTimestamp)>=G)this.currentTimestamp=$.timestamp;let K=this.currentTimestamp;this.currentTimestamp+=G;let Q=new K0({format:this.outputFormat,data:X,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:Y,timestamp:K});this.onSample(Q)}async flush(){}close(){}}class Z8 extends k6{_track;constructor($){if(!($ instanceof t))throw TypeError("audioTrack must be an InputAudioTrack.");super();this._track=$}async _createDecoder($,J){if(!await this._track.canDecode())throw Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let Y=this._track.codec,j=await this._track.getDecoderConfig();if(H(Y&&j),o.includes(j.codec))return new K5($,J,j);return new G5($,J,Y,j)}_createPacketSink(){return new K1(this._track)}async getSample($){G1($);for await(let J of this.mediaSamplesAtTimestamps([$]))return J;throw Error("Internal error: Iterator returned nothing.")}samples($=0,J=Number.POSITIVE_INFINITY){return this.mediaSamplesInRange($,J)}samplesAtTimestamps($){return this.mediaSamplesAtTimestamps($)}}class Q5{_audioSampleSink;constructor($){if(!($ instanceof t))throw TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Z8($)}_audioSampleToWrappedArrayBuffer($){let J={buffer:$.toAudioBuffer(),timestamp:$.timestamp,duration:$.duration};return $.close(),J}async getBuffer($){G1($);let J=await this._audioSampleSink.getSample($);return J&&this._audioSampleToWrappedArrayBuffer(J)}buffers($=0,J=Number.POSITIVE_INFINITY){return M8(this._audioSampleSink.samples($,J),(Y)=>this._audioSampleToWrappedArrayBuffer(Y))}buffersAtTimestamps($){return M8(this._audioSampleSink.samplesAtTimestamps($),(J)=>J&&this._audioSampleToWrappedArrayBuffer(J))}}/*!
146
+ * Copyright (c) 2025-present, Vanilagy and contributors
147
+ *
148
+ * This Source Code Form is subject to the terms of the Mozilla Public
149
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
150
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
151
+ */class g1{input;_backing;constructor($,J){this.input=$,this._backing=J}isVideoTrack(){return this instanceof D0}isAudioTrack(){return this instanceof t}isSubtitleTrack(){return this instanceof p1}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats($=Number.POSITIVE_INFINITY){let J=new K1(this),Y=Number.POSITIVE_INFINITY,j=Number.NEGATIVE_INFINITY,X=0,Z=0;for await(let G of J.packets(void 0,void 0,{metadataOnly:!0})){if(X>=$&&G.timestamp>=j)break;Y=Math.min(Y,G.timestamp),j=Math.max(j,G.timestamp+G.duration),X++,Z+=G.byteLength}return{packetCount:X,averagePacketRate:X?Number((X/(j-Y)).toPrecision(16)):0,averageBitrate:X?Number((8*Z/(j-Y)).toPrecision(16)):0}}}class D0 extends g1{_backing;constructor($,J){super($,J);this._backing=J}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180===0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180===0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let $=await this._backing.getColorSpace();return $.primaries==="bt2020"||$.primaries==="smpte432"||$.transfer==="pg"||$.transfer==="hlg"||$.matrix==="bt2020-ncl"}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=this._backing.getCodec();if(H(J!==null),e1.some((j)=>j.supports(J,$)))return!0;if(typeof VideoDecoder>"u")return!1;return(await VideoDecoder.isConfigSupported($)).supported===!0}catch($){return console.error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("packet must not be metadata-only to determine its type.");if(this.codec===null)return null;let J=await this.getDecoderConfig();return H(J),h6(this.codec,J,$.data)}}class t extends g1{_backing;constructor($,J){super($,J);this._backing=J}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let $=await this._backing.getDecoderConfig();if(!$)return!1;let J=this._backing.getCodec();if(H(J!==null),$8.some((j)=>j.supports(J,$)))return!0;if($.codec.startsWith("pcm-"))return!0;if(typeof AudioDecoder>"u")return!1;return(await AudioDecoder.isConfigSupported($)).supported===!0}catch($){return console.error("Error during decodability check:",$),!1}}async determinePacketType($){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if(this.codec===null)return null;return"key"}}class p1 extends g1{_backing;constructor($,J){super($,J);this._backing=J}get type(){return"subtitle"}get codec(){return this._backing.getCodec()}getCues(){return this._backing.getCues()}async exportToText($){let J=[];for await(let Z of this.getCues())J.push(Z);let Y=$||this.codec,j=this._backing.getCodecPrivate();if(Y==="srt"){let{formatCuesToSrt:Z}=await Promise.resolve().then(() => (x0(),S8));return Z(J)}if(Y==="ass"||Y==="ssa"){let{formatCuesToAss:Z,splitAssIntoCues:G}=await Promise.resolve().then(() => (x0(),S8)),K=j?G(j):{header:"",cues:[]};return Z(J,K.header)}if(Y==="webvtt"){let{formatCuesToWebVTT:Z}=await Promise.resolve().then(() => (x0(),S8));return Z(J,j||void 0)}let{formatCuesToSrt:X}=await Promise.resolve().then(() => (x0(),S8));return X(J)}async getCodecParameterString(){return this.codec}async canDecode(){return this.codec!==null}async determinePacketType($){return"key"}}/*!
152
+ * Copyright (c) 2025-present, Vanilagy and contributors
153
+ *
154
+ * This Source Code Form is subject to the terms of the Mozilla Public
155
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
156
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
157
+ */class I0{data;mimeType;constructor($,J){this.data=$;this.mimeType=J;if(!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(typeof J!=="string")throw TypeError("mimeType must be a string.")}}class l1{data;mimeType;name;description;constructor($,J,Y,j){this.data=$;this.mimeType=J;this.name=Y;this.description=j;if(!($ instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(J!==void 0&&typeof J!=="string")throw TypeError("mimeType, when provided, must be a string.");if(Y!==void 0&&typeof Y!=="string")throw TypeError("name, when provided, must be a string.");if(j!==void 0&&typeof j!=="string")throw TypeError("description, when provided, must be a string.")}}var h8=($)=>{if(!$||typeof $!=="object")throw TypeError("tags must be an object.");if($.title!==void 0&&typeof $.title!=="string")throw TypeError("tags.title, when provided, must be a string.");if($.description!==void 0&&typeof $.description!=="string")throw TypeError("tags.description, when provided, must be a string.");if($.artist!==void 0&&typeof $.artist!=="string")throw TypeError("tags.artist, when provided, must be a string.");if($.album!==void 0&&typeof $.album!=="string")throw TypeError("tags.album, when provided, must be a string.");if($.albumArtist!==void 0&&typeof $.albumArtist!=="string")throw TypeError("tags.albumArtist, when provided, must be a string.");if($.trackNumber!==void 0&&(!Number.isInteger($.trackNumber)||$.trackNumber<=0))throw TypeError("tags.trackNumber, when provided, must be a positive integer.");if($.tracksTotal!==void 0&&(!Number.isInteger($.tracksTotal)||$.tracksTotal<=0))throw TypeError("tags.tracksTotal, when provided, must be a positive integer.");if($.discNumber!==void 0&&(!Number.isInteger($.discNumber)||$.discNumber<=0))throw TypeError("tags.discNumber, when provided, must be a positive integer.");if($.discsTotal!==void 0&&(!Number.isInteger($.discsTotal)||$.discsTotal<=0))throw TypeError("tags.discsTotal, when provided, must be a positive integer.");if($.genre!==void 0&&typeof $.genre!=="string")throw TypeError("tags.genre, when provided, must be a string.");if($.date!==void 0&&(!($.date instanceof Date)||Number.isNaN($.date.getTime())))throw TypeError("tags.date, when provided, must be a valid Date.");if($.lyrics!==void 0&&typeof $.lyrics!=="string")throw TypeError("tags.lyrics, when provided, must be a string.");if($.images!==void 0){if(!Array.isArray($.images))throw TypeError("tags.images, when provided, must be an array.");for(let J of $.images){if(!J||typeof J!=="object")throw TypeError("Each image in tags.images must be an object.");if(!(J.data instanceof Uint8Array))throw TypeError("Each image.data must be a Uint8Array.");if(typeof J.mimeType!=="string")throw TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(J.kind))throw TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if($.comment!==void 0&&typeof $.comment!=="string")throw TypeError("tags.comment, when provided, must be a string.");if($.raw!==void 0){if(!$.raw||typeof $.raw!=="object")throw TypeError("tags.raw, when provided, must be an object.");for(let J of Object.values($.raw))if(J!==null&&typeof J!=="string"&&!(J instanceof Uint8Array)&&!(J instanceof I0)&&!(J instanceof l1))throw TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},m1=($)=>{return $.title===void 0&&$.description===void 0&&$.artist===void 0&&$.album===void 0&&$.albumArtist===void 0&&$.trackNumber===void 0&&$.tracksTotal===void 0&&$.discNumber===void 0&&$.discsTotal===void 0&&$.genre===void 0&&$.date===void 0&&$.lyrics===void 0&&(!$.images||$.images.length===0)&&$.comment===void 0&&($.raw===void 0||Object.keys($.raw).length===0)},L0={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},U5=($)=>{if(!$||typeof $!=="object")throw TypeError("disposition must be an object.");if($.default!==void 0&&typeof $.default!=="boolean")throw TypeError("disposition.default must be a boolean.");if($.forced!==void 0&&typeof $.forced!=="boolean")throw TypeError("disposition.forced must be a boolean.");if($.original!==void 0&&typeof $.original!=="boolean")throw TypeError("disposition.original must be a boolean.");if($.commentary!==void 0&&typeof $.commentary!=="boolean")throw TypeError("disposition.commentary must be a boolean.");if($.hearingImpaired!==void 0&&typeof $.hearingImpaired!=="boolean")throw TypeError("disposition.hearingImpaired must be a boolean.");if($.visuallyImpaired!==void 0&&typeof $.visuallyImpaired!=="boolean")throw TypeError("disposition.visuallyImpaired must be a boolean.")};/*!
158
+ * Copyright (c) 2025-present, Vanilagy and contributors
159
+ *
160
+ * This Source Code Form is subject to the terms of the Mozilla Public
161
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
162
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
163
+ */class j${source;fileSize;constructor($){this.source=$}requestSlice($,J){if(this.source._disposed)throw new q0;if(this.fileSize!==null&&$+J>this.fileSize)return null;let Y=$+J,j=this.source._read($,Y);if(j instanceof Promise)return j.then((X)=>{if(!X)return null;return new S0(X.bytes,X.view,X.offset,$,Y)});if(!j)return null;return new S0(j.bytes,j.view,j.offset,$,Y)}requestSliceRange($,J,Y){if(this.source._disposed)throw new q0;if(this.fileSize!==null)return this.requestSlice($,$0(this.fileSize-$,J,Y));let j=this.requestSlice($,Y),X=(Z)=>{if(Z)return Z;let G=(Q)=>{return H(Q!==null),this.requestSlice($,$0(Q-$,J,Y))},K=this.source._retrieveSize();if(K instanceof Promise)return K.then(G);return G(K)};if(j instanceof Promise)return j.then(X);return X(j)}}class S0{bytes;view;offset;start;end;bufferPos;constructor($,J,Y,j,X){this.bytes=$;this.view=J;this.offset=Y;this.start=j;this.end=X;this.bufferPos=j-Y}static tempFromBytes($){return new S0($,h($),0,0,$.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos($){this.bufferPos=$-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip($){this.bufferPos+=$}slice($,J=this.end-$){if($<this.start||$+J>this.end)throw RangeError("Slicing outside of original slice.");return new S0(this.bytes,this.view,this.offset,$,$+J)}}var M0=($,J)=>{if($.filePos<$.start||$.filePos+J>$.end)throw RangeError(`Tried reading [${$.filePos}, ${$.filePos+J}), but slice is [${$.start}, ${$.end}). This is likely an internal error, please report it alongside the file that caused it.`)},D=($,J)=>{M0($,J);let Y=$.bytes.subarray($.bufferPos,$.bufferPos+J);return $.bufferPos+=J,Y},y=($)=>{return M0($,1),$.view.getUint8($.bufferPos++)},G8=($,J)=>{M0($,2);let Y=$.view.getUint16($.bufferPos,J);return $.bufferPos+=2,Y},X0=($)=>{M0($,2);let J=$.view.getUint16($.bufferPos,!1);return $.bufferPos+=2,J},_1=($)=>{M0($,3);let J=T1($.view,$.bufferPos,!1);return $.bufferPos+=3,J},f8=($)=>{M0($,2);let J=$.view.getInt16($.bufferPos,!1);return $.bufferPos+=2,J},Q1=($,J)=>{M0($,4);let Y=$.view.getUint32($.bufferPos,J);return $.bufferPos+=4,Y},P=($)=>{M0($,4);let J=$.view.getUint32($.bufferPos,!1);return $.bufferPos+=4,J},h0=($)=>{M0($,4);let J=$.view.getUint32($.bufferPos,!0);return $.bufferPos+=4,J},q1=($)=>{M0($,4);let J=$.view.getInt32($.bufferPos,!1);return $.bufferPos+=4,J},n7=($)=>{M0($,4);let J=$.view.getInt32($.bufferPos,!0);return $.bufferPos+=4,J},X$=($,J)=>{let Y,j;if(J)Y=Q1($,!0),j=Q1($,!0);else j=Q1($,!1),Y=Q1($,!1);return j*4294967296+Y},O0=($)=>{let J=P($),Y=P($);return J*4294967296+Y},W5=($)=>{let J=q1($),Y=P($);return J*4294967296+Y},V5=($)=>{let J=h0($);return n7($)*4294967296+J},H5=($)=>{M0($,4);let J=$.view.getFloat32($.bufferPos,!1);return $.bufferPos+=4,J},i6=($)=>{M0($,8);let J=$.view.getFloat64($.bufferPos,!1);return $.bufferPos+=8,J},s=($,J)=>{M0($,J);let Y="";for(let j=0;j<J;j++)Y+=String.fromCharCode($.bytes[$.bufferPos++]);return Y};/*!
164
+ * Copyright (c) 2025-present, Vanilagy and contributors
165
+ *
166
+ * This Source Code Form is subject to the terms of the Mozilla Public
167
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
168
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
169
+ */var K8=7,Q8=9,g8=($)=>{let J=$.filePos,Y=D($,9),j=new f(Y);if(j.readBits(12)!==4095)return null;if(j.skipBits(1),j.readBits(2)!==0)return null;let G=j.readBits(1),K=j.readBits(2)+1,Q=j.readBits(4);if(Q===15)return null;j.skipBits(1);let q=j.readBits(3);if(q===0)throw Error("ADTS frames with channel configuration 0 are not supported.");j.skipBits(1),j.skipBits(1),j.skipBits(1),j.skipBits(1);let U=j.readBits(13);j.skipBits(11);let W=j.readBits(2)+1;if(W!==1)throw Error("ADTS frames with more than one AAC frame are not supported.");let V=null;if(G===1)$.filePos-=2;else V=j.readBits(16);return{objectType:K,samplingFrequencyIndex:Q,channelConfiguration:q,frameLength:U,numberOfAacFrames:W,crcCheck:V,startPos:J}};/*!
170
+ * Copyright (c) 2025-present, Vanilagy and contributors
171
+ *
172
+ * This Source Code Form is subject to the terms of the Mozilla Public
173
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
174
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
175
+ */var Z$=1024;class G$ extends W0{reader;metadataPromise=null;firstFrameHeader=null;loadedSamples=[];tracks=[];readingMutex=new w0;lastSampleLoaded=!1;lastLoadedPos=0;nextTimestampInSamples=0;constructor($){super($);this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{while(!this.firstFrameHeader&&!this.lastSampleLoaded)await this.advanceReader();H(this.firstFrameHeader),this.tracks=[new t(this.input,new N5(this))]})()}async advanceReader(){let $=this.reader.requestSliceRange(this.lastLoadedPos,K8,Q8);if($ instanceof Promise)$=await $;if(!$){this.lastSampleLoaded=!0;return}let J=g8($);if(!J){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&J.startPos+J.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}if(!this.firstFrameHeader)this.firstFrameHeader=J;let Y=a1[J.samplingFrequencyIndex];H(Y!==void 0);let j=Z$/Y,X=J.crcCheck?Q8:K8,Z={timestamp:this.nextTimestampInSamples/Y,duration:j,dataStart:J.startPos+X,dataSize:J.frameLength-X};this.loadedSamples.push(Z),this.nextTimestampInSamples+=Z$,this.lastLoadedPos=J.startPos+J.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let $=this.tracks[0];return H($),$.computeDuration()}async getMetadataTags(){return{}}}class N5{demuxer;constructor($){this.demuxer=$}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/Z$}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getName(){return null}getLanguageCode(){return a}getCodec(){return"aac"}getInternalCodecId(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){H(this.demuxer.firstFrameHeader);let $=N6[this.demuxer.firstFrameHeader.channelConfiguration];return H($!==void 0),$}getSampleRate(){H(this.demuxer.firstFrameHeader);let $=a1[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return H($!==void 0),$}getDisposition(){return{...L0}}async getDecoderConfig(){H(this.demuxer.firstFrameHeader);let $=new Uint8Array(3),J=new f($),{objectType:Y,samplingFrequencyIndex:j,channelConfiguration:X}=this.demuxer.firstFrameHeader;if(Y>31)J.writeBits(5,31),J.writeBits(6,Y-32);else J.writeBits(5,Y);return J.writeBits(4,j),J.writeBits(4,X),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:$.subarray(0,Math.ceil((J.pos-1)/8))}}async getPacketAtIndex($,J){if($===-1)return null;let Y=this.demuxer.loadedSamples[$];if(!Y)return null;let j;if(J.metadataOnly)j=G0;else{let X=this.demuxer.reader.requestSlice(Y.dataStart,Y.dataSize);if(X instanceof Promise)X=await X;if(!X)return null;j=D(X,Y.dataSize)}return new I(j,"key",Y.timestamp,Y.duration,$,Y.dataSize)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getNextPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{let j=Y1(this.demuxer.loadedSamples,$.timestamp,(Z)=>Z.timestamp);if(j===-1)throw Error("Packet was not created from this track.");let X=j+1;while(X>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(X,J)}finally{Y()}}async getPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{while(!0){let j=u(this.demuxer.loadedSamples,$,(X)=>X.timestamp);if(j===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(j,J);if(j>=0&&j+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(j,J);await this.demuxer.advanceReader()}}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
176
+ * Copyright (c) 2025-present, Vanilagy and contributors
177
+ *
178
+ * This Source Code Form is subject to the terms of the Mozilla Public
179
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
180
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
181
+ */var L1=16;var A5={H264:"avc",h264:"avc",AVC1:"avc",avc1:"avc",H265:"hevc",h265:"hevc",HEVC:"hevc",hevc:"hevc",hev1:"hevc",hvc1:"hevc",VP80:"vp8","VP8 ":"vp8",VP90:"vp9","VP9 ":"vp9",AV01:"av1",av01:"av1",XVID:"mpeg4",xvid:"mpeg4",DIVX:"mpeg4",DX50:"mpeg4",FMP4:"mpeg4",MP4V:"mpeg4"},R5={1:"pcm-s16",3:"pcm-f32",6:"alaw",7:"ulaw",85:"mp3",146:"ac3",255:"aac",8192:"aac",22127:"vorbis",26447:"vorbis",61868:"flac"};function k8($){return A5[$]||null}function K$($){return R5[$]||null}var o7={avc:"H264",hevc:"H265",vp8:"VP80",vp9:"VP90",av1:"AV01",mpeg4:"XVID"};function z5($){let J=o7[$];if(J)return J;for(let[Y,j]of Object.entries(A5))if(j===$)return Y;return null}function _5($){for(let[J,Y]of Object.entries(R5))if(Y===$)return Number(J);return null}function L5($){return{microSecPerFrame:$.getUint32(0,!0),maxBytesPerSec:$.getUint32(4,!0),paddingGranularity:$.getUint32(8,!0),flags:$.getUint32(12,!0),totalFrames:$.getUint32(16,!0),initialFrames:$.getUint32(20,!0),streams:$.getUint32(24,!0),suggestedBufferSize:$.getUint32(28,!0),width:$.getUint32(32,!0),height:$.getUint32(36,!0)}}function M5($){let J=new TextDecoder("latin1");return{fccType:J.decode(new Uint8Array($.buffer,$.byteOffset,4)),fccHandler:J.decode(new Uint8Array($.buffer,$.byteOffset+4,4)),flags:$.getUint32(8,!0),priority:$.getUint16(12,!0),language:$.getUint16(14,!0),initialFrames:$.getUint32(16,!0),scale:$.getUint32(20,!0),rate:$.getUint32(24,!0),start:$.getUint32(28,!0),length:$.getUint32(32,!0),suggestedBufferSize:$.getUint32(36,!0),quality:$.getUint32(40,!0),sampleSize:$.getUint32(44,!0),frame:{left:$.getUint16(48,!0),top:$.getUint16(50,!0),right:$.getUint16(52,!0),bottom:$.getUint16(54,!0)}}}function F5($){let J=new TextDecoder("latin1");return{size:$.getUint32(0,!0),width:$.getInt32(4,!0),height:$.getInt32(8,!0),planes:$.getUint16(12,!0),bitCount:$.getUint16(14,!0),compression:J.decode(new Uint8Array($.buffer,$.byteOffset+16,4)),sizeImage:$.getUint32(20,!0),xPelsPerMeter:$.getInt32(24,!0),yPelsPerMeter:$.getInt32(28,!0),clrUsed:$.getUint32(32,!0),clrImportant:$.getUint32(36,!0)}}function B5($){let J=$.getUint16(0,!0),Y=$.getUint16(2,!0),j=$.getUint32(4,!0),X=$.getUint32(8,!0),Z=$.getUint16(12,!0),G=$.getUint16(14,!0),K=0,Q;if($.byteLength>=18){if(K=$.getUint16(16,!0),K>0&&$.byteLength>=18+K)Q=new Uint8Array($.buffer,$.byteOffset+18,K)}return{formatTag:J,channels:Y,samplesPerSec:j,avgBytesPerSec:X,blockAlign:Z,bitsPerSample:G,cbSize:K,extraData:Q}}function w5($,J){return{ckid:new TextDecoder("latin1").decode(new Uint8Array($.buffer,$.byteOffset+J,4)),flags:$.getUint32(J+4,!0),offset:$.getUint32(J+8,!0),size:$.getUint32(J+12,!0)}}function Q$($,J){return $.toString().padStart(2,"0")+J}function O5($){if($.length!==4)return null;let J=$.substring(0,2),Y=$.substring(2),j=Number.parseInt(J,10);if(isNaN(j))return null;return{streamNumber:j,type:Y}}/*!
182
+ * Copyright (c) 2025-present, Vanilagy and contributors
183
+ *
184
+ * This Source Code Form is subject to the terms of the Mozilla Public
185
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
186
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
187
+ */class q${demuxer;streamInfo;packetToIndex=new WeakMap;constructor($,J){this.demuxer=$;this.streamInfo=J}getDisposition(){throw Error("Method not implemented.")}getId(){return this.streamInfo.index}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){if(this.streamInfo.header.fccType==="vids")return this.streamInfo.format.compression;if(this.streamInfo.header.fccType==="auds")return this.streamInfo.format.formatTag.toString();return null}getName(){return null}getLanguageCode(){return"eng"}getTimeResolution(){if(this.streamInfo.header.rate>0)return this.streamInfo.header.rate/this.streamInfo.header.scale;return 1e6}async getFirstTimestamp(){if(this.streamInfo.packets.length===0)return 0;if(this.streamInfo.keyPacketIndices.length>0){let $=this.streamInfo.keyPacketIndices[0],J=this.streamInfo.packets[$];return J.timestamp+J.duration}return this.streamInfo.packets[0].timestamp}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}async getFirstPacket($){if(this.streamInfo.keyPacketIndices.length===0)return null;let J=this.streamInfo.keyPacketIndices[0],Y=this.streamInfo.packets[J];if($.metadataOnly){let X=new I(new Uint8Array,"key",Y.timestamp,Y.duration,J,Y.entry.size);return this.packetToIndex.set(X,J),X}let j=await this.demuxer.readPacket(Y.entry,Y.timestamp,Y.duration,J);if(j)this.packetToIndex.set(j,J);return j}async getPacket($,J){if(this.streamInfo.presentationTimestamps.length===0)return null;let Y=u(this.streamInfo.presentationTimestamps,$,(K)=>K.timestamp);if(Y===-1){let Q=this.streamInfo.presentationTimestamps[0].packetIndex,q=this.streamInfo.packets[Q];if(J.metadataOnly){let W=new I(new Uint8Array,q.entry.flags&L1?"key":"delta",q.timestamp,q.duration,Q,q.entry.size);return this.packetToIndex.set(W,Q),W}let U=await this.demuxer.readPacket(q.entry,q.timestamp,q.duration,Q);if(U)this.packetToIndex.set(U,Q);return U}let X=this.streamInfo.presentationTimestamps[Y].packetIndex,Z=this.streamInfo.packets[X];if($>Z.timestamp&&Y+1<this.streamInfo.presentationTimestamps.length){let K=this.streamInfo.presentationTimestamps[Y+1],Q=this.streamInfo.packets[K.packetIndex];if($>Z.timestamp+Z.duration*0.5)X=K.packetIndex,Z=Q}if(J.metadataOnly){let K=new I(new Uint8Array,Z.entry.flags&L1?"key":"delta",Z.timestamp,Z.duration,X,Z.entry.size);return this.packetToIndex.set(K,X),K}let G=await this.demuxer.readPacket(Z.entry,Z.timestamp,Z.duration,X);if(G)this.packetToIndex.set(G,X);return G}async getNextPacket($,J){let Y=this.packetToIndex.get($);if(Y===void 0)throw Error("Packet was not created from this track.");let j=Y+1;if(j>=this.streamInfo.packets.length)return null;let X=this.streamInfo.packets[j];if(J.metadataOnly){let G=new I(new Uint8Array,X.entry.flags&L1?"key":"delta",X.timestamp,X.duration,j,X.entry.size);return this.packetToIndex.set(G,j),G}let Z=await this.demuxer.readPacket(X.entry,X.timestamp,X.duration,j);if(Z)this.packetToIndex.set(Z,j);return Z}async getKeyPacket($,J){if(this.streamInfo.keyPacketIndices.length===0)return null;let Y=-1,j=0,X=this.streamInfo.keyPacketIndices.length-1;while(j<=X){let K=Math.floor((j+X)/2),Q=this.streamInfo.keyPacketIndices[K];if(this.streamInfo.packets[Q].timestamp<=$)Y=Q,j=K+1;else X=K-1}if(Y===-1&&this.streamInfo.keyPacketIndices.length>0)Y=this.streamInfo.keyPacketIndices[0];if(Y===-1)return null;let Z=this.streamInfo.packets[Y];if(J.metadataOnly){let K=new I(new Uint8Array,"key",Z.timestamp,Z.duration,Y,Z.entry.size);return this.packetToIndex.set(K,Y),K}let G=await this.demuxer.readPacket(Z.entry,Z.timestamp,Z.duration,Y);if(G)this.packetToIndex.set(G,Y);return G}async getNextKeyPacket($,J){let Y=this.packetToIndex.get($);if(Y===void 0)throw Error("Packet was not created from this track.");let j=Y1(this.streamInfo.keyPacketIndices,Y,(K)=>K),X=-1;if(j!==-1){if(j+1<this.streamInfo.keyPacketIndices.length)X=this.streamInfo.keyPacketIndices[j+1]}else for(let K=0;K<this.streamInfo.keyPacketIndices.length;K++){let Q=this.streamInfo.keyPacketIndices[K];if(Q>Y){X=Q;break}}if(X===-1)return null;let Z=this.streamInfo.packets[X];if(J.metadataOnly){let K=new I(new Uint8Array,"key",Z.timestamp,Z.duration,X,Z.entry.size);return this.packetToIndex.set(K,X),K}let G=await this.demuxer.readPacket(Z.entry,Z.timestamp,Z.duration,X);if(G)this.packetToIndex.set(G,X);return G}}class P5 extends q${getDisposition(){throw Error("Method not implemented.")}decoderConfigPromise=null;getCodec(){let $=this.streamInfo.format,J=k8($.compression);if(!J||$.compression.trim()==="")J=k8(this.streamInfo.header.fccHandler);return J}getCodedWidth(){let $=this.streamInfo.format;return Math.abs($.width)}getCodedHeight(){let $=this.streamInfo.format;return Math.abs($.height)}getRotation(){return 0}async getColorSpace(){return{}}async canBeTransparent(){return!1}async getDecoderConfig(){let $=this.getCodec();if(!$)return null;return this.decoderConfigPromise??=(async()=>{return{codec:$,codedWidth:this.getCodedWidth(),codedHeight:this.getCodedHeight()}})()}}class C5 extends q${getDisposition(){throw Error("Method not implemented.")}decoderConfig=null;getCodec(){let $=this.streamInfo.format;return K$($.formatTag)}getNumberOfChannels(){return this.streamInfo.format.channels}getSampleRate(){return this.streamInfo.format.samplesPerSec}async getDecoderConfig(){let $=this.getCodec();if(!$)return null;return this.decoderConfig??={codec:$,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}}class o0 extends W0{reader;mainHeader=null;streams=[];index=[];moviStart=0;moviSize=0;isRIFX=!1;inputTracks=[];metadataPromise=null;constructor($){super($);this.reader=$._reader}static async _canReadInput($){let Y=await $._reader.requestSlice(0,12);if(!Y||Y.remainingLength<12)return!1;let j=D(Y,4);if(!j)return!1;let X=o0.fourcc(j);if(X!=="RIFF"&&X!=="RIFX"&&X!=="RF64")return!1;Y.skip(4);let Z=D(Y,4);if(!Z)return!1;return o0.fourcc(Z)==="AVI "}static fourcc($){if(!$||$.length!==4)return" ";return Y0.decode($)}async computeDuration(){if(await this.ensureMetadata(),this.mainHeader&&this.mainHeader.microSecPerFrame>0&&this.mainHeader.totalFrames>0)return this.mainHeader.totalFrames*this.mainHeader.microSecPerFrame/1e6;let $=0;for(let J of this.inputTracks){let Y=await J.computeDuration();if(Y>$)$=Y}return $}async getTracks(){return await this.ensureMetadata(),this.inputTracks}async getMimeType(){return"video/x-msvideo"}async getMetadataTags(){return{}}async ensureMetadata(){if(!this.metadataPromise)this.metadataPromise=this.readMetadata();await this.metadataPromise}async readMetadata(){let $=await this.reader.requestSlice(0,12);if(!$||$.remainingLength<12)throw Error("Invalid AVI file: insufficient header");let J=o0.fourcc(D($,4));if(h0($),o0.fourcc(D($,4))!=="AVI ")throw Error("Invalid AVI file type");this.isRIFX=J==="RIFX",await this.parseChunks(),this.processIndex(),this.createTracks()}async parseChunks(){let $=12;while(!0){let J=await this.readChunkHeader($);if(!J)break;if(J.fourcc==="LIST"){let Y=await this.reader.requestSlice($+8,4);if(!Y)break;let j=o0.fourcc(D(Y,4));if(j==="hdrl")await this.parseHeaderList($+12,J.size-4);else if(j==="movi")this.moviStart=$+8,this.moviSize=J.size-4;$+=8+J.size}else if(J.fourcc==="idx1")await this.parseIndex($+8,J.size),$+=8+J.size;else $+=8+J.size;if(J.size%2!==0)$++}}async readChunkHeader($){let J=await this.reader.requestSlice($,8);if(!J||J.remainingLength<8)return null;let Y=o0.fourcc(D(J,4)),j=this.isRIFX?h0(J):h0(J);return{fourcc:Y,size:j,position:$+8}}async parseHeaderList($,J){let Y=$+J,j=$;while(j<Y){let X=await this.readChunkHeader(j);if(!X)break;if(X.fourcc==="avih"){let Z=await this.reader.requestSlice(X.position,X.size);if(Z)this.mainHeader=L5(new DataView(Z.bytes.buffer,Z.bytes.byteOffset+Z.bufferPos,X.size));j=X.position+X.size}else if(X.fourcc==="LIST"){let Z=await this.reader.requestSlice(X.position,4);if(Z){if(o0.fourcc(D(Z,4))==="strl")await this.parseStreamList(X.position+4,X.size-4)}j=X.position+X.size}else j=X.position+X.size;if(X.size%2!==0)j++}}async parseStreamList($,J){let Y=$+J,j=$,X={packets:[],presentationTimestamps:[],keyPacketIndices:[],index:this.streams.length};while(j<Y){let Z=await this.readChunkHeader(j);if(!Z)break;if(Z.fourcc==="strh"){let G=await this.reader.requestSlice(Z.position,Z.size);if(G)X.header=M5(new DataView(G.bytes.buffer,G.bytes.byteOffset+G.bufferPos,Z.size));j=Z.position+Z.size}else if(Z.fourcc==="strf"){let G=await this.reader.requestSlice(Z.position,Z.size);if(G&&X.header){let K=new DataView(G.bytes.buffer,G.bytes.byteOffset+G.bufferPos,Z.size);if(X.header.fccType==="vids")X.format=F5(K);else if(X.header.fccType==="auds")X.format=B5(K)}j=Z.position+Z.size}else j=Z.position+Z.size;if(Z.size%2!==0)j++}if(X.header&&X.format){let Z={header:X.header,format:X.format,packets:X.packets,presentationTimestamps:X.presentationTimestamps,keyPacketIndices:X.keyPacketIndices,index:X.index};this.streams.push(Z)}}async parseIndex($,J){let Y=await this.reader.requestSlice($,J);if(!Y)return;let j=new DataView(Y.bytes.buffer,Y.bytes.byteOffset+Y.bufferPos,J),X=Math.floor(J/16);for(let Z=0;Z<X;Z++){let G=w5(j,Z*16);this.index.push(G)}}processIndex(){for(let $ of this.index){let J=O5($.ckid);if(!J)continue;let Y=J.streamNumber;if(Y>=this.streams.length)continue;let j=this.streams[Y],X=j.packets.length,Z=this.calculateTimestamp(j,X),G=this.calculatePacketDuration(j,X);if(j.packets.push({entry:$,timestamp:Z,duration:G}),j.presentationTimestamps.push({timestamp:Z,packetIndex:X}),$.flags&L1)j.keyPacketIndices.push(X)}for(let $ of this.streams)$.presentationTimestamps.sort((J,Y)=>J.timestamp-Y.timestamp)}createTracks(){for(let $ of this.streams){let{header:J,format:Y}=$;if(J.fccType==="vids"&&"compression"in Y){let j=Y,X=k8(j.compression);if(!X||j.compression.trim()==="")X=k8(J.fccHandler);if(X){let Z=new P5(this,$);$.track=Z;let G=new D0(this.input,Z);this.inputTracks.push(G)}}else if(J.fccType==="auds"&&"formatTag"in Y){if(K$(Y.formatTag)){let Z=new C5(this,$);$.track=Z;let G=new t(this.input,Z);this.inputTracks.push(G)}}}}async readPacket($,J,Y=0,j=-1){let X=this.moviStart+$.offset+8,Z=await this.reader.requestSlice(X,$.size);if(!Z)return null;let G=D(Z,$.size);if(!G)return null;return new I(G,$.flags&L1?"key":"delta",J,Y,j,G.byteLength)}calculateTimestamp($,J){if($.header.fccType==="vids"&&$.header.rate>0&&$.header.scale>0)return J*$.header.scale/$.header.rate;if($.header.fccType==="auds"){let Y=$.format;if($.header.sampleSize===0||$.header.sampleSize===1)return J*1152/Y.samplesPerSec;if($.header.rate>0&&$.header.scale>0)return J*$.header.scale/$.header.rate}return 0}calculatePacketDuration($,J){if($.header.fccType==="vids"&&$.header.rate>0&&$.header.scale>0)return $.header.scale/$.header.rate;if($.header.fccType==="auds"){let Y=$.format;if($.header.sampleSize===0||$.header.sampleSize===1)return 1152/Y.samplesPerSec;if($.header.rate>0&&$.header.scale>0)return $.header.scale/$.header.rate}return 0}}/*!
188
+ * Copyright (c) 2025-present, Vanilagy and contributors
189
+ *
190
+ * This Source Code Form is subject to the terms of the Mozilla Public
191
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
192
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
193
+ */var s6=($)=>{if($===0)return null;if($===1)return 192;if($>=2&&$<=5)return 144*2**$;if($===6)return"uncommon-u8";if($===7)return"uncommon-u16";if($>=8&&$<=15)return 2**$;return null},D5=($,J)=>{switch($){case 0:return J;case 1:return 88200;case 2:return 176400;case 3:return 192000;case 4:return 8000;case 5:return 16000;case 6:return 22050;case 7:return 24000;case 8:return 32000;case 9:return 44100;case 10:return 48000;case 11:return 96000;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},a6=($)=>{let J=0,Y=new f(D($,1));while(Y.readBits(1)===1)J++;if(J===0)return Y.readBits(7);let j=[],X=J-1,Z=new f(D($,X)),G=8-J-1;for(let Q=0;Q<G;Q++)j.unshift(Y.readBits(1));for(let Q=0;Q<X;Q++)for(let q=0;q<8;q++){let U=Z.readBits(1);if(q<2)continue;j.unshift(U)}return j.reduce((Q,q,U)=>{return Q|q<<U},0)},t6=($,J)=>{if(J==="uncommon-u16")return X0($)+1;if(J==="uncommon-u8")return y($)+1;if(typeof J==="number")return J;i(J),H(!1)},E5=($,J)=>{if(J==="uncommon-u16")return X0($);if(J==="uncommon-u16-10")return X0($)*10;if(J==="uncommon-u8")return y($);if(typeof J==="number")return J;return null},T5=($)=>{let Y=0;for(let j of $){Y^=j;for(let X=0;X<8;X++){if((Y&128)!==0)Y=Y<<1^7;else Y<<=1;Y&=255}}return Y};/*!
194
+ * Copyright (c) 2025-present, Vanilagy and contributors
195
+ *
196
+ * This Source Code Form is subject to the terms of the Mozilla Public
197
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
198
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
199
+ */class U$ extends W0{reader;loadedSamples=[];metadataPromise=null;track=null;metadataTags={};audioInfo=null;lastLoadedPos=null;blockingBit=null;readingMutex=new w0;lastSampleLoaded=!1;constructor($){super($);this.reader=$._reader}async computeDuration(){return await this.readMetadata(),H(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),H(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let $=4;return this.metadataPromise??=(async()=>{while(this.reader.fileSize===null||$<this.reader.fileSize){let J=this.reader.requestSlice($,4);if(J instanceof Promise)J=await J;if($+=4,J===null)throw Error(`Metadata block at position ${$} is too small! Corrupted file.`);H(J);let Y=y(J),j=_1(J),X=(Y&128)!==0;switch(Y&127){case 0:{let G=this.reader.requestSlice($,j);if(G instanceof Promise)G=await G;if(H(G),G===null)throw Error(`StreamInfo block at position ${$} is too small! Corrupted file.`);let K=D(G,34),Q=new f(K),q=Q.readBits(16),U=Q.readBits(16),W=Q.readBits(24),V=Q.readBits(24),N=Q.readBits(20),A=Q.readBits(3)+1;Q.readBits(5);let R=Q.readBits(36);Q.skipBits(128);let z=new Uint8Array(42);z.set(new Uint8Array([102,76,97,67]),0),z.set(new Uint8Array([128,0,0,34]),4),z.set(K,8),this.audioInfo={numberOfChannels:A,sampleRate:N,totalSamples:R,minimumBlockSize:q,maximumBlockSize:U,minimumFrameSize:W,maximumFrameSize:V,description:z},this.track=new t(this.input,new v5(this));break}case 4:{let G=this.reader.requestSlice($,j);if(G instanceof Promise)G=await G;H(G),P8(D(G,j),this.metadataTags);break}case 6:{let G=this.reader.requestSlice($,j);if(G instanceof Promise)G=await G;H(G);let K=P(G),Q=P(G),q=Y0.decode(D(G,Q)),U=P(G),W=Y0.decode(D(G,U));G.skip(16);let V=P(G),N=D(G,V);this.metadataTags.images??=[],this.metadataTags.images.push({data:N,mimeType:q,kind:K===3?"coverFront":K===4?"coverBack":"unknown",description:W});break}default:break}if($+=j,X){this.lastLoadedPos=$;break}}})()}async readNextFlacFrame({startPos:$,isFirstPacket:J}){H(this.audioInfo);let Y=6,j=16,X=this.audioInfo.maximumFrameSize+j,Z=await this.reader.requestSliceRange($,this.audioInfo.minimumFrameSize,X);if(!Z)return null;let G=this.readFlacFrameHeader({slice:Z,isFirstPacket:J});if(!G)return null;Z.filePos=$+this.audioInfo.minimumFrameSize;while(!0){if(Z.filePos>Z.end-Y)return{num:G.num,blockSize:G.blockSize,sampleRate:G.sampleRate,size:Z.end-$,isLastFrame:!0};if(y(Z)===255){let Q=Z.filePos,q=y(Z),U=this.blockingBit===1?249:248;if(q!==U){Z.filePos=Q;continue}Z.skip(-2);let W=Z.filePos-$,V=this.readFlacFrameHeader({slice:Z,isFirstPacket:!1});if(!V){Z.filePos=Q;continue}if(this.blockingBit===0){if(V.num-G.num!==1){Z.filePos=Q;continue}}else if(V.num-G.num!==G.blockSize){Z.filePos=Q;continue}return{num:G.num,blockSize:G.blockSize,sampleRate:G.sampleRate,size:W,isLastFrame:!1}}}}readFlacFrameHeader({slice:$,isFirstPacket:J}){let Y=$.filePos,j=D($,4),X=new f(j);if(X.readBits(15)!==32764)return null;if(this.blockingBit===null){H(J);let R=X.readBits(1);this.blockingBit=R}else if(this.blockingBit===1){if(H(!J),X.readBits(1)!==1)return null}else if(this.blockingBit===0){if(H(!J),X.readBits(1)!==0)return null}else throw Error("Invalid blocking bit");let G=s6(X.readBits(4));if(!G)return null;H(this.audioInfo);let K=D5(X.readBits(4),this.audioInfo.sampleRate);if(!K)return null;if(X.readBits(4),X.readBits(3),X.readBits(1)!==0)return null;let q=a6($),U=t6($,G),W=E5($,K);if(W===null)return null;if(W!==this.audioInfo.sampleRate)return null;let V=$.filePos-Y,N=y($);$.skip(-V),$.skip(-1);let A=T5(D($,V));if(N!==A)return null;return{num:q,blockSize:U,sampleRate:W}}async advanceReader(){await this.readMetadata(),H(this.lastLoadedPos!==null),H(this.audioInfo);let $=this.lastLoadedPos,J=await this.readNextFlacFrame({startPos:$,isFirstPacket:this.loadedSamples.length===0});if(!J){this.lastSampleLoaded=!0;return}let Y=this.loadedSamples[this.loadedSamples.length-1],X={blockOffset:Y?Y.blockOffset+Y.blockSize:0,blockSize:J.blockSize,byteOffset:$,byteSize:J.size};if(this.lastLoadedPos=this.lastLoadedPos+J.size,this.loadedSamples.push(X),J.isLastFrame){this.lastSampleLoaded=!0;return}}}class v5{demuxer;constructor($){this.demuxer=$}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getSampleRate(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return a}getTimeResolution(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...L0}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return H(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket($,J){if(H(this.demuxer.audioInfo),$<0)throw Error("Timestamp cannot be negative");let Y=await this.demuxer.readingMutex.acquire();try{while(!0){let j=u(this.demuxer.loadedSamples,$,(K)=>K.blockOffset/this.demuxer.audioInfo.sampleRate);if(j===-1){await this.demuxer.advanceReader();continue}let X=this.demuxer.loadedSamples[j],Z=X.blockOffset/this.demuxer.audioInfo.sampleRate,G=X.blockSize/this.demuxer.audioInfo.sampleRate;if(Z+G<=$){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,J);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(j,J)}}finally{Y()}}async getNextPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{let j=$.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&j>=this.demuxer.loadedSamples.length)return null;while(j>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(j,J)}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}async getPacketAtIndex($,J){let Y=this.demuxer.loadedSamples[$];if(!Y)return null;let j;if(J.metadataOnly)j=G0;else{let G=this.demuxer.reader.requestSlice(Y.byteOffset,Y.byteSize);if(G instanceof Promise)G=await G;if(!G)return null;j=D(G,Y.byteSize)}H(this.demuxer.audioInfo);let X=Y.blockOffset/this.demuxer.audioInfo.sampleRate,Z=Y.blockSize/this.demuxer.audioInfo.sampleRate;return new I(j,"key",X,Z,$,Y.byteSize)}async getFirstPacket($){while(this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,$)}}/*!
200
+ * Copyright (c) 2025-present, Vanilagy and contributors
201
+ *
202
+ * This Source Code Form is subject to the terms of the Mozilla Public
203
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
204
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
205
+ */var u8=128,W8=10,U8=["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"],b5=($,J)=>{let Y=$.filePos;J.raw??={},J.raw.TAG??=D($,u8-3),$.filePos=Y;let j=q8($,30);if(j)J.title??=j;let X=q8($,30);if(X)J.artist??=X;let Z=q8($,30);if(Z)J.album??=Z;let G=q8($,4),K=Number.parseInt(G,10);if(Number.isInteger(K)&&K>0)J.date??=new Date(K,0,1);let Q=D($,30),q;if(Q[28]===0&&Q[29]!==0){let W=Q[29];if(W>0)J.trackNumber??=W;$.skip(-30),q=q8($,28),$.skip(2)}else $.skip(-30),q=q8($,30);if(q)J.comment??=q;let U=y($);if(U<U8.length)J.genre??=U8[U]},q8=($,J)=>{let Y=D($,J),j=b1(Y.indexOf(0),Y.length),X=Y.subarray(0,j),Z="";for(let G=0;G<X.length;G++)Z+=String.fromCharCode(X[G]);return Z.trimEnd()},d1=($)=>{let J=$.filePos,Y=s($,3),j=y($),X=y($),Z=y($),G=P($);if(Y!=="ID3"||j===255||X===255||(G&2155905152)!==0)return $.filePos=J,null;let K=T6(G);return{majorVersion:j,revision:X,flags:Z,size:K}},e6=($,J,Y)=>{if(![2,3,4].includes(J.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${J.majorVersion}`);return}let j=D($,J.size),X=new x5(J,j);if(J.flags&16)X.removeFooter();if(J.flags&128&&J.majorVersion===3)X.ununsynchronizeAll();if(J.flags&64){let Z=X.readU32();if(J.majorVersion===3)X.pos+=Z;else X.pos+=Z-4}while(X.pos<=X.bytes.length-X.frameHeaderSize()){let Z=X.readId3V2Frame();if(!Z)break;let G=X.pos,K=X.pos+Z.size,Q=!1,q=!1,U=!1;if(J.majorVersion===3)Q=!!(Z.flags&64),q=!!(Z.flags&128);else if(J.majorVersion===4)Q=!!(Z.flags&4),q=!!(Z.flags&8),U=!!(Z.flags&2)||!!(J.flags&128);if(Q){console.warn(`Skipping encrypted ID3v2 frame ${Z.id}`),X.pos=K;continue}if(q){console.warn(`Skipping compressed ID3v2 frame ${Z.id}`),X.pos=K;continue}if(U)X.ununsynchronizeRegion(X.pos,K);if(Y.raw??={},Z.id[0]==="T")Y.raw[Z.id]??=X.readId3V2EncodingAndText(K);else Y.raw[Z.id]??=X.readBytes(Z.size);switch(X.pos=G,Z.id){case"TIT2":case"TT2":Y.title??=X.readId3V2EncodingAndText(K);break;case"TIT3":case"TT3":Y.description??=X.readId3V2EncodingAndText(K);break;case"TPE1":case"TP1":Y.artist??=X.readId3V2EncodingAndText(K);break;case"TALB":case"TAL":Y.album??=X.readId3V2EncodingAndText(K);break;case"TPE2":case"TP2":Y.albumArtist??=X.readId3V2EncodingAndText(K);break;case"TRCK":case"TRK":{let V=X.readId3V2EncodingAndText(K).split("/"),N=Number.parseInt(V[0],10),A=V[1]&&Number.parseInt(V[1],10);if(Number.isInteger(N)&&N>0)Y.trackNumber??=N;if(A&&Number.isInteger(A)&&A>0)Y.tracksTotal??=A}break;case"TPOS":case"TPA":{let V=X.readId3V2EncodingAndText(K).split("/"),N=Number.parseInt(V[0],10),A=V[1]&&Number.parseInt(V[1],10);if(Number.isInteger(N)&&N>0)Y.discNumber??=N;if(A&&Number.isInteger(A)&&A>0)Y.discsTotal??=A}break;case"TCON":case"TCO":{let W=X.readId3V2EncodingAndText(K),V=/^\((\d+)\)/.exec(W);if(V){let N=Number.parseInt(V[1]);if(U8[N]!==void 0){Y.genre??=U8[N];break}}if(V=/^\d+$/.exec(W),V){let N=Number.parseInt(V[0]);if(U8[N]!==void 0){Y.genre??=U8[N];break}}Y.genre??=W}break;case"TDRC":case"TDAT":{let W=X.readId3V2EncodingAndText(K),V=new Date(W);if(!Number.isNaN(V.getTime()))Y.date??=V}break;case"TYER":case"TYE":{let W=X.readId3V2EncodingAndText(K),V=Number.parseInt(W,10);if(Number.isInteger(V))Y.date??=new Date(V,0,1)}break;case"USLT":case"ULT":{let W=X.readU8();X.pos+=3,X.readId3V2Text(W,K),Y.lyrics??=X.readId3V2Text(W,K)}break;case"COMM":case"COM":{let W=X.readU8();X.pos+=3,X.readId3V2Text(W,K),Y.comment??=X.readId3V2Text(W,K)}break;case"APIC":case"PIC":{let W=X.readId3V2TextEncoding(),V;if(J.majorVersion===2){let z=X.readAscii(3);V=z==="PNG"?"image/png":z==="JPG"?"image/jpeg":"image/*"}else V=X.readId3V2Text(W,K);let N=X.readU8(),A=X.readId3V2Text(W,K).trimEnd(),R=K-X.pos;if(R>=0){let z=X.readBytes(R);if(!Y.images)Y.images=[];Y.images.push({data:z,mimeType:V,kind:N===3?"coverFront":N===4?"coverBack":"unknown",description:A})}}break;default:X.pos+=Z.size;break}X.pos=K}};class x5{header;bytes;pos=0;view;constructor($,J){this.header=$;this.bytes=J;this.view=new DataView(J.buffer,J.byteOffset,J.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let $=[];for(let J=0;J<this.bytes.length;J++){let Y=this.bytes[J];if($.push(Y),Y===255&&J!==this.bytes.length-1){if(this.bytes[J]===0)J++}}this.bytes=new Uint8Array($),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion($,J){let Y=[];for(let Z=$;Z<J;Z++){let G=this.bytes[Z];if(Y.push(G),G===255&&Z!==J-1){if(this.bytes[Z+1]===0)Z++}}let j=this.bytes.subarray(0,$),X=this.bytes.subarray(J);this.bytes=new Uint8Array(j.length+Y.length+X.length),this.bytes.set(j,0),this.bytes.set(Y,j.length),this.bytes.set(X,j.length+Y.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-W8),this.view=new DataView(this.bytes.buffer)}readBytes($){let J=this.bytes.subarray(this.pos,this.pos+$);return this.pos+=$,J}readU8(){let $=this.view.getUint8(this.pos);return this.pos+=1,$}readU16(){let $=this.view.getUint16(this.pos,!1);return this.pos+=2,$}readU24(){let $=this.view.getUint16(this.pos,!1),J=this.view.getUint8(this.pos+1);return this.pos+=3,$*256+J}readU32(){let $=this.view.getUint32(this.pos,!1);return this.pos+=4,$}readAscii($){let J="";for(let Y=0;Y<$;Y++)J+=String.fromCharCode(this.view.getUint8(this.pos+Y));return this.pos+=$,J}readId3V2Frame(){if(this.header.majorVersion===2){let G=this.readAscii(3);if(G==="\x00\x00\x00")return null;let K=this.readU24();return{id:G,size:K,flags:0}}let $=this.readAscii(4);if($==="\x00\x00\x00\x00")return null;let J=this.readU32(),Y=this.header.majorVersion===4?T6(J):J,j=this.readU16(),X=this.pos,Z=(G)=>{let K=this.pos+G;if(K>this.bytes.length)return!1;if(K<=this.bytes.length-this.frameHeaderSize()){this.pos+=G;let Q=this.readAscii(4);if(Q!=="\x00\x00\x00\x00"&&!/[0-9A-Z]{4}/.test(Q))return!1}return!0};if(!Z(Y)){let G=this.header.majorVersion===4?J:T6(J);if(Z(G))Y=G}return this.pos=X,{id:$,size:Y,flags:j}}readId3V2TextEncoding(){let $=this.readU8();if($>3)throw Error(`Unsupported text encoding: ${$}`);return $}readId3V2Text($,J){let Y=this.pos,j=this.readBytes(J-this.pos);switch($){case 0:{let X="";for(let Z=0;Z<j.length;Z++){let G=j[Z];if(G===0){this.pos=Y+Z+1;break}X+=String.fromCharCode(G)}return X}case 1:{if(j[0]===255&&j[1]===254){let Z=new TextDecoder("utf-16le"),G=b1(j.findIndex((K,Q)=>K===0&&j[Q+1]===0&&Q%2===0),j.length);return this.pos=Y+Math.min(G+2,j.length),Z.decode(j.subarray(2,G))}if(j[0]===254&&j[1]===255){let Z=new TextDecoder("utf-16be"),G=b1(j.findIndex((K,Q)=>K===0&&j[Q+1]===0&&Q%2===0),j.length);return this.pos=Y+Math.min(G+2,j.length),Z.decode(j.subarray(2,G))}let X=b1(j.findIndex((Z)=>Z===0),j.length);return this.pos=Y+Math.min(X+1,j.length),Y0.decode(j.subarray(0,X))}case 2:{let X=new TextDecoder("utf-16be"),Z=b1(j.findIndex((G,K)=>G===0&&j[K+1]===0&&K%2===0),j.length);return this.pos=Y+Math.min(Z+2,j.length),X.decode(j.subarray(0,Z))}case 3:{let X=b1(j.findIndex((Z)=>Z===0),j.length);return this.pos=Y+Math.min(X+1,j.length),Y0.decode(j.subarray(0,X))}}}readId3V2EncodingAndText($){if(this.pos>=$)return"";let J=this.readId3V2TextEncoding();return this.readId3V2Text(J,$)}}class p8{writer;helper=new Uint8Array(8);helperView=h(this.helper);constructor($){this.writer=$}writeId3V2Tag($){let J=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let Y=this.writer.getPos(),j=new Set;for(let{key:G,value:K}of v0($))switch(G){case"title":this.writeId3V2TextFrame("TIT2",K),j.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",K),j.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",K),j.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",K),j.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",K),j.add("TPE2");break;case"trackNumber":{let Q=$.tracksTotal!==void 0?`${K}/${$.tracksTotal}`:K.toString();this.writeId3V2TextFrame("TRCK",Q),j.add("TRCK")}break;case"discNumber":{let Q=$.discsTotal!==void 0?`${K}/${$.discsTotal}`:K.toString();this.writeId3V2TextFrame("TPOS",Q),j.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",K),j.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",K.toISOString().slice(0,10)),j.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(K),j.add("USLT");break;case"comment":this.writeId3V2CommentFrame(K),j.add("COMM");break;case"images":{let Q={coverFront:3,coverBack:4,unknown:0};for(let q of K){let U=Q[q.kind]??0,W=q.description??"";this.writeId3V2ApicFrame(q.mimeType,U,W,q.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:i(G)}if($.raw)for(let G in $.raw){let K=$.raw[G];if(K==null||G.length!==4||j.has(G))continue;let Q;if(typeof K==="string"){let q=m.encode(K);Q=new Uint8Array(q.byteLength+2),Q[0]=3,Q.set(q,1)}else if(K instanceof Uint8Array)Q=K;else continue;this.writeAscii(G),this.writeSynchsafeU32(Q.byteLength),this.writeU16(0),this.writer.write(Q)}let X=this.writer.getPos(),Z=X-Y;return this.writer.seek(J+6),this.writeSynchsafeU32(Z),this.writer.seek(X),Z+10}writeU8($){this.helper[0]=$,this.writer.write(this.helper.subarray(0,1))}writeU16($){this.helperView.setUint16(0,$,!1),this.writer.write(this.helper.subarray(0,2))}writeU32($){this.helperView.setUint32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii($){for(let J=0;J<$.length;J++)this.helper[J]=$.charCodeAt(J);this.writer.write(this.helper.subarray(0,$.length))}writeSynchsafeU32($){this.writeU32(uJ($))}writeIsoString($){let J=new Uint8Array($.length+1);for(let Y=0;Y<$.length;Y++)J[Y]=$.charCodeAt(Y);J[$.length]=0,this.writer.write(J)}writeUtf8String($){let J=m.encode($);this.writer.write(J),this.writeU8(0)}writeId3V2TextFrame($,J){let Y=A1(J),X=1+(Y?J.length:m.encode(J).byteLength)+1;if(this.writeAscii($),this.writeSynchsafeU32(X),this.writeU16(0),this.writeU8(Y?0:3),Y)this.writeIsoString(J);else this.writeUtf8String(J)}writeId3V2LyricsFrame($){let J=A1($),Y="",j=5+$.length+1;if(this.writeAscii("USLT"),this.writeSynchsafeU32(j),this.writeU16(0),this.writeU8(J?0:3),this.writeAscii("und"),J)this.writeIsoString(""),this.writeIsoString($);else this.writeUtf8String(""),this.writeUtf8String($)}writeId3V2CommentFrame($){let J=A1($),Y=J?$.length:m.encode($).byteLength,j="",X=5+Y+1;if(this.writeAscii("COMM"),this.writeSynchsafeU32(X),this.writeU16(0),this.writeU8(J?0:3),this.writeU8(117),this.writeU8(110),this.writeU8(100),J)this.writeIsoString(""),this.writeIsoString($);else this.writeUtf8String(""),this.writeUtf8String($)}writeId3V2ApicFrame($,J,Y,j){let X=A1($)&&A1(Y),Z=X?Y.length:m.encode(Y).byteLength,G=1+$.length+1+1+Z+1+j.byteLength;if(this.writeAscii("APIC"),this.writeSynchsafeU32(G),this.writeU16(0),this.writeU8(X?0:3),X)this.writeIsoString($);else this.writeUtf8String($);if(this.writeU8(J),X)this.writeIsoString(Y);else this.writeUtf8String(Y);this.writer.write(j)}}/*!
206
+ * Copyright (c) 2025-present, Vanilagy and contributors
207
+ *
208
+ * This Source Code Form is subject to the terms of the Mozilla Public
209
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
210
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
211
+ */var $2=($)=>{let Y=($.hasVideo?"video/":$.hasAudio?"audio/":"application/")+($.isQuickTime?"quicktime":"mp4");if($.codecStrings.length>0){let j=[...new Set($.codecStrings)];Y+=`; codecs="${j.join(", ")}"`}return Y};/*!
212
+ * Copyright (c) 2025-present, Vanilagy and contributors
213
+ *
214
+ * This Source Code Form is subject to the terms of the Mozilla Public
215
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
216
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
217
+ */var f0=8,U1=16,g0=($)=>{let J=P($),Y=s($,4),j=8;if(J===1)J=O0($),j=16;let Z=J-j;if(Z<0)return null;return{name:Y,totalSize:J,headerSize:j,contentSize:Z}},M1=($)=>{return q1($)/65536},J2=($)=>{return q1($)/1073741824},Y2=($)=>{let J=0;for(let Y=0;Y<4;Y++){J<<=7;let j=y($);if(J|=j&127,(j&128)===0)break}return J},k0=($)=>{let J=X0($);return $.skip(2),J=Math.min(J,$.remainingLength),Y0.decode(D($,J))},I5=($)=>{let J=g0($);if(!J||J.name!=="data")return null;if($.remainingLength<8)return null;let Y=P($);$.skip(4);let j=D($,J.contentSize-8);switch(Y){case 1:return Y0.decode(j);case 2:return new TextDecoder("utf-16be").decode(j);case 13:return new I0(j,"image/jpeg");case 14:return new I0(j,"image/png");case 27:return new I0(j,"image/bmp");default:return j}};/*!
218
+ * Copyright (c) 2025-present, Vanilagy and contributors
219
+ *
220
+ * This Source Code Form is subject to the terms of the Mozilla Public
221
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
222
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
223
+ */class H$ extends W0{reader;moovSlice=null;currentTrack=null;tracks=[];metadataPromise=null;movieTimescale=-1;movieDurationInTimescale=-1;isQuickTime=!1;metadataTags={};currentMetadataKeys=null;isFragmented=!1;fragmentTrackDefaults=[];currentFragment=null;lastReadFragment=null;constructor($){super($);this.reader=$._reader}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((Y)=>Y.computeDuration()));return Math.max(0,...J)}async getTracks(){return await this.readMetadata(),this.tracks.map(($)=>$.inputTrack)}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.tracks.map((J)=>J.inputTrack.getCodecParameterString()));return $2({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some((J)=>J.info?.type==="video"),hasAudio:this.tracks.some((J)=>J.info?.type==="audio"),codecStrings:$.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,f0,U1);if(J instanceof Promise)J=await J;if(!J)break;let Y=$,j=g0(J);if(!j)break;if(j.name==="ftyp"){let X=s(J,4);this.isQuickTime=X==="qt "}else if(j.name==="moov"){let X=this.reader.requestSlice(J.filePos,j.contentSize);if(X instanceof Promise)X=await X;if(!X)break;this.moovSlice=X,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((Z,G)=>Number(G.disposition.default)-Number(Z.disposition.default));for(let Z of this.tracks){let G=Z.editListPreviousSegmentDurations/this.movieTimescale;Z.editListOffset-=Math.round(G*Z.timescale)}break}$=Y+j.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let J=this.reader.requestSlice(this.reader.fileSize-4,4);if(J instanceof Promise)J=await J;H(J);let Y=P(J),j=this.reader.fileSize-Y;if(j>=0&&j<=this.reader.fileSize-U1){let X=this.reader.requestSliceRange(j,f0,U1);if(X instanceof Promise)X=await X;if(X){let Z=g0(X);if(Z&&Z.name==="mfra"){let G=this.reader.requestSlice(X.filePos,Z.contentSize);if(G instanceof Promise)G=await G;if(G)this.readContiguousBoxes(G)}}}}})()}getSampleTableForTrack($){if($.sampleTable)return $.sampleTable;let J={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};$.sampleTable=J,H(this.moovSlice);let Y=this.moovSlice.slice($.sampleTableByteOffset);if(this.currentTrack=$,this.traverseBox(Y),this.currentTrack=null,$.info?.type==="audio"&&$.info.codec&&o.includes($.info.codec)&&J.sampleCompositionTimeOffsets.length===0){H($.info?.type==="audio");let X=U0($.info.codec),Z=[],G=[];for(let K=0;K<J.sampleToChunk.length;K++){let Q=J.sampleToChunk[K],q=J.sampleToChunk[K+1],U=(q?q.startChunkIndex:J.chunkOffsets.length)-Q.startChunkIndex;for(let W=0;W<U;W++){let V=Q.startSampleIndex+W*Q.samplesPerChunk,N=V+Q.samplesPerChunk,A=u(J.sampleTimingEntries,V,(w)=>w.startIndex),R=J.sampleTimingEntries[A],z=u(J.sampleTimingEntries,N,(w)=>w.startIndex),_=J.sampleTimingEntries[z],L=R.startDecodeTimestamp+(V-R.startIndex)*R.delta,B=_.startDecodeTimestamp+(N-_.startIndex)*_.delta-L,F=n(Z);if(F&&F.delta===B)F.count++;else Z.push({startIndex:Q.startChunkIndex+W,startDecodeTimestamp:L,count:1,delta:B});let C=Q.samplesPerChunk*X.sampleSize*$.info.numberOfChannels;G.push(C)}Q.startSampleIndex=Q.startChunkIndex,Q.samplesPerChunk=1}J.sampleTimingEntries=Z,J.sampleSizes=G}if(J.sampleCompositionTimeOffsets.length>0){J.presentationTimestamps=[];for(let X of J.sampleTimingEntries)for(let Z=0;Z<X.count;Z++)J.presentationTimestamps.push({presentationTimestamp:X.startDecodeTimestamp+Z*X.delta,sampleIndex:X.startIndex+Z});for(let X of J.sampleCompositionTimeOffsets)for(let Z=0;Z<X.count;Z++){let G=X.startIndex+Z,K=J.presentationTimestamps[G];if(!K)continue;K.presentationTimestamp+=X.offset}J.presentationTimestamps.sort((X,Z)=>X.presentationTimestamp-Z.presentationTimestamp),J.presentationTimestampIndexMap=Array(J.presentationTimestamps.length).fill(-1);for(let X=0;X<J.presentationTimestamps.length;X++)J.presentationTimestampIndexMap[J.presentationTimestamps[X].sampleIndex]=X}return J}async readFragment($){if(this.lastReadFragment?.moofOffset===$)return this.lastReadFragment;let J=this.reader.requestSliceRange($,f0,U1);if(J instanceof Promise)J=await J;H(J);let Y=g0(J);H(Y?.name==="moof");let j=this.reader.requestSlice($,Y.totalSize);if(j instanceof Promise)j=await j;H(j),this.traverseBox(j);let X=this.lastReadFragment;H(X&&X.moofOffset===$);for(let[,Z]of X.trackData){let G=Z.track,{fragmentPositionCache:K}=G;if(!Z.startTimestampIsFinal){let q=G.fragmentLookupTable.find((U)=>U.moofOffset===X.moofOffset);if(q)W$(Z,q.timestamp);else{let U=u(K,X.moofOffset-1,(W)=>W.moofOffset);if(U!==-1){let W=K[U];W$(Z,W.endTimestamp)}}Z.startTimestampIsFinal=!0}let Q=u(K,Z.startTimestamp,(q)=>q.startTimestamp);if(Q===-1||K[Q].moofOffset!==X.moofOffset)K.splice(Q+1,0,{moofOffset:X.moofOffset,startTimestamp:Z.startTimestamp,endTimestamp:Z.endTimestamp})}return X}readContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-f0)if(!this.traverseBox($))break}*iterateContiguousBoxes($){let J=$.filePos;while($.filePos-J<=$.length-f0){let Y=$.filePos,j=g0($);if(!j)break;yield{boxInfo:j,slice:$},$.filePos=Y+j.totalSize}}traverseBox($){let J=$.filePos,Y=g0($);if(!Y)return!1;let j=$.filePos,X=J+Y.totalSize;switch(Y.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"mvhd":{let Z=y($);if($.skip(3),Z===1)$.skip(16),this.movieTimescale=P($),this.movieDurationInTimescale=O0($);else $.skip(8),this.movieTimescale=P($),this.movieDurationInTimescale=P($)}break;case"trak":{let Z={id:-1,demuxer:this,inputTrack:null,disposition:{...L0},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:a,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=Z,this.readContiguousBoxes($.slice(j,Y.contentSize)),Z.id!==-1&&Z.timescale!==-1&&Z.info!==null){if(Z.info.type==="video"&&Z.info.width!==-1){let G=Z;Z.inputTrack=new D0(this.input,new h5(G)),this.tracks.push(Z)}else if(Z.info.type==="audio"&&Z.info.numberOfChannels!==-1){let G=Z;Z.inputTrack=new t(this.input,new f5(G)),this.tracks.push(Z)}else if(Z.info.type==="subtitle"){let G=Z;Z.inputTrack=new p1(this.input,new g5(G)),this.tracks.push(Z)}}this.currentTrack=null}break;case"tkhd":{let Z=this.currentTrack;if(!Z)break;let G=y($),Q=!!(_1($)&1);if(Z.disposition.default=Q,G===0)$.skip(8),Z.id=P($),$.skip(4),Z.durationInMovieTimescale=P($);else if(G===1)$.skip(16),Z.id=P($),$.skip(4),Z.durationInMovieTimescale=O0($);else throw Error(`Incorrect track header version ${G}.`);$.skip(16);let q=[M1($),M1($),J2($),M1($),M1($),J2($),M1($),M1($),J2($)],U=N1(F8(a7(q),90));H(U===0||U===90||U===180||U===270),Z.rotation=U}break;case"elst":{let Z=this.currentTrack;if(!Z)break;let G=y($);$.skip(3);let K=!1,Q=0,q=P($);for(let U=0;U<q;U++){let W=G===1?O0($):P($),V=G===1?W5($):q1($),N=M1($);if(W===0)continue;if(K){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(V===-1){Q+=W;continue}if(N!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}Z.editListPreviousSegmentDurations=Q,Z.editListOffset=V,K=!0}}break;case"mdhd":{let Z=this.currentTrack;if(!Z)break;let G=y($);if($.skip(3),G===0)$.skip(8),Z.timescale=P($),Z.durationInMediaTimescale=P($);else if(G===1)$.skip(16),Z.timescale=P($),Z.durationInMediaTimescale=O0($);let K=X0($);if(K>0){Z.languageCode="";for(let Q=0;Q<3;Q++)Z.languageCode=String.fromCharCode(96+(K&31))+Z.languageCode,K>>=5;if(!d0(Z.languageCode))Z.languageCode=a}}break;case"hdlr":{let Z=this.currentTrack;if(!Z)break;$.skip(8);let G=s($,4);if(G==="vide")Z.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null};else if(G==="soun")Z.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null};else if(G==="text"||G==="subt"||G==="sbtl")Z.info={type:"subtitle",codec:null,codecPrivateText:null}}break;case"stbl":{let Z=this.currentTrack;if(!Z)break;Z.sampleTableByteOffset=J,this.readContiguousBoxes($.slice(j,Y.contentSize))}break;case"stsd":{let Z=this.currentTrack;if(!Z)break;if(Z.info===null||Z.sampleTable)break;let G=y($);$.skip(3);let K=P($);for(let Q=0;Q<K;Q++){let q=$.filePos,U=g0($);if(!U)break;Z.internalCodecId=U.name;let W=U.name.toLowerCase();if(Z.info.type==="video"){if(W==="avc1"||W==="avc3")Z.info.codec="avc",Z.info.avcType=W==="avc1"?1:3;else if(W==="hvc1"||W==="hev1")Z.info.codec="hevc";else if(W==="vp08")Z.info.codec="vp8";else if(W==="vp09")Z.info.codec="vp9";else if(W==="av01")Z.info.codec="av1";else if(W==="mp4v")Z.info.codec="mpeg4";else console.warn(`Unsupported video codec (sample entry type '${U.name}').`);$.skip(24),Z.info.width=X0($),Z.info.height=X0($),$.skip(50),this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}else if(Z.info.type==="subtitle"){$.skip(6);let V=X0($);if(W==="wvtt")Z.info.codec="webvtt";else if(W==="tx3g"||W==="text")Z.info.codec="tx3g";else if(W==="stpp")Z.info.codec="ttml";this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}else{if(W==="mp4a");else if(W==="opus")Z.info.codec="opus";else if(W==="flac")Z.info.codec="flac";else if(W==="twos"||W==="sowt"||W==="raw "||W==="in24"||W==="in32"||W==="fl32"||W==="fl64"||W==="lpcm"||W==="ipcm"||W==="fpcm");else if(W==="ulaw")Z.info.codec="ulaw";else if(W==="alaw")Z.info.codec="alaw";else if(W==="ac-3")Z.info.codec="ac3";else if(W==="ec-3")Z.info.codec="eac3";else console.warn(`Unsupported audio codec (sample entry type '${U.name}').`);$.skip(8);let V=X0($);$.skip(6);let N=X0($),A=X0($);$.skip(4);let R=P($)/65536;if(G===0&&V>0){if(V===1)$.skip(4),A=8*P($),$.skip(8);else if(V===2){$.skip(4),R=i6($),N=P($),$.skip(4),A=P($);let z=P($);if($.skip(8),W==="lpcm"){let _=A+7>>3,L=Boolean(z&1),M=Boolean(z&2),B=z&4?-1:0;if(A>0&&A<=64){if(L){if(A===32)Z.info.codec=M?"pcm-f32be":"pcm-f32"}else if(B&1<<_-1){if(_===1)Z.info.codec="pcm-s8";else if(_===2)Z.info.codec=M?"pcm-s16be":"pcm-s16";else if(_===3)Z.info.codec=M?"pcm-s24be":"pcm-s24";else if(_===4)Z.info.codec=M?"pcm-s32be":"pcm-s32"}else if(_===1)Z.info.codec="pcm-u8"}if(Z.info.codec===null)console.warn("Unsupported PCM format.")}}}if(Z.info.codec==="opus")R=b0;if(Z.info.numberOfChannels=N,Z.info.sampleRate=R,W==="twos")if(A===8)Z.info.codec="pcm-s8";else if(A===16)Z.info.codec="pcm-s16be";else console.warn(`Unsupported sample size ${A} for codec 'twos'.`),Z.info.codec=null;else if(W==="sowt")if(A===8)Z.info.codec="pcm-s8";else if(A===16)Z.info.codec="pcm-s16";else console.warn(`Unsupported sample size ${A} for codec 'sowt'.`),Z.info.codec=null;else if(W==="raw ")Z.info.codec="pcm-u8";else if(W==="in24")Z.info.codec="pcm-s24be";else if(W==="in32")Z.info.codec="pcm-s32be";else if(W==="fl32")Z.info.codec="pcm-f32be";else if(W==="fl64")Z.info.codec="pcm-f64be";else if(W==="ipcm")Z.info.codec="pcm-s16be";else if(W==="fpcm")Z.info.codec="pcm-f32be";this.readContiguousBoxes($.slice($.filePos,q+U.totalSize-$.filePos))}}}break;case"avcC":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info),Z.info.type==="video")Z.info.codecDescription=D($,Y.contentSize)}break;case"hvcC":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info),Z.info.type==="video")Z.info.codecDescription=D($,Y.contentSize)}break;case"vpcC":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="video"),$.skip(4);let G=y($),K=y($),Q=y($),q=Q>>4,U=Q>>1&7,W=Q&1,V=y($),N=y($),A=y($);Z.info.vp9CodecInfo={profile:G,level:K,bitDepth:q,chromaSubsampling:U,videoFullRangeFlag:W,colourPrimaries:V,transferCharacteristics:N,matrixCoefficients:A}}break;case"av1C":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="video"),$.skip(1);let G=y($),K=G>>5,Q=G&31,q=y($),U=q>>7,W=q>>6&1,V=q>>5&1,N=q>>4&1,A=q>>3&1,R=q>>2&1,z=q&3,_=K===2&&W?V?12:10:W?10:8;Z.info.av1CodecInfo={profile:K,level:Q,tier:U,bitDepth:_,monochrome:N,chromaSubsamplingX:A,chromaSubsamplingY:R,chromaSamplePosition:z}}break;case"colr":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info?.type==="video"),s($,4)!=="nclx")break;let K=X0($),Q=X0($),q=X0($),U=Boolean(y($)&128);Z.info.colorSpace={primaries:X6[K],transfer:Z6[Q],matrix:G6[q],fullRange:U}}break;case"wave":this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"esds":{let Z=this.currentTrack;if(!Z)break;if(Z.info?.type!=="audio"&&Z.info?.type!=="video")break;$.skip(4);let G=y($);H(G===3),Y2($),$.skip(2);let K=y($),Q=(K&128)!==0,q=(K&64)!==0,U=(K&32)!==0;if(Q)$.skip(2);if(q){let R=y($);$.skip(R)}if(U)$.skip(2);let W=y($);H(W===4);let V=Y2($),N=$.filePos,A=y($);if(Z.info.type==="audio")if(A===64||A===103)Z.info.codec="aac",Z.info.aacCodecInfo={isMpeg2:A===103};else if(A===105||A===107)Z.info.codec="mp3";else if(A===221)Z.info.codec="vorbis";else console.warn(`Unsupported audio codec (objectTypeIndication ${A}) - discarding track.`);else if(Z.info.type==="video"){if(A===32)Z.info.codec="mpeg4"}if($.skip(12),V>$.filePos-N){let R=y($);H(R===5);let z=Y2($);if(Z.info.codecDescription=D($,z),Z.info.type==="audio"&&Z.info.codec==="aac"){let _=x1(Z.info.codecDescription);if(_.numberOfChannels!==null)Z.info.numberOfChannels=_.numberOfChannels;if(_.sampleRate!==null)Z.info.sampleRate=_.sampleRate}}}break;case"enda":{let Z=this.currentTrack;if(!Z)break;if(H(Z.info?.type==="audio"),X0($)&255){if(Z.info.codec==="pcm-s16be")Z.info.codec="pcm-s16";else if(Z.info.codec==="pcm-s24be")Z.info.codec="pcm-s24";else if(Z.info.codec==="pcm-s32be")Z.info.codec="pcm-s32";else if(Z.info.codec==="pcm-f32be")Z.info.codec="pcm-f32";else if(Z.info.codec==="pcm-f64be")Z.info.codec="pcm-f64"}}break;case"pcmC":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(4);let G=y($),K=Boolean(G&1),Q=y($);if(Z.info.codec==="pcm-s16be")if(K)if(Q===16)Z.info.codec="pcm-s16";else if(Q===24)Z.info.codec="pcm-s24";else if(Q===32)Z.info.codec="pcm-s32";else console.warn(`Invalid ipcm sample size ${Q}.`),Z.info.codec=null;else if(Q===16)Z.info.codec="pcm-s16be";else if(Q===24)Z.info.codec="pcm-s24be";else if(Q===32)Z.info.codec="pcm-s32be";else console.warn(`Invalid ipcm sample size ${Q}.`),Z.info.codec=null;else if(Z.info.codec==="pcm-f32be")if(K)if(Q===32)Z.info.codec="pcm-f32";else if(Q===64)Z.info.codec="pcm-f64";else console.warn(`Invalid fpcm sample size ${Q}.`),Z.info.codec=null;else if(Q===32)Z.info.codec="pcm-f32be";else if(Q===64)Z.info.codec="pcm-f64be";else console.warn(`Invalid fpcm sample size ${Q}.`),Z.info.codec=null;break}case"dOps":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(1);let G=y($),K=X0($),Q=P($),q=f8($),U=y($),W;if(U!==0)W=D($,2+G);else W=new Uint8Array(0);let V=new Uint8Array(19+W.byteLength),N=new DataView(V.buffer);N.setUint32(0,1332770163,!1),N.setUint32(4,1214603620,!1),N.setUint8(8,1),N.setUint8(9,G),N.setUint16(10,K,!0),N.setUint32(12,Q,!0),N.setInt16(16,q,!0),N.setUint8(18,U),V.set(W,19),Z.info.codecDescription=V,Z.info.numberOfChannels=G}break;case"dfLa":{let Z=this.currentTrack;if(!Z)break;H(Z.info?.type==="audio"),$.skip(4);let G=127,K=128,Q=$.filePos;while($.filePos<X){let N=y($),A=_1($);if((N&G)===0){$.skip(10);let z=P($),_=z>>>12,L=(z>>9&7)+1;Z.info.sampleRate=_,Z.info.numberOfChannels=L,$.skip(20)}else $.skip(A);if(N&K)break}let q=$.filePos;$.filePos=Q;let U=D($,q-Q),W=new Uint8Array(4+U.byteLength);new DataView(W.buffer).setUint32(0,1716281667,!1),W.set(U,4),Z.info.codecDescription=W}break;case"stts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=0,Q=0;for(let q=0;q<G;q++){let U=P($),W=P($);Z.sampleTable.sampleTimingEntries.push({startIndex:K,startDecodeTimestamp:Q,count:U,delta:W}),K+=U,Q+=U*W}}break;case"ctts":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=0;for(let Q=0;Q<G;Q++){let q=P($),U=q1($);Z.sampleTable.sampleCompositionTimeOffsets.push({startIndex:K,count:q,offset:U}),K+=q}}break;case"stsz":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($),K=P($);if(G===0)for(let Q=0;Q<K;Q++){let q=P($);Z.sampleTable.sampleSizes.push(q)}else Z.sampleTable.sampleSizes.push(G)}break;case"stz2":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),$.skip(3);let G=y($),K=P($),Q=D($,Math.ceil(K*G/8)),q=new f(Q);for(let U=0;U<K;U++){let W=q.readBits(G);Z.sampleTable.sampleSizes.push(W)}}break;case"stss":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4),Z.sampleTable.keySampleIndices=[];let G=P($);for(let K=0;K<G;K++){let Q=P($)-1;Z.sampleTable.keySampleIndices.push(Q)}if(Z.sampleTable.keySampleIndices[0]!==0)Z.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let Q=0;Q<G;Q++){let q=P($)-1,U=P($),W=P($);Z.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:q,samplesPerChunk:U,sampleDescriptionIndex:W})}let K=0;for(let Q=0;Q<Z.sampleTable.sampleToChunk.length;Q++)if(Z.sampleTable.sampleToChunk[Q].startSampleIndex=K,Q<Z.sampleTable.sampleToChunk.length-1){let U=Z.sampleTable.sampleToChunk[Q+1].startChunkIndex-Z.sampleTable.sampleToChunk[Q].startChunkIndex;K+=U*Z.sampleTable.sampleToChunk[Q].samplesPerChunk}}break;case"stco":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let K=0;K<G;K++){let Q=P($);Z.sampleTable.chunkOffsets.push(Q)}}break;case"co64":{let Z=this.currentTrack;if(!Z)break;if(!Z.sampleTable)break;$.skip(4);let G=P($);for(let K=0;K<G;K++){let Q=O0($);Z.sampleTable.chunkOffsets.push(Q)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes($.slice(j,Y.contentSize));break;case"mehd":{let Z=y($);$.skip(3);let G=Z===1?O0($):P($);this.movieDurationInTimescale=G}break;case"trex":{$.skip(4);let Z=P($),G=P($),K=P($),Q=P($),q=P($);this.fragmentTrackDefaults.push({trackId:Z,defaultSampleDescriptionIndex:G,defaultSampleDuration:K,defaultSampleSize:Q,defaultSampleFlags:q})}break;case"tfra":{let Z=y($);$.skip(3);let G=P($),K=this.tracks.find((_)=>_.id===G);if(!K)break;let Q=P($),q=(Q&48)>>4,U=(Q&12)>>2,W=Q&3,V=[y,X0,_1,P],N=V[q],A=V[U],R=V[W],z=P($);for(let _=0;_<z;_++){let L=Z===1?O0($):P($),M=Z===1?O0($):P($);N($),A($),R($),K.fragmentLookupTable.push({timestamp:L,moofOffset:M})}K.fragmentLookupTable.sort((_,L)=>_.timestamp-L.timestamp);for(let _=0;_<K.fragmentLookupTable.length-1;_++){let L=K.fragmentLookupTable[_],M=K.fragmentLookupTable[_+1];if(L.timestamp===M.timestamp)K.fragmentLookupTable.splice(_+1,1),_--}}break;case"moof":this.currentFragment={moofOffset:J,moofSize:Y.totalSize,implicitBaseDataOffset:J,trackData:new Map},this.readContiguousBoxes($.slice(j,Y.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(H(this.currentFragment),this.readContiguousBoxes($.slice(j,Y.contentSize)),this.currentTrack){let Z=this.currentFragment.trackData.get(this.currentTrack.id);if(Z){let{currentFragmentState:G}=this.currentTrack;if(H(G),G.startTimestamp!==null)W$(Z,G.startTimestamp),Z.startTimestampIsFinal=!0}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{H(this.currentFragment),$.skip(1);let Z=_1($),G=Boolean(Z&1),K=Boolean(Z&2),Q=Boolean(Z&8),q=Boolean(Z&16),U=Boolean(Z&32),W=Boolean(Z&65536),V=Boolean(Z&131072),N=P($),A=this.tracks.find((z)=>z.id===N);if(!A)break;let R=this.fragmentTrackDefaults.find((z)=>z.trackId===N);if(this.currentTrack=A,A.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:R?.defaultSampleDescriptionIndex??null,defaultSampleDuration:R?.defaultSampleDuration??null,defaultSampleSize:R?.defaultSampleSize??null,defaultSampleFlags:R?.defaultSampleFlags??null,startTimestamp:null},G)A.currentFragmentState.baseDataOffset=O0($);else if(V)A.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset;if(K)A.currentFragmentState.sampleDescriptionIndex=P($);if(Q)A.currentFragmentState.defaultSampleDuration=P($);if(q)A.currentFragmentState.defaultSampleSize=P($);if(U)A.currentFragmentState.defaultSampleFlags=P($);if(W)A.currentFragmentState.defaultSampleDuration=0}break;case"tfdt":{let Z=this.currentTrack;if(!Z)break;H(Z.currentFragmentState);let G=y($);$.skip(3);let K=G===0?P($):O0($);Z.currentFragmentState.startTimestamp=K}break;case"trun":{let Z=this.currentTrack;if(!Z)break;if(H(this.currentFragment),H(Z.currentFragmentState),this.currentFragment.trackData.has(Z.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}let G=y($),K=_1($),Q=Boolean(K&1),q=Boolean(K&4),U=Boolean(K&256),W=Boolean(K&512),V=Boolean(K&1024),N=Boolean(K&2048),A=P($),R=Z.currentFragmentState.baseDataOffset;if(Q)R+=q1($);let z=null;if(q)z=P($);let _=R;if(A===0){this.currentFragment.implicitBaseDataOffset=_;break}let L=0,M={track:Z,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(Z.id,M);for(let C=0;C<A;C++){let w;if(U)w=P($);else H(Z.currentFragmentState.defaultSampleDuration!==null),w=Z.currentFragmentState.defaultSampleDuration;let v;if(W)v=P($);else H(Z.currentFragmentState.defaultSampleSize!==null),v=Z.currentFragmentState.defaultSampleSize;let k;if(V)k=P($);else H(Z.currentFragmentState.defaultSampleFlags!==null),k=Z.currentFragmentState.defaultSampleFlags;if(C===0&&z!==null)k=z;let S=0;if(N)if(G===0)S=P($);else S=q1($);let T=!(k&65536);M.samples.push({presentationTimestamp:L+S,duration:w,byteOffset:_,byteSize:v,isKeyFrame:T}),_+=v,L+=w}M.presentationTimestamps=M.samples.map((C,w)=>({presentationTimestamp:C.presentationTimestamp,sampleIndex:w})).sort((C,w)=>C.presentationTimestamp-w.presentationTimestamp);for(let C=0;C<M.presentationTimestamps.length;C++){let w=M.presentationTimestamps[C],v=M.samples[w.sampleIndex];if(M.firstKeyFrameTimestamp===null&&v.isKeyFrame)M.firstKeyFrameTimestamp=v.presentationTimestamp;if(C<M.presentationTimestamps.length-1){let k=M.presentationTimestamps[C+1];v.duration=k.presentationTimestamp-w.presentationTimestamp}}let B=M.samples[M.presentationTimestamps[0].sampleIndex],F=M.samples[n(M.presentationTimestamps).sampleIndex];M.startTimestamp=B.presentationTimestamp,M.endTimestamp=F.presentationTimestamp+F.duration,this.currentFragment.implicitBaseDataOffset=_}break;case"udta":{let Z=this.iterateContiguousBoxes($.slice(j,Y.contentSize));for(let{boxInfo:G,slice:K}of Z){if(G.name!=="meta"&&!this.currentTrack){let Q=K.filePos;if(this.metadataTags.raw??={},G.name[0]==="©")this.metadataTags.raw[G.name]??=k0(K);else this.metadataTags.raw[G.name]??=D(K,G.contentSize);K.filePos=Q}switch(G.name){case"meta":K.skip(-G.headerSize),this.traverseBox(K);break;case"©nam":case"name":if(this.currentTrack)this.currentTrack.name=Y0.decode(D(K,G.contentSize));else this.metadataTags.title??=k0(K);break;case"©des":if(!this.currentTrack)this.metadataTags.description??=k0(K);break;case"©ART":if(!this.currentTrack)this.metadataTags.artist??=k0(K);break;case"©alb":if(!this.currentTrack)this.metadataTags.album??=k0(K);break;case"albr":if(!this.currentTrack)this.metadataTags.albumArtist??=k0(K);break;case"©gen":if(!this.currentTrack)this.metadataTags.genre??=k0(K);break;case"©day":if(!this.currentTrack){let Q=new Date(k0(K));if(!Number.isNaN(Q.getTime()))this.metadataTags.date??=Q}break;case"©cmt":if(!this.currentTrack)this.metadataTags.comment??=k0(K);break;case"©lyr":if(!this.currentTrack)this.metadataTags.lyrics??=k0(K);break}}}break;case"meta":{if(this.currentTrack)break;let G=P($)!==0;if(this.currentMetadataKeys=new Map,G)this.readContiguousBoxes($.slice(j,Y.contentSize));else this.readContiguousBoxes($.slice(j+4,Y.contentSize-4));this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;$.skip(4);let Z=P($);for(let G=0;G<Z;G++){let K=P($);$.skip(4);let Q=Y0.decode(D($,K-8));this.currentMetadataKeys.set(G+1,Q)}}break;case"ilst":{if(!this.currentMetadataKeys)break;let Z=this.iterateContiguousBoxes($.slice(j,Y.contentSize));for(let{boxInfo:G,slice:K}of Z){let Q=G.name,q=(Q.charCodeAt(0)<<24)+(Q.charCodeAt(1)<<16)+(Q.charCodeAt(2)<<8)+Q.charCodeAt(3);if(this.currentMetadataKeys.has(q))Q=this.currentMetadataKeys.get(q);let U=I5(K);switch(this.metadataTags.raw??={},this.metadataTags.raw[Q]??=U,Q){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":if(typeof U==="string")this.metadataTags.title??=U;break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":if(typeof U==="string")this.metadataTags.description??=U;break;case"©ART":case"com.apple.quicktime.artist":case"artist":if(typeof U==="string")this.metadataTags.artist??=U;break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":if(typeof U==="string")this.metadataTags.album??=U;break;case"aART":case"album_artist":if(typeof U==="string")this.metadataTags.albumArtist??=U;break;case"©cmt":case"com.apple.quicktime.comment":case"comment":if(typeof U==="string")this.metadataTags.comment??=U;break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":if(typeof U==="string")this.metadataTags.genre??=U;break;case"©lyr":case"lyrics":if(typeof U==="string")this.metadataTags.lyrics??=U;break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof U==="string"){let W=new Date(U);if(!Number.isNaN(W.getTime()))this.metadataTags.date??=W}break;case"covr":case"com.apple.quicktime.artwork":if(U instanceof I0)this.metadataTags.images??=[],this.metadataTags.images.push({data:U.data,kind:"coverFront",mimeType:U.mimeType});else if(U instanceof Uint8Array)this.metadataTags.images??=[],this.metadataTags.images.push({data:U,kind:"coverFront",mimeType:"image/*"});break;case"track":if(typeof U==="string"){let W=U.split("/"),V=Number.parseInt(W[0],10),N=W[1]&&Number.parseInt(W[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(N&&Number.isInteger(N)&&N>0)this.metadataTags.tracksTotal??=N}break;case"trkn":if(U instanceof Uint8Array&&U.length>=6){let W=h(U),V=W.getUint16(2,!1),N=W.getUint16(4,!1);if(V>0)this.metadataTags.trackNumber??=V;if(N>0)this.metadataTags.tracksTotal??=N}break;case"disc":case"disk":if(U instanceof Uint8Array&&U.length>=6){let W=h(U),V=W.getUint16(2,!1),N=W.getUint16(4,!1);if(V>0)this.metadataTags.discNumber??=V;if(N>0)this.metadataTags.discsTotal??=N}break}}}break}return $.filePos=X,!0}}class j2{internalTrack;packetToSampleIndex=new WeakMap;packetToFragmentLocation=new WeakMap;constructor($){this.internalTrack=$}getId(){return this.internalTrack.id}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}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket($){let J=await this.fetchPacketForSampleIndex(0,$);if(J||!this.internalTrack.demuxer.isFragmented)return J;return this.performFragmentedLookup(null,(Y)=>{if(Y.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,$)}mapTimestampIntoTimescale($){return y1($*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket($,J){let Y=this.mapTimestampIntoTimescale($),j=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=V$(j,Y),Z=await this.fetchPacketForSampleIndex(X,J);if(!S5(j)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(G)=>{let K=G.trackData.get(this.internalTrack.id);if(!K)return{sampleIndex:-1,correctSampleFound:!1};let Q=u(K.presentationTimestamps,Y,(W)=>W.presentationTimestamp),q=Q!==-1?K.presentationTimestamps[Q].sampleIndex:-1,U=Q!==-1&&Y<K.endTimestamp;return{sampleIndex:q,correctSampleFound:U}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0)return this.fetchPacketForSampleIndex(Y+1,J);let j=this.packetToFragmentLocation.get($);if(j===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(j.fragment,(X)=>{if(X===j.fragment){let Z=X.trackData.get(this.internalTrack.id);if(j.sampleIndex+1<Z.samples.length)return{sampleIndex:j.sampleIndex+1,correctSampleFound:!0}}else if(X.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,J)}async getKeyPacket($,J){let Y=this.mapTimestampIntoTimescale($),j=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),X=r7(j,Y),Z=await this.fetchPacketForSampleIndex(X,J);if(!S5(j)||!this.internalTrack.demuxer.isFragmented)return Z;return this.performFragmentedLookup(null,(G)=>{let K=G.trackData.get(this.internalTrack.id);if(!K)return{sampleIndex:-1,correctSampleFound:!1};let Q=Q6(K.presentationTimestamps,(W)=>{return K.samples[W.sampleIndex].isKeyFrame&&W.presentationTimestamp<=Y}),q=Q!==-1?K.presentationTimestamps[Q].sampleIndex:-1,U=Q!==-1&&Y<K.endTimestamp;return{sampleIndex:q,correctSampleFound:U}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToSampleIndex.get($);if(Y!==void 0){let X=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),Z=s7(X,Y);return this.fetchPacketForSampleIndex(Z,J)}let j=this.packetToFragmentLocation.get($);if(j===void 0)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(j.fragment,(X)=>{if(X===j.fragment){let G=X.trackData.get(this.internalTrack.id).samples.findIndex((K,Q)=>K.isKeyFrame&&Q>j.sampleIndex);if(G!==-1)return{sampleIndex:G,correctSampleFound:!0}}else{let Z=X.trackData.get(this.internalTrack.id);if(Z&&Z.firstKeyFrameTimestamp!==null){let G=Z.samples.findIndex((K)=>K.isKeyFrame);return H(G!==-1),{sampleIndex:G,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,J)}async fetchPacketForSampleIndex($,J){if($===-1)return null;let Y=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),j=i7(Y,$);if(!j)return null;let X;if(J.metadataOnly)X=G0;else{let Q=this.internalTrack.demuxer.reader.requestSlice(j.sampleOffset,j.sampleSize);if(Q instanceof Promise)Q=await Q;H(Q),X=D(Q,j.sampleSize)}let Z=(j.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,G=j.duration/this.internalTrack.timescale,K=new I(X,j.isKeyFrame?"key":"delta",Z,G,$,j.sampleSize);return this.packetToSampleIndex.set(K,$),K}async fetchPacketInFragment($,J,Y){if(J===-1)return null;let X=$.trackData.get(this.internalTrack.id).samples[J];H(X);let Z;if(Y.metadataOnly)Z=G0;else{let q=this.internalTrack.demuxer.reader.requestSlice(X.byteOffset,X.byteSize);if(q instanceof Promise)q=await q;H(q),Z=D(q,X.byteSize)}let G=(X.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,K=X.duration/this.internalTrack.timescale,Q=new I(Z,X.isKeyFrame?"key":"delta",G,K,$.moofOffset+J,X.byteSize);return this.packetToFragmentLocation.set(Q,{fragment:$,sampleIndex:J}),Q}async performFragmentedLookup($,J,Y,j,X){let Z=this.internalTrack.demuxer,G=null,K=null,Q=-1;if($){let{sampleIndex:R,correctSampleFound:z}=J($);if(z)return this.fetchPacketInFragment($,R,X);if(R!==-1)K=$,Q=R}let q=u(this.internalTrack.fragmentLookupTable,Y,(R)=>R.timestamp),U=q!==-1?this.internalTrack.fragmentLookupTable[q]:null,W=u(this.internalTrack.fragmentPositionCache,Y,(R)=>R.startTimestamp),V=W!==-1?this.internalTrack.fragmentPositionCache[W]:null,N=Math.max(U?.moofOffset??0,V?.moofOffset??0)||null,A;if(!$)A=N??0;else if(N===null||$.moofOffset>=N)A=$.moofOffset+$.moofSize,G=$;else A=N;while(!0){if(G){let L=G.trackData.get(this.internalTrack.id);if(L&&L.startTimestamp>j)break}let R=Z.reader.requestSliceRange(A,f0,U1);if(R instanceof Promise)R=await R;if(!R)break;let z=A,_=g0(R);if(!_)break;if(_.name==="moof"){G=await Z.readFragment(z);let{sampleIndex:L,correctSampleFound:M}=J(G);if(M)return this.fetchPacketInFragment(G,L,X);if(L!==-1)K=G,Q=L}A=z+_.totalSize}if(U&&(!K||K.moofOffset<U.moofOffset)){let R=this.internalTrack.fragmentLookupTable[q-1];H(!R||R.timestamp<U.timestamp);let z=R?.timestamp??Number.NEGATIVE_INFINITY;return this.performFragmentedLookup(null,J,z,j,X)}if(K)return this.fetchPacketInFragment(K,Q,X);return null}}class h5 extends j2{internalTrack;decoderConfigPromise=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=$&&x6($.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){let $=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=$&&I6($.data)}return{codec:V6(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}})()}}class f5 extends j2{internalTrack;decoderConfig=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:H6(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}}}class g5 extends j2{internalTrack;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodecPrivate(){return this.internalTrack.info.codecPrivateText}async*getCues(){let $=await this.getFirstPacket({});while($){let J="";if(this.internalTrack.info.codec==="webvtt"){let Y=new Uint8Array($.data),j=new S0(Y,new DataView(Y.buffer,Y.byteOffset,Y.byteLength),0,0,Y.length);while(j.remainingLength>0){let X=g0(j);if(!X)break;if(X.name==="vttc"){let Z=j.filePos+X.contentSize;while(j.filePos<Z&&j.remainingLength>0){let G=g0(j);if(!G)break;if(G.name==="payl"){let K=D(j,G.contentSize),Q=new TextDecoder("utf-8");J+=Q.decode(K)}else j.skip(G.contentSize)}}else if(X.name==="vtte")j.skip(X.contentSize);else j.skip(X.contentSize)}}else J=new TextDecoder("utf-8").decode($.data);if(J)yield{timestamp:$.timestamp,duration:$.duration,text:J};$=await this.getNextPacket($,{})}}}var V$=($,J)=>{if($.presentationTimestamps){let X=u($.presentationTimestamps,J,(Z)=>Z.presentationTimestamp);if(X===-1)return-1;return $.presentationTimestamps[X].sampleIndex}let Y=u($.sampleTimingEntries,J,(X)=>X.startDecodeTimestamp);if(Y===-1)return-1;let j=$.sampleTimingEntries[Y];return j.startIndex+Math.min(Math.floor((J-j.startDecodeTimestamp)/j.delta),j.count-1)},r7=($,J)=>{if(!$.keySampleIndices)return V$($,J);if($.presentationTimestamps){let Y=u($.presentationTimestamps,J,(j)=>j.presentationTimestamp);if(Y===-1)return-1;for(let j=Y;j>=0;j--){let X=$.presentationTimestamps[j].sampleIndex;if(Y1($.keySampleIndices,X,(G)=>G)!==-1)return X}return-1}else{let Y=V$($,J),j=u($.keySampleIndices,Y,(X)=>X);return $.keySampleIndices[j]??-1}},i7=($,J)=>{let Y=u($.sampleTimingEntries,J,(_)=>_.startIndex),j=$.sampleTimingEntries[Y];if(!j||j.startIndex+j.count<=J)return null;let Z=j.startDecodeTimestamp+(J-j.startIndex)*j.delta,G=u($.sampleCompositionTimeOffsets,J,(_)=>_.startIndex),K=$.sampleCompositionTimeOffsets[G];if(K&&J-K.startIndex<K.count)Z+=K.offset;let Q=$.sampleSizes[Math.min(J,$.sampleSizes.length-1)],q=u($.sampleToChunk,J,(_)=>_.startSampleIndex),U=$.sampleToChunk[q];H(U);let W=U.startChunkIndex+Math.floor((J-U.startSampleIndex)/U.samplesPerChunk),V=$.chunkOffsets[W],N=U.startSampleIndex+(W-U.startChunkIndex)*U.samplesPerChunk,A=0,R=V;if($.sampleSizes.length===1)R+=Q*(J-N),A+=Q*U.samplesPerChunk;else for(let _=N;_<N+U.samplesPerChunk;_++){let L=$.sampleSizes[_];if(_<J)R+=L;A+=L}let z=j.delta;if($.presentationTimestamps){let _=$.presentationTimestampIndexMap[J];if(H(_!==void 0),_<$.presentationTimestamps.length-1)z=$.presentationTimestamps[_+1].presentationTimestamp-Z}return{presentationTimestamp:Z,duration:z,sampleOffset:R,sampleSize:Q,chunkOffset:V,chunkSize:A,isKeyFrame:$.keySampleIndices?Y1($.keySampleIndices,J,(_)=>_)!==-1:!0}},s7=($,J)=>{if(!$.keySampleIndices)return J+1;let Y=u($.keySampleIndices,J,(j)=>j);return $.keySampleIndices[Y+1]??-1},W$=($,J)=>{$.startTimestamp+=J,$.endTimestamp+=J;for(let Y of $.samples)Y.presentationTimestamp+=J;for(let Y of $.presentationTimestamps)Y.presentationTimestamp+=J},a7=($)=>{let[J,,,Y]=$,j=Math.hypot(J,Y),X=J/j,Z=Y/j,G=-Math.atan2(Z,X)*(180/Math.PI);if(!Number.isFinite(G))return 0;return G},S5=($)=>{return $.sampleSizes.length===0};/*!
224
+ * Copyright (c) 2025-present, Vanilagy and contributors
225
+ *
226
+ * This Source Code Form is subject to the terms of the Mozilla Public
227
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
228
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
229
+ */class l8{value;constructor($){this.value=$}}class m8{value;constructor($){this.value=$}}class X2{value;constructor($){this.value=$}}class r0{value;constructor($){this.value=$}}var t7=[440786851,408125543],V8=[290298740,357149030,524531317,374648427,475249515,423732329,272869232,307544935],d8=[...t7,...V8],k5=($)=>{if($<256)return 1;if($<65536)return 2;if($<16777216)return 3;if($<4294967296)return 4;if($<1099511627776)return 5;return 6},u5=($)=>{if($<1n<<8n)return 1;if($<1n<<16n)return 2;if($<1n<<24n)return 3;if($<1n<<32n)return 4;if($<1n<<40n)return 5;if($<1n<<48n)return 6;if($<1n<<56n)return 7;return 8},p5=($)=>{if($>=-64&&$<64)return 1;if($>=-8192&&$<8192)return 2;if($>=-1048576&&$<1048576)return 3;if($>=-134217728&&$<134217728)return 4;if($>=-17179869184&&$<17179869184)return 5;return 6},e7=($)=>{if($<127)return 1;if($<16383)return 2;if($<2097151)return 3;if($<268435455)return 4;if($<34359738367)return 5;if($<4398046511103)return 6;throw Error("EBML varint size not supported "+$)};class A${writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);offsets=new WeakMap;dataOffsets=new WeakMap;constructor($){this.writer=$}writeByte($){this.helperView.setUint8(0,$),this.writer.write(this.helper.subarray(0,1))}writeFloat32($){this.helperView.setFloat32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64($){this.helperView.setFloat64(0,$,!1),this.writer.write(this.helper)}writeUnsignedInt($,J=k5($)){let Y=0;switch(J){case 6:this.helperView.setUint8(Y++,$/1099511627776|0);case 5:this.helperView.setUint8(Y++,$/4294967296|0);case 4:this.helperView.setUint8(Y++,$>>24);case 3:this.helperView.setUint8(Y++,$>>16);case 2:this.helperView.setUint8(Y++,$>>8);case 1:this.helperView.setUint8(Y++,$);break;default:throw Error("Bad unsigned int size "+J)}this.writer.write(this.helper.subarray(0,Y))}writeUnsignedBigInt($,J=u5($)){let Y=0;for(let j=J-1;j>=0;j--)this.helperView.setUint8(Y++,Number($>>BigInt(j*8)&0xffn));this.writer.write(this.helper.subarray(0,Y))}writeSignedInt($,J=p5($)){if($<0)$+=2**(J*8);this.writeUnsignedInt($,J)}writeVarInt($,J=e7($)){let Y=0;switch(J){case 1:this.helperView.setUint8(Y++,128|$);break;case 2:this.helperView.setUint8(Y++,64|$>>8),this.helperView.setUint8(Y++,$);break;case 3:this.helperView.setUint8(Y++,32|$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 4:this.helperView.setUint8(Y++,16|$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 5:this.helperView.setUint8(Y++,8|$/4294967296&7),this.helperView.setUint8(Y++,$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;case 6:this.helperView.setUint8(Y++,4|$/1099511627776&3),this.helperView.setUint8(Y++,$/4294967296|0),this.helperView.setUint8(Y++,$>>24),this.helperView.setUint8(Y++,$>>16),this.helperView.setUint8(Y++,$>>8),this.helperView.setUint8(Y++,$);break;default:throw Error("Bad EBML varint size "+J)}this.writer.write(this.helper.subarray(0,Y))}writeAsciiString($){this.writer.write(new Uint8Array($.split("").map((J)=>J.charCodeAt(0))))}writeEBML($){if($===null)return;if($ instanceof Uint8Array)this.writer.write($);else if(Array.isArray($))for(let J of $)this.writeEBML(J);else if(this.offsets.set($,this.writer.getPos()),this.writeUnsignedInt($.id),Array.isArray($.data)){let J=this.writer.getPos(),Y=$.size===-1?1:$.size??4;if($.size===-1)this.writeByte(255);else this.writer.seek(this.writer.getPos()+Y);let j=this.writer.getPos();if(this.dataOffsets.set($,j),this.writeEBML($.data),$.size!==-1){let X=this.writer.getPos()-j,Z=this.writer.getPos();this.writer.seek(J),this.writeVarInt(X,Y),this.writer.seek(Z)}}else if(typeof $.data==="number"){let J=$.size??k5($.data);this.writeVarInt(J),this.writeUnsignedInt($.data,J)}else if(typeof $.data==="bigint"){let J=$.size??u5($.data);this.writeVarInt(J),this.writeUnsignedBigInt($.data,J)}else if(typeof $.data==="string")this.writeVarInt($.data.length),this.writeAsciiString($.data);else if($.data instanceof Uint8Array)this.writeVarInt($.data.byteLength,$.size),this.writer.write($.data);else if($.data instanceof l8)this.writeVarInt(4),this.writeFloat32($.data.value);else if($.data instanceof m8)this.writeVarInt(8),this.writeFloat64($.data.value);else if($.data instanceof X2){let J=$.size??p5($.data.value);this.writeVarInt(J),this.writeSignedInt($.data.value,J)}else if($.data instanceof r0){let J=m.encode($.data.value);this.writeVarInt(J.length),this.writer.write(J)}else i($.data)}}var N$=8,P0=2,u0=2*N$,R$=($)=>{let J=y($);if($.skip(-1),J===0)return null;let Y=1,j=128;while((J&j)===0)Y++,j>>=1;return Y},H8=($)=>{let J=y($);if(J===0)return null;let Y=1,j=128;while((J&j)===0)Y++,j>>=1;let X=J&j-1;for(let Z=1;Z<Y;Z++)X*=256,X+=y($);return X},g=($,J)=>{if(J<1||J>8)throw Error("Bad unsigned int size "+J);let Y=0;for(let j=0;j<J;j++)Y*=256,Y+=y($);return Y},l5=($,J)=>{if(J<1)throw Error("Bad unsigned int size "+J);let Y=0n;for(let j=0;j<J;j++)Y<<=8n,Y+=BigInt(y($));return Y};var Z2=($)=>{let J=R$($);if(J===null)return null;return g($,J)},z$=($)=>{let J=y($);if(J===255)J=null;else if($.skip(-1),J=H8($),J===72057594037927940)J=null;return J},p0=($)=>{let J=Z2($);if(J===null)return null;let Y=z$($);return{id:J,size:Y}},F1=($,J)=>{let Y=D($,J),j=0;while(j<J&&Y[j]!==0)j+=1;return String.fromCharCode(...Y.subarray(0,j))},N8=($,J)=>{let Y=D($,J),j=0;while(j<J&&Y[j]!==0)j+=1;return Y0.decode(Y.subarray(0,j))},G2=($,J)=>{if(J===0)return 0;if(J!==4&&J!==8)throw Error("Bad float size "+J);return J===4?H5($):i6($)},K2=async($,J,Y,j)=>{let X=new Set(Y),Z=J;while(j===null||Z<j){let G=$.requestSliceRange(Z,P0,u0);if(G instanceof Promise)G=await G;if(!G)break;let K=p0(G);if(!K)break;if(X.has(K.id))return{pos:Z,found:!0};W1(K.size),Z=G.filePos+K.size}return{pos:j!==null&&j>Z?j:Z,found:!1}},_$=async($,J,Y,j)=>{let Z=new Set(Y),G=J;while(G<j){let K=$.requestSliceRange(G,0,Math.min(65536,j-G));if(K instanceof Promise)K=await K;if(!K)break;if(K.length<N$)break;for(let Q=0;Q<K.length-N$;Q++){K.filePos=G;let q=Z2(K);if(q!==null&&Z.has(q))return G;G++}}return null},A0={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",mpeg4:"V_MPEG4/ISO/ASP",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",srt:"S_TEXT/UTF8",ass:"S_TEXT/ASS",ssa:"S_TEXT/SSA"};function W1($){if($===null)throw Error("Undefined element size is used in a place where it is not supported.")}/*!
230
+ * Copyright (c) 2025-present, Vanilagy and contributors
231
+ *
232
+ * This Source Code Form is subject to the terms of the Mozilla Public
233
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
234
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
235
+ */var Q2=($)=>{let Y=($.hasVideo?"video/":$.hasAudio?"audio/":"application/")+($.isWebM?"webm":"x-matroska");if($.codecStrings.length>0){let j=[...new Set($.codecStrings.filter(Boolean))];Y+=`; codecs="${j.join(", ")}"`}return Y};/*!
236
+ * Copyright (c) 2025-present, Vanilagy and contributors
237
+ *
238
+ * This Source Code Form is subject to the terms of the Mozilla Public
239
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
240
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
241
+ */var L$=[{id:290298740,flag:"seekHeadSeen"},{id:357149030,flag:"infoSeen"},{id:374648427,flag:"tracksSeen"},{id:475249515,flag:"cuesSeen"}],d5=10485760;class M$ extends W0{reader;readMetadataPromise=null;segments=[];currentSegment=null;currentTrack=null;currentCluster=null;currentBlock=null;currentBlockAdditional=null;currentCueTime=null;currentDecodingInstruction=null;currentTagTargetIsMovie=!0;currentSimpleTagName=null;currentAttachedFile=null;isWebM=!1;constructor($){super($);this.reader=$._reader}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((Y)=>Y.computeDuration()));return Math.max(0,...J)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(($)=>$.tracks.map((J)=>J.inputTrack))}async getMimeType(){await this.readMetadata();let $=await this.getTracks(),J=await Promise.all($.map((Y)=>Y.getCodecParameterString()));return Q2({isWebM:this.isWebM,hasVideo:this.segments.some((Y)=>Y.tracks.some((j)=>j.info?.type==="video")),hasAudio:this.segments.some((Y)=>Y.tracks.some((j)=>j.info?.type==="audio")),codecStrings:J.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let J of this.segments)if(!J.metadataTagsCollected){if(this.reader.fileSize!==null)await this.loadSegmentMetadata(J);J.metadataTagsCollected=!0}let $={};for(let J of this.segments)$={...$,...J.metadataTags};return $}readMetadata(){return this.readMetadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,P0,u0);if(J instanceof Promise)J=await J;if(!J)break;let Y=p0(J);if(!Y)break;let{id:j,size:X}=Y,Z=J.filePos;if(j===440786851){W1(X);let G=this.reader.requestSlice(Z,X);if(G instanceof Promise)G=await G;if(!G)break;this.readContiguousElements(G)}else if(j===408125543){if(await this.readSegment(Z,X),X===null)break;if(this.reader.fileSize===null)break}else if(j===524531317){if(this.reader.fileSize===null)break;if(X===null)X=(await K2(this.reader,Z,d8,this.reader.fileSize)).pos-Z;let G=n(this.segments);if(G)G.elementEndPos=Z+X}W1(X),$=Z+X}})()}async readSegment($,J){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:$,elementEndPos:J===null?null:$+J,clusterSeekStartPos:$,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let Y=$;while(this.currentSegment.elementEndPos===null||Y<this.currentSegment.elementEndPos){let G=this.reader.requestSliceRange(Y,P0,u0);if(G instanceof Promise)G=await G;if(!G)break;let K=Y,Q=p0(G);if(!Q||!V8.includes(Q.id)&&Q.id!==236){let N=await _$(this.reader,K,V8,Math.min(this.currentSegment.elementEndPos??Number.POSITIVE_INFINITY,K+d5));if(N){Y=N;continue}break}let{id:q,size:U}=Q,W=G.filePos,V=L$.findIndex((N)=>N.id===q);if(V!==-1){let N=L$[V].flag;this.currentSegment[N]=!0,W1(U);let A=this.reader.requestSlice(W,U);if(A instanceof Promise)A=await A;if(A)this.readContiguousElements(A)}else if(q===307544935||q===423732329){if(q===307544935)this.currentSegment.tagsSeen=!0;else this.currentSegment.attachmentsSeen=!0;W1(U);let N=this.reader.requestSlice(W,U);if(N instanceof Promise)N=await N;if(N)this.readContiguousElements(N)}else if(q===524531317){this.currentSegment.clusterSeekStartPos=K;break}if(U===null)break;Y=W+U}if(this.currentSegment.seekEntries.sort((G,K)=>G.segmentPosition-K.segmentPosition),this.reader.fileSize!==null)for(let G of this.currentSegment.seekEntries){let K=L$.find((N)=>N.id===G.id);if(!K)continue;if(this.currentSegment[K.flag])continue;let Q=this.reader.requestSliceRange($+G.segmentPosition,P0,u0);if(Q instanceof Promise)Q=await Q;if(!Q)continue;let q=p0(Q);if(!q)continue;let{id:U,size:W}=q;if(U!==K.id)continue;W1(W),this.currentSegment[K.flag]=!0;let V=this.reader.requestSlice(Q.filePos,W);if(V instanceof Promise)V=await V;if(!V)continue;this.readContiguousElements(V)}if(this.currentSegment.timestampScale===-1)this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1000;this.currentSegment.tracks.sort((G,K)=>Number(K.disposition.default)-Number(G.disposition.default));let j=new Map(this.currentSegment.tracks.map((G)=>[G.id,G]));for(let G of this.currentSegment.cuePoints){let K=j.get(G.trackId);if(K)K.cuePoints.push(G)}for(let G of this.currentSegment.tracks){G.cuePoints.sort((K,Q)=>K.time-Q.time);for(let K=0;K<G.cuePoints.length-1;K++){let Q=G.cuePoints[K],q=G.cuePoints[K+1];if(Q.time===q.time)G.cuePoints.splice(K+1,1),K--}}let X=null,Z=Number.NEGATIVE_INFINITY;for(let G of this.currentSegment.tracks)if(G.cuePoints.length>Z)Z=G.cuePoints.length,X=G;for(let G of this.currentSegment.tracks)if(G.cuePoints.length===0)G.cuePoints=X.cuePoints;this.currentSegment=null}async readCluster($,J){if(J.lastReadCluster?.elementStartPos===$)return J.lastReadCluster;let Y=this.reader.requestSliceRange($,P0,u0);if(Y instanceof Promise)Y=await Y;H(Y);let j=$,X=p0(Y);H(X);let Z=X.id;H(Z===524531317);let G=X.size,K=Y.filePos;if(G===null)G=(await K2(this.reader,K,d8,J.elementEndPos)).pos-K;let Q=this.reader.requestSlice(K,G);if(Q instanceof Promise)Q=await Q;let q={segment:J,elementStartPos:j,elementEndPos:K+G,dataStartPos:K,timestamp:-1,trackData:new Map};if(this.currentCluster=q,Q){let U=this.readContiguousElements(Q,d8);q.elementEndPos=U}for(let[,U]of q.trackData){let W=U.track;H(U.blocks.length>0);let V=!1;for(let z=0;z<U.blocks.length;z++){let _=U.blocks[z];_.timestamp+=q.timestamp,V||=_.lacing!==0}U.presentationTimestamps=U.blocks.map((z,_)=>({timestamp:z.timestamp,blockIndex:_})).sort((z,_)=>z.timestamp-_.timestamp);for(let z=0;z<U.presentationTimestamps.length;z++){let _=U.presentationTimestamps[z],L=U.blocks[_.blockIndex];if(U.firstKeyFrameTimestamp===null&&L.isKeyFrame)U.firstKeyFrameTimestamp=L.timestamp;if(z<U.presentationTimestamps.length-1){let M=U.presentationTimestamps[z+1];L.duration=M.timestamp-L.timestamp}else if(L.duration===0){if(W.defaultDuration!=null){if(L.lacing===0)L.duration=W.defaultDuration}}}if(V)this.expandLacedBlocks(U.blocks,W),U.presentationTimestamps=U.blocks.map((z,_)=>({timestamp:z.timestamp,blockIndex:_})).sort((z,_)=>z.timestamp-_.timestamp);let N=U.blocks[U.presentationTimestamps[0].blockIndex],A=U.blocks[n(U.presentationTimestamps).blockIndex];U.startTimestamp=N.timestamp,U.endTimestamp=A.timestamp+A.duration;let R=u(W.clusterPositionCache,U.startTimestamp,(z)=>z.startTimestamp);if(R===-1||W.clusterPositionCache[R].elementStartPos!==j)W.clusterPositionCache.splice(R+1,0,{elementStartPos:q.elementStartPos,startTimestamp:U.startTimestamp})}return J.lastReadCluster=q,q}getTrackDataInCluster($,J){let Y=$.trackData.get(J);if(!Y){let j=$.segment.tracks.find((X)=>X.id===J);if(!j)return null;Y={track:j,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},$.trackData.set(J,Y)}return Y}expandLacedBlocks($,J){for(let Y=0;Y<$.length;Y++){let j=$[Y];if(j.lacing===0)continue;if(!j.decoded)j.data=this.decodeBlockData(J,j.data),j.decoded=!0;let X=S0.tempFromBytes(j.data),Z=[],G=y(X)+1;switch(j.lacing){case 1:{let Q=0;for(let q=0;q<G-1;q++){let U=0;while(X.bufferPos<X.length){let W=y(X);if(U+=W,W<255){Z.push(U),Q+=U;break}}}Z.push(X.length-(X.bufferPos+Q))}break;case 2:{let Q=X.length-1,q=Math.floor(Q/G);for(let U=0;U<G;U++)Z.push(q)}break;case 3:{let Q=H8(X);H(Q!==null);let q=Q;Z.push(q);let U=q;for(let W=1;W<G-1;W++){let V=X.bufferPos,N=H8(X);H(N!==null);let A=N,z=(1<<(X.bufferPos-V)*7-1)-1,_=A-z;q+=_,Z.push(q),U+=q}Z.push(X.length-(X.bufferPos+U))}break;default:H(!1)}H(Z.length===G),$.splice(Y,1);let K=j.duration||G*(J.defaultDuration??0);for(let Q=0;Q<G;Q++){let q=Z[Q],U=D(X,q),W=j.timestamp+K*Q/G,V=K/G;$.splice(Y+Q,0,{timestamp:W,duration:V,isKeyFrame:j.isKeyFrame,data:U,lacing:0,decoded:!0,mainAdditional:j.mainAdditional})}Y+=G,Y--}}async loadSegmentMetadata($){for(let J of $.seekEntries){if(J.id===307544935&&!$.tagsSeen);else if(J.id===423732329&&!$.attachmentsSeen);else continue;let Y=this.reader.requestSliceRange($.dataStartPos+J.segmentPosition,P0,u0);if(Y instanceof Promise)Y=await Y;if(!Y)continue;let j=p0(Y);if(!j||j.id!==J.id)continue;let{size:X}=j;W1(X),H(!this.currentSegment),this.currentSegment=$;let Z=this.reader.requestSlice(Y.filePos,X);if(Z instanceof Promise)Z=await Z;if(Z)this.readContiguousElements(Z);if(this.currentSegment=null,J.id===307544935)$.tagsSeen=!0;else if(J.id===423732329)$.attachmentsSeen=!0}}readContiguousElements($,J){let Y=$.filePos;while($.filePos-Y<=$.length-P0){let j=$.filePos;if(!this.traverseElement($,J))return j}return $.filePos}traverseElement($,J){let Y=p0($);if(!Y)return!1;if(J&&J.includes(Y.id))return!1;let{id:j,size:X}=Y,Z=$.filePos;switch(W1(X),j){case 17026:this.isWebM=F1($,X)==="webm";break;case 19899:{if(!this.currentSegment)break;let G={id:-1,segmentPosition:-1};if(this.currentSegment.seekEntries.push(G),this.readContiguousElements($.slice(Z,X)),G.id===-1||G.segmentPosition===-1)this.currentSegment.seekEntries.pop()}break;case 21419:{let G=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!G)break;G.id=g($,X)}break;case 21420:{let G=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!G)break;G.segmentPosition=g($,X)}break;case 2807729:{if(!this.currentSegment)break;this.currentSegment.timestampScale=g($,X),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case 17545:{if(!this.currentSegment)break;this.currentSegment.duration=G2($,X)}break;case 174:{if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...L0},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:a,decodingInstructions:[],info:null},this.readContiguousElements($.slice(Z,X)),this.currentTrack.decodingInstructions.some((G)=>{return G.data?.type!=="decompress"||G.scope!==1||G.data.algorithm!==3}))console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null;if(this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let G=this.currentTrack.codecId.indexOf("/"),K=G===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,G);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.codecId===A0.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===A0.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(K===A0.vp8)this.currentTrack.info.codec="vp8";else if(K===A0.vp9)this.currentTrack.info.codec="vp9";else if(K===A0.av1)this.currentTrack.info.codec="av1";else if(this.currentTrack.codecId===A0.mpeg4)this.currentTrack.info.codec="mpeg4",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;let Q=this.currentTrack,q=new D0(this.input,new c5(Q));this.currentTrack.inputTrack=q,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){if(K===A0.aac)this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===A0.mp3)this.currentTrack.info.codec="mp3";else if(K===A0.opus)this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=b0;else if(K===A0.vorbis)this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(K===A0.flac)this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(K===A0.ac3)this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(K===A0.eac3)this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId==="A_PCM/INT/LIT"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32"}else if(this.currentTrack.codecId==="A_PCM/INT/BIG"){if(this.currentTrack.info.bitDepth===8)this.currentTrack.info.codec="pcm-u8";else if(this.currentTrack.info.bitDepth===16)this.currentTrack.info.codec="pcm-s16be";else if(this.currentTrack.info.bitDepth===24)this.currentTrack.info.codec="pcm-s24be";else if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-s32be"}else if(this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"){if(this.currentTrack.info.bitDepth===32)this.currentTrack.info.codec="pcm-f32";else if(this.currentTrack.info.bitDepth===64)this.currentTrack.info.codec="pcm-f64"}let Q=this.currentTrack,q=new t(this.input,new n5(Q));this.currentTrack.inputTrack=q,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="subtitle"){let Q=this.currentTrack.codecId;if(Q==="S_TEXT/UTF8")this.currentTrack.info.codec="srt";else if(Q==="S_TEXT/SSA"||Q==="S_SSA")this.currentTrack.info.codec="ssa";else if(Q==="S_TEXT/ASS"||Q==="S_ASS")this.currentTrack.info.codec="ass";else if(Q==="S_TEXT/WEBVTT"||Q==="D_WEBVTT"||Q==="D_WEBVTT/SUBTITLES")this.currentTrack.info.codec="webvtt";if(this.currentTrack.codecPrivate){let W=new TextDecoder("utf-8");this.currentTrack.info.codecPrivateText=W.decode(this.currentTrack.codecPrivate)}let q=this.currentTrack,U=new p1(this.input,new o5(q));this.currentTrack.inputTrack=U,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case 215:{if(!this.currentTrack)break;this.currentTrack.id=g($,X)}break;case 131:{if(!this.currentTrack)break;let G=g($,X);if(G===1)this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1};else if(G===2)this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null};else if(G===17)this.currentTrack.info={type:"subtitle",codec:null,codecPrivateText:null}}break;case 185:{if(!this.currentTrack)break;if(!g($,X))this.currentSegment.tracks.pop(),this.currentTrack=null}break;case 136:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!g($,X)}break;case 21930:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!g($,X)}break;case 21934:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!g($,X)}break;case 21931:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!g($,X)}break;case 21932:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!g($,X)}break;case 21935:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!g($,X)}break;case 134:{if(!this.currentTrack)break;this.currentTrack.codecId=F1($,X)}break;case 25506:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=D($,X)}break;case 2352003:{if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*g($,X)/1e9}break;case 21358:{if(!this.currentTrack)break;this.currentTrack.name=N8($,X)}break;case 2274716:{if(!this.currentTrack)break;if(this.currentTrack.languageCode!==a)break;if(this.currentTrack.languageCode=F1($,X),!d0(this.currentTrack.languageCode))this.currentTrack.languageCode=a}break;case 2274717:{if(!this.currentTrack)break;let K=F1($,X).split("-")[0];if(K)this.currentTrack.languageCode=K;else this.currentTrack.languageCode=a}break;case 224:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,X))}break;case 176:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=g($,X)}break;case 186:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=g($,X)}break;case 21440:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=g($,X)===1}break;case 21936:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements($.slice(Z,X))}break;case 21937:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let G=g($,X),K=G6[G]??null;this.currentTrack.info.colorSpace.matrix=K}break;case 21945:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=g($,X)===2}break;case 21946:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let G=g($,X),K=Z6[G]??null;this.currentTrack.info.colorSpace.transfer=K}break;case 21947:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let G=g($,X),K=X6[G]??null;this.currentTrack.info.colorSpace.primaries=K}break;case 30320:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements($.slice(Z,X))}break;case 30325:{if(this.currentTrack?.info?.type!=="video")break;let K=-G2($,X);try{this.currentTrack.info.rotation=N1(K)}catch{}}break;case 225:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements($.slice(Z,X))}break;case 181:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=G2($,X)}break;case 159:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=g($,X)}break;case 25188:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=g($,X)}break;case 187:{if(!this.currentSegment)break;this.readContiguousElements($.slice(Z,X)),this.currentCueTime=null}break;case 179:this.currentCueTime=g($,X);break;case 183:{if(this.currentCueTime===null)break;H(this.currentSegment);let G={time:this.currentCueTime,trackId:-1,clusterPosition:-1};if(this.currentSegment.cuePoints.push(G),this.readContiguousElements($.slice(Z,X)),G.trackId===-1||G.clusterPosition===-1)this.currentSegment.cuePoints.pop()}break;case 247:{let G=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!G)break;G.trackId=g($,X)}break;case 241:{let G=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!G)break;H(this.currentSegment),G.clusterPosition=this.currentSegment.dataStartPos+g($,X)}break;case 231:{if(!this.currentCluster)break;this.currentCluster.timestamp=g($,X)}break;case 163:{if(!this.currentCluster)break;let G=H8($);if(G===null)break;let K=this.getTrackDataInCluster(this.currentCluster,G);if(!K)break;let Q=f8($),q=y($),U=q>>1&3,W=!!(q&128);if(K.track.info?.type==="audio"&&K.track.info.codec)W=!0;let V=D($,X-($.filePos-Z)),N=K.track.decodingInstructions.length>0;K.blocks.push({timestamp:Q,duration:0,isKeyFrame:W,data:V,lacing:U,decoded:!N,mainAdditional:null})}break;case 160:{if(!this.currentCluster)break;this.readContiguousElements($.slice(Z,X)),this.currentBlock=null}break;case 161:{if(!this.currentCluster)break;let G=H8($);if(G===null)break;let K=this.getTrackDataInCluster(this.currentCluster,G);if(!K)break;let Q=f8($),U=y($)>>1&3,W=D($,X-($.filePos-Z)),V=K.track.decodingInstructions.length>0;this.currentBlock={timestamp:Q,duration:0,isKeyFrame:!0,data:W,lacing:U,decoded:!V,mainAdditional:null},K.blocks.push(this.currentBlock)}break;case 30113:this.readContiguousElements($.slice(Z,X));break;case 166:{if(!this.currentBlock)break;if(this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements($.slice(Z,X)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1)this.currentBlock.mainAdditional=this.currentBlockAdditional.data;this.currentBlockAdditional=null}break;case 165:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=D($,X)}break;case 238:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=g($,X)}break;case 155:{if(!this.currentBlock)break;this.currentBlock.duration=g($,X)}break;case 251:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case 29555:this.currentTagTargetIsMovie=!0,this.readContiguousElements($.slice(Z,X));break;case 25536:this.readContiguousElements($.slice(Z,X));break;case 26826:if(g($,X)!==50)this.currentTagTargetIsMovie=!1;break;case 25541:case 25545:case 25540:case 25542:this.currentTagTargetIsMovie=!1;break;case 26568:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements($.slice(Z,X))}break;case 17827:this.currentSimpleTagName=N8($,X);break;case 17543:{if(!this.currentSimpleTagName)break;let G=N8($,X);this.processTagValue(this.currentSimpleTagName,G)}break;case 17541:{if(!this.currentSimpleTagName)break;let G=D($,X);this.processTagValue(this.currentSimpleTagName,G)}break;case 24999:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements($.slice(Z,X));let G=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData)G.raw??={},G.raw[this.currentAttachedFile.fileUid.toString()]=new l1(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0);if(this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let K=this.currentAttachedFile.fileName,Q="unknown";if(K){let q=K.toLowerCase();if(q.startsWith("cover."))Q="coverFront";else if(q.startsWith("back."))Q="coverBack"}G.images??=[],G.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:Q,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case 18094:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=l5($,X)}break;case 18030:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=N8($,X)}break;case 18016:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=F1($,X)}break;case 18012:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=D($,X)}break;case 18046:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=N8($,X)}break;case 28032:{if(!this.currentTrack)break;this.readContiguousElements($.slice(Z,X)),this.currentTrack.decodingInstructions.sort((G,K)=>K.order-G.order)}break;case 25152:{if(this.currentDecodingInstruction={order:0,scope:1,data:null},this.readContiguousElements($.slice(Z,X)),this.currentDecodingInstruction.data)this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction);this.currentDecodingInstruction=null}break;case 20529:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=g($,X)}break;case 20530:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=g($,X)}break;case 20532:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:0,settings:null},this.readContiguousElements($.slice(Z,X))}break;case 16980:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=g($,X)}break;case 16981:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=D($,X)}break;case 20533:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return $.filePos=Z+X,!0}decodeBlockData($,J){H($.decodingInstructions.length>0);let Y=J;for(let j of $.decodingInstructions)switch(H(j.data),j.data.type){case"decompress":switch(j.data.algorithm){case 3:if(j.data.settings&&j.data.settings.length>0){let X=j.data.settings,Z=new Uint8Array(X.length+Y.length);Z.set(X,0),Z.set(Y,X.length),Y=Z}break;default:}break;default:}return Y}processTagValue($,J){if(!this.currentSegment?.metadataTags)return;let Y=this.currentSegment.metadataTags;if(Y.raw??={},Y.raw[$]??=J,typeof J==="string")switch($.toLowerCase()){case"title":Y.title??=J;break;case"description":Y.description??=J;break;case"artist":Y.artist??=J;break;case"album":Y.album??=J;break;case"album_artist":Y.albumArtist??=J;break;case"genre":Y.genre??=J;break;case"comment":Y.comment??=J;break;case"lyrics":Y.lyrics??=J;break;case"date":{let j=new Date(J);if(!Number.isNaN(j.getTime()))Y.date??=j}break;case"track_number":case"part_number":{let j=J.split("/"),X=Number.parseInt(j[0],10),Z=j[1]&&Number.parseInt(j[1],10);if(Number.isInteger(X)&&X>0)Y.trackNumber??=X;if(Z&&Number.isInteger(Z)&&Z>0)Y.tracksTotal??=Z}break;case"disc_number":case"disc":{let j=J.split("/"),X=Number.parseInt(j[0],10),Z=j[1]&&Number.parseInt(j[1],10);if(Number.isInteger(X)&&X>0)Y.discNumber??=X;if(Z&&Number.isInteger(Z)&&Z>0)Y.discsTotal??=Z}break}}}class q2{internalTrack;packetToClusterLocation=new WeakMap;constructor($){this.internalTrack=$}getId(){return this.internalTrack.id}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket($){return this.performClusterLookup(null,(J)=>{if(J.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,$)}intoTimescale($){return y1($*this.internalTrack.segment.timestampFactor)}async getPacket($,J){let Y=this.intoTimescale($);return this.performClusterLookup(null,(j)=>{let X=j.trackData.get(this.internalTrack.id);if(!X)return{blockIndex:-1,correctBlockFound:!1};let Z=u(X.presentationTimestamps,Y,(Q)=>Q.timestamp),G=Z!==-1?X.presentationTimestamps[Z].blockIndex:-1,K=Z!==-1&&Y<X.endTimestamp;return{blockIndex:G,correctBlockFound:K}},Y,Y,J)}async getNextPacket($,J){let Y=this.packetToClusterLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(Y.cluster,(j)=>{if(j===Y.cluster){let X=j.trackData.get(this.internalTrack.id);if(Y.blockIndex+1<X.blocks.length)return{blockIndex:Y.blockIndex+1,correctBlockFound:!0}}else if(j.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,J)}async getKeyPacket($,J){let Y=this.intoTimescale($);return this.performClusterLookup(null,(j)=>{let X=j.trackData.get(this.internalTrack.id);if(!X)return{blockIndex:-1,correctBlockFound:!1};let Z=Q6(X.presentationTimestamps,(Q)=>{return X.blocks[Q.blockIndex].isKeyFrame&&Q.timestamp<=Y}),G=Z!==-1?X.presentationTimestamps[Z].blockIndex:-1,K=Z!==-1&&Y<X.endTimestamp;return{blockIndex:G,correctBlockFound:K}},Y,Y,J)}async getNextKeyPacket($,J){let Y=this.packetToClusterLocation.get($);if(Y===void 0)throw Error("Packet was not created from this track.");return this.performClusterLookup(Y.cluster,(j)=>{if(j===Y.cluster){let Z=j.trackData.get(this.internalTrack.id).blocks.findIndex((G,K)=>G.isKeyFrame&&K>Y.blockIndex);if(Z!==-1)return{blockIndex:Z,correctBlockFound:!0}}else{let X=j.trackData.get(this.internalTrack.id);if(X&&X.firstKeyFrameTimestamp!==null){let Z=X.blocks.findIndex((G)=>G.isKeyFrame);return H(Z!==-1),{blockIndex:Z,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,J)}async fetchPacketInCluster($,J,Y){if(J===-1)return null;let X=$.trackData.get(this.internalTrack.id).blocks[J];if(H(X),!X.decoded)X.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,X.data),X.decoded=!0;let Z=Y.metadataOnly?G0:X.data,G=X.timestamp/this.internalTrack.segment.timestampFactor,K=X.duration/this.internalTrack.segment.timestampFactor,Q={};if(X.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode)Q.alpha=Y.metadataOnly?G0:X.mainAdditional,Q.alphaByteLength=X.mainAdditional.byteLength;let q=new I(Z,X.isKeyFrame?"key":"delta",G,K,$.dataStartPos+J,X.data.byteLength,Q);return this.packetToClusterLocation.set(q,{cluster:$,blockIndex:J}),q}async performClusterLookup($,J,Y,j,X){let{demuxer:Z,segment:G}=this.internalTrack,K=null,Q=null,q=-1;if($){let{blockIndex:z,correctBlockFound:_}=J($);if(_)return this.fetchPacketInCluster($,z,X);if(z!==-1)Q=$,q=z}let U=u(this.internalTrack.cuePoints,Y,(z)=>z.time),W=U!==-1?this.internalTrack.cuePoints[U]:null,V=u(this.internalTrack.clusterPositionCache,Y,(z)=>z.startTimestamp),N=V!==-1?this.internalTrack.clusterPositionCache[V]:null,A=Math.max(W?.clusterPosition??0,N?.elementStartPos??0)||null,R;if(!$)R=A??G.clusterSeekStartPos;else if(A===null||$.elementStartPos>=A)R=$.elementEndPos,K=$;else R=A;while(G.elementEndPos===null||R<=G.elementEndPos-P0){if(K){let w=K.trackData.get(this.internalTrack.id);if(w&&w.startTimestamp>j)break}let z=Z.reader.requestSliceRange(R,P0,u0);if(z instanceof Promise)z=await z;if(!z)break;let _=R,L=p0(z);if(!L||!V8.includes(L.id)&&L.id!==236){let w=await _$(Z.reader,_,V8,Math.min(G.elementEndPos??Number.POSITIVE_INFINITY,_+d5));if(w){R=w;continue}break}let{id:M,size:B}=L,F=z.filePos;if(M===524531317){K=await Z.readCluster(_,G),B=K.elementEndPos-F;let{blockIndex:w,correctBlockFound:v}=J(K);if(v)return this.fetchPacketInCluster(K,w,X);if(w!==-1)Q=K,q=w}if(B===null)H(M!==524531317),B=(await K2(Z.reader,F,d8,G.elementEndPos)).pos-F;let C=F+B;if(G.elementEndPos===null){let w=Z.reader.requestSliceRange(C,P0,u0);if(w instanceof Promise)w=await w;if(!w)break;if(Z2(w)===408125543){G.elementEndPos=C;break}}R=C}if(W&&(!Q||Q.elementStartPos<W.clusterPosition)){let z=this.internalTrack.cuePoints[U-1];H(!z||z.time<W.time);let _=z?.time??Number.NEGATIVE_INFINITY;return this.performClusterLookup(null,J,_,j,X)}if(Q)return this.fetchPacketInCluster(Q,q,X);return null}}class c5 extends q2{internalTrack;decoderConfigPromise=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfigPromise??=(async()=>{let $=null;if(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)$=await this.getFirstPacket({});return{codec:V6({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"&&$?v6($.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&$?b6($.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&$?x6($.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&$?I6($.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}})()}}class n5 extends q2{internalTrack;decoderConfig=null;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){if(!this.internalTrack.info.codec)return null;return this.decoderConfig??={codec:H6({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}}}class o5 extends q2{internalTrack;constructor($){super($);this.internalTrack=$}getCodec(){return this.internalTrack.info.codec}getCodecPrivate(){return this.internalTrack.info.codecPrivateText}async*getCues(){let $=await this.getFirstPacket({});while($){let Y=new TextDecoder("utf-8").decode($.data);yield{timestamp:$.timestamp,duration:$.duration,text:Y},$=await this.getNextPacket($,{})}}}/*!
242
+ * Copyright (c) 2025-present, Vanilagy and contributors
243
+ *
244
+ * This Source Code Form is subject to the terms of the Mozilla Public
245
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
246
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
247
+ */var c8=async($,J,Y)=>{let j=J;while(Y===null||j<Y){let X=$.requestSlice(j,O6);if(X instanceof Promise)X=await X;if(!X)break;let Z=P(X),G=E6(Z,$.fileSize!==null?$.fileSize-j:null);if(G.header)return{header:G.header,startPos:j};j+=G.bytesAdvanced}return null};/*!
248
+ * Copyright (c) 2025-present, Vanilagy and contributors
249
+ *
250
+ * This Source Code Form is subject to the terms of the Mozilla Public
251
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
252
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
253
+ */class F$ extends W0{reader;metadataPromise=null;firstFrameHeader=null;loadedSamples=[];metadataTags=null;tracks=[];readingMutex=new w0;lastSampleLoaded=!1;lastLoadedPos=0;nextTimestampInSamples=0;constructor($){super($);this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{while(!this.firstFrameHeader&&!this.lastSampleLoaded)await this.advanceReader();if(!this.firstFrameHeader)throw Error("No valid MP3 frame found.");this.tracks=[new t(this.input,new r5(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)while(!0){let G=this.reader.requestSlice(this.lastLoadedPos,W8);if(G instanceof Promise)G=await G;if(!G){this.lastSampleLoaded=!0;return}let K=d1(G);if(!K)break;this.lastLoadedPos=G.filePos+K.size}let $=await c8(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!$){this.lastSampleLoaded=!0;return}let J=$.header;this.lastLoadedPos=$.startPos+J.totalSize-1;let Y=Y8(J.mpegVersionId,J.channel),j=this.reader.requestSlice($.startPos+Y,4);if(j instanceof Promise)j=await j;if(j){let G=P(j);if(G===J8||G===C6)return}if(!this.firstFrameHeader)this.firstFrameHeader=J;if(J.sampleRate!==this.firstFrameHeader.sampleRate)console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${J.sampleRate} Hz. Might be a bug, so please report this file.`);let X=J.audioSamplesInFrame/this.firstFrameHeader.sampleRate,Z={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:X,dataStart:$.startPos,dataSize:J.totalSize};this.loadedSamples.push(Z),this.nextTimestampInSamples+=J.audioSamplesInFrame;return}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let $=this.tracks[0];return H($),$.computeDuration()}async getMetadataTags(){let $=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let J=0,Y=!1;while(!0){let j=this.reader.requestSlice(J,W8);if(j instanceof Promise)j=await j;if(!j)break;let X=d1(j);if(!X)break;Y=!0;let Z=this.reader.requestSlice(j.filePos,X.size);if(Z instanceof Promise)Z=await Z;if(!Z)break;e6(Z,X,this.metadataTags),J=j.filePos+X.size}if(!Y&&this.reader.fileSize!==null&&this.reader.fileSize>=u8){let j=this.reader.requestSlice(this.reader.fileSize-u8,u8);if(j instanceof Promise)j=await j;if(H(j),s(j,3)==="TAG")b5(j,this.metadataTags)}return this.metadataTags}finally{$()}}}class r5{demuxer;constructor($){this.demuxer=$}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getName(){return null}getLanguageCode(){return a}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return H(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...L0}}async getDecoderConfig(){return H(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex($,J){if($===-1)return null;let Y=this.demuxer.loadedSamples[$];if(!Y)return null;let j;if(J.metadataOnly)j=G0;else{let X=this.demuxer.reader.requestSlice(Y.dataStart,Y.dataSize);if(X instanceof Promise)X=await X;if(!X)return null;j=D(X,Y.dataSize)}return new I(j,"key",Y.timestamp,Y.duration,$,Y.dataSize)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getNextPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{let j=Y1(this.demuxer.loadedSamples,$.timestamp,(Z)=>Z.timestamp);if(j===-1)throw Error("Packet was not created from this track.");let X=j+1;while(X>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded)await this.demuxer.advanceReader();return this.getPacketAtIndex(X,J)}finally{Y()}}async getPacket($,J){let Y=await this.demuxer.readingMutex.acquire();try{while(!0){let j=u(this.demuxer.loadedSamples,$,(X)=>X.timestamp);if(j===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(j,J);if(j>=0&&j+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(j,J);await this.demuxer.advanceReader()}}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
254
+ * Copyright (c) 2025-present, Vanilagy and contributors
255
+ *
256
+ * This Source Code Form is subject to the terms of the Mozilla Public
257
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
258
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
259
+ */var n8=1399285583,$j=79764919,i5=new Uint32Array(256);for(let $=0;$<256;$++){let J=$<<24;for(let Y=0;Y<8;Y++)J=J&2147483648?J<<1^$j:J<<1;i5[$]=J>>>0&4294967295}var U2=($)=>{let J=h($),Y=J.getUint32(22,!0);J.setUint32(22,0,!0);let j=0;for(let X=0;X<$.length;X++){let Z=$[X];j=(j<<8^i5[j>>>24^Z])>>>0}return J.setUint32(22,Y,!0),j},W2=($,J,Y)=>{let j=0,X=null;if($.length>0){if(J.codec==="vorbis"){H(J.vorbisInfo);let Z=J.vorbisInfo.modeBlockflags.length,K=(1<<zJ(Z-1))-1<<1,Q=($[0]&K)>>1;if(Q>=J.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let q=Y,U=J.vorbisInfo.modeBlockflags[Q];if(X=J.vorbisInfo.blocksizes[U],U===1){let W=(K|1)+1,V=$[0]&W?1:0;q=J.vorbisInfo.blocksizes[V]}j=q!==null?q+X>>2:0}else if(J.codec==="opus")j=sJ($).durationInSamples}return{durationInSamples:j,vorbisBlockSize:X}},V2=($)=>{let J="audio/ogg";if($.codecStrings){let Y=[...new Set($.codecStrings)];J+=`; codecs="${Y.join(", ")}"`}return J};/*!
260
+ * Copyright (c) 2025-present, Vanilagy and contributors
261
+ *
262
+ * This Source Code Form is subject to the terms of the Mozilla Public
263
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
264
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
265
+ */var B1=27,c1=282,H2=c1+65025,A8=($)=>{let J=$.filePos;if(h0($)!==n8)return null;$.skip(1);let j=y($),X=V5($),Z=h0($),G=h0($),K=h0($),Q=y($),q=new Uint8Array(Q);for(let N=0;N<Q;N++)q[N]=y($);let U=27+Q,W=q.reduce((N,A)=>N+A,0),V=U+W;return{headerStartPos:J,totalSize:V,dataStartPos:J+U,dataSize:W,headerType:j,granulePosition:X,serialNumber:Z,sequenceNumber:G,checksum:K,lacingValues:q}},s5=($,J)=>{while($.filePos<J-3){let Y=h0($),j=Y&255,X=Y>>>8&255,Z=Y>>>16&255,G=Y>>>24&255,K=79;if(j!==79&&X!==79&&Z!==79&&G!==79)continue;if($.skip(-4),Y===n8)return!0;$.skip(1)}return!1};/*!
266
+ * Copyright (c) 2025-present, Vanilagy and contributors
267
+ *
268
+ * This Source Code Form is subject to the terms of the Mozilla Public
269
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
270
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
271
+ */class B$ extends W0{reader;metadataPromise=null;bitstreams=[];tracks=[];metadataTags={};constructor($){super($);this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=0;while(!0){let J=this.reader.requestSliceRange($,B1,c1);if(J instanceof Promise)J=await J;if(!J)break;let Y=A8(J);if(!Y)break;if(!(Y.headerType&2))break;this.bitstreams.push({serialNumber:Y.serialNumber,bosPage:Y,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),$=Y.headerStartPos+Y.totalSize}for(let J of this.bitstreams){let Y=await this.readPacket(J.bosPage,0);if(!Y)continue;if(Y.data.byteLength>=7&&Y.data[0]===1&&Y.data[1]===118&&Y.data[2]===111&&Y.data[3]===114&&Y.data[4]===98&&Y.data[5]===105&&Y.data[6]===115)await this.readVorbisMetadata(Y,J);else if(Y.data.byteLength>=8&&Y.data[0]===79&&Y.data[1]===112&&Y.data[2]===117&&Y.data[3]===115&&Y.data[4]===72&&Y.data[5]===101&&Y.data[6]===97&&Y.data[7]===100)await this.readOpusMetadata(Y,J);if(J.codecInfo.codec!==null)this.tracks.push(new t(this.input,new e5(J,this)))}})()}async readVorbisMetadata($,J){let Y=await this.findNextPacketStart($);if(!Y)return;let j=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!j)return;if(Y=await this.findNextPacketStart(j),!Y)return;let X=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!X)return;if(j.data[0]!==3||X.data[0]!==5)return;let Z=[],G=(U)=>{while(!0){if(Z.push(Math.min(255,U)),U<255)break;U-=255}};G($.data.length),G(j.data.length);let K=new Uint8Array(1+Z.length+$.data.length+j.data.length+X.data.length);K[0]=2,K.set(Z,1),K.set($.data,1+Z.length),K.set(j.data,1+Z.length+$.data.length),K.set(X.data,1+Z.length+$.data.length+j.data.length),J.codecInfo.codec="vorbis",J.description=K,J.lastMetadataPacket=X;let Q=h($.data);J.numberOfChannels=Q.getUint8(11),J.sampleRate=Q.getUint32(12,!0);let q=Q.getUint8(28);J.codecInfo.vorbisInfo={blocksizes:[1<<(q&15),1<<(q>>4)],modeBlockflags:S6(X.data).modeBlockflags},P8(j.data.subarray(7),this.metadataTags)}async readOpusMetadata($,J){let Y=await this.findNextPacketStart($);if(!Y)return;let j=await this.readPacket(Y.startPage,Y.startSegmentIndex);if(!j)return;J.codecInfo.codec="opus",J.description=$.data,J.lastMetadataPacket=j;let X=z1($.data);J.numberOfChannels=X.outputChannelCount,J.sampleRate=b0,J.codecInfo.opusInfo={preSkip:X.preSkip},P8(j.data.subarray(8),this.metadataTags)}async readPacket($,J){H(J<$.lacingValues.length);let Y=0;for(let U=0;U<J;U++)Y+=$.lacingValues[U];let j=$,X=Y,Z=J,G=[];$:while(!0){let U=this.reader.requestSlice(j.dataStartPos,j.dataSize);if(U instanceof Promise)U=await U;H(U);let W=D(U,j.dataSize);while(!0){if(Z===j.lacingValues.length){G.push(W.subarray(Y,X));break}let N=j.lacingValues[Z];if(X+=N,N<255){G.push(W.subarray(Y,X));break $}Z++}let V=j.headerStartPos+j.totalSize;while(!0){let N=this.reader.requestSliceRange(V,B1,c1);if(N instanceof Promise)N=await N;if(!N)return null;let A=A8(N);if(!A)return null;if(j=A,j.serialNumber===$.serialNumber)break;V=j.headerStartPos+j.totalSize}Y=0,X=0,Z=0}let K=G.reduce((U,W)=>U+W.length,0),Q=new Uint8Array(K),q=0;for(let U=0;U<G.length;U++){let W=G[U];Q.set(W,q),q+=W.length}return{data:Q,endPage:j,endSegmentIndex:Z}}async findNextPacketStart($){if($.endSegmentIndex<$.endPage.lacingValues.length-1)return{startPage:$.endPage,startSegmentIndex:$.endSegmentIndex+1};if(!!($.endPage.headerType&4))return null;let Y=$.endPage.headerStartPos+$.endPage.totalSize;while(!0){let j=this.reader.requestSliceRange(Y,B1,c1);if(j instanceof Promise)j=await j;if(!j)return null;let X=A8(j);if(!X)return null;if(X.serialNumber===$.endPage.serialNumber)return{startPage:X,startSegmentIndex:0};Y=X.headerStartPos+X.totalSize}}async getMimeType(){await this.readMetadata();let $=await Promise.all(this.tracks.map((J)=>J.getCodecParameterString()));return V2({codecStrings:$.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let $=await this.getTracks(),J=await Promise.all($.map((Y)=>Y.computeDuration()));return Math.max(0,...J)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class e5{bitstream;demuxer;internalSampleRate;encodedPacketToMetadata=new WeakMap;sequentialScanCache=[];sequentialScanMutex=new w0;constructor($,J){this.bitstream=$;this.demuxer=J;this.internalSampleRate=$.codecInfo.codec==="opus"?b0:$.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return H(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 a}getDisposition(){return{...L0}}async getFirstTimestamp(){return 0}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}granulePositionToTimestampInSamples($){if(this.bitstream.codecInfo.codec==="opus")return H(this.bitstream.codecInfo.opusInfo),$-this.bitstream.codecInfo.opusInfo.preSkip;return $}createEncodedPacketFromOggPacket($,J,Y){if(!$)return null;let{durationInSamples:j,vorbisBlockSize:X}=W2($.data,this.bitstream.codecInfo,J.vorbisLastBlocksize),Z=new I(Y.metadataOnly?G0:$.data,"key",Math.max(0,J.timestampInSamples)/this.internalSampleRate,j/this.internalSampleRate,$.endPage.headerStartPos+$.endSegmentIndex,$.data.byteLength);return this.encodedPacketToMetadata.set(Z,{packet:$,timestampInSamples:J.timestampInSamples,durationInSamples:j,vorbisLastBlockSize:J.vorbisLastBlocksize,vorbisBlockSize:X}),Z}async getFirstPacket($){H(this.bitstream.lastMetadataPacket);let J=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!J)return null;let Y=0;if(this.bitstream.codecInfo.codec==="opus")H(this.bitstream.codecInfo.opusInfo),Y-=this.bitstream.codecInfo.opusInfo.preSkip;let j=await this.demuxer.readPacket(J.startPage,J.startSegmentIndex);return this.createEncodedPacketFromOggPacket(j,{timestampInSamples:Y,vorbisLastBlocksize:null},$)}async getNextPacket($,J){let Y=this.encodedPacketToMetadata.get($);if(!Y)throw Error("Packet was not created from this track.");let j=await this.demuxer.findNextPacketStart(Y.packet);if(!j)return null;let X=Y.timestampInSamples+Y.durationInSamples,Z=await this.demuxer.readPacket(j.startPage,j.startSegmentIndex);return this.createEncodedPacketFromOggPacket(Z,{timestampInSamples:X,vorbisLastBlocksize:Y.vorbisBlockSize},J)}async getPacket($,J){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential($,J);let Y=y1($*this.internalSampleRate);if(Y===0)return this.getFirstPacket(J);if(Y<0)return null;H(this.bitstream.lastMetadataPacket);let j=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!j)return null;let X=j.startPage,Z=this.demuxer.reader.fileSize,G=[X];$:while(X.headerStartPos+X.totalSize<Z){let _=X.headerStartPos,L=Math.floor((_+Z)/2),M=L;while(!0){let B=Math.min(M+H2,Z-B1),F=this.demuxer.reader.requestSlice(M,B-M);if(F instanceof Promise)F=await F;if(H(F),!s5(F,B)){Z=L+B1;continue $}let w=this.demuxer.reader.requestSliceRange(F.filePos,B1,c1);if(w instanceof Promise)w=await w;H(w);let v=A8(w);H(v);let k=!1;if(v.serialNumber===this.bitstream.serialNumber)k=!0;else{let T=this.demuxer.reader.requestSlice(v.headerStartPos,v.totalSize);if(T instanceof Promise)T=await T;H(T);let r=D(T,v.totalSize);k=U2(r)===v.checksum}if(!k){M=v.headerStartPos+4;continue}if(k&&v.serialNumber!==this.bitstream.serialNumber){M=v.headerStartPos+v.totalSize;continue}if(v.granulePosition===-1){M=v.headerStartPos+v.totalSize;continue}if(this.granulePositionToTimestampInSamples(v.granulePosition)>Y)Z=v.headerStartPos;else X=v,G.push(v);continue $}}let K=j.startPage;for(let _ of G){if(_.granulePosition===X.granulePosition)break;if(!K||_.headerStartPos>K.headerStartPos)K=_}let Q=K,q=[Q];while(!0){if(Q.serialNumber===this.bitstream.serialNumber&&Q.granulePosition===X.granulePosition)break;let _=Q.headerStartPos+Q.totalSize,L=this.demuxer.reader.requestSliceRange(_,B1,c1);if(L instanceof Promise)L=await L;H(L);let M=A8(L);if(H(M),Q=M,Q.serialNumber===this.bitstream.serialNumber)q.push(Q)}H(Q.granulePosition!==-1);let U=null,W,V,N=Q,A=0;if(Q.headerStartPos===j.startPage.headerStartPos)W=this.granulePositionToTimestampInSamples(0),V=!0,U=0;else{W=0,V=!1;for(let M=Q.lacingValues.length-1;M>=0;M--)if(Q.lacingValues[M]<255){U=M+1;break}if(U===null)throw Error("Invalid page with granule position: no packets end on this page.");A=U-1;let _={data:G0,endPage:N,endSegmentIndex:A};if(await this.demuxer.findNextPacketStart(_)){let M=t5(q,Q,U);H(M);let B=a5(q,M.page,M.segmentIndex);if(B)Q=B.page,U=B.segmentIndex}else while(!0){let M=t5(q,Q,U);if(!M)break;let B=a5(q,M.page,M.segmentIndex);if(!B)break;if(Q=B.page,U=B.segmentIndex,M.page.headerStartPos!==N.headerStartPos){N=M.page,A=M.segmentIndex;break}}}let R=null,z=null;while(Q!==null){H(U!==null);let _=await this.demuxer.readPacket(Q,U);if(!_)break;if(!(Q.headerStartPos===j.startPage.headerStartPos&&U<j.startSegmentIndex)){let B=this.createEncodedPacketFromOggPacket(_,{timestampInSamples:W,vorbisLastBlocksize:z?.vorbisBlockSize??null},J);H(B);let F=this.encodedPacketToMetadata.get(B);if(H(F),!V&&_.endPage.headerStartPos===N.headerStartPos&&_.endSegmentIndex===A)W=this.granulePositionToTimestampInSamples(Q.granulePosition),V=!0,B=this.createEncodedPacketFromOggPacket(_,{timestampInSamples:W-F.durationInSamples,vorbisLastBlocksize:z?.vorbisBlockSize??null},J),H(B),F=this.encodedPacketToMetadata.get(B),H(F);else W+=F.durationInSamples;if(R=B,z=F,V&&(Math.max(W,0)>Y||Math.max(F.timestampInSamples,0)===Y))break}let M=await this.demuxer.findNextPacketStart(_);if(!M)break;Q=M.startPage,U=M.startSegmentIndex}return R}async getPacketSequential($,J){let Y=await this.sequentialScanMutex.acquire();try{let j=y1($*this.internalSampleRate);$=j/this.internalSampleRate;let X=u(this.sequentialScanCache,j,(K)=>K.timestampInSamples),Z;if(X!==-1){let K=this.sequentialScanCache[X];Z=this.createEncodedPacketFromOggPacket(K.packet,{timestampInSamples:K.timestampInSamples,vorbisLastBlocksize:K.vorbisLastBlockSize},J)}else Z=await this.getFirstPacket(J);let G=0;while(Z&&Z.timestamp<$){let K=await this.getNextPacket(Z,J);if(!K||K.timestamp>$)break;if(Z=K,G++,G===100){G=0;let Q=this.encodedPacketToMetadata.get(Z);if(H(Q),this.sequentialScanCache.length>0)H(n(this.sequentialScanCache).timestampInSamples<=Q.timestampInSamples);this.sequentialScanCache.push(Q)}}return Z}finally{Y()}}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}var a5=($,J,Y)=>{let j=J,X=Y;$:while(!0){X--;for(X;X>=0;X--)if(j.lacingValues[X]<255){X++;break $}if(H(X===-1),!(j.headerType&1)){X=0;break}let G=g2($,(K)=>K.headerStartPos<j.headerStartPos);if(!G)return null;j=G,X=j.lacingValues.length}if(H(X!==-1),X===j.lacingValues.length){let Z=$[$.indexOf(j)+1];H(Z),j=Z,X=0}return{page:j,segmentIndex:X}},t5=($,J,Y)=>{if(Y>0)return{page:J,segmentIndex:Y-1};let j=g2($,(X)=>X.headerStartPos<J.headerStartPos);if(!j)return null;return{page:j,segmentIndex:j.lacingValues.length-1}};/*!
272
+ * Copyright (c) 2025-present, Vanilagy and contributors
273
+ *
274
+ * This Source Code Form is subject to the terms of the Mozilla Public
275
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
276
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
277
+ */class w$ extends W0{reader;metadataPromise=null;dataStart=-1;dataSize=-1;audioInfo=null;tracks=[];lastKnownPacketIndex=0;metadataTags={};constructor($){super($);this.reader=$._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let $=this.reader.requestSlice(0,12);if($ instanceof Promise)$=await $;H($);let J=s($,4),Y=J!=="RIFX",j=J==="RF64",X=Q1($,Y),Z=j?this.reader.fileSize:Math.min(X+8,this.reader.fileSize??Number.POSITIVE_INFINITY);if(s($,4)!=="WAVE")throw Error("Invalid WAVE file - wrong format");let K=0,Q=null,q=$.filePos;while(Z===null||q<Z){let W=this.reader.requestSlice(q,8);if(W instanceof Promise)W=await W;if(!W)break;let V=s(W,4),N=Q1(W,Y),A=W.filePos;if(j&&K===0&&V!=="ds64")throw Error('Invalid RF64 file: First chunk must be "ds64".');if(V==="fmt ")await this.parseFmtChunk(A,N,Y);else if(V==="data"){if(Q??=N,this.dataStart=W.filePos,this.dataSize=Math.min(Q,(Z??Number.POSITIVE_INFINITY)-this.dataStart),this.reader.fileSize===null)break}else if(V==="ds64"){let R=this.reader.requestSlice(A,N);if(R instanceof Promise)R=await R;if(!R)break;let z=X$(R,Y);Q=X$(R,Y),Z=Math.min(z+8,this.reader.fileSize??Number.POSITIVE_INFINITY)}else if(V==="LIST")await this.parseListChunk(A,N,Y);else if(V==="ID3 "||V==="id3 ")await this.parseId3Chunk(A,N);q=A+N+(N&1),K++}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.tracks.push(new t(this.input,new $Y(this)))})()}async parseFmtChunk($,J,Y){let j=this.reader.requestSlice($,J);if(j instanceof Promise)j=await j;if(!j)return;let X=G8(j,Y),Z=G8(j,Y),G=Q1(j,Y);j.skip(4);let K=G8(j,Y),Q;if(J===14)Q=8;else Q=G8(j,Y);if(J>=18&&X!==357){let q=G8(j,Y),U=J-18;if(Math.min(U,q)>=22&&X===65534){j.skip(6);let V=D(j,16);X=V[0]|V[1]<<8}}if(X===7||X===6)Q=8;this.audioInfo={format:X,numberOfChannels:Z,sampleRate:G,sampleSizeInBytes:Math.ceil(Q/8),blockSizeInBytes:K}}async parseListChunk($,J,Y){let j=this.reader.requestSlice($,J);if(j instanceof Promise)j=await j;if(!j)return;let X=s(j,4);if(X!=="INFO"&&X!=="INF0")return;let Z=j.filePos;while(Z<=$+J-8){j.filePos=Z;let G=s(j,4),K=Q1(j,Y),Q=D(j,K),q=0;for(let W=0;W<Q.length;W++){if(Q[W]===0)break;q++}let U=String.fromCharCode(...Q.subarray(0,q));switch(this.metadataTags.raw??={},this.metadataTags.raw[G]=U,G){case"INAM":case"TITL":this.metadataTags.title??=U;break;case"TIT3":this.metadataTags.description??=U;break;case"IART":this.metadataTags.artist??=U;break;case"IPRD":this.metadataTags.album??=U;break;case"IPRT":case"ITRK":case"TRCK":{let W=U.split("/"),V=Number.parseInt(W[0],10),N=W[1]&&Number.parseInt(W[1],10);if(Number.isInteger(V)&&V>0)this.metadataTags.trackNumber??=V;if(N&&Number.isInteger(N)&&N>0)this.metadataTags.tracksTotal??=N}break;case"ICRD":case"IDIT":{let W=new Date(U);if(!Number.isNaN(W.getTime()))this.metadataTags.date??=W}break;case"YEAR":{let W=Number.parseInt(U,10);if(Number.isInteger(W)&&W>0)this.metadataTags.date??=new Date(W,0,1)}break;case"IGNR":case"GENR":this.metadataTags.genre??=U;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=U;break}Z+=8+K+(K&1)}}async parseId3Chunk($,J){let Y=this.reader.requestSlice($,J);if(Y instanceof Promise)Y=await Y;if(!Y)return;let j=d1(Y);if(j){let X=Y.slice($+10,j.size);e6(X,j,this.metadataTags)}}getCodec(){if(H(this.audioInfo),this.audioInfo.format===7)return"ulaw";if(this.audioInfo.format===6)return"alaw";if(this.audioInfo.format===1){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}if(this.audioInfo.format===3){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32"}return null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();let $=this.tracks[0];return H($),$.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}var R8=2048;class $Y{demuxer;constructor($){this.demuxer=$}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let $=this.demuxer.getCodec();if(!$)return null;return H(this.demuxer.audioInfo),{codec:$,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}}async computeDuration(){let $=await this.getPacket(Number.POSITIVE_INFINITY,{metadataOnly:!0});return($?.timestamp??0)+($?.duration??0)}getNumberOfChannels(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return H(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return a}getDisposition(){return{...L0}}async getFirstTimestamp(){return 0}async getPacketAtIndex($,J){H(this.demuxer.audioInfo);let Y=$*R8*this.demuxer.audioInfo.blockSizeInBytes;if(Y>=this.demuxer.dataSize)return null;let j=Math.min(R8*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-Y);if(this.demuxer.reader.fileSize===null){let K=this.demuxer.reader.requestSlice(this.demuxer.dataStart+Y,j);if(K instanceof Promise)K=await K;if(!K)return null}let X;if(J.metadataOnly)X=G0;else{let K=this.demuxer.reader.requestSlice(this.demuxer.dataStart+Y,j);if(K instanceof Promise)K=await K;H(K),X=D(K,j)}let Z=$*R8/this.demuxer.audioInfo.sampleRate,G=j/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max($,Z),new I(X,"key",Z,G,$,j)}getFirstPacket($){return this.getPacketAtIndex(0,$)}async getPacket($,J){H(this.demuxer.audioInfo);let Y=Math.floor(Math.min($*this.demuxer.audioInfo.sampleRate/R8,(this.demuxer.dataSize-1)/(R8*this.demuxer.audioInfo.blockSizeInBytes))),j=await this.getPacketAtIndex(Y,J);if(j)return j;if(Y===0)return null;H(this.demuxer.reader.fileSize===null);let X=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,J);while(X){let Z=await this.getNextPacket(X,J);if(!Z)break;X=Z}return X}getNextPacket($,J){H(this.demuxer.audioInfo);let Y=Math.round($.timestamp*this.demuxer.audioInfo.sampleRate/R8);return this.getPacketAtIndex(Y+1,J)}getKeyPacket($,J){return this.getPacket($,J)}getNextKeyPacket($,J){return this.getNextPacket($,J)}}/*!
278
+ * Copyright (c) 2025-present, Vanilagy and contributors
279
+ *
280
+ * This Source Code Form is subject to the terms of the Mozilla Public
281
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
282
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
283
+ */class E0{}class N2 extends E0{async _getMajorBrand($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return null;if(J.skip(4),s(J,4)!=="ftyp")return null;return s(J,4)}_createDemuxer($){return new H$($)}}class O$ extends N2{async _canReadInput($){let J=await this._getMajorBrand($);return!!J&&J!=="qt "}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class P$ extends N2{async _canReadInput($){return await this._getMajorBrand($)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class A2 extends E0{async isSupportedEBMLOfDocType($,J){let Y=$._reader.requestSlice(0,u0);if(Y instanceof Promise)Y=await Y;if(!Y)return!1;let j=R$(Y);if(j===null)return!1;if(j<1||j>8)return!1;if(g(Y,j)!==440786851)return!1;let Z=z$(Y);if(Z===null)return!1;let G=$._reader.requestSlice(Y.filePos,Z);if(G instanceof Promise)G=await G;if(!G)return!1;let K=Y.filePos;while(G.filePos<=K+Z-P0){let Q=p0(G);if(!Q)break;let{id:q,size:U}=Q,W=G.filePos;if(U===null)return!1;switch(q){case 17030:if(g(G,U)!==1)return!1;break;case 17143:if(g(G,U)!==1)return!1;break;case 17026:if(F1(G,U)!==J)return!1;break;case 17031:if(g(G,U)>4)return!1;break}G.filePos=W+U}return!0}_canReadInput($){return this.isSupportedEBMLOfDocType($,"matroska")}_createDemuxer($){return new M$($)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class C$ extends A2{_canReadInput($){return this.isSupportedEBMLOfDocType($,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class D$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,10);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=0,j=!1;while(!0){let Q=$._reader.requestSlice(Y,W8);if(Q instanceof Promise)Q=await Q;if(!Q)break;let q=d1(Q);if(!q)break;j=!0,Y=Q.filePos+q.size}let X=await c8($._reader,Y,Y+4096);if(!X)return!1;if(j)return!0;Y=X.startPos+X.header.totalSize;let Z=await c8($._reader,Y,Y+O6);if(!Z)return!1;let G=X.header,K=Z.header;if(G.channel!==K.channel||G.sampleRate!==K.sampleRate)return!1;return!0}_createDemuxer($){return new F$($)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class E$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=s(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),s(J,4)==="WAVE"}_createDemuxer($){return new w$($)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class T$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return s(J,4)==="OggS"}_createDemuxer($){return new B$($)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class y$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,4);if(J instanceof Promise)J=await J;if(!J)return!1;return s(J,4)==="fLaC"}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer($){return new U$($)}}class v$ extends E0{async _canReadInput($){let J=$._reader.requestSliceRange(0,K8,Q8);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=g8(J);if(!Y)return!1;if(J=$._reader.requestSliceRange(Y.frameLength,K8,Q8),J instanceof Promise)J=await J;if(!J)return!1;let j=g8(J);if(!j)return!1;return Y.objectType===j.objectType&&Y.samplingFrequencyIndex===j.samplingFrequencyIndex&&Y.channelConfiguration===j.channelConfiguration}_createDemuxer($){return new G$($)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}var JY=new O$,YY=new P$,R2=new A2,jY=new C$,XY=new D$,ZY=new E$,GY=new T$,KY=new v$,QY=new y$;class b$ extends E0{async _canReadInput($){let J=$._reader.requestSlice(0,12);if(J instanceof Promise)J=await J;if(!J)return!1;let Y=s(J,4);if(Y!=="RIFF"&&Y!=="RIFX"&&Y!=="RF64")return!1;return J.skip(4),s(J,4)==="AVI "}_createDemuxer($){return new o0($)}get name(){return"AVI"}get mimeType(){return"video/x-msvideo"}}var qY=new b$,Jj=[JY,YY,R2,jY,ZY,GY,QY,XY,KY,qY];import*as UY from"node:fs/promises";/*!
284
+ * Copyright (c) 2025-present, Vanilagy and contributors
285
+ *
286
+ * This Source Code Form is subject to the terms of the Mozilla Public
287
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
288
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
289
+ */class i0{_disposed=!1;_sizePromise=null;async getSizeOrNull(){if(this._disposed)throw new q0;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new q0;let $=await this.getSizeOrNull();if($===null)throw Error("Cannot determine the size of an unsized source.");return $}onread=null}class WY extends i0{_bytes;_view;_onreadCalled=!1;constructor($){if(!($ instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&$ instanceof SharedArrayBuffer)&&!ArrayBuffer.isView($))throw TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super();this._bytes=l($),this._view=h($)}_retrieveSize(){return this._bytes.byteLength}_read(){if(!this._onreadCalled)this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0;return{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class VY extends i0{_blob;_orchestrator;constructor($,J={}){if(!($ instanceof Blob))throw TypeError("blob must be a Blob.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._blob=$,this._orchestrator=new z2({maxCacheSize:J.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:I$.fileSystem})}_retrieveSize(){let $=this._blob.size;return this._orchestrator.fileSize=$,$}_read($,J){return this._orchestrator.read($,J)}_readers=new WeakMap;async _runWorker($){let J=this._readers.get($);if(J===void 0){if("stream"in this._blob&&!s1())J=this._blob.slice($.currentPos).stream().getReader();else J=null;this._readers.set($,J)}while($.currentPos<$.targetPos&&!$.aborted)if(J){let{done:Y,value:j}=await J.read();if(Y)throw this._orchestrator.forgetWorker($),Error("Blob reader stopped unexpectedly before all requested data was read.");if($.aborted)break;this.onread?.($.currentPos,$.currentPos+j.length),this._orchestrator.supplyWorkerData($,j)}else{let Y=await this._blob.slice($.currentPos,$.targetPos).arrayBuffer();if($.aborted)break;this.onread?.($.currentPos,$.currentPos+Y.byteLength),this._orchestrator.supplyWorkerData($,new Uint8Array(Y))}$.running=!1}_dispose(){this._orchestrator.dispose()}}var HY=524288,Yj=($,J,Y)=>{if(J instanceof Error&&(J.message.includes("Failed to fetch")||J.message.includes("Load failed")||J.message.includes("NetworkError when attempting to fetch resource"))){let X=null;try{if(typeof window<"u"&&typeof window.location<"u")X=new URL(Y instanceof Request?Y.url:Y,window.location.href).origin}catch{}if((typeof navigator<"u"&&typeof navigator.onLine==="boolean"?navigator.onLine:!0)&&X!==null&&X!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**($-2),16)};class NY extends i0{_url;_getRetryDelay;_options;_orchestrator;_existingResponses=new WeakMap;constructor($,J={}){if(typeof $!=="string"&&!($ instanceof URL)&&!(typeof Request<"u"&&$ instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.requestInit!==void 0&&(!J.requestInit||typeof J.requestInit!=="object"))throw TypeError("options.requestInit, when provided, must be an object.");if(J.getRetryDelay!==void 0&&typeof J.getRetryDelay!=="function")throw TypeError("options.getRetryDelay, when provided, must be a function.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(J.fetchFn!==void 0&&typeof J.fetchFn!=="function")throw TypeError("options.fetchFn, when provided, must be a function.");super();this._url=$,this._options=J,this._getRetryDelay=J.getRetryDelay??Yj,this._orchestrator=new z2({maxCacheSize:J.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:I$.network})}async _retrieveSize(){let $=new AbortController,J=await u2(this._options.fetchFn??fetch,this._url,k2(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:$.signal}),this._getRetryDelay,()=>this._disposed);if(!J.ok)throw Error(`Error fetching ${String(this._url)}: ${J.status} ${J.statusText}`);let Y,j;if(J.status===206)j=this._getTotalLengthFromRangeResponse(J),Y=this._orchestrator.createWorker(0,Math.min(j,HY));else{let X=J.headers.get("Content-Length");if(X)j=Number(X),Y=this._orchestrator.createWorker(0,j),this._orchestrator.options.maxCacheSize=Number.POSITIVE_INFINITY,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.");else throw Error(`HTTP response (status ${J.status}) must surface Content-Length header.`)}return this._orchestrator.fileSize=j,this._existingResponses.set(Y,{response:J,abortController:$}),this._orchestrator.runWorker(Y),j}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while(!0){let J=this._existingResponses.get($);this._existingResponses.delete($);let Y=J?.abortController,j=J?.response;if(!Y)Y=new AbortController,j=await u2(this._options.fetchFn??fetch,this._url,k2(this._options.requestInit??{},{headers:{Range:`bytes=${$.currentPos}-`},signal:Y.signal}),this._getRetryDelay,()=>this._disposed);if(H(j),!j.ok)throw Error(`Error fetching ${String(this._url)}: ${j.status} ${j.statusText}`);if($.currentPos>0&&j.status!==206)throw Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!j.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");let X=j.body.getReader();while(!0){if($.currentPos>=$.targetPos||$.aborted){Y.abort(),$.running=!1;return}let Z;try{Z=await X.read()}catch(Q){let q=this._getRetryDelay(1,Q,this._url);if(q!==null){console.error("Error while reading response stream. Attempting to resume.",Q),await new Promise((U)=>setTimeout(U,1000*q));break}throw Q}if($.aborted)break;let{done:G,value:K}=Z;if(G){if(this._orchestrator.forgetWorker($),$.currentPos>=$.targetPos){this._orchestrator.forgetWorker($),$.running=!1;return}break}this.onread?.($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}if($.aborted)break}$.running=!1}_getTotalLengthFromRangeResponse($){let J=$.headers.get("Content-Range");if(J){let j=/\/(\d+)/.exec(J);if(j)return Number(j[1])}let Y=$.headers.get("Content-Length");if(Y)return Number(Y);throw Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}class AY extends i0{_streamSource;_fileHandle=null;constructor($,J={}){if(typeof $!=="string")throw TypeError("filePath must be a string.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._streamSource=new x$({getSize:async()=>{return this._fileHandle=await UY.open($,"r"),H(this._fileHandle),(await this._fileHandle.stat()).size},read:async(Y,j)=>{H(this._fileHandle);let X=new Uint8Array(j-Y);return await this._fileHandle.read(X,0,j-Y,Y),X},maxCacheSize:J.maxCacheSize,prefetchProfile:"fileSystem"})}_read($,J){return this._streamSource._read($,J)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}}class x$ extends i0{_options;_orchestrator;constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(typeof $.getSize!=="function")throw TypeError("options.getSize must be a function.");if(typeof $.read!=="function")throw TypeError("options.read must be a function.");if($.dispose!==void 0&&typeof $.dispose!=="function")throw TypeError("options.dispose, when provided, must be a function.");if($.maxCacheSize!==void 0&&(!R1($.maxCacheSize)||$.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if($.prefetchProfile&&!["none","fileSystem","network"].includes($.prefetchProfile))throw TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super();this._options=$,this._orchestrator=new z2({maxCacheSize:$.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:I$[$.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){let $=this._options.getSize();if($ instanceof Promise)return $.then((J)=>{if(!Number.isInteger(J)||J<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=J,J});if(!Number.isInteger($)||$<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=$,$}_read($,J){return this._orchestrator.read($,J)}async _runWorker($){while($.currentPos<$.targetPos&&!$.aborted){let{currentPos:J,targetPos:Y}=$,j=this._options.read($.currentPos,Y);if(j instanceof Promise)j=await j;if($.aborted)break;if(j instanceof Uint8Array){if(j=l(j),j.length!==Y-$.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${Y-$.currentPos} bytes, but got ${j.length}.`);this.onread?.($.currentPos,$.currentPos+j.length),this._orchestrator.supplyWorkerData($,j)}else if(j instanceof ReadableStream){let X=j.getReader();while($.currentPos<Y&&!$.aborted){let{done:Z,value:G}=await X.read();if(Z){if($.currentPos<Y)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${Y-J} bytes, but got ${$.currentPos-J}`);break}if(!(G instanceof Uint8Array))throw TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if($.aborted)break;let K=l(G);this.onread?.($.currentPos,$.currentPos+K.length),this._orchestrator.supplyWorkerData($,K)}}else throw TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}$.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}class RY extends i0{_stream;_reader=null;_cache=[];_maxCacheSize;_pendingSlices=[];_currentIndex=0;_targetIndex=0;_maxRequestedIndex=0;_endIndex=null;_pulling=!1;constructor($,J={}){if(!($ instanceof ReadableStream))throw TypeError("stream must be a ReadableStream.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");if(J.maxCacheSize!==void 0&&(!R1(J.maxCacheSize)||J.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super();this._stream=$,this._maxCacheSize=J.maxCacheSize??16777216}_retrieveSize(){return this._endIndex}_read($,J){if(this._endIndex!==null&&J>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,J);let Y=u(this._cache,$,(q)=>q.start),j=Y!==-1?this._cache[Y]:null;if(j&&j.start<=$&&J<=j.end)return{bytes:j.bytes,view:j.view,offset:j.start};let X=$,Z=new Uint8Array(J-$);if(Y!==-1)for(let q=Y;q<this._cache.length;q++){let U=this._cache[q];if(U.start>=J)break;let W=Math.max($,U.start);if(W>X)this._throwDueToCacheMiss();let V=Math.min(J,U.end);if(W<V)Z.set(U.bytes.subarray(W-U.start,V-U.start),W-$),X=V}if(X===J)return{bytes:Z,view:h(Z),offset:$};if(this._currentIndex>X)this._throwDueToCacheMiss();let{promise:G,resolve:K,reject:Q}=c();if(this._pendingSlices.push({start:$,end:J,bytes:Z,resolve:K,reject:Q}),this._targetIndex=Math.max(this._targetIndex,J),!this._pulling)this._pulling=!0,this._pull().catch((q)=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach((U)=>U.reject(q)),this._pendingSlices.length=0;else throw q});return G}_throwDueToCacheMiss(){throw Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}async _pull(){this._reader??=this._stream.getReader();while(this._currentIndex<this._targetIndex&&!this._disposed){let{done:$,value:J}=await this._reader.read();if($){for(let X of this._pendingSlices)X.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let Y=this._currentIndex,j=this._currentIndex+J.byteLength;for(let X=0;X<this._pendingSlices.length;X++){let Z=this._pendingSlices[X],G=Math.max(Y,Z.start),K=Math.min(j,Z.end);if(G<K){if(Z.bytes.set(J.subarray(G-Y,K-Y),G-Z.start),K===Z.end)Z.resolve({bytes:Z.bytes,view:h(Z.bytes),offset:Z.start}),this._pendingSlices.splice(X,1),X--}}this._cache.push({start:Y,end:j,bytes:J,view:h(J),age:0});while(this._cache.length>0){let X=this._cache[0];if(this._maxRequestedIndex-X.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=J.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0}}var I$={none:($,J)=>({start:$,end:J}),fileSystem:($,J)=>{return $=Math.floor(($-65536)/65536)*65536,J=Math.ceil((J+65536)/65536)*65536,{start:$,end:J}},network:($,J,Y)=>{$=Math.max(0,Math.floor(($-65536)/65536)*65536);for(let X of Y){let G=Math.max((X.startPos+X.targetPos)/2,X.targetPos-8388608);if(q6($,J,G,X.targetPos)){let K=X.targetPos-X.startPos,Q=Math.ceil((K+1)/8388608)*8388608,q=2**Math.ceil(Math.log2(K+1)),U=Math.min(q,Q);J=Math.max(J,X.startPos+U)}}return J=Math.max(J,$+HY),{start:$,end:J}}};class z2{options;fileSize=null;nextAge=0;workers=[];cache=[];currentCacheSize=0;disposed=!1;constructor($){this.options=$}read($,J){H(this.fileSize!==null);let Y=this.options.prefetchProfile($,J,this.workers),j=Math.max(Y.start,0),X=Math.min(Y.end,this.fileSize);H(j<=$&&J<=X);let Z=null,G=u(this.cache,$,(_)=>_.start),K=G!==-1?this.cache[G]:null;if(K&&K.start<=$&&J<=K.end)K.age=this.nextAge++,Z={bytes:K.bytes,view:K.view,offset:K.start};let Q=u(this.cache,j,(_)=>_.start),q=Z?null:new Uint8Array(J-$),U=0,W=j,V=[];if(Q!==-1){for(let _=Q;_<this.cache.length;_++){let L=this.cache[_];if(L.start>=X)break;if(L.end<=j)continue;let M=Math.max(j,L.start),B=Math.min(X,L.end);if(H(M<=B),W<M)V.push({start:W,end:M});if(W=B,q){let F=Math.max($,L.start),C=Math.min(J,L.end);if(F<C){let w=F-$;if(q.set(L.bytes.subarray(F-L.start,C-L.start),w),w===U)U=C-$}}L.age=this.nextAge++}if(W<X)V.push({start:W,end:X})}else V.push({start:j,end:X});if(q&&U>=q.length)Z={bytes:q,view:h(q),offset:$};if(V.length===0)return H(Z),Z;let{promise:N,resolve:A,reject:R}=c(),z=[];for(let _ of V){let L=Math.max($,_.start),M=Math.min(J,_.end);if(L===_.start&&M===_.end)z.push(_);else if(L<M)z.push({start:L,end:M})}for(let _ of V){let L=q&&{start:$,bytes:q,holes:z,resolve:A,reject:R},M=!1;for(let B of this.workers)if(q6(_.start-131072,_.start,B.currentPos,B.targetPos)){if(B.targetPos=Math.max(B.targetPos,_.end),M=!0,L&&!B.pendingSlices.includes(L))B.pendingSlices.push(L);if(!B.running)this.runWorker(B);break}if(!M){let B=this.createWorker(_.start,_.end);if(L)B.pendingSlices=[L];this.runWorker(B)}}if(!Z)H(q),Z=N.then((_)=>({bytes:_,view:h(_),offset:$}));return Z}createWorker($,J){let Y={startPos:$,currentPos:$,targetPos:J,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};this.workers.push(Y);while(this.workers.length>this.options.maxWorkerCount){let j=0,X=this.workers[0];for(let Z=1;Z<this.workers.length;Z++){let G=this.workers[Z];if(G.age<X.age)j=Z,X=G}if(X.running&&X.pendingSlices.length>0)break;X.aborted=!0,this.workers.splice(j,1)}return Y}runWorker($){H(!$.running),H($.currentPos<$.targetPos),$.running=!0,$.age=this.nextAge++,this.options.runWorker($).catch((J)=>{if($.running=!1,$.pendingSlices.length>0)$.pendingSlices.forEach((Y)=>Y.reject(J)),$.pendingSlices.length=0;else throw J})}supplyWorkerData($,J){H(!$.aborted);let Y=$.currentPos,j=Y+J.length;this.insertIntoCache({start:Y,end:j,bytes:J,view:h(J),age:this.nextAge++}),$.currentPos+=J.length,$.targetPos=Math.max($.targetPos,$.currentPos);for(let X=0;X<$.pendingSlices.length;X++){let Z=$.pendingSlices[X],G=Math.max(Y,Z.start),K=Math.min(j,Z.start+Z.bytes.length);if(G<K)Z.bytes.set(J.subarray(G-Y,K-Y),G-Z.start);for(let Q=0;Q<Z.holes.length;Q++){let q=Z.holes[Q];if(Y<=q.start&&j>q.start)q.start=j;if(q.end<=q.start)Z.holes.splice(Q,1),Q--}if(Z.holes.length===0)Z.resolve(Z.bytes),$.pendingSlices.splice(X,1),X--}for(let X=0;X<this.workers.length;X++){let Z=this.workers[X];if($===Z||Z.running)continue;if(q6(Y,j,Z.currentPos,Z.targetPos))this.workers.splice(X,1),X--}}forgetWorker($){let J=this.workers.indexOf($);H(J!==-1),this.workers.splice(J,1)}insertIntoCache($){if(this.options.maxCacheSize===0)return;let J=u(this.cache,$.start,(Y)=>Y.start)+1;if(J>0){let Y=this.cache[J-1];if(Y.end>=$.end)return;if(Y.end>$.start){let j=new Uint8Array($.end-Y.start);j.set(Y.bytes,0),j.set($.bytes,$.start-Y.start),this.currentCacheSize+=$.end-Y.end,Y.bytes=j,Y.view=h(j),Y.end=$.end,J--,$=Y}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length}else this.cache.splice(J,0,$),this.currentCacheSize+=$.bytes.length;for(let Y=J+1;Y<this.cache.length;Y++){let j=this.cache[Y];if($.end<=j.start)break;if($.end>=j.end){this.cache.splice(Y,1),this.currentCacheSize-=j.bytes.length,Y--;continue}let X=new Uint8Array(j.end-$.start);X.set($.bytes,0),X.set(j.bytes,j.start-$.start),this.currentCacheSize-=$.end-j.start,$.bytes=X,$.view=h(X),$.end=j.end,this.cache.splice(Y,1);break}while(this.currentCacheSize>this.options.maxCacheSize){let Y=0,j=this.cache[0];for(let X=1;X<this.cache.length;X++){let Z=this.cache[X];if(Z.age<j.age)Y=X,j=Z}if(this.currentCacheSize-j.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(Y,1),this.currentCacheSize-=j.bytes.length}}dispose(){for(let $ of this.workers)$.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}/*!
290
+ * Copyright (c) 2025-present, Vanilagy and contributors
291
+ *
292
+ * This Source Code Form is subject to the terms of the Mozilla Public
293
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
294
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
295
+ */U6();class z8{_source;_formats;_demuxerPromise=null;_format=null;_reader;_disposed=!1;get disposed(){return this._disposed}constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!Array.isArray($.formats)||$.formats.some((J)=>!(J instanceof E0)))throw TypeError("options.formats must be an array of InputFormat.");if(!($.source instanceof i0))throw TypeError("options.source must be a Source.");if($.source._disposed)throw Error("options.source must not be disposed.");this._formats=$.formats,this._source=$.source,this._reader=new j$($.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let $ of this._formats)if(await $._canReadInput(this))return this._format=$,$._createDemuxer(this);throw Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),H(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter((J)=>J.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter((J)=>J.isAudioTrack())}async getSubtitleTracks(){return(await this.getTracks()).filter((J)=>J.isSubtitleTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find((J)=>J.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find((J)=>J.isAudioTrack())??null}get subtitleTracks(){return this.getSubtitleTracks()}get videoTracks(){return this.getVideoTracks()}get audioTracks(){return this.getAudioTracks()}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(this._disposed)return;this._disposed=!0,this._source._disposed=!0,this._source._dispose()}[Symbol.dispose](){this.dispose()}}class q0 extends Error{constructor($="Input has been disposed."){super($);this.name="InputDisposedError"}}x0();/*!
296
+ * Copyright (c) 2025-present, Vanilagy and contributors
297
+ *
298
+ * This Source Code Form is subject to the terms of the Mozilla Public
299
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
300
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
301
+ */class o8{_connectedTrack=null;_closingPromise=null;_closed=!1;_timestampOffset=0;_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($){}close(){if(this._closingPromise)return;let $=this._connectedTrack;if(!$)throw Error("Cannot call close without connecting the source to an output track.");if($.output.state==="pending")throw Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{if(await this._flushAndClose(!1),this._closed=!0,$.output.state==="finalizing"||$.output.state==="finalized")return;$.output._muxer.onTrackClose($)})()}async _flushOrWaitForOngoingClose($){if(this._closingPromise)return this._closingPromise;return this._flushAndClose($)}}class w1 extends o8{_connectedTrack=null;_codec;constructor($){super();if(!j0.includes($))throw TypeError(`Invalid video codec '${$}'. Must be one of: ${j0.join(", ")}.`);this._codec=$}}class _2 extends w1{constructor($){super($)}add($,J){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("Metadata-only packets cannot be added.");if(J!==void 0&&(!J||typeof J!=="object"))throw TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,$,J)}}class L2{source;encodingConfig;ensureEncoderPromise=null;encoderInitialized=!1;encoder=null;muxer=null;lastMultipleOfKeyFrameInterval=-1;codedWidth=null;codedHeight=null;resizeCanvas=null;customEncoder=null;customEncoderCallSerializer=new v1;customEncoderQueueSize=0;alphaEncoder=null;splitter=null;splitterCreationFailed=!1;alphaFrameQueue=[];error=null;errorNeedsNewStack=!0;constructor($,J){this.source=$;this.encodingConfig=J}async add($,J,Y){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if($.codedWidth!==this.codedWidth||$.codedHeight!==this.codedHeight){let G=this.encodingConfig.sizeChangeBehavior??"deny";if(G==="passThrough");else if(G==="deny")throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${$.codedWidth}x${$.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);else{let K=!1;if(!this.resizeCanvas){if(typeof document<"u")this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight;else this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight);K=!0}let Q=this.resizeCanvas.getContext("2d",{alpha:n0()});if(H(Q),!K)if(n0())Q.fillStyle="black",Q.fillRect(0,0,this.codedWidth,this.codedHeight);else Q.clearRect(0,0,this.codedWidth,this.codedHeight);if($.drawWithFit(Q,{fit:G}),J)$.close();$=new J0(this.resizeCanvas,{timestamp:$.timestamp,duration:$.duration,rotation:$.rotation}),J=!0}}}else this.codedWidth=$.codedWidth,this.codedHeight=$.codedHeight;if(!this.encoderInitialized){if(!this.ensureEncoderPromise)this.ensureEncoder($);if(!this.encoderInitialized)await this.ensureEncoderPromise}H(this.encoderInitialized);let j=this.encodingConfig.keyFrameInterval??5,X=Math.floor($.timestamp/j),Z={...Y,keyFrame:Y?.keyFrame||j===0||X!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=X,this.customEncoder){this.customEncoderQueueSize++;let G=$.clone(),K=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(G,Z)).then(()=>this.customEncoderQueueSize--).catch((Q)=>this.error??=Q).finally(()=>{G.close()});if(this.customEncoderQueueSize>=4)await K}else{H(this.encoder);let G=$.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(G,Z),G.close();else if(!!G.format&&!G.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(G,Z),G.close();else{let{displayWidth:Q,displayHeight:q}=G;if(!this.splitter)try{this.splitter=new zY(Q,q)}catch(U){console.error("Due to an error, only color data will be encoded.",U),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(G,Z),G.close()}if(this.splitter){let U=this.splitter.extractColor(G),W=this.splitter.extractAlpha(G);this.alphaFrameQueue.push(W),this.encoder.encode(U,Z),U.close(),G.close()}}if(J)$.close();if(this.encoder.encodeQueueSize>=4)await new Promise((K)=>this.encoder.addEventListener("dequeue",K,{once:!0}))}await this.muxer.mutex.currentPromise}finally{if(J)$.close()}}ensureEncoder($){let J=Error();this.ensureEncoderPromise=(async()=>{let Y=R6({width:$.codedWidth,height:$.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(Y);let j=I1.find((X)=>X.supports(this.encodingConfig.codec,Y));if(j)this.customEncoder=new j,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=Y,this.customEncoder.onPacket=(X,Z)=>{if(!(X instanceof I))throw TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(Z!==void 0&&(!Z||typeof Z!=="object"))throw TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(X,Z),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,X,Z).catch((G)=>{this.error??=G,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw Error("VideoEncoder is not supported by this browser.");if(Y.alpha="discard",this.encodingConfig.alpha==="keep")Y.latencyMode="quality";if((Y.width%2===1||Y.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw Error(`The dimensions ${Y.width}x${Y.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(Y)).supported)throw Error(`This specific encoder configuration (${Y.codec}, ${Y.bitrate} bps, ${Y.width}x${Y.height}, hardware acceleration: ${Y.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let G=[],K=[],Q=0,q=0,U=(W,V,N)=>{let A={};if(V){let z=new Uint8Array(V.byteLength);V.copyTo(z),A.alpha=z}let R=I.fromEncodedChunk(W,A);this.encodingConfig.onEncodedPacket?.(R,N),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,R,N).catch((z)=>{this.error??=z,this.errorNeedsNewStack=!1})};if(this.encoder=new VideoEncoder({output:(W,V)=>{if(!this.alphaEncoder){U(W,null,V);return}let N=this.alphaFrameQueue.shift();if(H(N!==void 0),N)this.alphaEncoder.encode(N,{keyFrame:W.type==="key"}),q++,N.close(),G.push({chunk:W,meta:V});else if(q===0)U(W,null,V);else K.push(Q+q),G.push({chunk:W,meta:V})},error:(W)=>{W.stack=J.stack,this.error??=W}}),this.encoder.configure(Y),this.encodingConfig.alpha==="keep")this.alphaEncoder=new VideoEncoder({output:(W,V)=>{q--;let N=G.shift();H(N!==void 0),U(N.chunk,W,N.meta),Q++;while(K.length>0&&K[0]===Q){K.shift();let A=G.shift();H(A!==void 0),U(A.chunk,null,A.meta)}},error:(W)=>{W.stack=J.stack,this.error??=W}}),this.alphaEncoder.configure(Y)}H(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose($){if(!$)this.checkForEncoderError();if(this.customEncoder){if(!$)this.customEncoderCallSerializer.call(()=>this.customEncoder.flush());await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())}else if(this.encoder){if(!$)await this.encoder.flush(),await this.alphaEncoder?.flush();if(this.encoder.state!=="closed")this.encoder.close();if(this.alphaEncoder&&this.alphaEncoder.state!=="closed")this.alphaEncoder.close();this.alphaFrameQueue.forEach((J)=>J?.close()),this.splitter?.close()}if(!$)this.checkForEncoderError()}getQueueSize(){if(this.customEncoder)return this.customEncoderQueueSize;return this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error){if(this.errorNeedsNewStack)this.error.stack=Error().stack;throw this.error}}}class zY{canvas;gl;colorProgram;alphaProgram;vao;sourceTexture;lastFrame=null;alphaResolutionLocation;constructor($,J){if(typeof OffscreenCanvas<"u")this.canvas=new OffscreenCanvas($,J);else this.canvas=document.createElement("canvas"),this.canvas.width=$,this.canvas.height=J;let Y=this.canvas.getContext("webgl2",{alpha:!0});if(!Y)throw Error("Couldn't acquire WebGL 2 context.");this.gl=Y,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)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
302
+ in vec2 a_position;
303
+ in vec2 a_texCoord;
304
+ out vec2 v_texCoord;
305
+
306
+ void main() {
307
+ gl_Position = vec4(a_position, 0.0, 1.0);
308
+ v_texCoord = a_texCoord;
309
+ }
310
+ `)}createColorProgram(){let $=this.createVertexShader(),J=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
311
+ precision highp float;
312
+
313
+ uniform sampler2D u_sourceTexture;
314
+ in vec2 v_texCoord;
315
+ out vec4 fragColor;
316
+
317
+ void main() {
318
+ vec4 source = texture(u_sourceTexture, v_texCoord);
319
+ fragColor = vec4(source.rgb, 1.0);
320
+ }
321
+ `),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createAlphaProgram(){let $=this.createVertexShader(),J=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
322
+ precision highp float;
323
+
324
+ uniform sampler2D u_sourceTexture;
325
+ uniform vec2 u_resolution; // The width and height of the canvas
326
+ in vec2 v_texCoord;
327
+ out vec4 fragColor;
328
+
329
+ // This function determines the value for a single byte in the YUV stream
330
+ float getByteValue(float byteOffset) {
331
+ float width = u_resolution.x;
332
+ float height = u_resolution.y;
333
+
334
+ float yPlaneSize = width * height;
335
+
336
+ if (byteOffset < yPlaneSize) {
337
+ // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
338
+ float y = floor(byteOffset / width);
339
+ float x = mod(byteOffset, width);
340
+
341
+ // Add 0.5 to sample the center of the texel
342
+ vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
343
+
344
+ // The luma value is the alpha from the source texture
345
+ return texture(u_sourceTexture, sampleCoord).a;
346
+ } else {
347
+ // Write a fixed value for chroma and beyond
348
+ return 128.0 / 255.0;
349
+ }
350
+ }
351
+
352
+ void main() {
353
+ // Each fragment writes 4 bytes (R, G, B, A)
354
+ float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
355
+ float baseByteOffset = pixelIndex * 4.0;
356
+
357
+ vec4 result;
358
+ for (int i = 0; i < 4; i++) {
359
+ float currentByteOffset = baseByteOffset + float(i);
360
+ result[i] = getByteValue(currentByteOffset);
361
+ }
362
+
363
+ fragColor = result;
364
+ }
365
+ `),Y=this.gl.createProgram();return this.gl.attachShader(Y,$),this.gl.attachShader(Y,J),this.gl.linkProgram(Y),Y}createShader($,J){let Y=this.gl.createShader($);if(this.gl.shaderSource(Y,J),this.gl.compileShader(Y),!this.gl.getShaderParameter(Y,this.gl.COMPILE_STATUS))console.error("Shader compile error:",this.gl.getShaderInfoLog(Y));return Y}createVAO(){let $=this.gl.createVertexArray();this.gl.bindVertexArray($);let J=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),Y=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,Y),this.gl.bufferData(this.gl.ARRAY_BUFFER,J,this.gl.STATIC_DRAW);let j=this.gl.getAttribLocation(this.colorProgram,"a_position"),X=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(j),this.gl.vertexAttribPointer(j,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(X),this.gl.vertexAttribPointer(X,2,this.gl.FLOAT,!1,16,8),$}createTexture(){let $=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,$),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),$}updateTexture($){if(this.lastFrame===$)return;if($.displayWidth!==this.canvas.width||$.displayHeight!==this.canvas.height)this.canvas.width=$.displayWidth,this.canvas.height=$.displayHeight;this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,$),this.lastFrame=$}extractColor($){return this.updateTexture($),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:$.timestamp,duration:$.duration??void 0,alpha:"discard"})}extractAlpha($){this.updateTexture($),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:J,height:Y}=this.canvas,j=Math.ceil(J/2)*Math.ceil(Y/2),X=J*Y+j*2,Z=Math.ceil(X/(J*4)),G=new Uint8Array(4*J*Z);this.gl.readPixels(0,0,J,Z,this.gl.RGBA,this.gl.UNSIGNED_BYTE,G),G=G.subarray(0,X),H(G[J*Y]===128),H(G[G.length-1]===128);let K={format:"I420",codedWidth:J,codedHeight:Y,timestamp:$.timestamp,duration:$.duration??void 0,transfer:[G.buffer]};return new VideoFrame(G,K)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class r8 extends w1{_encoder;constructor($){_6($);super($.codec);this._encoder=new L2(this,$)}add($,J){if(!($ instanceof J0))throw TypeError("videoSample must be a VideoSample.");return this._encoder.add($,!1,J)}_flushAndClose($){return this._encoder.flushAndClose($)}}class _Y extends w1{_encoder;_canvas;constructor($,J){if(!(typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&$ instanceof OffscreenCanvas))throw TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");_6(J);super(J.codec);this._encoder=new L2(this,J),this._canvas=$}add($,J=0,Y){if(!Number.isFinite($)||$<0)throw TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(J)||J<0)throw TypeError("duration must be a non-negative number.");let j=new J0(this._canvas,{timestamp:$,duration:J});return this._encoder.add(j,!0,Y)}_flushAndClose($){return this._encoder.flushAndClose($)}}class LY extends w1{_encoder;_abortController=null;_track;_workerTrackId=null;_workerListener=null;_promiseWithResolvers=c();_errorPromiseAccessed=!1;_paused=!1;_lastSampleTimestamp=null;_pauseOffset=0;get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor($,J){if(!($ instanceof MediaStreamTrack)||$.kind!=="video")throw TypeError("track must be a video MediaStreamTrack.");_6(J),J={...J,latencyMode:"realtime"};super(J.codec);this._encoder=new L2(this,J),this._track=$}async _start(){if(!this._errorPromiseAccessed)console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");this._abortController=new AbortController;let $=null,J=!1,Y=(j)=>{if(J){j.close();return}let X=j.timestamp/1e6;if(this._paused){if($!==null){if(this._lastSampleTimestamp!==null){let K=X-this._lastSampleTimestamp;this._pauseOffset-=K}this._lastSampleTimestamp=X}j.close();return}if($===null){$=X;let G=this._connectedTrack.output._muxer;if(G.firstMediaStreamTimestamp===null)G.firstMediaStreamTimestamp=performance.now()/1000,this._timestampOffset=-$;else this._timestampOffset=performance.now()/1000-G.firstMediaStreamTimestamp-$}if(this._lastSampleTimestamp=X,this._encoder.getQueueSize()>=4){j.close();return}let Z=new J0(j,{timestamp:X+this._pauseOffset});this._encoder.add(Z,!0).catch((G)=>{if(J=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(G),this._workerTrackId!==null)h$({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){let j=new MediaStreamTrackProcessor({track:this._track}),X=new WritableStream({write:Y});j.readable.pipeTo(X,{signal:this._abortController.signal}).catch((Z)=>{if(Z instanceof DOMException&&Z.name==="AbortError")return;this._promiseWithResolvers.reject(Z)})}else if(await Gj())this._workerTrackId=Xj++,h$({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=(X)=>{let Z=X.data;if(Z.type==="videoFrame"&&Z.trackId===this._workerTrackId)Y(Z.videoFrame);else if(Z.type==="error"&&Z.trackId===this._workerTrackId)this._promiseWithResolvers.reject(Z.error)},T0.addEventListener("message",this._workerListener);else throw Error("MediaStreamTrackProcessor is required but not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose($){if(this._abortController)this._abortController.abort(),this._abortController=null;if(this._workerTrackId!==null)H(this._workerListener),h$({type:"stopTrack",trackId:this._workerTrackId}),await new Promise((J)=>{let Y=(j)=>{let X=j.data;if(X.type==="trackStopped"&&X.trackId===this._workerTrackId)H(this._workerListener),T0.removeEventListener("message",this._workerListener),T0.removeEventListener("message",Y),J()};T0.addEventListener("message",Y)});await this._encoder.flushAndClose($)}}class O1 extends o8{_connectedTrack=null;_codec;constructor($){super();if(!Z0.includes($))throw TypeError(`Invalid audio codec '${$}'. Must be one of: ${Z0.join(", ")}.`);this._codec=$}}class M2 extends O1{constructor($){super($)}add($,J){if(!($ instanceof I))throw TypeError("packet must be an EncodedPacket.");if($.isMetadataOnly)throw TypeError("Metadata-only packets cannot be added.");if(J!==void 0&&(!J||typeof J!=="object"))throw TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,$,J)}}class F2{source;encodingConfig;ensureEncoderPromise=null;encoderInitialized=!1;encoder=null;muxer=null;lastNumberOfChannels=null;lastSampleRate=null;isPcmEncoder=!1;outputSampleSize=null;writeOutputValue=null;customEncoder=null;customEncoderCallSerializer=new v1;customEncoderQueueSize=0;lastEndSampleIndex=null;error=null;errorNeedsNewStack=!0;constructor($,J){this.source=$;this.encodingConfig=J}async add($,J){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if($.numberOfChannels!==this.lastNumberOfChannels||$.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${$.numberOfChannels} channels at ${$.sampleRate} Hz.`)}else this.lastNumberOfChannels=$.numberOfChannels,this.lastSampleRate=$.sampleRate;if(!this.encoderInitialized){if(!this.ensureEncoderPromise)this.ensureEncoder($);if(!this.encoderInitialized)await this.ensureEncoderPromise}H(this.encoderInitialized);{let Y=Math.round($.timestamp*$.sampleRate),j=Math.round(($.timestamp+$.duration)*$.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=j;else{let X=Y-this.lastEndSampleIndex;if(X>=64){let Z=new K0({data:new Float32Array(X*$.numberOfChannels),format:"f32-planar",sampleRate:$.sampleRate,numberOfChannels:$.numberOfChannels,numberOfFrames:X,timestamp:this.lastEndSampleIndex/$.sampleRate});await this.add(Z,!0),this.lastEndSampleIndex+=$.numberOfFrames}}this.lastEndSampleIndex=j}if(this.customEncoder){this.customEncoderQueueSize++;let Y=$.clone(),j=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(Y)).then(()=>this.customEncoderQueueSize--).catch((X)=>this.error??=X).finally(()=>{Y.close()});if(this.customEncoderQueueSize>=4)await j;await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding($,J);else{H(this.encoder);let Y=$.toAudioData();if(this.encoder.encode(Y),Y.close(),J)$.close();if(this.encoder.encodeQueueSize>=4)await new Promise((j)=>this.encoder.addEventListener("dequeue",j,{once:!0}));await this.muxer.mutex.currentPromise}}finally{if(J)$.close()}}async doPcmEncoding($,J){H(this.outputSampleSize),H(this.writeOutputValue);let{numberOfChannels:Y,numberOfFrames:j,sampleRate:X,timestamp:Z}=$,G=2048,K=[];for(let W=0;W<j;W+=G){let V=Math.min(G,$.numberOfFrames-W),N=V*Y*this.outputSampleSize,A=new ArrayBuffer(N),R=new DataView(A);K.push({frameCount:V,view:R})}let Q=$.allocationSize({planeIndex:0,format:"f32-planar"}),q=new Float32Array(Q/Float32Array.BYTES_PER_ELEMENT);for(let W=0;W<Y;W++){$.copyTo(q,{planeIndex:W,format:"f32-planar"});for(let V=0;V<K.length;V++){let{frameCount:N,view:A}=K[V];for(let R=0;R<N;R++)this.writeOutputValue(A,(R*Y+W)*this.outputSampleSize,q[V*G+R])}}if(J)$.close();let U={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:Y,sampleRate:X}};for(let W=0;W<K.length;W++){let{frameCount:V,view:N}=K[W],A=N.buffer,R=W*G,z=new I(new Uint8Array(A),"key",Z+R/X,V/X);this.encodingConfig.onEncodedPacket?.(z,U),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,z,U)}}ensureEncoder($){let J=Error();this.ensureEncoderPromise=(async()=>{let{numberOfChannels:Y,sampleRate:j}=$,X=z6({numberOfChannels:Y,sampleRate:j,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(X);let Z=S1.find((G)=>G.supports(this.encodingConfig.codec,X));if(Z)this.customEncoder=new Z,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=X,this.customEncoder.onPacket=(G,K)=>{if(!(G instanceof I))throw TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(K!==void 0&&(!K||typeof K!=="object"))throw TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(G,K),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,G,K).catch((Q)=>{this.error??=Q,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(o.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(X)).supported)throw Error(`This specific encoder configuration (${X.codec}, ${X.bitrate} bps, ${X.numberOfChannels} channels, ${X.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(K,Q)=>{if(this.encodingConfig.codec==="aac"&&Q?.decoderConfig){let U=!1;if(!Q.decoderConfig.description||Q.decoderConfig.description.byteLength<2)U=!0;else U=x1(l(Q.decoderConfig.description)).objectType===0;if(U){let W=Number(n(X.codec.split(".")));Q.decoderConfig.description=bJ({objectType:W,numberOfChannels:Q.decoderConfig.numberOfChannels,sampleRate:Q.decoderConfig.sampleRate})}}let q=I.fromEncodedChunk(K);this.encodingConfig.onEncodedPacket?.(q,Q),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,q,Q).catch((U)=>{this.error??=U,this.errorNeedsNewStack=!1})},error:(K)=>{K.stack=J.stack,this.error??=K}}),this.encoder.configure(X)}H(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let $=this.encodingConfig.codec,{dataType:J,sampleSize:Y,littleEndian:j}=U0($);switch(this.outputSampleSize=Y,Y){case 1:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint8(Z,$0((G+1)*127.5,0,255));else if(J==="signed")this.writeOutputValue=(X,Z,G)=>{X.setInt8(Z,$0(Math.round(G*128),-128,127))};else if(J==="ulaw")this.writeOutputValue=(X,Z,G)=>{let K=$0(Math.floor(G*32767),-32768,32767);X.setUint8(Z,aJ(K))};else if(J==="alaw")this.writeOutputValue=(X,Z,G)=>{let K=$0(Math.floor(G*32767),-32768,32767);X.setUint8(Z,eJ(K))};else H(!1);break;case 2:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint16(Z,$0((G+1)*32767.5,0,65535),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>X.setInt16(Z,$0(Math.round(G*32767),-32768,32767),j);else H(!1);break;case 3:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>L8(X,Z,$0((G+1)*8388607.5,0,16777215),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>AJ(X,Z,$0(Math.round(G*8388607),-8388608,8388607),j);else H(!1);break;case 4:if(J==="unsigned")this.writeOutputValue=(X,Z,G)=>X.setUint32(Z,$0((G+1)*2147483647.5,0,4294967295),j);else if(J==="signed")this.writeOutputValue=(X,Z,G)=>X.setInt32(Z,$0(Math.round(G*2147483647),-2147483648,2147483647),j);else if(J==="float")this.writeOutputValue=(X,Z,G)=>X.setFloat32(Z,G,j);else H(!1);break;case 8:if(J==="float")this.writeOutputValue=(X,Z,G)=>X.setFloat64(Z,G,j);else H(!1);break;default:i(Y),H(!1)}}async flushAndClose($){if(!$)this.checkForEncoderError();if(this.customEncoder){if(!$)this.customEncoderCallSerializer.call(()=>this.customEncoder.flush());await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())}else if(this.encoder){if(!$)await this.encoder.flush();if(this.encoder.state!=="closed")this.encoder.close()}if(!$)this.checkForEncoderError()}getQueueSize(){if(this.customEncoder)return this.customEncoderQueueSize;if(this.isPcmEncoder)return 0;return this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error){if(this.errorNeedsNewStack)this.error.stack=Error().stack;throw this.error}}}class i8 extends O1{_encoder;constructor($){L6($);super($.codec);this._encoder=new F2(this,$)}add($){if(!($ instanceof K0))throw TypeError("audioSample must be an AudioSample.");return this._encoder.add($,!1)}_flushAndClose($){return this._encoder.flushAndClose($)}}class MY extends O1{_encoder;_accumulatedTime=0;constructor($){L6($);super($.codec);this._encoder=new F2(this,$)}async add($){if(!($ instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let J=K0._fromAudioBuffer($,this._accumulatedTime);this._accumulatedTime+=$.duration;for(let Y of J)await this._encoder.add(Y,!0)}_flushAndClose($){return this._encoder.flushAndClose($)}}class FY extends O1{_encoder;_abortController=null;_track;_audioContext=null;_scriptProcessorNode=null;_promiseWithResolvers=c();_errorPromiseAccessed=!1;_paused=!1;_lastSampleTimestamp=null;_pauseOffset=0;get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor($,J){if(!($ instanceof MediaStreamTrack)||$.kind!=="audio")throw TypeError("track must be an audio MediaStreamTrack.");L6(J);super(J.codec);this._encoder=new F2(this,J),this._track=$}async _start(){if(!this._errorPromiseAccessed)console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");this._abortController=new AbortController;let $=null,J=!1,Y=(j)=>{if(J){j.close();return}let X=j.timestamp;if(this._paused){if($!==null){if(this._lastSampleTimestamp!==null){let G=X-this._lastSampleTimestamp;this._pauseOffset-=G}this._lastSampleTimestamp=X}j.close();return}if($===null){$=j.timestamp;let Z=this._connectedTrack.output._muxer;if(Z.firstMediaStreamTimestamp===null)Z.firstMediaStreamTimestamp=performance.now()/1000,this._timestampOffset=-$;else this._timestampOffset=performance.now()/1000-Z.firstMediaStreamTimestamp-$}if(this._lastSampleTimestamp=X,this._encoder.getQueueSize()>=4){j.close();return}j.setTimestamp(X+this._pauseOffset),this._encoder.add(j,!0).catch((Z)=>{J=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(Z),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){let j=new MediaStreamTrackProcessor({track:this._track}),X=new WritableStream({write:(Z)=>Y(new K0(Z))});j.readable.pipeTo(X,{signal:this._abortController.signal}).catch((Z)=>{if(Z instanceof DOMException&&Z.name==="AbortError")return;this._promiseWithResolvers.reject(Z)})}else{let j=window.AudioContext||window.webkitAudioContext;this._audioContext=new j({sampleRate:this._track.getSettings().sampleRate});let X=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));if(this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended")await this._audioContext.resume();X.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let Z=0;this._scriptProcessorNode.onaudioprocess=(G)=>{let K=K0._fromAudioBuffer(G.inputBuffer,Z);Z+=G.inputBuffer.duration;for(let Q of K)Y(Q)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose($){if(this._abortController)this._abortController.abort(),this._abortController=null;if(this._audioContext)H(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend();await this._encoder.flushAndClose($)}}var jj=()=>{let $=(j,X)=>{if(X)self.postMessage(j,{transfer:X});else self.postMessage(j)};$({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});let J=new Map,Y=new Map;self.addEventListener("message",(j)=>{let X=j.data;switch(X.type){case"videoTrack":{Y.set(X.trackId,X.track);let Z=new MediaStreamTrackProcessor({track:X.track}),G=new WritableStream({write:(Q)=>{if(!Y.has(X.trackId)){Q.close();return}$({type:"videoFrame",trackId:X.trackId,videoFrame:Q},[Q])}}),K=new AbortController;J.set(X.trackId,K),Z.readable.pipeTo(G,{signal:K.signal}).catch((Q)=>{if(Q instanceof DOMException&&Q.name==="AbortError")return;$({type:"error",trackId:X.trackId,error:Q})})}break;case"stopTrack":{let Z=J.get(X.trackId);if(Z)Z.abort(),J.delete(X.trackId);Y.get(X.trackId)?.stop(),Y.delete(X.trackId),$({type:"trackStopped",trackId:X.trackId})}break;default:i(X)}})},Xj=0,T0=null,Zj=()=>{let $=new Blob([`(${jj.toString()})()`],{type:"application/javascript"}),J=URL.createObjectURL($);T0=new Worker(J)},S$=null,Gj=async()=>{if(S$!==null)return S$;if(!T0)Zj();return new Promise(($)=>{H(T0);let J=(Y)=>{let j=Y.data;if(j.type==="support")S$=j.supported,T0.removeEventListener("message",J),$(j.supported)};T0.addEventListener("message",J)})},h$=($,J)=>{if(H(T0),J)T0.postMessage($,J);else T0.postMessage($)};class s8 extends o8{_connectedTrack=null;_codec;constructor($){super();if(!z0.includes($))throw TypeError(`Invalid subtitle codec '${$}'. Must be one of: ${z0.join(", ")}.`);this._codec=$}}class B2 extends s8{_parser;_error=null;constructor($){super($);this._parser=new c6({codec:$,output:(J,Y)=>{this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,J,Y).catch((j)=>{this._error??=j instanceof Error?j:Error(String(j))})}})}add($){if(typeof $!=="string")throw TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse($),this._connectedTrack.output._muxer.mutex.currentPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose($){if(!$)this._checkForError()}}/*!
366
+ * Copyright (c) 2025-present, Vanilagy and contributors
367
+ *
368
+ * This Source Code Form is subject to the terms of the Mozilla Public
369
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
370
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
371
+ */class V0{output;mutex=new w0;firstMediaStreamTimestamp=null;constructor($){this.output=$}onTrackClose($){}trackTimestampInfo=new WeakMap;validateAndNormalizeTimestamp($,J,Y){J+=$.source._timestampOffset;let j=this.trackTimestampInfo.get($);if(!j){if(!Y)throw Error("First packet must be a key packet.");j={maxTimestamp:J,maxTimestampBeforeLastKeyPacket:J},this.trackTimestampInfo.set($,j)}if(J<0)throw Error(`Timestamps must be non-negative (got ${J}s).`);if(Y)j.maxTimestampBeforeLastKeyPacket=j.maxTimestamp;if(J<j.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 ${J}s, but largest timestamp is ${j.maxTimestampBeforeLastKeyPacket}s.`);return j.maxTimestamp=Math.max(j.maxTimestamp,J),J}}/*!
372
+ * Copyright (c) 2025-present, Vanilagy and contributors
373
+ *
374
+ * This Source Code Form is subject to the terms of the Mozilla Public
375
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
376
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
377
+ */class f$ extends V0{format;writer;header=new Uint8Array(7);headerBitstream=new f(this.header);audioSpecificConfig=null;constructor($,J){super($);this.format=J,this.writer=$._writer}async start(){}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw Error("ADTS does not support video.")}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{if(this.validateAndNormalizeTimestamp($,J.timestamp,J.type==="key"),!this.audioSpecificConfig){_0(Y);let G=Y?.decoderConfig?.description;H(G),this.audioSpecificConfig=x1(l(G));let{objectType:K,frequencyIndex:Q,channelConfiguration:q}=this.audioSpecificConfig,U=K-1;this.headerBitstream.writeBits(12,4095),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(2,0),this.headerBitstream.writeBits(1,1),this.headerBitstream.writeBits(2,U),this.headerBitstream.writeBits(4,Q),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(3,q),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(1,0),this.headerBitstream.skipBits(13),this.headerBitstream.writeBits(11,2047),this.headerBitstream.writeBits(2,0)}let X=J.data.byteLength+this.header.byteLength;this.headerBitstream.pos=30,this.headerBitstream.writeBits(13,X);let Z=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(J.data),this.format._options.onFrame){let G=new Uint8Array(X);G.set(this.header,0),G.set(J.data,this.header.byteLength),this.format._options.onFrame(G,Z)}await this.writer.flush()}finally{j()}}async addSubtitleCue(){throw Error("ADTS does not support subtitles.")}async finalize(){}}/*!
378
+ * Copyright (c) 2025-present, Vanilagy and contributors
379
+ *
380
+ * This Source Code Form is subject to the terms of the Mozilla Public
381
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
382
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
383
+ */class g${writer;isRIFX=!1;constructor($,J=!1){this.writer=$,this.isRIFX=J}writeString($){this.writer.write(m.encode($))}writeFourCC($){let J=new Uint8Array(4);for(let Y=0;Y<4&&Y<$.length;Y++)J[Y]=$.charCodeAt(Y);this.writer.write(J)}writeUint32($){let J=new ArrayBuffer(4);new DataView(J).setUint32(0,$,!this.isRIFX),this.writer.write(new Uint8Array(J))}writeUint16($){let J=new ArrayBuffer(2);new DataView(J).setUint16(0,$,!this.isRIFX),this.writer.write(new Uint8Array(J))}writeInt32($){let J=new ArrayBuffer(4);new DataView(J).setInt32(0,$,!this.isRIFX),this.writer.write(new Uint8Array(J))}writeInt16($){let J=new ArrayBuffer(2);new DataView(J).setInt16(0,$,!this.isRIFX),this.writer.write(new Uint8Array(J))}writeBytes($){this.writer.write($)}writePadding(){if(this.writer.getPos()%2!==0)this.writer.write(new Uint8Array(1))}startList($){this.writeFourCC("LIST");let J=this.writer.getPos();return this.writeUint32(0),this.writeFourCC($),J}endList($){let J=this.writer.getPos(),Y=J-$-8;this.writer.seek($),this.writeUint32(Y),this.writer.seek(J)}startChunk($){this.writeFourCC($);let J=this.writer.getPos();return this.writeUint32(0),J}endChunk($){let J=this.writer.getPos(),Y=J-$-4;this.writer.seek($),this.writeUint32(Y),this.writer.seek(J),this.writePadding()}}/*!
384
+ * Copyright (c) 2025-present, Vanilagy and contributors
385
+ *
386
+ * This Source Code Form is subject to the terms of the Mozilla Public
387
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
388
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
389
+ */class k$ extends V0{writer;riffWriter;format;trackDatas=[];allTracksKnown=c();fileStartPos=0;hdrlListSizePos=0;moviListSizePos=0;moviDataStart=0;mainHeaderPos=0;streamHeaderPositions=[];index=[];totalFrames=0;maxBytesPerSec=0;duration=0;headerFinalized=!1;constructor($,J){super($);if(this.writer=$._writer,this.format=J,this.riffWriter=new g$(this.writer),this.format._options.large);}async start(){let $=await this.mutex.acquire();this.fileStartPos=this.writer.getPos(),this.riffWriter.writeFourCC("RIFF"),this.riffWriter.writeUint32(0),this.riffWriter.writeFourCC("AVI "),this.hdrlListSizePos=this.riffWriter.startList("hdrl"),this.writeMainHeader(),await this.writer.flush(),$()}writeMainHeader(){this.riffWriter.writeFourCC("avih"),this.riffWriter.writeUint32(56),this.mainHeaderPos=this.writer.getPos(),this.riffWriter.writeUint32(41667),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(16),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.writer.write(new Uint8Array(16))}async finalizeHeader(){if(this.headerFinalized)return;this.allTracksKnown.resolve();for(let $=0;$<this.trackDatas.length;$++)this.writeStreamList(this.trackDatas[$],$);this.riffWriter.endList(this.hdrlListSizePos),this.moviListSizePos=this.riffWriter.startList("movi"),this.moviDataStart=this.writer.getPos(),this.headerFinalized=!0}writeStreamList($,J){if(!$)return;let Y=this.riffWriter.startList("strl");if(this.riffWriter.writeFourCC("strh"),this.riffWriter.writeUint32(56),this.streamHeaderPositions[J]=this.writer.getPos(),$.type==="video"){let j=$;this.riffWriter.writeFourCC("vids"),this.riffWriter.writeFourCC(j.info.fourcc),this.riffWriter.writeUint32(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(1000),this.riffWriter.writeUint32(Math.round(j.info.frameRate*1000)),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(1e4),this.riffWriter.writeUint32(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint16(j.info.width),this.riffWriter.writeUint16(j.info.height)}else if($.type==="audio"){let j=$,X=j.info.bitsPerSample/8*j.info.numberOfChannels;this.riffWriter.writeFourCC("auds"),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(1),this.riffWriter.writeUint32(j.info.sampleRate),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(4294967295),this.riffWriter.writeUint32(X),this.riffWriter.writeUint16(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint16(0),this.riffWriter.writeUint16(0)}if(this.riffWriter.writeFourCC("strf"),$.type==="video"){let j=$;this.riffWriter.writeUint32(40),this.riffWriter.writeUint32(40),this.riffWriter.writeInt32(j.info.width),this.riffWriter.writeInt32(j.info.height),this.riffWriter.writeUint16(1),this.riffWriter.writeUint16(24),this.riffWriter.writeFourCC(j.info.fourcc),this.riffWriter.writeUint32(0),this.riffWriter.writeInt32(0),this.riffWriter.writeInt32(0),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(0)}else if($.type==="audio"){let j=$,X=j.info.numberOfChannels*(j.info.bitsPerSample/8);this.riffWriter.writeUint32(16),this.riffWriter.writeUint16(j.info.formatTag),this.riffWriter.writeUint16(j.info.numberOfChannels),this.riffWriter.writeUint32(j.info.sampleRate),this.riffWriter.writeUint32(j.info.sampleRate*X),this.riffWriter.writeUint16(X),this.riffWriter.writeUint16(j.info.bitsPerSample)}this.riffWriter.endList(Y)}async getMimeType(){return"video/x-msvideo"}getVideoTrackData($){for(let J of this.trackDatas)if(J.track===$)return J;return null}getAudioTrackData($){for(let J of this.trackDatas)if(J.track===$)return J;return null}async addEncodedVideoPacket($,J,Y){let j=await this.mutex.acquire(),X=this.getVideoTrackData($);if(!X){let Q=z5($.source._codec);if(!Q)throw Error(`Unsupported video codec for AVI: ${$.source._codec}`);t1(Y),X={track:$,type:"video",info:{width:Y.decoderConfig.codedWidth||640,height:Y.decoderConfig.codedHeight||480,frameRate:30,fourcc:Q,decoderConfig:Y.decoderConfig},chunkQueue:[],frameCount:0,sampleCount:0,maxChunkSize:0,lastTimestamp:0},this.trackDatas.push(X)}if(!this.headerFinalized)await this.finalizeHeader();let Z=this.trackDatas.indexOf(X),G=Q$(Z,"dc"),K=this.writer.getPos()-this.moviDataStart;this.riffWriter.writeFourCC(G),this.riffWriter.writeUint32(J.data.length),this.writer.write(J.data),this.riffWriter.writePadding(),this.index.push({ckid:G,flags:J.type==="key"?L1:0,offset:K,size:J.data.length}),X.frameCount++,X.lastTimestamp=J.timestamp,X.maxChunkSize=Math.max(X.maxChunkSize,J.data.length),this.totalFrames=Math.max(this.totalFrames,X.frameCount),this.duration=Math.max(this.duration,J.timestamp),j()}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire(),X=this.getAudioTrackData($);if(!X){let q=_5($.source._codec);if(q===null)throw Error(`Unsupported audio codec for AVI: ${$.source._codec}`);_0(Y),X={track:$,type:"audio",info:{numberOfChannels:Y.decoderConfig.numberOfChannels||2,sampleRate:Y.decoderConfig.sampleRate||48000,bitsPerSample:16,formatTag:q,decoderConfig:Y.decoderConfig},chunkQueue:[],frameCount:0,sampleCount:0,maxChunkSize:0,lastTimestamp:0},this.trackDatas.push(X)}if(!this.headerFinalized)await this.finalizeHeader();let Z=this.trackDatas.indexOf(X),G=Q$(Z,"wb"),K=this.writer.getPos()-this.moviDataStart;this.riffWriter.writeFourCC(G),this.riffWriter.writeUint32(J.data.length),this.writer.write(J.data),this.riffWriter.writePadding(),this.index.push({ckid:G,flags:0,offset:K,size:J.data.length});let Q=X.info.bitsPerSample/8*X.info.numberOfChannels;X.sampleCount+=Math.floor(J.data.length/Q),X.lastTimestamp=J.timestamp,X.maxChunkSize=Math.max(X.maxChunkSize,J.data.length),this.duration=Math.max(this.duration,J.timestamp),j()}async addSubtitleCue($,J,Y){throw Error("AVI format does not support subtitle tracks")}async finalize(){let $=await this.mutex.acquire();if(!this.headerFinalized)await this.finalizeHeader();if(this.moviListSizePos)this.riffWriter.endList(this.moviListSizePos);if(this.index.length>0){let Y=this.riffWriter.startChunk("idx1");for(let j of this.index)this.riffWriter.writeFourCC(j.ckid),this.riffWriter.writeUint32(j.flags),this.riffWriter.writeUint32(j.offset),this.riffWriter.writeUint32(j.size);this.riffWriter.endChunk(Y)}let J=this.writer.getPos();this.writer.seek(this.fileStartPos+4),this.riffWriter.writeUint32(J-this.fileStartPos-8),this.updateMainHeader(),this.updateStreamHeaders(),this.writer.seek(J),await this.writer.flush(),$()}updateMainHeader(){this.writer.seek(this.mainHeaderPos);let $=41667,J=0,Y=0,j=0;for(let X of this.trackDatas){if(X.type==="video"){let Z=X;if(J=Math.max(J,Z.info.width),Y=Math.max(Y,Z.info.height),Z.info.frameRate>0)$=Math.round(1e6/Z.info.frameRate)}j=Math.max(j,X.maxChunkSize)}this.riffWriter.writeUint32($),this.riffWriter.writeUint32(this.maxBytesPerSec),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(16),this.riffWriter.writeUint32(this.totalFrames),this.riffWriter.writeUint32(0),this.riffWriter.writeUint32(this.trackDatas.length),this.riffWriter.writeUint32(j),this.riffWriter.writeUint32(J),this.riffWriter.writeUint32(Y)}updateStreamHeaders(){for(let $=0;$<this.trackDatas.length;$++){let J=this.trackDatas[$];if(!J)continue;let Y=this.streamHeaderPositions[$];if(!Y)continue;if(this.writer.seek(Y+28),J.type==="video")this.riffWriter.writeUint32(J.frameCount);else if(J.type==="audio")this.riffWriter.writeUint32(J.sampleCount);this.writer.seek(Y+32),this.riffWriter.writeUint32(J.maxChunkSize)}}}/*!
390
+ * Copyright (c) 2025-present, Vanilagy and contributors
391
+ *
392
+ * This Source Code Form is subject to the terms of the Mozilla Public
393
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
394
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
395
+ */var BY=new Uint8Array([102,76,97,67]),Kj=38,Qj=34;class u$ extends V0{writer;metadataWritten=!1;blockSizes=[];frameSizes=[];sampleRate=null;channels=null;bitsPerSample=null;format;constructor($,J){super($);this.writer=$._writer,this.format=J}async start(){this.writer.write(BY)}writeHeader({bitsPerSample:$,minimumBlockSize:J,maximumBlockSize:Y,minimumFrameSize:j,maximumFrameSize:X,sampleRate:Z,channels:G,totalSamples:K}){H(this.writer.getPos()===4);let Q=!m1(this.output._metadataTags),q=new f(new Uint8Array(4));q.writeBits(1,Number(!Q)),q.writeBits(7,0),q.writeBits(24,Qj),this.writer.write(q.bytes);let U=new f(new Uint8Array(18));if(U.writeBits(16,J),U.writeBits(16,Y),U.writeBits(24,j),U.writeBits(24,X),U.writeBits(20,Z),U.writeBits(3,G-1),U.writeBits(5,$-1),K>=4294967296)throw Error("This muxer only supports writing up to 2 ** 32 samples");U.writeBits(4,0),U.writeBits(32,K),this.writer.write(U.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock($){let J=32+$.mimeType.length+($.description?.length??0)+$.data.length,Y=new Uint8Array(J),j=0,X=h(Y);X.setUint32(j,$.kind==="coverFront"?3:$.kind==="coverBack"?4:0),j+=4,X.setUint32(j,$.mimeType.length),j+=4,Y.set(m.encode($.mimeType),8),j+=$.mimeType.length,X.setUint32(j,$.description?.length??0),j+=4,Y.set(m.encode($.description??""),j),j+=$.description?.length??0,j+=16,X.setUint32(j,$.data.length),j+=4,Y.set($.data,j),j+=$.data.length,H(j===J);let Z=new f(new Uint8Array(4));Z.writeBits(1,0),Z.writeBits(7,6),Z.writeBits(24,J),this.writer.write(Z.bytes),this.writer.write(Y)}writeVorbisCommentAndPictureBlock(){if(this.writer.seek(Kj+BY.byteLength),m1(this.output._metadataTags)){this.metadataWritten=!0;return}let $=this.output._metadataTags.images??[];for(let j of $)this.writePictureBlock(j);let J=C8(new Uint8Array(0),this.output._metadataTags,!1),Y=new f(new Uint8Array(4));Y.writeBits(1,1),Y.writeBits(7,4),Y.writeBits(24,J.length),this.writer.write(Y.bytes),this.writer.write(J),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw Error("FLAC does not support video.")}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();_0(Y),H(Y),H(Y.decoderConfig),H(Y.decoderConfig.description);try{if(this.validateAndNormalizeTimestamp($,J.timestamp,J.type==="key"),this.sampleRate===null)this.sampleRate=Y.decoderConfig.sampleRate;if(this.channels===null)this.channels=Y.decoderConfig.numberOfChannels;if(this.bitsPerSample===null){let U=new f(l(Y.decoderConfig.description));U.skipBits(167);let W=U.readBits(5)+1;this.bitsPerSample=W}if(!this.metadataWritten)this.writeVorbisCommentAndPictureBlock();let X=S0.tempFromBytes(J.data);D(X,2);let Z=D(X,2),G=new f(Z),K=s6(G.readBits(4));if(K===null)throw Error("Invalid FLAC frame: Invalid block size.");a6(X);let Q=t6(X,K);this.blockSizes.push(Q),this.frameSizes.push(J.data.length);let q=this.writer.getPos();if(this.writer.write(J.data),this.format._options.onFrame)this.format._options.onFrame(J.data,q);await this.writer.flush()}finally{j()}}addSubtitleCue(){throw Error("FLAC does not support subtitles.")}async finalize(){let $=await this.mutex.acquire(),J=Number.POSITIVE_INFINITY,Y=0,j=Number.POSITIVE_INFINITY,X=0,Z=0;for(let G=0;G<this.blockSizes.length;G++){if(j=Math.min(j,this.frameSizes[G]),X=Math.max(X,this.frameSizes[G]),Y=Math.max(Y,this.blockSizes[G]),Z+=this.blockSizes[G],G===this.blockSizes.length-1)continue;J=Math.min(J,this.blockSizes[G])}H(this.sampleRate!==null),H(this.channels!==null),H(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:J,maximumBlockSize:Y,minimumFrameSize:j,maximumFrameSize:X,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:Z}),$()}}x0();/*!
396
+ * Copyright (c) 2025-present, Vanilagy and contributors
397
+ *
398
+ * This Source Code Form is subject to the terms of the Mozilla Public
399
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
400
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
401
+ */class w2{ensureMonotonicity=!1;start(){}trackedWrites=null;trackedStart=-1;trackedEnd=-1;maybeTrackWrites($){if(!this.trackedWrites)return;let J=this.getPos();if(J<this.trackedStart){if(J+$.byteLength<=this.trackedStart)return;$=$.subarray(this.trackedStart-J),J=0}let Y=J+$.byteLength-this.trackedStart,j=this.trackedWrites.byteLength;while(j<Y)j*=2;if(j!==this.trackedWrites.byteLength){let X=new Uint8Array(j);X.set(this.trackedWrites,0),this.trackedWrites=X}this.trackedWrites.set($,J-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,J+$.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),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 J={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,J}}var p$=65536,l$=4294967296;class a8 extends w2{pos=0;target;buffer;bytes;maxPos=0;supportsResize;constructor($){super();if(this.target=$,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(p$,{maxByteLength:l$})}catch{this.buffer=new ArrayBuffer(p$),this.supportsResize=!1}else this.buffer=new ArrayBuffer(p$);this.bytes=new Uint8Array(this.buffer)}ensureSize($){let J=this.buffer.byteLength;while(J<$)J*=2;if(J===this.buffer.byteLength)return;if(J>l$)throw Error(`ArrayBuffer exceeded maximum size of ${l$} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(J);else{let Y=new ArrayBuffer(J),j=new Uint8Array(Y);j.set(this.bytes,0),this.buffer=Y,this.bytes=j}}write($){this.maybeTrackWrites($),this.ensureSize(this.pos+$.byteLength),this.bytes.set($,this.pos),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek($){this.pos=$}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice($,J){return this.bytes.slice($,J)}}var qj=16777216,Uj=2;class m$ extends w2{pos=0;target;sections=[];lastWriteEnd=0;lastFlushEnd=0;writer=null;chunked;chunkSize;chunks=[];constructor($){super();this.target=$,this.chunked=$._options.chunked??!1,this.chunkSize=$._options.chunkSize??qj}start(){this.writer=this.target._writable.getWriter()}write($){if(this.pos>this.lastWriteEnd){let J=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(J))}this.maybeTrackWrites($),this.sections.push({data:$.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek($){this.pos=$}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){let Y=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(Y))}if(H(this.writer),this.sections.length===0)return;let $=[],J=[...this.sections].sort((Y,j)=>Y.start-j.start);$.push({start:J[0].start,size:J[0].data.byteLength});for(let Y=1;Y<J.length;Y++){let j=$[$.length-1],X=J[Y];if(X.start<=j.start+j.size)j.size=Math.max(j.size,X.start+X.data.byteLength-j.start);else $.push({start:X.start,size:X.data.byteLength})}for(let Y of $){Y.data=new Uint8Array(Y.size);for(let j of this.sections)if(Y.start<=j.start&&j.start<Y.start+Y.size)Y.data.set(j.data,j.start-Y.start);if(this.writer.desiredSize!==null&&this.writer.desiredSize<=0)await this.writer.ready;if(this.chunked)this.writeDataIntoChunks(Y.data,Y.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&Y.start!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:Y.data,position:Y.start}),this.lastFlushEnd=Y.start+Y.data.byteLength}}this.sections.length=0}writeDataIntoChunks($,J){let Y=this.chunks.findIndex((K)=>K.start<=J&&J<K.start+this.chunkSize);if(Y===-1)Y=this.createChunk(J);let j=this.chunks[Y],X=J-j.start,Z=$.subarray(0,Math.min(this.chunkSize-X,$.byteLength));j.data.set(Z,X);let G={start:X,end:X+Z.byteLength};if(this.insertSectionIntoChunk(j,G),j.written[0].start===0&&j.written[0].end===this.chunkSize)j.shouldFlush=!0;if(this.chunks.length>Uj){for(let K=0;K<this.chunks.length-1;K++)this.chunks[K].shouldFlush=!0;this.tryToFlushChunks()}if(Z.byteLength<$.byteLength)this.writeDataIntoChunks($.subarray(Z.byteLength),J+Z.byteLength)}insertSectionIntoChunk($,J){let Y=0,j=$.written.length-1,X=-1;while(Y<=j){let Z=Math.floor(Y+(j-Y+1)/2);if($.written[Z].start<=J.start)Y=Z+1,X=Z;else j=Z-1}if($.written.splice(X+1,0,J),X===-1||$.written[X].end<J.start)X++;while(X<$.written.length-1&&$.written[X].end>=$.written[X+1].start)$.written[X].end=Math.max($.written[X].end,$.written[X+1].end),$.written.splice(X+1,1)}createChunk($){let Y={start:Math.floor($/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(Y),this.chunks.sort((j,X)=>j.start-X.start),this.chunks.indexOf(Y)}tryToFlushChunks($=!1){H(this.writer);for(let J=0;J<this.chunks.length;J++){let Y=this.chunks[J];if(!Y.shouldFlush&&!$)continue;for(let j of Y.written){let X=Y.start+j.start;if(this.ensureMonotonicity&&X!==this.lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:Y.data.subarray(j.start,j.end),position:X}),this.lastFlushEnd=Y.start+j.end}this.chunks.splice(J--,1)}}finalize(){if(this.chunked)this.tryToFlushChunks(!0);return H(this.writer),this.writer.close()}async close(){return this.writer?.close()}}class d$ extends w2{target;pos=0;constructor($){super();this.target=$}write($){this.maybeTrackWrites($),this.target.onwrite?.(this.pos,this.pos+$.byteLength),this.pos+=$.byteLength}getPos(){return this.pos}seek($){this.pos=$}async flush(){}async finalize(){}async close(){}}import Wj from"node:fs/promises";/*!
402
+ * Copyright (c) 2025-present, Vanilagy and contributors
403
+ *
404
+ * This Source Code Form is subject to the terms of the Mozilla Public
405
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
406
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
407
+ */class P1{_output=null;onwrite=null}class O2 extends P1{buffer=null;_createWriter(){return new a8(this)}}class c$ extends P1{_writable;_options;constructor($,J={}){super();if(!($ instanceof WritableStream))throw TypeError("StreamTarget requires a WritableStream instance.");if(J!=null&&typeof J!=="object")throw TypeError("StreamTarget options, when provided, must be an object.");if(J.chunked!==void 0&&typeof J.chunked!=="boolean")throw TypeError("options.chunked, when provided, must be a boolean.");if(J.chunkSize!==void 0&&(!Number.isInteger(J.chunkSize)||J.chunkSize<1024))throw TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=$,this._options=J}_createWriter(){return new m$(this)}}class wY extends P1{_streamTarget;_fileHandle=null;constructor($,J={}){if(typeof $!=="string")throw TypeError("filePath must be a string.");if(!J||typeof J!=="object")throw TypeError("options must be an object.");super();let Y=new WritableStream({start:async()=>{this._fileHandle=await Wj.open($,"w"),H(this._fileHandle)},write:async(j)=>{H(this._fileHandle),await this._fileHandle.write(j.data,0,j.data.byteLength,j.position)},close:async()=>{if(this._fileHandle)await this._fileHandle.close(),this._fileHandle=null}});this._streamTarget=new c$(Y,{chunked:!0,...J}),this._streamTarget._output=this._output}_createWriter(){return this._streamTarget._createWriter()}}class P2 extends P1{_createWriter(){return new d$(this)}}x0();/*!
408
+ * Copyright (c) 2025-present, Vanilagy and contributors
409
+ *
410
+ * This Source Code Form is subject to the terms of the Mozilla Public
411
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
412
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
413
+ */class D2{writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);offsets=new WeakMap;constructor($){this.writer=$}writeU32($){this.helperView.setUint32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeU64($){this.helperView.setUint32(0,Math.floor($/4294967296),!1),this.helperView.setUint32(4,$,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii($){for(let J=0;J<$.length;J++)if(this.helperView.setUint8(J%8,$.charCodeAt(J)),J%8===7)this.writer.write(this.helper);if($.length%8!==0)this.writer.write(this.helper.subarray(0,$.length%8))}writeBox($){if(this.offsets.set($,this.writer.getPos()),$.contents&&!$.children)this.writeBoxHeader($,$.size??$.contents.byteLength+8),this.writer.write($.contents);else{let J=this.writer.getPos();if(this.writeBoxHeader($,0),$.contents)this.writer.write($.contents);if($.children){for(let X of $.children)if(X)this.writeBox(X)}let Y=this.writer.getPos(),j=$.size??Y-J;this.writer.seek(J),this.writeBoxHeader($,j),this.writer.seek(Y)}}writeBoxHeader($,J){if(this.writeU32($.largeSize?1:J),this.writeAscii($.type),$.largeSize)this.writeU64(J)}measureBoxHeader($){return 8+($.largeSize?8:0)}patchBox($){let J=this.offsets.get($);H(J!==void 0);let Y=this.writer.getPos();this.writer.seek(J),this.writeBox($),this.writer.seek(Y)}measureBox($){if($.contents&&!$.children)return this.measureBoxHeader($)+$.contents.byteLength;let J=this.measureBoxHeader($);if($.contents)J+=$.contents.byteLength;if($.children){for(let Y of $.children)if(Y)J+=this.measureBox(Y)}return J}}var p=new Uint8Array(8),t0=new DataView(p.buffer),e=($)=>{return[($%256+256)%256]},b=($)=>{return t0.setUint16(0,$,!1),[p[0],p[1]]},CY=($)=>{return t0.setInt16(0,$,!1),[p[0],p[1]]},DY=($)=>{return t0.setUint32(0,$,!1),[p[1],p[2],p[3]]},O=($)=>{return t0.setUint32(0,$,!1),[p[0],p[1],p[2],p[3]]},D1=($)=>{return t0.setInt32(0,$,!1),[p[0],p[1],p[2],p[3]]},n1=($)=>{return t0.setUint32(0,Math.floor($/4294967296),!1),t0.setUint32(4,$,!1),[p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]]},EY=($)=>{return t0.setInt16(0,256*$,!1),[p[0],p[1]]},V1=($)=>{return t0.setInt32(0,65536*$,!1),[p[0],p[1],p[2],p[3]]},n$=($)=>{return t0.setInt32(0,1073741824*$,!1),[p[0],p[1],p[2],p[3]]},o$=($,J)=>{let Y=[],j=$;do{let X=j&127;if(j>>=7,Y.length>0)X|=128;if(Y.push(X),J!==void 0)J--}while(j>0||J);return Y.reverse()},R0=($,J=!1)=>{let Y=Array($.length).fill(null).map((j,X)=>$.charCodeAt(X));if(J)Y.push(0);return Y},i$=($)=>{let J=null;for(let Y of $)if(!J||Y.timestamp>J.timestamp)J=Y;return J},TY=($)=>{let J=$*(Math.PI/180),Y=Math.round(Math.cos(J)),j=Math.round(Math.sin(J));return[Y,j,0,-j,Y,0,0,0,1]},yY=TY(0),vY=($)=>{return[V1($[0]),V1($[1]),n$($[2]),V1($[3]),V1($[4]),n$($[5]),V1($[6]),V1($[7]),n$($[8])]},x=($,J,Y)=>({type:$,contents:J&&new Uint8Array(J.flat(10)),children:Y}),d=($,J,Y,j,X)=>x($,[e(J),DY(Y),j??[]],X),bY=($)=>{if($.isQuickTime)return x("ftyp",[R0("qt "),O(512),R0("qt ")]);if($.fragmented)return x("ftyp",[R0("iso5"),O(512),R0("iso5"),R0("iso6"),R0("mp41")]);return x("ftyp",[R0("isom"),O(512),R0("isom"),$.holdsAvc?R0("avc1"):[],R0("mp41")])},t8=($)=>({type:"mdat",largeSize:$}),xY=($)=>({type:"free",size:$}),_8=($)=>x("moov",void 0,[Vj($.creationTime,$.trackDatas),...$.trackDatas.map((J)=>Hj(J,$.creationTime)),$.isFragmented?rj($.trackDatas):null,jX($)]),Vj=($,J)=>{let Y=Q0(Math.max(0,...J.filter((G)=>G.samples.length>0).map((G)=>{let K=i$(G.samples);return K.timestamp+K.duration})),C2),j=Math.max(0,...J.map((G)=>G.track.id))+1,X=!E1($)||!E1(Y),Z=X?n1:O;return d("mvhd",+X,0,[Z($),Z($),O(C2),Z(Y),V1(1),EY(1),Array(10).fill(0),vY(yY),Array(24).fill(0),O(j)])},Hj=($,J)=>{let Y=lY($);return x("trak",void 0,[Nj($,J),Aj($,J),Y.name!==void 0?x("udta",void 0,[x("name",[...m.encode(Y.name)])]):null])},Nj=($,J)=>{let Y=i$($.samples),j=Q0(Y?Y.timestamp+Y.duration:0,C2),X=!E1(J)||!E1(j),Z=X?n1:O,G;if($.type==="video"){let Q=$.track.metadata.rotation;G=TY(Q??0)}else G=yY;let K=2;if($.track.metadata.disposition?.default!==!1)K|=1;return d("tkhd",+X,K,[Z(J),Z(J),O($.track.id),O(0),Z(j),Array(8).fill(0),b(0),b($.track.id),EY($.type==="audio"?1:0),b(0),vY(G),V1($.type==="video"?$.info.width:0),V1($.type==="video"?$.info.height:0)])},Aj=($,J)=>x("mdia",void 0,[Rj($,J),s$(!0,zj[$.type],_j[$.type]),Lj($)]),Rj=($,J)=>{let Y=i$($.samples),j=Q0(Y?Y.timestamp+Y.duration:0,$.timescale),X=!E1(J)||!E1(j),Z=X?n1:O;return d("mdhd",+X,0,[Z(J),Z(J),O($.timescale),Z(j),b(pY($.track.metadata.languageCode??a)),b(0)])},zj={video:"vide",audio:"soun",subtitle:"text"},_j={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},s$=($,J,Y,j="\x00\x00\x00\x00")=>d("hdlr",0,0,[$?R0("mhlr"):O(0),R0(J),R0(j),O(0),O(0),R0(Y,!0)]),Lj=($)=>x("minf",void 0,[wj[$.type](),Oj(),Dj($)]),Mj=()=>d("vmhd",0,1,[b(0),b(0),b(0),b(0)]),Fj=()=>d("smhd",0,0,[b(0),b(0)]),Bj=()=>d("nmhd",0,0),wj={video:Mj,audio:Fj,subtitle:Bj},Oj=()=>x("dinf",void 0,[Pj()]),Pj=()=>d("dref",0,0,[O(1)],[Cj()]),Cj=()=>d("url ",0,1),Dj=($)=>{let J=$.compositionTimeOffsetTable.length>1||$.compositionTimeOffsetTable.some((Y)=>Y.sampleCompositionTimeOffset!==0);return x("stbl",void 0,[Ej($),pj($),J?nj($):null,J?oj($):null,mj($),dj($),cj($),lj($)])},Ej=($)=>{let J;if($.type==="video")J=Tj(KX($.track.source._codec,$.info.decoderConfig.codec),$);else if($.type==="audio"){let Y=uY($.track.source._codec,$.muxer.isQuickTime);H(Y),J=Ij(Y,$)}else if($.type==="subtitle"){let Y=UX[$.track.source._codec];if(!Y)throw Error(`Subtitle codec '${$.track.source._codec}' is not supported in MP4/MOV. Only WebVTT is supported.`);J=kj(Y,$)}return H(J),d("stsd",0,0,[O(1)],[J])},Tj=($,J)=>x($,[Array(6).fill(0),b(1),b(0),b(0),Array(12).fill(0),b(J.info.width),b(J.info.height),O(4718592),O(4718592),O(0),b(1),Array(32).fill(0),b(24),CY(65535)],[QX[J.track.source._codec](J),K6(J.info.decoderConfig.colorSpace)?yj(J):null]),yj=($)=>x("colr",[R0("nclx"),b(e0[$.info.decoderConfig.colorSpace.primaries]),b($1[$.info.decoderConfig.colorSpace.transfer]),b(J1[$.info.decoderConfig.colorSpace.matrix]),e(($.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),vj=($)=>$.info.decoderConfig&&x("avcC",[...l($.info.decoderConfig.description)]),bj=($)=>$.info.decoderConfig&&x("hvcC",[...l($.info.decoderConfig.description)]),OY=($)=>{if(!$.info.decoderConfig)return null;let J=$.info.decoderConfig,Y=J.codec.split("."),j=Number(Y[1]),X=Number(Y[2]),Z=Number(Y[3]),G=Y[4]?Number(Y[4]):1,K=Y[8]?Number(Y[8]):Number(J.colorSpace?.fullRange??0),Q=(Z<<4)+(G<<1)+K,q=Y[5]?Number(Y[5]):J.colorSpace?.primaries?e0[J.colorSpace.primaries]:2,U=Y[6]?Number(Y[6]):J.colorSpace?.transfer?$1[J.colorSpace.transfer]:2,W=Y[7]?Number(Y[7]):J.colorSpace?.matrix?J1[J.colorSpace.matrix]:2;return d("vpcC",1,0,[e(j),e(X),e(Q),e(q),e(U),e(W),b(0)])},xj=($)=>{return x("av1C",W6($.info.decoderConfig.codec))},Ij=($,J)=>{let Y=0,j,X=16;if(o.includes(J.track.source._codec)){let Z=J.track.source._codec,{sampleSize:G}=U0(Z);if(X=8*G,X>16)Y=1}if(Y===0)j=[Array(6).fill(0),b(1),b(Y),b(0),O(0),b(J.info.numberOfChannels),b(X),b(0),b(0),b(J.info.sampleRate<65536?J.info.sampleRate:0),b(0)];else j=[Array(6).fill(0),b(1),b(Y),b(0),O(0),b(J.info.numberOfChannels),b(Math.min(X,16)),b(0),b(0),b(J.info.sampleRate<65536?J.info.sampleRate:0),b(0),O(1),O(X/8),O(J.info.numberOfChannels*X/8),O(2)];return x($,j,[qX(J.track.source._codec,J.muxer.isQuickTime)?.(J)??null])},r$=($)=>{let J;switch($.track.source._codec){case"aac":J=64;break;case"mp3":J=107;break;case"vorbis":J=221;break;default:throw Error(`Unhandled audio codec: ${$.track.source._codec}`)}let Y=[...e(J),...e(21),...DY(0),...O(0),...O(0)];if($.info.decoderConfig.description){let j=l($.info.decoderConfig.description);Y=[...Y,...e(5),...o$(j.byteLength),...j]}return Y=[...b(1),...e(0),...e(4),...o$(Y.length),...Y,...e(6),...e(1),...e(2)],Y=[...e(3),...o$(Y.length),...Y],d("esds",0,0,Y)},C1=($)=>{return x("wave",void 0,[Sj($),hj($),x("\x00\x00\x00\x00")])},Sj=($)=>{return x("frma",[R0(uY($.track.source._codec,$.muxer.isQuickTime))])},hj=($)=>{let{littleEndian:J}=U0($.track.source._codec);return x("enda",[b(+J)])},fj=($)=>{let J=$.info.numberOfChannels,Y=3840,j=$.info.sampleRate,X=0,Z=0,G=new Uint8Array(0),K=$.info.decoderConfig?.description;if(K){H(K.byteLength>=18);let Q=l(K),q=z1(Q);if(J=q.outputChannelCount,Y=q.preSkip,j=q.inputSampleRate,X=q.outputGain,Z=q.channelMappingFamily,q.channelMappingTable)G=q.channelMappingTable}return x("dOps",[e(0),e(J),b(Y),O(j),CY(X),e(Z),...G])},gj=($)=>{let J=$.info.decoderConfig?.description;H(J);let Y=l(J);return d("dfLa",0,0,[...Y.subarray(4)])},s0=($)=>{let{littleEndian:J,sampleSize:Y}=U0($.track.source._codec),j=+J;return d("pcmC",0,0,[e(j),e(8*Y)])},kj=($,J)=>{let Y=WX[J.track.source._codec];if(!Y)throw Error(`Subtitle codec '${J.track.source._codec}' is not supported in MP4/MOV. Only WebVTT is supported.`);return x($,[Array(6).fill(0),b(1)],[Y(J)])},uj=($)=>x("vttC",[...m.encode($.info.config.description)]);var pj=($)=>{return d("stts",0,0,[O($.timeToSampleTable.length),$.timeToSampleTable.map((J)=>[O(J.sampleCount),O(J.sampleDelta)])])},lj=($)=>{if($.samples.every((Y)=>Y.type==="key"))return null;let J=[...$.samples.entries()].filter(([,Y])=>Y.type==="key");return d("stss",0,0,[O(J.length),J.map(([Y])=>O(Y+1))])},mj=($)=>{return d("stsc",0,0,[O($.compactlyCodedChunkTable.length),$.compactlyCodedChunkTable.map((J)=>[O(J.firstChunk),O(J.samplesPerChunk),O(1)])])},dj=($)=>{if($.type==="audio"&&$.info.requiresPcmTransformation){let{sampleSize:J}=U0($.track.source._codec);return d("stsz",0,0,[O(J*$.info.numberOfChannels),O($.samples.reduce((Y,j)=>Y+Q0(j.duration,$.timescale),0))])}return d("stsz",0,0,[O(0),O($.samples.length),$.samples.map((J)=>O(J.size))])},cj=($)=>{if($.finalizedChunks.length>0&&n($.finalizedChunks).offset>=4294967296)return d("co64",0,0,[O($.finalizedChunks.length),$.finalizedChunks.map((J)=>n1(J.offset))]);return d("stco",0,0,[O($.finalizedChunks.length),$.finalizedChunks.map((J)=>O(J.offset))])},nj=($)=>{return d("ctts",1,0,[O($.compositionTimeOffsetTable.length),$.compositionTimeOffsetTable.map((J)=>[O(J.sampleCount),D1(J.sampleCompositionTimeOffset)])])},oj=($)=>{let{POSITIVE_INFINITY:J,NEGATIVE_INFINITY:Y,POSITIVE_INFINITY:j,NEGATIVE_INFINITY:X}=Number;H($.compositionTimeOffsetTable.length>0),H($.samples.length>0);for(let G=0;G<$.compositionTimeOffsetTable.length;G++){let K=$.compositionTimeOffsetTable[G];J=Math.min(J,K.sampleCompositionTimeOffset),Y=Math.max(Y,K.sampleCompositionTimeOffset)}for(let G=0;G<$.samples.length;G++){let K=$.samples[G];j=Math.min(j,Q0(K.timestamp,$.timescale)),X=Math.max(X,Q0(K.timestamp+K.duration,$.timescale))}let Z=Math.max(-J,0);if(X>=2147483648)return null;return d("cslg",0,0,[D1(Z),D1(J),D1(Y),D1(j),D1(X)])},rj=($)=>{return x("mvex",void 0,$.map(ij))},ij=($)=>{return d("trex",0,0,[O($.track.id),O(1),O(0),O(0),O(0)])},a$=($,J)=>{return x("moof",void 0,[sj($),...J.map(aj)])},sj=($)=>{return d("mfhd",0,0,[O($)])},IY=($)=>{let J=0,Y=0,j=0,X=0,Z=$.type==="delta";if(Y|=+Z,Z)J|=1;else J|=2;return J<<24|Y<<16|j<<8|X},aj=($)=>{return x("traf",void 0,[tj($),ej($),$X($)])},tj=($)=>{H($.currentChunk);let J=0;J|=8,J|=16,J|=32,J|=131072;let Y=$.currentChunk.samples[1]??$.currentChunk.samples[0],j={duration:Y.timescaleUnitsToNextSample,size:Y.size,flags:IY(Y)};return d("tfhd",0,J,[O($.track.id),O(j.duration),O(j.size),O(j.flags)])},ej=($)=>{return H($.currentChunk),d("tfdt",1,0,[n1(Q0($.currentChunk.startTimestamp,$.timescale))])},$X=($)=>{H($.currentChunk);let J=$.currentChunk.samples.map((R)=>R.timescaleUnitsToNextSample),Y=$.currentChunk.samples.map((R)=>R.size),j=$.currentChunk.samples.map(IY),X=$.currentChunk.samples.map((R)=>Q0(R.timestamp-R.decodeTimestamp,$.timescale)),Z=new Set(J),G=new Set(Y),K=new Set(j),Q=new Set(X),q=K.size===2&&j[0]!==j[1],U=Z.size>1,W=G.size>1,V=!q&&K.size>1,N=Q.size>1||[...Q].some((R)=>R!==0),A=0;return A|=1,A|=4*+q,A|=256*+U,A|=512*+W,A|=1024*+V,A|=2048*+N,d("trun",1,A,[O($.currentChunk.samples.length),O($.currentChunk.offset-$.currentChunk.moofOffset||0),q?O(j[0]):[],$.currentChunk.samples.map((R,z)=>[U?O(J[z]):[],W?O(Y[z]):[],V?O(j[z]):[],N?D1(X[z]):[]])])},SY=($)=>{return x("mfra",void 0,[...$.map(JX),YX()])},JX=($,J)=>{return d("tfra",1,0,[O($.track.id),O(63),O($.finalizedChunks.length),$.finalizedChunks.map((j)=>[n1(Q0(j.samples[0].timestamp,$.timescale)),n1(j.moofOffset),O(J+1),O(1),O(1)])])},YX=()=>{return d("mfro",0,0,[O(0)])},hY=()=>x("vtte"),fY=($,J,Y,j,X)=>x("vttc",void 0,[X!==null?x("vsid",[D1(X)]):null,Y!==null?x("iden",[...m.encode(Y)]):null,J!==null?x("ctim",[...m.encode(k1(J))]):null,j!==null?x("sttg",[...m.encode(j)]):null,x("payl",[...m.encode($)])]),gY=($)=>x("vtta",[...m.encode($)]),jX=($)=>{let J=[],Y=$.format._options.metadataFormat??"auto",j=$.output._metadataTags;if(Y==="mdir"||Y==="auto"&&!$.isQuickTime){let X=ZX(j);if(X)J.push(X)}else if(Y==="mdta"){let X=GX(j);if(X)J.push(X)}else if(Y==="udta"||Y==="auto"&&$.isQuickTime)XX(J,$.output._metadataTags);if(J.length===0)return null;return x("udta",void 0,J)},XX=($,J)=>{for(let{key:Y,value:j}of v0(J))switch(Y){case"title":$.push(a0("©nam",j));break;case"description":$.push(a0("©des",j));break;case"artist":$.push(a0("©ART",j));break;case"album":$.push(a0("©alb",j));break;case"albumArtist":$.push(a0("albr",j));break;case"genre":$.push(a0("©gen",j));break;case"date":$.push(a0("©day",j.toISOString().slice(0,10)));break;case"comment":$.push(a0("©cmt",j));break;case"lyrics":$.push(a0("©lyr",j));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:i(Y)}if(J.raw)for(let Y in J.raw){let j=J.raw[Y];if(j==null||Y.length!==4||$.some((X)=>X.type===Y))continue;if(typeof j==="string")$.push(a0(Y,j));else if(j instanceof Uint8Array)$.push(x(Y,Array.from(j)))}},a0=($,J)=>{let Y=m.encode(J);return x($,[b(Y.length),b(pY("und")),Array.from(Y)])},PY={"image/jpeg":13,"image/png":14,"image/bmp":27},kY=($,J)=>{let Y=[];for(let{key:j,value:X}of v0($))switch(j){case"title":Y.push({key:J?"title":"©nam",value:l0(X)});break;case"description":Y.push({key:J?"description":"©des",value:l0(X)});break;case"artist":Y.push({key:J?"artist":"©ART",value:l0(X)});break;case"album":Y.push({key:J?"album":"©alb",value:l0(X)});break;case"albumArtist":Y.push({key:J?"album_artist":"aART",value:l0(X)});break;case"comment":Y.push({key:J?"comment":"©cmt",value:l0(X)});break;case"genre":Y.push({key:J?"genre":"©gen",value:l0(X)});break;case"lyrics":Y.push({key:J?"lyrics":"©lyr",value:l0(X)});break;case"date":Y.push({key:J?"date":"©day",value:l0(X.toISOString().slice(0,10))});break;case"images":for(let Z of X){if(Z.kind!=="coverFront")continue;Y.push({key:"covr",value:x("data",[O(PY[Z.mimeType]??0),O(0),Array.from(Z.data)])})}break;case"trackNumber":if(J){let Z=$.tracksTotal!==void 0?`${X}/${$.tracksTotal}`:X.toString();Y.push({key:"track",value:l0(Z)})}else Y.push({key:"trkn",value:x("data",[O(0),O(0),b(0),b(X),b($.tracksTotal??0),b(0)])});break;case"discNumber":if(!J)Y.push({key:"disc",value:x("data",[O(0),O(0),b(0),b(X),b($.discsTotal??0),b(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:i(j)}if($.raw)for(let j in $.raw){let X=$.raw[j];if(X==null||!J&&j.length!==4||Y.some((Z)=>Z.key===j))continue;if(typeof X==="string")Y.push({key:j,value:l0(X)});else if(X instanceof Uint8Array)Y.push({key:j,value:x("data",[O(0),O(0),Array.from(X)])});else if(X instanceof I0)Y.push({key:j,value:x("data",[O(PY[X.mimeType]??0),O(0),Array.from(X.data)])})}return Y},ZX=($)=>{let J=kY($,!1);if(J.length===0)return null;return d("meta",0,0,void 0,[s$(!1,"mdir","","appl"),x("ilst",void 0,J.map((Y)=>x(Y.key,void 0,[Y.value])))])},GX=($)=>{let J=kY($,!0);if(J.length===0)return null;return x("meta",void 0,[s$(!1,"mdta",""),d("keys",0,0,[O(J.length)],J.map((Y)=>x("mdta",[...m.encode(Y.key)]))),x("ilst",void 0,J.map((Y,j)=>{let X=String.fromCharCode(...O(j+1));return x(X,void 0,[Y.value])}))])},l0=($)=>{return x("data",[O(1),O(0),...m.encode($)])},KX=($,J)=>{switch($){case"avc":return J.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";default:throw Error(`Invalid codec name ${$}`)}};var QX={avc:vj,hevc:bj,vp8:OY,vp9:OY,av1:xj,mpeg4:()=>null},uY=($,J)=>{switch($){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"eac3":return"ec-3"}if(J)switch($){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"}switch($){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"}throw Error(`Unsupported audio codec: ${$}`)},qX=($,J)=>{switch($){case"aac":return r$;case"mp3":return r$;case"opus":return fj;case"vorbis":return r$;case"flac":return gj}if(J)switch($){case"pcm-s24":return C1;case"pcm-s24be":return C1;case"pcm-s32":return C1;case"pcm-s32be":return C1;case"pcm-f32":return C1;case"pcm-f32be":return C1;case"pcm-f64":return C1;case"pcm-f64be":return C1}switch($){case"pcm-s16":return s0;case"pcm-s16be":return s0;case"pcm-s24":return s0;case"pcm-s24be":return s0;case"pcm-s32":return s0;case"pcm-s32be":return s0;case"pcm-f32":return s0;case"pcm-f32be":return s0;case"pcm-f64":return s0;case"pcm-f64be":return s0}return null},UX={webvtt:"wvtt",tx3g:"tx3g",ttml:"stpp"},WX={webvtt:uj,tx3g:()=>null,ttml:()=>null},pY=($)=>{H($.length===3);let J=0;for(let Y=0;Y<3;Y++)J<<=5,J+=$.charCodeAt(Y)-96;return J};/*!
414
+ * Copyright (c) 2025-present, Vanilagy and contributors
415
+ *
416
+ * This Source Code Form is subject to the terms of the Mozilla Public
417
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
418
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
419
+ */var C2=1000,VX=2082844800,lY=($)=>{let J={},Y=$.track;if(Y.metadata.name!==void 0)J.name=Y.metadata.name;return J},Q0=($,J,Y=!0)=>{let j=$*J;return Y?Math.round(j):j};class t$ extends V0{format;writer;boxWriter;fastStart;isFragmented;isQuickTime;auxTarget=new O2;auxWriter=this.auxTarget._createWriter();auxBoxWriter=new D2(this.auxWriter);mdat=null;ftypSize=null;trackDatas=[];allTracksKnown=c();creationTime=Math.floor(Date.now()/1000)+VX;finalizedChunks=[];nextFragmentNumber=1;maxWrittenTimestamp=Number.NEGATIVE_INFINITY;minimumFragmentDuration;constructor($,J){super($);this.format=J,this.writer=$._writer,this.boxWriter=new D2(this.writer),this.isQuickTime=J instanceof e8;let Y=this.writer instanceof a8?"in-memory":!1;if(this.fastStart=J._options.fastStart??Y,this.isFragmented=this.fastStart==="fragmented",this.fastStart==="in-memory"||this.isFragmented)this.writer.ensureMonotonicity=!0;this.minimumFragmentDuration=J._options.minimumFragmentDuration??1}async start(){let $=await this.mutex.acquire(),J=this.output._tracks.some((Y)=>Y.type==="video"&&Y.source._codec==="avc");if(this.format._options.onFtyp)this.writer.startTrackingWrites();if(this.boxWriter.writeBox(bY({isQuickTime:this.isQuickTime,holdsAvc:J,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:Y,start:j}=this.writer.stopTrackingWrites();this.format._options.onFtyp(Y,j)}if(this.ftypSize=this.writer.getPos(),this.fastStart==="in-memory");else if(this.fastStart==="reserve"){for(let Y of this.output._tracks)if(Y.metadata.maximumPacketCount===void 0)throw Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else if(this.isFragmented);else{if(this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat=t8(!0),this.boxWriter.writeBox(this.mdat)}await this.writer.flush(),$()}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let $=this.trackDatas.map((J)=>{if(J.type==="video")return J.info.decoderConfig.codec;if(J.type==="audio")return J.info.decoderConfig.codec;return{webvtt:"wvtt",tx3g:"tx3g",ttml:"stpp",srt:"wvtt",ass:"wvtt",ssa:"wvtt"}[J.track.source._codec]});return $2({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some((J)=>J.type==="video"),hasAudio:this.trackDatas.some((J)=>J.type==="audio"),codecStrings:$})}getVideoTrackData($,J,Y){let j=this.trackDatas.find((Q)=>Q.track===$);if(j)return j;t1(Y),H(Y),H(Y.decoderConfig);let X={...Y.decoderConfig};H(X.codedWidth!==void 0),H(X.codedHeight!==void 0);let Z=!1;if($.source._codec==="avc"&&!X.description){let Q=v6(J.data);if(!Q)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.");X.description=nJ(Q),Z=!0}else if($.source._codec==="hevc"&&!X.description){let Q=b6(J.data);if(!Q)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.");X.description=rJ(Q),Z=!0}let G=_J(1/($.metadata.frameRate??57600),1e6).denominator,K={muxer:this,track:$,type:"video",info:{width:X.codedWidth,height:X.codedHeight,decoderConfig:X,requiresAnnexBTransformation:Z},timescale:G,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};if(this.trackDatas.push(K),this.trackDatas.sort((Q,q)=>Q.track.id-q.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return K}getAudioTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;_0(J),H(J),H(J.decoderConfig);let j={muxer:this,track:$,type:"audio",info:{numberOfChannels:J.decoderConfig.numberOfChannels,sampleRate:J.decoderConfig.sampleRate,decoderConfig:J.decoderConfig,requiresPcmTransformation:!this.isFragmented&&o.includes($.source._codec)},timescale:J.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}getSubtitleTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;A6(J),H(J),H(J.config);let j={muxer:this,track:$,type:"subtitle",info:{config:J.config},timescale:1000,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}async addEncodedVideoPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getVideoTrackData($,J,Y),Z=J.data;if(X.info.requiresAnnexBTransformation){let Q=dJ(Z);if(!Q)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.");Z=Q}let G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key"),K=this.createSampleForTrack(X,Z,G,J.duration,J.type);await this.registerSample(X,K)}finally{j()}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getAudioTrackData($,Y),Z=this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key"),G=this.createSampleForTrack(X,J.data,Z,J.duration,J.type);if(X.info.requiresPcmTransformation)await this.maybePadWithSilence(X,Z);await this.registerSample(X,G)}finally{j()}}async maybePadWithSilence($,J){let Y=n($.samples),j=Y?Y.timestamp+Y.duration:0,X=J-j,Z=Q0(X,$.timescale);if(Z>0){let{sampleSize:G,silentValue:K}=U0($.info.decoderConfig.codec),Q=Z*$.info.numberOfChannels,q=new Uint8Array(G*Q).fill(K),U=this.createSampleForTrack($,new Uint8Array(q.buffer),j,X,"key");await this.registerSample($,U)}}async addSubtitleCue($,J,Y){let j=await this.mutex.acquire();try{let X=this.getSubtitleTrackData($,Y);if(this.validateAndNormalizeTimestamp(X.track,J.timestamp,!0),$.source._codec==="webvtt")X.cueQueue.push(J),await this.processWebVTTCues(X,J.timestamp);else throw Error(`${$.source._codec} subtitles are not supported in ${this.format._name}. Only WebVTT is supported.`)}finally{j()}}async processWebVTTCues($,J){while($.cueQueue.length>0){let Y=new Set([]);for(let Q of $.cueQueue)H(Q.timestamp<=J),H($.lastCueEndTimestamp<=Q.timestamp+Q.duration),Y.add(Math.max(Q.timestamp,$.lastCueEndTimestamp)),Y.add(Q.timestamp+Q.duration);let j=[...Y].sort((Q,q)=>Q-q),X=j[0],Z=j[1]??X;if(J<Z)break;if($.lastCueEndTimestamp<X){this.auxWriter.seek(0);let Q=hY();this.auxBoxWriter.writeBox(Q);let q=this.auxWriter.getSlice(0,this.auxWriter.getPos()),U=this.createSampleForTrack($,q,$.lastCueEndTimestamp,X-$.lastCueEndTimestamp,"key");await this.registerSample($,U),$.lastCueEndTimestamp=X}this.auxWriter.seek(0);for(let Q=0;Q<$.cueQueue.length;Q++){let q=$.cueQueue[Q];if(q.timestamp>=Z)break;u1.lastIndex=0;let U=u1.test(q.text),W=q.timestamp+q.duration,V=$.cueToSourceId.get(q);if(V===void 0&&Z<W)V=$.nextSourceId++,$.cueToSourceId.set(q,V);if(q.notes){let A=gY(q.notes);this.auxBoxWriter.writeBox(A)}let N=fY(q.text,U?X:null,q.identifier??null,q.settings??null,V??null);if(this.auxBoxWriter.writeBox(N),W===Z)$.cueQueue.splice(Q--,1)}let G=this.auxWriter.getSlice(0,this.auxWriter.getPos()),K=this.createSampleForTrack($,G,X,Z-X,"key");await this.registerSample($,K),$.lastCueEndTimestamp=Z}}createSampleForTrack($,J,Y,j,X){return{timestamp:Y,decodeTimestamp:Y,duration:j,data:J,size:J.byteLength,type:X,timescaleUnitsToNextSample:Q0(j,$.timescale)}}processTimestamps($,J){if($.timestampProcessingQueue.length===0)return;if($.type==="audio"&&$.info.requiresPcmTransformation){let j=0;for(let X=0;X<$.timestampProcessingQueue.length;X++){let Z=$.timestampProcessingQueue[X],G=Q0(Z.duration,$.timescale);j+=G}if($.timeToSampleTable.length===0)$.timeToSampleTable.push({sampleCount:j,sampleDelta:1});else{let X=n($.timeToSampleTable);X.sampleCount+=j}$.timestampProcessingQueue.length=0;return}let Y=$.timestampProcessingQueue.map((j)=>j.timestamp).sort((j,X)=>j-X);for(let j=0;j<$.timestampProcessingQueue.length;j++){let X=$.timestampProcessingQueue[j];if(X.decodeTimestamp=Y[j],!this.isFragmented&&$.lastTimescaleUnits===null)X.decodeTimestamp=0;let Z=Q0(X.timestamp-X.decodeTimestamp,$.timescale),G=Q0(X.duration,$.timescale);if($.lastTimescaleUnits!==null){H($.lastSample);let K=Q0(X.decodeTimestamp,$.timescale,!1),Q=Math.round(K-$.lastTimescaleUnits);if(H(Q>=0),$.lastTimescaleUnits+=Q,$.lastSample.timescaleUnitsToNextSample=Q,!this.isFragmented){let q=n($.timeToSampleTable);if(H(q),q.sampleCount===1){q.sampleDelta=Q;let W=$.timeToSampleTable[$.timeToSampleTable.length-2];if(W&&W.sampleDelta===Q)W.sampleCount++,$.timeToSampleTable.pop(),q=W}else if(q.sampleDelta!==Q)q.sampleCount--,$.timeToSampleTable.push(q={sampleCount:1,sampleDelta:Q});if(q.sampleDelta===G)q.sampleCount++;else $.timeToSampleTable.push({sampleCount:1,sampleDelta:G});let U=n($.compositionTimeOffsetTable);if(H(U),U.sampleCompositionTimeOffset===Z)U.sampleCount++;else $.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:Z})}}else if($.lastTimescaleUnits=Q0(X.decodeTimestamp,$.timescale,!1),!this.isFragmented)$.timeToSampleTable.push({sampleCount:1,sampleDelta:G}),$.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:Z});$.lastSample=X}if($.timestampProcessingQueue.length=0,H($.lastSample),H($.lastTimescaleUnits!==null),J!==void 0&&$.lastSample.timescaleUnitsToNextSample===0){H(J.type==="key");let j=Q0(J.timestamp,$.timescale,!1),X=Math.round(j-$.lastTimescaleUnits);$.lastSample.timescaleUnitsToNextSample=X}}async registerSample($,J){if(J.type==="key")this.processTimestamps($,J);if($.timestampProcessingQueue.push(J),this.isFragmented)$.sampleQueue.push(J),await this.interleaveSamples();else if(this.fastStart==="reserve")await this.registerSampleFastStartReserve($,J);else await this.addSampleToTrack($,J)}async addSampleToTrack($,J){if(!this.isFragmented){if($.samples.push(J),this.fastStart==="reserve"){let j=$.track.metadata.maximumPacketCount;if(H(j!==void 0),$.samples.length>j)throw Error(`Track #${$.track.id} has already reached the maximum packet count (${j}). Either add less packets or increase the maximum packet count.`)}}let Y=!1;if(!$.currentChunk)Y=!0;else{$.currentChunk.startTimestamp=Math.min($.currentChunk.startTimestamp,J.timestamp);let j=J.timestamp-$.currentChunk.startTimestamp;if(this.isFragmented){let X=this.trackDatas.every((Z)=>{if($===Z)return J.type==="key";let G=Z.sampleQueue[0];if(G)return G.type==="key";return Z.track.source._closed});if(j>=this.minimumFragmentDuration&&X&&J.timestamp>this.maxWrittenTimestamp)Y=!0,await this.finalizeFragment()}else Y=j>=0.5}if(Y){if($.currentChunk)await this.finalizeCurrentChunk($);$.currentChunk={startTimestamp:J.timestamp,samples:[],offset:null,moofOffset:null}}if(H($.currentChunk),$.currentChunk.samples.push(J),this.isFragmented)this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,J.timestamp)}async finalizeCurrentChunk($){if(H(!this.isFragmented),!$.currentChunk)return;$.finalizedChunks.push($.currentChunk),this.finalizedChunks.push($.currentChunk);let J=$.currentChunk.samples.length;if($.type==="audio"&&$.info.requiresPcmTransformation)J=$.currentChunk.samples.reduce((Y,j)=>Y+Q0(j.duration,$.timescale),0);if($.compactlyCodedChunkTable.length===0||n($.compactlyCodedChunkTable).samplesPerChunk!==J)$.compactlyCodedChunkTable.push({firstChunk:$.finalizedChunks.length,samplesPerChunk:J});if(this.fastStart==="in-memory"){$.currentChunk.offset=0;return}$.currentChunk.offset=this.writer.getPos();for(let Y of $.currentChunk.samples)H(Y.data),this.writer.write(Y.data),Y.data=null;await this.writer.flush()}async interleaveSamples($=!1){if(H(this.isFragmented),!$&&!this.allTracksAreKnown())return;$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let X of this.trackDatas){if(!$&&X.sampleQueue.length===0&&!X.track.source._closed)break $;if(X.sampleQueue.length>0&&X.sampleQueue[0].timestamp<Y)J=X,Y=X.sampleQueue[0].timestamp}if(!J)break;let j=J.sampleQueue.shift();await this.addSampleToTrack(J,j)}}async finalizeFragment($=!0){H(this.isFragmented);let J=this.nextFragmentNumber++;if(J===1){if(this.format._options.onMoov)this.writer.startTrackingWrites();let V=_8(this);if(this.boxWriter.writeBox(V),this.format._options.onMoov){let{data:N,start:A}=this.writer.stopTrackingWrites();this.format._options.onMoov(N,A)}}let Y=this.trackDatas.filter((V)=>V.currentChunk),j=a$(J,Y),X=this.writer.getPos(),Z=X+this.boxWriter.measureBox(j),G=Z+f0,K=Number.POSITIVE_INFINITY;for(let V of Y){V.currentChunk.offset=G,V.currentChunk.moofOffset=X;for(let N of V.currentChunk.samples)G+=N.size;K=Math.min(K,V.currentChunk.startTimestamp)}let Q=G-Z,q=Q>=4294967296;if(q)for(let V of Y)V.currentChunk.offset+=U1-f0;if(this.format._options.onMoof)this.writer.startTrackingWrites();let U=a$(J,Y);if(this.boxWriter.writeBox(U),this.format._options.onMoof){let{data:V,start:N}=this.writer.stopTrackingWrites();this.format._options.onMoof(V,N,K)}if(H(this.writer.getPos()===Z),this.format._options.onMdat)this.writer.startTrackingWrites();let W=t8(q);W.size=Q,this.boxWriter.writeBox(W),this.writer.seek(Z+(q?U1:f0));for(let V of Y)for(let N of V.currentChunk.samples)this.writer.write(N.data),N.data=null;if(this.format._options.onMdat){let{data:V,start:N}=this.writer.stopTrackingWrites();this.format._options.onMdat(V,N)}for(let V of Y)V.finalizedChunks.push(V.currentChunk),this.finalizedChunks.push(V.currentChunk),V.currentChunk=null;if($)await this.writer.flush()}async registerSampleFastStartReserve($,J){if(this.allTracksAreKnown()){if(!this.mdat){let Y=_8(this),X=this.boxWriter.measureBox(Y)+this.computeSampleTableSizeUpperBound()+4096;if(H(this.ftypSize!==null),this.writer.seek(this.ftypSize+X),this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat=t8(!0),this.boxWriter.writeBox(this.mdat);for(let Z of this.trackDatas){for(let G of Z.sampleQueue)await this.addSampleToTrack(Z,G);Z.sampleQueue.length=0}}await this.addSampleToTrack($,J)}else $.sampleQueue.push(J)}computeSampleTableSizeUpperBound(){H(this.fastStart==="reserve");let $=0;for(let J of this.trackDatas){let Y=J.track.metadata.maximumPacketCount;H(Y!==void 0),$+=8*Math.ceil(0.6666666666666666*Y),$+=4*Y,$+=8*Math.ceil(0.6666666666666666*Y),$+=12*Math.ceil(0.6666666666666666*Y),$+=4*Y,$+=8*Y}return $}async onTrackClose($){let J=await this.mutex.acquire();if($.type==="subtitle"&&$.source._codec==="webvtt"){let Y=this.trackDatas.find((j)=>j.track===$);if(Y)await this.processWebVTTCues(Y,Number.POSITIVE_INFINITY)}if(this.allTracksAreKnown())this.allTracksKnown.resolve();if(this.isFragmented)await this.interleaveSamples();J()}async finalize(){let $=await this.mutex.acquire();this.allTracksKnown.resolve();for(let J of this.trackDatas)if(J.type==="subtitle"&&J.track.source._codec==="webvtt")await this.processWebVTTCues(J,Number.POSITIVE_INFINITY);if(this.isFragmented){await this.interleaveSamples(!0);for(let J of this.trackDatas)this.processTimestamps(J);await this.finalizeFragment(!1)}else for(let J of this.trackDatas)this.processTimestamps(J),await this.finalizeCurrentChunk(J);if(this.fastStart==="in-memory"){this.mdat=t8(!1);let J;for(let j=0;j<2;j++){let X=_8(this),Z=this.boxWriter.measureBox(X);J=this.boxWriter.measureBox(this.mdat);let G=this.writer.getPos()+Z+J;for(let K of this.finalizedChunks){K.offset=G;for(let{data:Q}of K.samples)H(Q),G+=Q.byteLength,J+=Q.byteLength}if(G<4294967296)break;if(J>=4294967296)this.mdat.largeSize=!0}if(this.format._options.onMoov)this.writer.startTrackingWrites();let Y=_8(this);if(this.boxWriter.writeBox(Y),this.format._options.onMoov){let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onMoov(j,X)}if(this.format._options.onMdat)this.writer.startTrackingWrites();this.mdat.size=J,this.boxWriter.writeBox(this.mdat);for(let j of this.finalizedChunks)for(let X of j.samples)H(X.data),this.writer.write(X.data),X.data=null;if(this.format._options.onMdat){let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onMdat(j,X)}}else if(this.isFragmented){let J=this.writer.getPos(),Y=SY(this.trackDatas);this.boxWriter.writeBox(Y);let j=this.writer.getPos()-J;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(j)}else{H(this.mdat);let J=this.boxWriter.offsets.get(this.mdat);H(J!==void 0);let Y=this.writer.getPos()-J;if(this.mdat.size=Y,this.mdat.largeSize=Y>=4294967296,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:X,start:Z}=this.writer.stopTrackingWrites();this.format._options.onMdat(X,Z)}let j=_8(this);if(this.fastStart==="reserve"){if(H(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov)this.writer.startTrackingWrites();this.boxWriter.writeBox(j);let X=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(xY(X))}else{if(this.format._options.onMoov)this.writer.startTrackingWrites();this.boxWriter.writeBox(j)}if(this.format._options.onMoov){let{data:X,start:Z}=this.writer.stopTrackingWrites();this.format._options.onMoov(X,Z)}}$()}}x0();/*!
420
+ * Copyright (c) 2025-present, Vanilagy and contributors
421
+ *
422
+ * This Source Code Form is subject to the terms of the Mozilla Public
423
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
424
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
425
+ */var HX=-32768,NX=32767,mY="Mediabunny",dY=6,cY=5,AX={video:1,audio:2,subtitle:17};class e$ extends V0{writer;ebmlWriter;format;trackDatas=[];allTracksKnown=c();segment=null;segmentInfo=null;seekHead=null;tracksElement=null;tagsElement=null;attachmentsElement=null;segmentDuration=null;cues=null;currentCluster=null;currentClusterStartMsTimestamp=null;currentClusterMaxMsTimestamp=null;trackDatasInCurrentCluster=new Map;duration=0;constructor($,J){super($);if(this.writer=$._writer,this.format=J,this.ebmlWriter=new A$(this.writer),this.format._options.appendOnly)this.writer.ensureMonotonicity=!0}async start(){let $=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),$()}writeEBMLHeader(){if(this.format._options.onEbmlHeader)this.writer.startTrackingWrites();let $={id:440786851,data:[{id:17030,data:1},{id:17143,data:1},{id:17138,data:4},{id:17139,data:8},{id:17026,data:this.format instanceof $6?"webm":"matroska"},{id:17031,data:2},{id:17029,data:2}]};if(this.ebmlWriter.writeEBML($),this.format._options.onEbmlHeader){let{data:J,start:Y}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(J,Y)}}maybeCreateSeekHead($){if(this.format._options.appendOnly)return;let J=new Uint8Array([28,83,187,107]),Y=new Uint8Array([21,73,169,102]),j=new Uint8Array([22,84,174,107]),X=new Uint8Array([25,65,164,105]),Z=new Uint8Array([18,84,195,103]),G={id:290298740,data:[{id:19899,data:[{id:21419,data:J},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:Y},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:19899,data:[{id:21419,data:j},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:19899,data:[{id:21419,data:X},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:19899,data:[{id:21419,data:Z},{id:21420,size:5,data:$?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=G}createSegmentInfo(){let $={id:17545,data:new m8(0)};this.segmentDuration=$;let J={id:357149030,data:[{id:2807729,data:1e6},{id:19840,data:mY},{id:22337,data:mY},!this.format._options.appendOnly?$:null]};this.segmentInfo=J}createTracks(){let $={id:374648427,data:[]};this.tracksElement=$;for(let J of this.trackDatas){let Y=A0[J.track.source._codec];H(Y);let j=0;if(J.type==="audio"&&J.track.source._codec==="opus"){j=80000000;let X=J.info.decoderConfig.description;if(X){let Z=l(X),G=z1(Z);j=Math.round(1e9*(G.preSkip/b0))}}$.data.push({id:174,data:[{id:215,data:J.track.id},{id:29637,data:J.track.id},{id:131,data:AX[J.type]},J.track.metadata.disposition?.default===!1?{id:136,data:0}:null,J.track.metadata.disposition?.forced?{id:21930,data:1}:null,J.track.metadata.disposition?.hearingImpaired?{id:21931,data:1}:null,J.track.metadata.disposition?.visuallyImpaired?{id:21932,data:1}:null,J.track.metadata.disposition?.original?{id:21934,data:1}:null,J.track.metadata.disposition?.commentary?{id:21935,data:1}:null,{id:156,data:0},{id:2274716,data:J.track.metadata.languageCode??a},{id:134,data:Y},{id:22186,data:0},{id:22203,data:j},J.track.metadata.name!==void 0?{id:21358,data:new r0(J.track.metadata.name)}:null,J.type==="video"?this.videoSpecificTrackInfo(J):null,J.type==="audio"?this.audioSpecificTrackInfo(J):null,J.type==="subtitle"?this.subtitleSpecificTrackInfo(J):null]})}}videoSpecificTrackInfo($){let{frameRate:J,rotation:Y}=$.track.metadata,j=[$.info.decoderConfig.description?{id:25506,data:l($.info.decoderConfig.description)}:null,J?{id:2352003,data:1e9/J}:null],X=Y?N1(-Y):0,Z=$.info.decoderConfig.colorSpace,G={id:224,data:[{id:176,data:$.info.width},{id:186,data:$.info.height},$.info.alphaMode?{id:21440,data:1}:null,K6(Z)?{id:21936,data:[{id:21937,data:J1[Z.matrix]},{id:21946,data:$1[Z.transfer]},{id:21947,data:e0[Z.primaries]},{id:21945,data:Z.fullRange?2:1}]}:null,X?{id:30320,data:[{id:30321,data:0},{id:30325,data:new l8((X+180)%360-180)}]}:null]};return j.push(G),j}audioSpecificTrackInfo($){let J=o.includes($.track.source._codec)?U0($.track.source._codec):null;return[$.info.decoderConfig.description?{id:25506,data:l($.info.decoderConfig.description)}:null,{id:225,data:[{id:181,data:new l8($.info.sampleRate)},{id:159,data:$.info.numberOfChannels},J?{id:25188,data:8*J.sampleSize}:null]}]}subtitleSpecificTrackInfo($){return[{id:25506,data:m.encode($.info.config.description)}]}maybeCreateTags(){let $=[],J=(X,Z)=>{$.push({id:26568,data:[{id:17827,data:new r0(X)},typeof Z==="string"?{id:17543,data:new r0(Z)}:{id:17541,data:Z}]})},Y=this.output._metadataTags,j=new Set;for(let{key:X,value:Z}of v0(Y))switch(X){case"title":J("TITLE",Z),j.add("TITLE");break;case"description":J("DESCRIPTION",Z),j.add("DESCRIPTION");break;case"artist":J("ARTIST",Z),j.add("ARTIST");break;case"album":J("ALBUM",Z),j.add("ALBUM");break;case"albumArtist":J("ALBUM_ARTIST",Z),j.add("ALBUM_ARTIST");break;case"genre":J("GENRE",Z),j.add("GENRE");break;case"comment":J("COMMENT",Z),j.add("COMMENT");break;case"lyrics":J("LYRICS",Z),j.add("LYRICS");break;case"date":J("DATE",Z.toISOString().slice(0,10)),j.add("DATE");break;case"trackNumber":{let G=Y.tracksTotal!==void 0?`${Z}/${Y.tracksTotal}`:Z.toString();J("PART_NUMBER",G),j.add("PART_NUMBER")}break;case"discNumber":{let G=Y.discsTotal!==void 0?`${Z}/${Y.discsTotal}`:Z.toString();J("DISC",G),j.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:i(X)}if(Y.raw)for(let X in Y.raw){let Z=Y.raw[X];if(Z==null||j.has(X))continue;if(typeof Z==="string"||Z instanceof Uint8Array)J(X,Z)}if($.length===0)return;this.tagsElement={id:307544935,data:[{id:29555,data:[{id:25536,data:[{id:26826,data:50},{id:25546,data:"MOVIE"}]},...$]}]}}maybeCreateAttachments(){let $=this.output._metadataTags,J=[],Y=new Set,j=$.images??[];for(let X of j){let Z=X.name;if(Z===void 0)Z=(X.kind==="coverFront"?"cover":X.kind==="coverBack"?"back":"image")+(MJ(X.mimeType)??"");let G;while(!0){G=0n;for(let K=0;K<8;K++)G<<=8n,G|=BigInt(Math.floor(Math.random()*256));if(G!==0n&&!Y.has(G))break}Y.add(G),J.push({id:24999,data:[X.description!==void 0?{id:18046,data:new r0(X.description)}:null,{id:18030,data:new r0(Z)},{id:18016,data:X.mimeType},{id:18012,data:X.data},{id:18094,data:G}]})}for(let[X,Z]of Object.entries($.raw??{})){if(!(Z instanceof l1))continue;if(!/^\d+$/.test(X))continue;if(j.find((K)=>K.mimeType===Z.mimeType&&wJ(K.data,Z.data)))continue;J.push({id:24999,data:[Z.description!==void 0?{id:18046,data:new r0(Z.description)}:null,{id:18030,data:new r0(Z.name??"")},{id:18016,data:Z.mimeType??""},{id:18012,data:Z.data},{id:18094,data:BigInt(X)}]})}if(J.length===0)return;this.attachmentsElement={id:423732329,data:J}}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let $={id:408125543,size:this.format._options.appendOnly?-1:dY,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=$,this.format._options.onSegmentHeader)this.writer.startTrackingWrites();if(this.ebmlWriter.writeEBML($),this.format._options.onSegmentHeader){let{data:J,start:Y}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(J,Y)}}createCues(){this.cues={id:475249515,data:[]}}get segmentDataOffset(){return H(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let $=this.trackDatas.map((J)=>{if(J.type==="video")return J.info.decoderConfig.codec;if(J.type==="audio")return J.info.decoderConfig.codec;return{webvtt:"S_TEXT/WEBVTT",tx3g:"S_TEXT/UTF8",ttml:"S_TEXT/WEBVTT",srt:"S_TEXT/UTF8",ass:"S_TEXT/ASS",ssa:"S_TEXT/SSA"}[J.track.source._codec]});return Q2({isWebM:this.format instanceof $6,hasVideo:this.trackDatas.some((J)=>J.type==="video"),hasAudio:this.trackDatas.some((J)=>J.type==="audio"),codecStrings:$})}getVideoTrackData($,J,Y){let j=this.trackDatas.find((Z)=>Z.track===$);if(j)return j;t1(Y),H(Y),H(Y.decoderConfig),H(Y.decoderConfig.codedWidth!==void 0),H(Y.decoderConfig.codedHeight!==void 0);let X={track:$,type:"video",info:{width:Y.decoderConfig.codedWidth,height:Y.decoderConfig.codedHeight,decoderConfig:Y.decoderConfig,alphaMode:!!J.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};if($.source._codec==="vp9")X.info.decoderConfig={...X.info.decoderConfig,description:new Uint8Array(yJ(X.info.decoderConfig.codec))};else if($.source._codec==="av1")X.info.decoderConfig={...X.info.decoderConfig,description:new Uint8Array(W6(X.info.decoderConfig.codec))};if(this.trackDatas.push(X),this.trackDatas.sort((Z,G)=>Z.track.id-G.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return X}getAudioTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;_0(J),H(J),H(J.decoderConfig);let j={track:$,type:"audio",info:{numberOfChannels:J.decoderConfig.numberOfChannels,sampleRate:J.decoderConfig.sampleRate,decoderConfig:J.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}getSubtitleTrackData($,J){let Y=this.trackDatas.find((X)=>X.track===$);if(Y)return Y;A6(J),H(J),H(J.config);let j={track:$,type:"subtitle",info:{config:J.config},chunkQueue:[],lastWrittenMsTimestamp:null};if(this.trackDatas.push(j),this.trackDatas.sort((X,Z)=>X.track.id-Z.track.id),this.allTracksAreKnown())this.allTracksKnown.resolve();return j}async addEncodedVideoPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getVideoTrackData($,J,Y),Z=J.type==="key",G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,Z),K=J.duration;if($.metadata.frameRate!==void 0)G=F8(G,1/$.metadata.frameRate),K=F8(K,1/$.metadata.frameRate);let Q=X.info.alphaMode?J.sideData.alpha??null:null,q=this.createInternalChunk(J.data,G,K,J.type,Q);if($.source._codec==="vp9")this.fixVP9ColorSpace(X,q);X.chunkQueue.push(q),await this.interleaveChunks()}finally{j()}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getAudioTrackData($,Y),Z=J.type==="key",G=this.validateAndNormalizeTimestamp(X.track,J.timestamp,Z),K=this.createInternalChunk(J.data,G,J.duration,J.type);X.chunkQueue.push(K),await this.interleaveChunks()}finally{j()}}async addSubtitleCue($,J,Y){let j=await this.mutex.acquire();try{let X=this.getSubtitleTrackData($,Y),Z=this.validateAndNormalizeTimestamp(X.track,J.timestamp,!0),G=J.text,K=Math.round(Z*1000);if($.source._codec==="ass"||$.source._codec==="ssa")G=Y$(G);else u1.lastIndex=0,G=G.replace(u1,(W)=>{let N=I8(W.slice(1,-1))-K;return`<${k1(N)}>`});let Q=m.encode(G),q=`${J.settings??""}
426
+ ${J.identifier??""}
427
+ ${J.notes??""}`,U=this.createInternalChunk(Q,Z,J.duration,"key",q.trim()?m.encode(q):null);X.chunkQueue.push(U),await this.interleaveChunks()}finally{j()}}async interleaveChunks($=!1){if(!$&&!this.allTracksAreKnown())return;$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let X of this.trackDatas){if(!$&&X.chunkQueue.length===0&&!X.track.source._closed)break $;if(X.chunkQueue.length>0&&X.chunkQueue[0].timestamp<Y)J=X,Y=X.chunkQueue[0].timestamp}if(!J)break;let j=J.chunkQueue.shift();this.writeBlock(J,j)}if(!$)await this.writer.flush()}fixVP9ColorSpace($,J){if(J.type!=="key")return;if(!$.info.decoderConfig.colorSpace||!$.info.decoderConfig.colorSpace.matrix)return;let Y=new f(J.data);Y.skipBits(2);let j=Y.readBits(1),Z=(Y.readBits(1)<<1)+j;if(Z===3)Y.skipBits(1);if(Y.readBits(1))return;if(Y.readBits(1)!==0)return;if(Y.skipBits(2),Y.readBits(24)!==4817730)return;if(Z>=2)Y.skipBits(1);let q={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[$.info.decoderConfig.colorSpace.matrix];WJ(J.data,Y.pos,Y.pos+3,q)}createInternalChunk($,J,Y,j,X=null){return{data:$,type:j,timestamp:J,duration:Y,additions:X}}writeBlock($,J){if(!this.segment)this.createSegment();let Y=Math.round(1000*J.timestamp),j=this.trackDatas.every((q)=>{if($===q)return J.type==="key";let U=q.chunkQueue[0];if(U)return U.type==="key";return q.track.source._closed}),X=!1;if(!this.currentCluster)X=!0;else{H(this.currentClusterStartMsTimestamp!==null),H(this.currentClusterMaxMsTimestamp!==null);let q=Y-this.currentClusterStartMsTimestamp;X=j&&Y>this.currentClusterMaxMsTimestamp&&q>=1000*(this.format._options.minimumClusterDuration??1)||q>NX}if(X)this.createNewCluster(Y);let Z=Y-this.currentClusterStartMsTimestamp;if(Z<HX)return;let G=new Uint8Array(4),K=new DataView(G.buffer);K.setUint8(0,128|$.track.id),K.setInt16(1,Z,!1);let Q=Math.round(1000*J.duration);if(!J.additions){K.setUint8(3,Number(J.type==="key")<<7);let q={id:163,data:[G,J.data]};this.ebmlWriter.writeEBML(q)}else{let q={id:160,data:[{id:161,data:[G,J.data]},J.type==="delta"?{id:251,data:new X2($.lastWrittenMsTimestamp-Y)}:null,J.additions?{id:30113,data:[{id:166,data:[{id:238,data:1},{id:165,data:J.additions}]}]}:null,Q>0?{id:155,data:Q}:null]};this.ebmlWriter.writeEBML(q)}if(this.duration=Math.max(this.duration,Y+Q),$.lastWrittenMsTimestamp=Y,!this.trackDatasInCurrentCluster.has($))this.trackDatasInCurrentCluster.set($,{firstMsTimestamp:Y});this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,Y)}createNewCluster($){if(this.currentCluster)this.finalizeCurrentCluster();if(this.format._options.onCluster)this.writer.startTrackingWrites();this.currentCluster={id:524531317,size:this.format._options.appendOnly?-1:cY,data:[{id:231,data:$}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=$,this.currentClusterMaxMsTimestamp=$,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(H(this.currentCluster),!this.format._options.appendOnly){let j=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),X=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(j,cY),this.writer.seek(X)}if(this.format._options.onCluster){H(this.currentClusterStartMsTimestamp!==null);let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onCluster(j,X,this.currentClusterStartMsTimestamp/1000)}let $=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,J=new Map;for(let[j,{firstMsTimestamp:X}]of this.trackDatasInCurrentCluster){if(!J.has(X))J.set(X,[]);J.get(X).push(j)}let Y=[...J.entries()].sort((j,X)=>j[0]-X[0]);for(let[j,X]of Y)H(this.cues),this.cues.data.push({id:187,data:[{id:179,data:j},...X.map((Z)=>{return{id:183,data:[{id:247,data:Z.track.id},{id:241,data:$}]}})]})}async onTrackClose(){let $=await this.mutex.acquire();if(this.allTracksAreKnown())this.allTracksKnown.resolve();await this.interleaveChunks(),$()}async finalize(){let $=await this.mutex.acquire();if(this.allTracksKnown.resolve(),!this.segment)this.createSegment();if(await this.interleaveChunks(!0),this.currentCluster)this.finalizeCurrentCluster();if(H(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let J=this.writer.getPos(),Y=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(Y,dY),this.segmentDuration.data=new m8(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),H(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(J)}$()}}/*!
428
+ * Copyright (c) 2025-present, Vanilagy and contributors
429
+ *
430
+ * This Source Code Form is subject to the terms of the Mozilla Public
431
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
432
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
433
+ */class $J{writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);constructor($){this.writer=$}writeU32($){this.helperView.setUint32(0,$,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame($){let J=this.writer.getPos(),Y=255,j=224|$.mpegVersionId<<3|$.layer<<1,X;if($.mpegVersionId&2)X=$.mpegVersionId&1?0:1;else X=1;let Z=0,G=155,K=-1,Q=X*16*4+$.layer*16;for(let R=0;R<16;R++){let z=P6[Q+R];if(D6(X,$.layer,1000*z,$.sampleRate,Z)>=G){K=R;break}}if(K===-1)throw Error("No suitable bitrate found.");let q=K<<4|$.frequencyIndex<<2|Z<<1,U=$.channel<<6|$.modeExtension<<4|$.copyright<<3|$.original<<2|$.emphasis;this.helper[0]=255,this.helper[1]=j,this.helper[2]=q,this.helper[3]=U,this.writer.write(this.helper.subarray(0,4));let W=Y8($.mpegVersionId,$.channel);this.writer.seek(J+W),this.writeU32(J8);let V=0;if($.frameCount!==null)V|=1;if($.fileSize!==null)V|=2;if($.toc!==null)V|=4;this.writeU32(V),this.writeU32($.frameCount??0),this.writeU32($.fileSize??0),this.writer.write($.toc??new Uint8Array(100));let N=P6[Q+K],A=D6(X,$.layer,1000*N,$.sampleRate,Z);this.writer.seek(J+A)}}/*!
434
+ * Copyright (c) 2025-present, Vanilagy and contributors
435
+ *
436
+ * This Source Code Form is subject to the terms of the Mozilla Public
437
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
438
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
439
+ */class JJ extends V0{format;writer;mp3Writer;xingFrameData=null;frameCount=0;framePositions=[];xingFramePos=null;constructor($,J){super($);this.format=J,this.writer=$._writer,this.mp3Writer=new $J($._writer)}async start(){if(!m1(this.output._metadataTags))new p8(this.writer).writeId3V2Tag(this.output._metadataTags)}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw Error("MP3 does not support video.")}async addEncodedAudioPacket($,J){let Y=await this.mutex.acquire();try{let j=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&j){let X=h(J.data);if(X.byteLength<4)throw Error("Invalid MP3 header in sample.");let Z=X.getUint32(0,!1),G=E6(Z,null).header;if(!G)throw Error("Invalid MP3 header in sample.");let K=Y8(G.mpegVersionId,G.channel);if(X.byteLength>=K+4){let Q=X.getUint32(K,!1);if(Q===J8||Q===C6)return}this.xingFrameData={mpegVersionId:G.mpegVersionId,layer:G.layer,frequencyIndex:G.frequencyIndex,sampleRate:G.sampleRate,channel:G.channel,modeExtension:G.modeExtension,copyright:G.copyright,original:G.original,emphasis:G.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}if(this.validateAndNormalizeTimestamp($,J.timestamp,J.type==="key"),this.writer.write(J.data),this.frameCount++,await this.writer.flush(),j)this.framePositions.push(this.writer.getPos())}finally{Y()}}async addSubtitleCue(){throw Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;let $=await this.mutex.acquire(),J=this.writer.getPos();this.writer.seek(this.xingFramePos);let Y=new Uint8Array(100);for(let j=0;j<100;j++){let X=Math.floor(this.framePositions.length*(j/100));H(X!==-1&&X<this.framePositions.length);let Z=this.framePositions[X];Y[j]=256*(Z/J)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=J,this.xingFrameData.toc=Y,this.format._options.onXingFrame)this.writer.startTrackingWrites();if(this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:j,start:X}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(j,X)}this.writer.seek(J),$()}}/*!
440
+ * Copyright (c) 2025-present, Vanilagy and contributors
441
+ *
442
+ * This Source Code Form is subject to the terms of the Mozilla Public
443
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
444
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
445
+ */var RX=8192;class YJ extends V0{format;writer;trackDatas=[];bosPagesWritten=!1;allTracksKnown=c();pageBytes=new Uint8Array(H2);pageView=new DataView(this.pageBytes.buffer);constructor($,J){super($);this.format=J,this.writer=$._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,V2({codecStrings:this.trackDatas.map(($)=>$.codecInfo.codec)})}addEncodedVideoPacket(){throw Error("Video tracks are not supported.")}getTrackData($,J){let Y=this.trackDatas.find((Z)=>Z.track===$);if(Y)return Y;let j;do j=Math.floor(4294967296*Math.random());while(this.trackDatas.some((Z)=>Z.serialNumber===j));H($.source._codec==="vorbis"||$.source._codec==="opus"),_0(J),H(J),H(J.decoderConfig);let X={track:$,serialNumber:j,internalSampleRate:$.source._codec==="opus"?b0:J.decoderConfig.sampleRate,codecInfo:{codec:$.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0};if(this.queueHeaderPackets(X,J),this.trackDatas.push(X),this.allTracksAreKnown())this.allTracksKnown.resolve();return X}queueHeaderPackets($,J){if(H(J.decoderConfig),$.track.source._codec==="vorbis"){H(J.decoderConfig.description);let Y=l(J.decoderConfig.description);if(Y[0]!==2)throw TypeError("First byte of Vorbis decoder description must be 2.");let j=1,X=()=>{let A=0;while(!0){let R=Y[j++];if(R===void 0)throw TypeError("Vorbis decoder description is too short.");if(A+=R,R<255)return A}},Z=X(),G=X();if(Y.length-j<=0)throw TypeError("Vorbis decoder description is too short.");let Q=Y.subarray(j,j+=Z);j+=G;let q=Y.subarray(j),U=new Uint8Array(7);U[0]=3,U[1]=118,U[2]=111,U[3]=114,U[4]=98,U[5]=105,U[6]=115;let W=C8(U,this.output._metadataTags,!0);$.packetQueue.push({data:Q,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:W,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:q,endGranulePosition:0,timestamp:0,forcePageFlush:!0});let N=h(Q).getUint8(28);$.codecInfo.vorbisInfo={blocksizes:[1<<(N&15),1<<(N>>4)],modeBlockflags:S6(q).modeBlockflags}}else if($.track.source._codec==="opus"){if(!J.decoderConfig.description)throw TypeError("For Ogg, Opus decoder description is required.");let Y=l(J.decoderConfig.description),j=new Uint8Array(8),X=h(j);X.setUint32(0,1332770163,!1),X.setUint32(4,1415669619,!1);let Z=C8(j,this.output._metadataTags,!0);$.packetQueue.push({data:Y,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:Z,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),$.codecInfo.opusInfo={preSkip:z1(Y).preSkip}}}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{let X=this.getTrackData($,Y);this.validateAndNormalizeTimestamp(X.track,J.timestamp,J.type==="key");let Z=X.currentTimestampInSamples,{durationInSamples:G,vorbisBlockSize:K}=W2(J.data,X.codecInfo,X.vorbisLastBlocksize);X.currentTimestampInSamples+=G,X.vorbisLastBlocksize=K,X.packetQueue.push({data:J.data,endGranulePosition:X.currentTimestampInSamples,timestamp:Z/X.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{j()}}addSubtitleCue(){throw Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let $ of this.output._tracks)if(!$.source._closed&&!this.trackDatas.some((J)=>J.track===$))return!1;return!0}async interleavePages($=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(let J of this.trackDatas)while(J.packetQueue.length>0){let Y=J.packetQueue.shift();if(this.writePacket(J,Y,!1),Y.forcePageFlush)break}this.bosPagesWritten=!0}$:while(!0){let J=null,Y=Number.POSITIVE_INFINITY;for(let Z of this.trackDatas){if(!$&&Z.packetQueue.length<=1&&!Z.track.source._closed)break $;if(Z.packetQueue.length>0&&Z.packetQueue[0].timestamp<Y)J=Z,Y=Z.packetQueue[0].timestamp}if(!J)break;let j=J.packetQueue.shift(),X=J.packetQueue.length===0;this.writePacket(J,j,X)}if(!$)await this.writer.flush()}writePacket($,J,Y){let j=J.data.length,X=0,Z=0;while(!0){if($.currentLacingValues.length===0&&X>0)$.currentPageStartsWithFreshPacket=!1;let K=Math.min(255,j);$.currentLacingValues.push(K),$.currentPageSize++,Z+=K;let Q=j<255;if($.currentLacingValues.length===255){let q=J.data.subarray(X,Z);if(X=Z,$.currentPageData.push(q),$.currentPageSize+=q.length,this.writePage($,Y&&Q),Q)return}if(Q)break;j-=255}let G=J.data.subarray(X);if($.currentPageData.push(G),$.currentPageSize+=G.length,$.currentGranulePosition=J.endGranulePosition,$.currentPageSize>=RX||J.forcePageFlush)this.writePage($,Y)}writePage($,J){this.pageView.setUint32(0,n8,!0),this.pageView.setUint8(4,0);let Y=0;if(!$.currentPageStartsWithFreshPacket)Y|=1;if($.pagesWritten===0)Y|=2;if(J)Y|=4;this.pageView.setUint8(5,Y);let j=$.currentLacingValues.every((K)=>K===255)?-1:$.currentGranulePosition;RJ(this.pageView,6,j,!0),this.pageView.setUint32(14,$.serialNumber,!0),this.pageView.setUint32(18,$.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,$.currentLacingValues.length),this.pageBytes.set($.currentLacingValues,27);let X=27+$.currentLacingValues.length;for(let K of $.currentPageData)this.pageBytes.set(K,X),X+=K.length;let Z=this.pageBytes.subarray(0,X),G=U2(Z);if(this.pageView.setUint32(22,G,!0),$.pagesWritten++,$.currentLacingValues.length=0,$.currentPageData.length=0,$.currentPageSize=27,$.currentPageStartsWithFreshPacket=!0,this.format._options.onPage)this.writer.startTrackingWrites();if(this.writer.write(Z),this.format._options.onPage){let{data:K,start:Q}=this.writer.stopTrackingWrites();this.format._options.onPage(K,Q,$.track.source)}}async onTrackClose(){let $=await this.mutex.acquire();if(this.allTracksAreKnown())this.allTracksKnown.resolve();await this.interleavePages(),$()}async finalize(){let $=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(let J of this.trackDatas)if(J.currentLacingValues.length>0)this.writePage(J,!0);$()}}/*!
446
+ * Copyright (c) 2025-present, Vanilagy and contributors
447
+ *
448
+ * This Source Code Form is subject to the terms of the Mozilla Public
449
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
450
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
451
+ */class jJ{writer;helper=new Uint8Array(8);helperView=new DataView(this.helper.buffer);constructor($){this.writer=$}writeU16($){this.helperView.setUint16(0,$,!0),this.writer.write(this.helper.subarray(0,2))}writeU32($){this.helperView.setUint32(0,$,!0),this.writer.write(this.helper.subarray(0,4))}writeU64($){this.helperView.setUint32(0,$,!0),this.helperView.setUint32(4,Math.floor($/4294967296),!0),this.writer.write(this.helper)}writeAscii($){this.writer.write(new TextEncoder().encode($))}}/*!
452
+ * Copyright (c) 2025-present, Vanilagy and contributors
453
+ *
454
+ * This Source Code Form is subject to the terms of the Mozilla Public
455
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
456
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
457
+ */class XJ extends V0{format;isRf64;writer;riffWriter;headerWritten=!1;dataSize=0;sampleRate=null;sampleCount=0;riffSizePos=null;dataSizePos=null;ds64RiffSizePos=null;ds64DataSizePos=null;ds64SampleCountPos=null;constructor($,J){super($);this.format=J,this.writer=$._writer,this.riffWriter=new jJ($._writer),this.isRf64=!!J._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw Error("WAVE does not support video.")}async addEncodedAudioPacket($,J,Y){let j=await this.mutex.acquire();try{if(!this.headerWritten)_0(Y),H(Y),H(Y.decoderConfig),this.writeHeader($,Y.decoderConfig),this.sampleRate=Y.decoderConfig.sampleRate,this.headerWritten=!0;if(this.validateAndNormalizeTimestamp($,J.timestamp,J.type==="key"),!this.isRf64&&this.writer.getPos()+J.data.byteLength>=4294967296)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(J.data),this.dataSize+=J.data.byteLength,this.sampleCount+=Math.round(J.duration*this.sampleRate),await this.writer.flush()}finally{j()}}async addSubtitleCue(){throw Error("WAVE does not support subtitles.")}writeHeader($,J){if(this.format._options.onHeader)this.writer.startTrackingWrites();let Y,j=$.source._codec,X=U0(j);if(X.dataType==="ulaw")Y=7;else if(X.dataType==="alaw")Y=6;else if(X.dataType==="float")Y=3;else Y=1;let{numberOfChannels:Z,sampleRate:G}=J,K=X.sampleSize*Z;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64)this.riffWriter.writeU32(4294967295);else this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0);if(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);if(this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(Y),this.riffWriter.writeU16(Z),this.riffWriter.writeU32(G),this.riffWriter.writeU32(G*K),this.riffWriter.writeU16(K),this.riffWriter.writeU16(8*X.sampleSize),!m1(this.output._metadataTags)){let Q=this.format._options.metadataFormat??"info";if(Q==="info")this.writeInfoChunk(this.output._metadataTags);else if(Q==="id3")this.writeId3Chunk(this.output._metadataTags);else i(Q)}if(this.riffWriter.writeAscii("data"),this.isRf64)this.riffWriter.writeU32(4294967295);else this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0);if(this.format._options.onHeader){let{data:Q,start:q}=this.writer.stopTrackingWrites();this.format._options.onHeader(Q,q)}}writeInfoChunk($){let J=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let Y=new Set,j=(G,K)=>{if(!A1(K)){console.warn(`Didn't write tag '${G}' because '${K}' is not ISO 8859-1-compatible.`);return}let Q=K.length+1,q=new Uint8Array(Q);for(let U=0;U<K.length;U++)q[U]=K.charCodeAt(U);if(this.riffWriter.writeAscii(G),this.riffWriter.writeU32(Q),this.writer.write(q),Q&1)this.writer.write(new Uint8Array(1));Y.add(G)};for(let{key:G,value:K}of v0($))switch(G){case"title":j("INAM",K),Y.add("INAM");break;case"artist":j("IART",K),Y.add("IART");break;case"album":j("IPRD",K),Y.add("IPRD");break;case"trackNumber":{let Q=$.tracksTotal!==void 0?`${K}/${$.tracksTotal}`:K.toString();j("ITRK",Q),Y.add("ITRK")}break;case"genre":j("IGNR",K),Y.add("IGNR");break;case"date":j("ICRD",K.toISOString().slice(0,10)),Y.add("ICRD");break;case"comment":j("ICMT",K),Y.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:i(G)}if($.raw)for(let G in $.raw){let K=$.raw[G];if(K==null||G.length!==4||Y.has(G))continue;if(typeof K==="string")j(G,K)}let X=this.writer.getPos(),Z=X-J-8;if(this.writer.seek(J+4),this.riffWriter.writeU32(Z),this.writer.seek(X),Z&1)this.writer.write(new Uint8Array(1))}writeId3Chunk($){let J=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let j=new p8(this.writer).writeId3V2Tag($),X=this.writer.getPos();if(this.writer.seek(J+4),this.riffWriter.writeU32(j),this.writer.seek(X),j&1)this.writer.write(new Uint8Array(1))}async finalize(){let $=await this.mutex.acquire(),J=this.writer.getPos();if(this.isRf64)H(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(J-8),H(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),H(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount);else H(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(J-8),H(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize);this.writer.seek(J),$()}}/*!
458
+ * Copyright (c) 2025-present, Vanilagy and contributors
459
+ *
460
+ * This Source Code Form is subject to the terms of the Mozilla Public
461
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
462
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
463
+ */class y0{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(($)=>j0.includes($))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(($)=>Z0.includes($))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(($)=>z0.includes($))}_codecUnsupportedHint($){return""}}class T2 extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes($.fastStart))throw TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if($.minimumFragmentDuration!==void 0&&(!Number.isFinite($.minimumFragmentDuration)||$.minimumFragmentDuration<0))throw TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if($.onFtyp!==void 0&&typeof $.onFtyp!=="function")throw TypeError("options.onFtyp, when provided, must be a function.");if($.onMoov!==void 0&&typeof $.onMoov!=="function")throw TypeError("options.onMoov, when provided, must be a function.");if($.onMdat!==void 0&&typeof $.onMdat!=="function")throw TypeError("options.onMdat, when provided, must be a function.");if($.onMoof!==void 0&&typeof $.onMoof!=="function")throw TypeError("options.onMoof, when provided, must be a function.");if($.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes($.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super();this._options=$}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:Number.POSITIVE_INFINITY},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}_createMuxer($){return new t$($,this)}}class J6 extends T2{constructor($){super($)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...j0,...X1,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","webvtt"]}_codecUnsupportedHint($){if(new e8().getSupportedCodecs().includes($))return" Switching to MOV will grant support for this codec.";return""}}class e8 extends T2{constructor($){super($)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...j0,...Z0,"webvtt"]}_codecUnsupportedHint($){if(new J6().getSupportedCodecs().includes($))return" Switching to MP4 will grant support for this codec.";return""}}class E2 extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.appendOnly!==void 0&&typeof $.appendOnly!=="boolean")throw TypeError("options.appendOnly, when provided, must be a boolean.");if($.minimumClusterDuration!==void 0&&(!Number.isFinite($.minimumClusterDuration)||$.minimumClusterDuration<0))throw TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if($.onEbmlHeader!==void 0&&typeof $.onEbmlHeader!=="function")throw TypeError("options.onEbmlHeader, when provided, must be a function.");if($.onSegmentHeader!==void 0&&typeof $.onSegmentHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");if($.onCluster!==void 0&&typeof $.onCluster!=="function")throw TypeError("options.onCluster, when provided, must be a function.");super();this._options=$}_createMuxer($){return new e$($,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:Number.POSITIVE_INFINITY},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...j0,...X1,...o.filter(($)=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes($)),...z0]}get supportsVideoRotationMetadata(){return!1}}class $6 extends E2{constructor($){super($)}getSupportedCodecs(){return[...j0.filter(($)=>["vp8","vp9","av1"].includes($)),...Z0.filter(($)=>["opus","vorbis"].includes($)),...z0]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint($){if(new E2().getSupportedCodecs().includes($))return" Switching to MKV will grant support for this codec.";return""}}class nY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.xingHeader!==void 0&&typeof $.xingHeader!=="boolean")throw TypeError("options.xingHeader, when provided, must be a boolean.");if($.onXingFrame!==void 0&&typeof $.onXingFrame!=="function")throw TypeError("options.onXingFrame, when provided, must be a function.");super();this._options=$}_createMuxer($){return new JJ($,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}}class oY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.large!==void 0&&typeof $.large!=="boolean")throw TypeError("options.large, when provided, must be a boolean.");if($.metadataFormat!==void 0&&!["info","id3"].includes($.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if($.onHeader!==void 0&&typeof $.onHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");super();this._options=$}_createMuxer($){return new XJ($,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[...o.filter(($)=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class rY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.onPage!==void 0&&typeof $.onPage!=="function")throw TypeError("options.onPage, when provided, must be a function.");super();this._options=$}_createMuxer($){return new YJ($,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:0},total:{min:1,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Z0.filter(($)=>["vorbis","opus"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class iY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.onFrame!==void 0&&typeof $.onFrame!=="function")throw TypeError("options.onFrame, when provided, must be a function.");super();this._options=$}_createMuxer($){return new f$($,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}}class sY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if($.large!==void 0&&typeof $.large!=="boolean")throw TypeError("options.large, when provided, must be a boolean.");if($.onHeader!==void 0&&typeof $.onHeader!=="function")throw TypeError("options.onHeader, when provided, must be a function.");if($.onIndex!==void 0&&typeof $.onIndex!=="function")throw TypeError("options.onIndex, when provided, must be a function.");super();this._options=$}_createMuxer($){return new k$($,this)}get _name(){return"AVI"}getSupportedTrackCounts(){return{video:{min:0,max:Number.POSITIVE_INFINITY},audio:{min:0,max:Number.POSITIVE_INFINITY},subtitle:{min:0,max:0},total:{min:1,max:4294967295}}}get fileExtension(){return".avi"}get mimeType(){return"video/x-msvideo"}getSupportedCodecs(){return[...j0.filter(($)=>["avc","hevc","vp8","vp9","av1","mpeg4"].includes($)),...Z0.filter(($)=>["mp3","aac","vorbis","flac","ac3","pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes($))]}get supportsVideoRotationMetadata(){return!1}}class aY extends y0{_options;constructor($={}){if(!$||typeof $!=="object")throw TypeError("options must be an object.");super();this._options=$}_createMuxer($){return new u$($,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}}/*!
464
+ * Copyright (c) 2025-present, Vanilagy and contributors
465
+ *
466
+ * This Source Code Form is subject to the terms of the Mozilla Public
467
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
468
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
469
+ */var tY=["video","audio","subtitle"],ZJ=($)=>{if(!$||typeof $!=="object")throw TypeError("metadata must be an object.");if($.languageCode!==void 0&&!d0($.languageCode))throw TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if($.name!==void 0&&typeof $.name!=="string")throw TypeError("metadata.name, when provided, must be a string.");if($.disposition!==void 0)U5($.disposition);if($.maximumPacketCount!==void 0&&(!Number.isInteger($.maximumPacketCount)||$.maximumPacketCount<0))throw TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class Y6{format;target;state="pending";_muxer;_writer;_tracks=[];_startPromise=null;_cancelPromise=null;_finalizePromise=null;_mutex=new w0;_metadataTags={};constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!($.format instanceof y0))throw TypeError("options.format must be an OutputFormat.");if(!($.target instanceof P1))throw TypeError("options.target must be a Target.");if($.target._output)throw Error("Target is already used for another output.");$.target._output=this,this.format=$.format,this.target=$.target,this._writer=$.target._createWriter(),this._muxer=$.format._createMuxer(this)}addVideoTrack($,J={}){if(!($ instanceof w1))throw TypeError("source must be a VideoSource.");if(ZJ(J),J.rotation!==void 0&&![0,90,180,270].includes(J.rotation))throw TypeError(`Invalid video rotation: ${J.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&J.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(J.frameRate!==void 0&&(!Number.isFinite(J.frameRate)||J.frameRate<=0))throw TypeError(`Invalid video frame rate: ${J.frameRate}. Must be a positive number.`);this._addTrack("video",$,J)}addAudioTrack($,J={}){if(!($ instanceof O1))throw TypeError("source must be an AudioSource.");ZJ(J),this._addTrack("audio",$,J)}addSubtitleTrack($,J={}){if(!($ instanceof s8))throw TypeError("source must be a SubtitleSource.");ZJ(J),this._addTrack("subtitle",$,J)}setMetadataTags($){if(h8($),this.state!=="pending")throw Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=$}_addTrack($,J,Y){if(this.state!=="pending")throw Error("Cannot add track after output has been started or canceled.");if(J._connectedTrack)throw Error("Source is already used for a track.");let j=this.format.getSupportedTrackCounts(),X=this._tracks.reduce((Q,q)=>Q+(q.type===$?1:0),0),Z=j[$].max;if(X===Z)throw Error(Z===0?`${this.format._name} does not support ${$} tracks.`:`${this.format._name} does not support more than ${Z} ${$} track${Z===1?"":"s"}.`);let G=j.total.max;if(this._tracks.length===G)throw Error(`${this.format._name} does not support more than ${G} tracks${G===1?"":"s"} in total.`);let K={id:this._tracks.length+1,output:this,type:$,source:J,metadata:Y};if(K.type==="video"){let Q=this.format.getSupportedVideoCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}else if(K.type==="audio"){let Q=this.format.getSupportedAudioCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}else if(K.type==="subtitle"){let Q=this.format.getSupportedSubtitleCodecs();if(Q.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(K.source._codec));if(!Q.includes(K.source._codec))throw Error(`Codec '${K.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${Q.map((q)=>`'${q}'`).join(", ")}.`+this.format._codecUnsupportedHint(K.source._codec))}this._tracks.push(K),J._connectedTrack=K}async start(){let $=this.format.getSupportedTrackCounts();for(let Y of tY){let j=this._tracks.reduce((Z,G)=>Z+(G.type===Y?1:0),0),X=$[Y].min;if(j<X)throw Error(X===$[Y].max?`${this.format._name} requires exactly ${X} ${Y} track${X===1?"":"s"}.`:`${this.format._name} requires at least ${X} ${Y} track${X===1?"":"s"}.`)}let J=$.total.min;if(this._tracks.length<J)throw Error(J===$.total.max?`${this.format._name} requires exactly ${J} track${J===1?"":"s"}.`:`${this.format._name} requires at least ${J} track${J===1?"":"s"}.`);if(this.state==="canceled")throw Error("Output has been canceled.");if(this._startPromise)return console.warn("Output has already been started."),this._startPromise;return this._startPromise=(async()=>{this.state="started",this._writer.start();let Y=await this._mutex.acquire();await this._muxer.start();let j=this._tracks.map((X)=>X.source._start());await Promise.all(j),Y()})()}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"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let $=await this._mutex.acquire(),J=this._tracks.map((Y)=>Y.source._flushOrWaitForOngoingClose(!0));await Promise.all(J),await this._writer.close(),$()})()}async finalize(){if(this.state==="pending")throw Error("Cannot finalize before starting.");if(this.state==="canceled")throw Error("Cannot finalize after canceling.");if(this._finalizePromise)return console.warn("Output has already been finalized."),this._finalizePromise;return this._finalizePromise=(async()=>{this.state="finalizing";let $=await this._mutex.acquire(),J=this._tracks.map((Y)=>Y.source._flushOrWaitForOngoingClose(!1));await Promise.all(J),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",$()})()}}x0();/*!
470
+ * Copyright (c) 2025-present, Vanilagy and contributors
471
+ *
472
+ * This Source Code Form is subject to the terms of the Mozilla Public
473
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
474
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
475
+ */var eY=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.video, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.video.discard, when provided, must be a boolean.");if($?.forceTranscode!==void 0&&typeof $.forceTranscode!=="boolean")throw TypeError("options.video.forceTranscode, when provided, must be a boolean.");if($?.codec!==void 0&&!j0.includes($.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${j0.join(", ")}.`);if($?.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if($?.width!==void 0&&(!Number.isInteger($.width)||$.width<=0))throw TypeError("options.video.width, when provided, must be a positive integer.");if($?.height!==void 0&&(!Number.isInteger($.height)||$.height<=0))throw TypeError("options.video.height, when provided, must be a positive integer.");if($?.fit!==void 0&&!["fill","contain","cover"].includes($.fit))throw TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if($?.width!==void 0&&$.height!==void 0&&$.fit===void 0)throw TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if($?.rotate!==void 0&&![0,90,180,270].includes($.rotate))throw TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if($?.allowRotationMetadata!==void 0&&typeof $.allowRotationMetadata!=="boolean")throw TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if($?.crop!==void 0)b8($.crop,"options.video.");if($?.frameRate!==void 0&&(!Number.isFinite($.frameRate)||$.frameRate<=0))throw TypeError("options.video.frameRate, when provided, must be a finite positive number.");if($?.alpha!==void 0&&!["discard","keep"].includes($.alpha))throw TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if($?.keyFrameInterval!==void 0&&(!Number.isFinite($.keyFrameInterval)||$.keyFrameInterval<0))throw TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if($?.process!==void 0&&typeof $.process!=="function")throw TypeError("options.video.process, when provided, must be a function.");if($?.processedWidth!==void 0&&(!Number.isInteger($.processedWidth)||$.processedWidth<=0))throw TypeError("options.video.processedWidth, when provided, must be a positive integer.");if($?.processedHeight!==void 0&&(!Number.isInteger($.processedHeight)||$.processedHeight<=0))throw TypeError("options.video.processedHeight, when provided, must be a positive integer.");if($?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes($.hardwareAcceleration))throw TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.")},$7=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.audio, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.audio.discard, when provided, must be a boolean.");if($?.forceTranscode!==void 0&&typeof $.forceTranscode!=="boolean")throw TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if($?.codec!==void 0&&!Z0.includes($.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${Z0.join(", ")}.`);if($?.bitrate!==void 0&&!($.bitrate instanceof N0)&&(!Number.isInteger($.bitrate)||$.bitrate<=0))throw TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if($?.numberOfChannels!==void 0&&(!Number.isInteger($.numberOfChannels)||$.numberOfChannels<=0))throw TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if($?.sampleRate!==void 0&&(!Number.isInteger($.sampleRate)||$.sampleRate<=0))throw TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if($?.process!==void 0&&typeof $.process!=="function")throw TypeError("options.audio.process, when provided, must be a function.");if($?.processedNumberOfChannels!==void 0&&(!Number.isInteger($.processedNumberOfChannels)||$.processedNumberOfChannels<=0))throw TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if($?.processedSampleRate!==void 0&&(!Number.isInteger($.processedSampleRate)||$.processedSampleRate<=0))throw TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.")},J7=($)=>{if($!==void 0&&(!$||typeof $!=="object"))throw TypeError("options.subtitle, when provided, must be an object.");if($?.discard!==void 0&&typeof $.discard!=="boolean")throw TypeError("options.subtitle.discard, when provided, must be a boolean.");if($?.codec!==void 0&&!z0.includes($.codec))throw TypeError(`options.subtitle.codec, when provided, must be one of: ${z0.join(", ")}.`)},GJ=2,KJ=48000;class QJ{input;output;_options;_startTimestamp;_endTimestamp;_addedCounts={video:0,audio:0,subtitle:0};_totalTrackCount=0;_trackPromises=[];_started;_start;_executed=!1;_synchronizer=new j7;_totalDuration=null;_maxTimestamps=new Map;_canceled=!1;_externalSubtitleSources=[];onProgress=void 0;_computeProgress=!1;_lastProgress=0;isValid=!1;utilizedTracks=[];discardedTracks=[];static async init($){let J=new QJ($);return await J._init(),J}constructor($){if(!$||typeof $!=="object")throw TypeError("options must be an object.");if(!($.input instanceof z8))throw TypeError("options.input must be an Input.");if(!($.output instanceof Y6))throw TypeError("options.output must be an Output.");if($.output._tracks.length>0||Object.keys($.output._metadataTags).length>0||$.output.state!=="pending")throw TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(typeof $.video!=="function")eY($.video);if(typeof $.audio!=="function")$7($.audio);if(typeof $.subtitle!=="function")J7($.subtitle);if($.trim!==void 0&&(!$.trim||typeof $.trim!=="object"))throw TypeError("options.trim, when provided, must be an object.");if($.trim?.start!==void 0&&(!Number.isFinite($.trim.start)||$.trim.start<0))throw TypeError("options.trim.start, when provided, must be a non-negative number.");if($.trim?.end!==void 0&&(!Number.isFinite($.trim.end)||$.trim.end<0))throw TypeError("options.trim.end, when provided, must be a non-negative number.");if($.trim?.start!==void 0&&$.trim.end!==void 0&&$.trim.start>=$.trim.end)throw TypeError("options.trim.start must be less than options.trim.end.");if($.tags!==void 0&&(typeof $.tags!=="object"||!$.tags)&&typeof $.tags!=="function")throw TypeError("options.tags, when provided, must be an object or a function.");if(typeof $.tags==="object")h8($.tags);if($.showWarnings!==void 0&&typeof $.showWarnings!=="boolean")throw TypeError("options.showWarnings, when provided, must be a boolean.");this._options=$,this.input=$.input,this.output=$.output,this._startTimestamp=$.trim?.start??0,this._endTimestamp=$.trim?.end??Number.POSITIVE_INFINITY;let{promise:J,resolve:Y}=c();this._started=J,this._start=Y}async _init(){let $=await this.input.getTracks(),J=this.output.format.getSupportedTrackCounts(),Y=1,j=1,X=1;for(let q of $){let U;if(q.isVideoTrack()){if(this._options.video)if(typeof this._options.video==="function")U=await this._options.video(q,Y),eY(U),Y++;else U=this._options.video}else if(q.isAudioTrack()){if(this._options.audio)if(typeof this._options.audio==="function")U=await this._options.audio(q,j),$7(U),j++;else U=this._options.audio}else if(q.isSubtitleTrack()){if(this._options.subtitle)if(typeof this._options.subtitle==="function")U=await this._options.subtitle(q,X),J7(U),X++;else U=this._options.subtitle}else H(!1);if(U?.discard){this.discardedTracks.push({track:q,reason:"discarded_by_user"});continue}if(this._totalTrackCount===J.total.max){this.discardedTracks.push({track:q,reason:"max_track_count_reached"});continue}if(this._addedCounts[q.type]===J[q.type].max){this.discardedTracks.push({track:q,reason:"max_track_count_of_type_reached"});continue}if(q.isVideoTrack())await this._processVideoTrack(q,U??{});else if(q.isAudioTrack())await this._processAudioTrack(q,U??{});else if(q.isSubtitleTrack())await this._processSubtitleTrack(q,U??{})}let Z=await this.input.getMetadataTags(),G;if(this._options.tags){let q=typeof this._options.tags==="function"?await this._options.tags(Z):this._options.tags;h8(q),G=q}else G=Z;let K=(await this.input.getFormat()).mimeType===this.output.format.mimeType,Q=Z.raw===G.raw;if(Z.raw&&Q&&!K)delete G.raw;if(this.output.setMetadataTags(G),this.isValid=this._totalTrackCount>=J.total.min&&this._addedCounts.video>=J.video.min&&this._addedCounts.audio>=J.audio.min&&this._addedCounts.subtitle>=J.subtitle.min,this._options.showWarnings??!0){let q=[],U=this.discardedTracks.filter((W)=>W.reason!=="discarded_by_user");if(U.length>0)q.push("Some tracks had to be discarded from the conversion:",U);if(!this.isValid)q.push(`
476
+
477
+ `+this._getInvalidityExplanation().join(""));if(q.length>0)console.warn(...q)}}_getInvalidityExplanation(){let $=[];if(this.discardedTracks.length===0)$.push("Due to missing tracks, this conversion cannot be executed.");else{let J=this.discardedTracks.every((Y)=>Y.reason==="discarded_by_user"||Y.reason==="no_encodable_target_codec");if($.push("Due to discarded tracks, this conversion cannot be executed."),J){let Y=this.discardedTracks.flatMap((j)=>{if(j.reason==="discarded_by_user")return[];if(j.track.type==="video")return this.output.format.getSupportedVideoCodecs();if(j.track.type==="audio")return this.output.format.getSupportedAudioCodecs();return this.output.format.getSupportedSubtitleCodecs()});if(Y.length===1)$.push(`
478
+ Tracks were discarded because your environment is not able to encode '${Y[0]}'.`);else $.push(`
479
+ Tracks were discarded because your environment is not able to encode any of the following codecs: ${Y.map((j)=>`'${j}'`).join(", ")}.`);if(Y.includes("mp3"))$.push(`
480
+ The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`);if(Y.includes("mpeg4"))$.push(`
481
+ The @mediabunny/mpeg4 extension package provides support for encoding and decoding MPEG-4 Part 2.`);if(Y.includes("ac3")||Y.includes("eac3"))$.push(`
482
+ The @mediabunny/eac3 extension package provides support for encoding and decoding AC-3 and E-AC-3.`)}else $.push(`
483
+ Check the discardedTracks field for more info.`)}return $}addExternalSubtitleTrack($,J={},Y){if(this._executed)throw Error("Cannot add subtitle tracks after conversion has been executed.");if(this.output.state!=="pending")throw Error("Cannot add subtitle tracks after output has been started.");let j=this.output.format.getSupportedTrackCounts();if(this._addedCounts.subtitle+this._externalSubtitleSources.length>=j.subtitle.max)throw Error(`Cannot add more subtitle tracks. Maximum of ${j.subtitle.max} subtitle track(s) allowed.`);if(this._totalTrackCount+this._externalSubtitleSources.length+1>j.total.max)throw Error(`Cannot add more tracks. Maximum of ${j.total.max} total track(s) allowed.`);this._externalSubtitleSources.push({source:$,metadata:J,contentProvider:Y}),this.isValid=this._totalTrackCount+this._externalSubtitleSources.length>=j.total.min&&this._addedCounts.video>=j.video.min&&this._addedCounts.audio>=j.audio.min&&this._addedCounts.subtitle+this._externalSubtitleSources.length>=j.subtitle.min}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.
484
+ `+this._getInvalidityExplanation().join(""));if(this._executed)throw Error("Conversion cannot be executed twice.");if(this._executed=!0,this.onProgress){this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let J of this.utilizedTracks)this._maxTimestamps.set(J.id,0);this.onProgress?.(0)}for(let{source:J,metadata:Y}of this._externalSubtitleSources)this.output.addSubtitleTrack(J,Y);await this.output.start(),this._start();let $=this._externalSubtitleSources.filter((J)=>J.contentProvider).map((J)=>J.contentProvider());if($.length>0)this._trackPromises.push(...$);try{await Promise.all(this._trackPromises)}catch(J){if(!this._canceled)this.cancel();throw J}if(this._canceled)await new Promise(()=>{});if(await this.output.finalize(),this._computeProgress)this.onProgress?.(1)}async cancel(){if(this.output.state==="finalizing"||this.output.state==="finalized")return;if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}async _processVideoTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j,X=N1($.rotation+(J.rotate??0)),Z=this.output.format.supportsVideoRotationMetadata&&(J.allowRotationMetadata??!0),[G,K]=X%180===0?[$.codedWidth,$.codedHeight]:[$.codedHeight,$.codedWidth],Q=J.crop;if(Q)v8(Q,G,K);let[q,U]=Q?[Q.width,Q.height]:[G,K],W=q,V=U,N=W/V,A=(B)=>Math.ceil(B/2)*2;if(J.width!==void 0&&J.height===void 0)W=A(J.width),V=A(Math.round(W/N));else if(J.width===void 0&&J.height!==void 0)V=A(J.height),W=A(Math.round(V*N));else if(J.width!==void 0&&J.height!==void 0)W=A(J.width),V=A(J.height);let R=await $.getFirstTimestamp(),z=!!J.forceTranscode||this._startTimestamp>0||R<0||!!J.frameRate||J.keyFrameInterval!==void 0||J.process!==void 0,_=W!==q||V!==U||X!==0&&(!Z||J.process!==void 0)||!!Q,L=J.alpha??"discard",M=this.output.format.getSupportedVideoCodecs();if(!z&&!J.bitrate&&!_&&M.includes(Y)&&(!J.codec||J.codec===Y)){let B=new _2(Y);j=B,this._trackPromises.push((async()=>{await this._started;let F=new K1($),w={decoderConfig:await $.getDecoderConfig()??void 0},v=Number.isFinite(this._endTimestamp)?await F.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let k of F.packets(void 0,v,{verifyKeyPackets:!0})){if(this._canceled)return;if(L==="discard")delete k.sideData.alpha,delete k.sideData.alphaByteLength;if(this._reportProgress($.id,k.timestamp),await B.add(k,w),this._synchronizer.shouldWait($.id,k.timestamp))await this._synchronizer.wait(k.timestamp)}B.close(),this._synchronizer.closeTrack($.id)})())}else{if(!await $.canDecode()){this.discardedTracks.push({track:$,reason:"undecodable_source_codec"});return}if(J.codec)M=M.filter((k)=>k===J.codec);let F=J.bitrate??M6,C=await n2(M,{width:J.process&&J.processedWidth?J.processedWidth:W,height:J.process&&J.processedHeight?J.processedHeight:V,bitrate:F});if(!C){this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}let w={codec:C,bitrate:F,keyFrameInterval:J.keyFrameInterval,sizeChangeBehavior:J.fit??"passThrough",alpha:L,hardwareAcceleration:J.hardwareAcceleration},v=new r8(w);if(j=v,!_){let k=new Y6({format:new J6,target:new P2}),S=new r8(w);k.addVideoTrack(S),await k.start();let r=await new X8($).getSample(R);if(r)try{await S.add(r),r.close(),await k.finalize()}catch(H0){console.info("Error when probing encoder support. Falling back to rerender path.",H0),_=!0,k.cancel()}else await k.cancel()}if(_)this._trackPromises.push((async()=>{await this._started;let S=new u6($,{width:W,height:V,fit:J.fit??"fill",rotation:X,crop:J.crop,poolSize:1,alpha:L==="keep"}).canvases(this._startTimestamp,this._endTimestamp),T=J.frameRate,r=null,H0=null,o1=null,F0=async(B0)=>{H(r),H(T!==void 0);let C0=Math.round((B0-H0)*T);for(let r1=1;r1<C0;r1++){let H1=new J0(r,{timestamp:H0+r1/T,duration:1/T});await this._registerVideoSample($,J,v,H1),H1.close()}};for await(let{canvas:B0,timestamp:C0,duration:r1}of S){if(this._canceled)return;let H1=Math.max(C0-this._startTimestamp,0);if(o1=H1+r1,T!==void 0){let j6=Math.floor(H1*T)/T;if(r!==null){if(j6<=H0){r=B0,H0=j6;continue}await F0(j6)}H1=j6}let qJ=new J0(B0,{timestamp:H1,duration:T!==void 0?1/T:r1});if(await this._registerVideoSample($,J,v,qJ),qJ.close(),T!==void 0)r=B0,H0=H1}if(r)H(o1!==null),H(T!==void 0),await F0(Math.floor(o1*T)/T);v.close(),this._synchronizer.closeTrack($.id)})());else this._trackPromises.push((async()=>{await this._started;let k=new X8($),S=J.frameRate,T=null,r=null,H0=null,o1=async(F0)=>{H(T),H(S!==void 0);let B0=Math.round((F0-r)*S);for(let C0=1;C0<B0;C0++)T.setTimestamp(r+C0/S),T.setDuration(1/S),await this._registerVideoSample($,J,v,T);T.close()};for await(let F0 of k.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){T?.close();return}let B0=Math.max(F0.timestamp-this._startTimestamp,0);if(H0=B0+F0.duration,S!==void 0){let C0=Math.floor(B0*S)/S;if(T!==null){if(C0<=r){T.close(),T=F0,r=C0;continue}await o1(C0)}B0=C0,F0.setDuration(1/S)}if(F0.setTimestamp(B0),await this._registerVideoSample($,J,v,F0),S!==void 0)T=F0,r=B0;else F0.close()}if(T)H(H0!==null),H(S!==void 0),await o1(Math.floor(H0*S)/S);v.close(),this._synchronizer.closeTrack($.id)})())}this.output.addVideoTrack(j,{frameRate:J.frameRate,languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0,disposition:$.disposition,rotation:_?0:X}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push($)}async _registerVideoSample($,J,Y,j){if(this._canceled)return;this._reportProgress($.id,j.timestamp);let X;if(!J.process)X=[j];else{let Z=J.process(j);if(Z instanceof Promise)Z=await Z;if(!Array.isArray(Z))Z=Z===null?[]:[Z];X=Z.map((G)=>{if(G instanceof J0)return G;if(typeof VideoFrame<"u"&&G instanceof VideoFrame)return new J0(G);return new J0(G,{timestamp:j.timestamp,duration:j.duration})})}for(let Z of X){if(this._canceled)break;if(await Y.add(Z),this._synchronizer.shouldWait($.id,Z.timestamp))await this._synchronizer.wait(Z.timestamp)}for(let Z of X)if(Z!==j)Z.close()}async _processAudioTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j,X=$.numberOfChannels,Z=$.sampleRate,G=await $.getFirstTimestamp(),K=J.numberOfChannels??X,Q=J.sampleRate??Z,q=K!==X||Q!==Z||this._startTimestamp>0||G<0,U=this.output.format.getSupportedAudioCodecs();if(!J.forceTranscode&&!J.bitrate&&!q&&U.includes(Y)&&(!J.codec||J.codec===Y)&&!J.process){let W=new M2(Y);j=W,this._trackPromises.push((async()=>{await this._started;let V=new K1($),A={decoderConfig:await $.getDecoderConfig()??void 0},R=Number.isFinite(this._endTimestamp)?await V.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let z of V.packets(void 0,R)){if(this._canceled)return;if(this._reportProgress($.id,z.timestamp),await W.add(z,A),this._synchronizer.shouldWait($.id,z.timestamp))await this._synchronizer.wait(z.timestamp)}W.close(),this._synchronizer.closeTrack($.id)})())}else{if(!await $.canDecode()){this.discardedTracks.push({track:$,reason:"undecodable_source_codec"});return}let V=null;if(J.codec)U=U.filter((R)=>R===J.codec);let N=J.bitrate??M6,A=await w8(U,{numberOfChannels:J.process&&J.processedNumberOfChannels?J.processedNumberOfChannels:K,sampleRate:J.process&&J.processedSampleRate?J.processedSampleRate:Q,bitrate:N});if(!A.some((R)=>X1.includes(R))&&U.some((R)=>X1.includes(R))&&(K!==GJ||Q!==KJ)){let z=(await w8(U,{numberOfChannels:GJ,sampleRate:KJ,bitrate:N})).find((_)=>X1.includes(_));if(z)q=!0,V=z,K=GJ,Q=KJ}else V=A[0]??null;if(V===null){this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}if(q)j=this._resampleAudio($,J,V,K,Q,N);else{let R=new i8({codec:V,bitrate:N});j=R,this._trackPromises.push((async()=>{await this._started;let z=new Z8($);for await(let _ of z.samples(void 0,this._endTimestamp)){if(this._canceled)return;await this._registerAudioSample($,J,R,_),_.close()}R.close(),this._synchronizer.closeTrack($.id)})())}}this.output.addAudioTrack(j,{languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0,disposition:$.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push($)}async _registerAudioSample($,J,Y,j){if(this._canceled)return;this._reportProgress($.id,j.timestamp);let X;if(!J.process)X=[j];else{let Z=J.process(j);if(Z instanceof Promise)Z=await Z;if(!Array.isArray(Z))Z=Z===null?[]:[Z];if(!Z.every((G)=>G instanceof K0))throw TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");X=Z}for(let Z of X){if(this._canceled)break;if(await Y.add(Z),this._synchronizer.shouldWait($.id,Z.timestamp))await this._synchronizer.wait(Z.timestamp)}for(let Z of X)if(Z!==j)Z.close()}async _processSubtitleTrack($,J){let Y=$.codec;if(!Y){this.discardedTracks.push({track:$,reason:"unknown_source_codec"});return}let j=J.codec??Y,X=this.output.format.getSupportedSubtitleCodecs();if(!X.includes(j))if(!J.codec&&X.includes(Y))j=Y;else{this.discardedTracks.push({track:$,reason:"no_encodable_target_codec"});return}let Z=new B2(j);this._trackPromises.push((async()=>{await this._started;let G;if(this._startTimestamp===0&&!Number.isFinite(this._endTimestamp)&&j===Y)G=await $.exportToText();else{let K=[];for await(let Q of $.getCues()){let q=Q.timestamp+Q.duration;if(this._startTimestamp>0||Number.isFinite(this._endTimestamp)){if(q<=this._startTimestamp||Q.timestamp>=this._endTimestamp)continue;let U=Math.max(Q.timestamp-this._startTimestamp,0),W=Math.min(q-this._startTimestamp,this._endTimestamp-this._startTimestamp);K.push({...Q,timestamp:U,duration:W-U})}else K.push(Q);if(this._canceled)return}if(j==="srt")G=n6(K);else if(j==="webvtt")G=o6(K);else if(j==="ass"||j==="ssa")G=r6(K,"");else G=await $.exportToText(j)}await Z.add(G),Z.close()})()),this.output.addSubtitleTrack(Z,{languageCode:d0($.languageCode)?$.languageCode:void 0,name:$.name??void 0}),this._addedCounts.subtitle++,this._totalTrackCount++,this.utilizedTracks.push($)}_resampleAudio($,J,Y,j,X,Z){let G=new i8({codec:Y,bitrate:Z});return this._trackPromises.push((async()=>{await this._started;let K=new X7({targetNumberOfChannels:j,targetSampleRate:X,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async(U)=>{await this._registerAudioSample($,J,G,U),U.close()}}),q=new Z8($).samples(this._startTimestamp,this._endTimestamp);for await(let U of q){if(this._canceled)return;await K.add(U),U.close()}await K.finalize(),G.close(),this._synchronizer.closeTrack($.id)})()),G}_reportProgress($,J){if(!this._computeProgress)return;H(this._totalDuration!==null),this._maxTimestamps.set($,Math.max(J,this._maxTimestamps.get($)));let Y=Math.min(...this._maxTimestamps.values()),j=$0(Y/this._totalDuration,0,1);if(j!==this._lastProgress)this._lastProgress=j,this.onProgress?.(j)}}var Y7=5;class j7{maxTimestamps=new Map;resolvers=[];computeMinAndMaybeResolve(){let $=Number.POSITIVE_INFINITY;for(let[,J]of this.maxTimestamps)$=Math.min($,J);for(let J=0;J<this.resolvers.length;J++){let Y=this.resolvers[J];if(Y.timestamp-$<Y7)Y.resolve(),this.resolvers.splice(J,1),J--}return $}shouldWait($,J){this.maxTimestamps.set($,Math.max(J,this.maxTimestamps.get($)??Number.NEGATIVE_INFINITY));let Y=this.computeMinAndMaybeResolve();return J-Y>=Y7}wait($){let{promise:J,resolve:Y}=c();return this.resolvers.push({timestamp:$,resolve:Y}),J}closeTrack($){this.maxTimestamps.delete($),this.computeMinAndMaybeResolve()}}class X7{sourceSampleRate=null;targetSampleRate;sourceNumberOfChannels=null;targetNumberOfChannels;startTime;endTime;onSample;bufferSizeInFrames;bufferSizeInSamples;outputBuffer;bufferStartFrame;maxWrittenFrame;channelMixer;tempSourceBuffer;constructor($){this.targetSampleRate=$.targetSampleRate,this.targetNumberOfChannels=$.targetNumberOfChannels,this.startTime=$.startTime,this.endTime=$.endTime,this.onSample=$.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){H(this.sourceNumberOfChannels!==null);let $=this.sourceNumberOfChannels,J=this.targetNumberOfChannels;if($===1&&J===2)this.channelMixer=(Y,j)=>{return Y[j*$]};else if($===1&&J===4)this.channelMixer=(Y,j,X)=>{return Y[j*$]*+(X<2)};else if($===1&&J===6)this.channelMixer=(Y,j,X)=>{return Y[j*$]*+(X===2)};else if($===2&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return 0.5*(Y[X]+Y[X+1])};else if($===2&&J===4)this.channelMixer=(Y,j,X)=>{return Y[j*$+X]*+(X<2)};else if($===2&&J===6)this.channelMixer=(Y,j,X)=>{return Y[j*$+X]*+(X<2)};else if($===4&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return 0.25*(Y[X]+Y[X+1]+Y[X+2]+Y[X+3])};else if($===4&&J===2)this.channelMixer=(Y,j,X)=>{let Z=j*$;return 0.5*(Y[Z+X]+Y[Z+X+2])};else if($===4&&J===6)this.channelMixer=(Y,j,X)=>{let Z=j*$;if(X<2)return Y[Z+X];if(X===2||X===3)return 0;return Y[Z+X-2]};else if($===6&&J===1)this.channelMixer=(Y,j)=>{let X=j*$;return Math.SQRT1_2*(Y[X]+Y[X+1])+Y[X+2]+0.5*(Y[X+4]+Y[X+5])};else if($===6&&J===2)this.channelMixer=(Y,j,X)=>{let Z=j*$;return Y[Z+X]+Math.SQRT1_2*(Y[Z+2]+Y[Z+X+4])};else if($===6&&J===4)this.channelMixer=(Y,j,X)=>{let Z=j*$;if(X<2)return Y[Z+X]+Math.SQRT1_2*Y[Z+2];return Y[Z+X+2]};else this.channelMixer=(Y,j,X)=>{return X<$?Y[j*$+X]:0}}ensureTempBufferSize($){let J=this.tempSourceBuffer.length;while(J<$)J*=2;if(J!==this.tempSourceBuffer.length){let Y=new Float32Array(J);Y.set(this.tempSourceBuffer),this.tempSourceBuffer=Y}}async add($){if(this.sourceSampleRate===null)this.sourceSampleRate=$.sampleRate,this.sourceNumberOfChannels=$.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup();let J=$.numberOfFrames*$.numberOfChannels;this.ensureTempBufferSize(J);let Y=$.allocationSize({planeIndex:0,format:"f32"}),j=new Float32Array(this.tempSourceBuffer.buffer,0,Y/4);$.copyTo(j,{planeIndex:0,format:"f32"});let X=$.timestamp-this.startTime,Z=$.numberOfFrames/this.sourceSampleRate,G=Math.min(X+Z,this.endTime-this.startTime),K=Math.floor(X*this.targetSampleRate),Q=Math.ceil(G*this.targetSampleRate);for(let q=K;q<Q;q++){if(q<this.bufferStartFrame)continue;while(q>=this.bufferStartFrame+this.bufferSizeInFrames)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let U=q-this.bufferStartFrame;H(U<this.bufferSizeInFrames);let N=(q/this.targetSampleRate-X)*this.sourceSampleRate,A=Math.floor(N),R=Math.ceil(N),z=N-A;for(let _=0;_<this.targetNumberOfChannels;_++){let L=0,M=0;if(A>=0&&A<$.numberOfFrames)L=this.channelMixer(j,A,_);if(R>=0&&R<$.numberOfFrames)M=this.channelMixer(j,R,_);let B=L+z*(M-L),F=U*this.targetNumberOfChannels+_;this.outputBuffer[F]+=B}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,U)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let $=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,J=new Float32Array($);J.set(this.outputBuffer.subarray(0,$));let Y=this.bufferStartFrame/this.targetSampleRate,j=new K0({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:Y,data:J});await this.onSample(j),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}}class Z7 extends z8{_resolvedDemuxer=null;constructor($){super({source:$,formats:[R2]})}async _ensureDemuxer(){if(!this._resolvedDemuxer)this._resolvedDemuxer=await this._getDemuxer();return this._resolvedDemuxer}async getVideoTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isVideoTrack()).map((j)=>this._wrapVideoTrackWithCuePoints(j,$))}async getPrimaryVideoTrack(){let $=await this._ensureDemuxer(),Y=(await this.getTracks()).find((j)=>j.isVideoTrack());if(!Y)return null;return this._wrapVideoTrackWithCuePoints(Y,$)}get videoTracks(){return this.getVideoTracks()}async getAudioTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isAudioTrack()).map((j)=>this._wrapAudioTrackWithCuePoints(j,$))}get audioTracks(){return this.getAudioTracks()}async getPrimaryAudioTrack(){let $=await this._ensureDemuxer(),Y=(await this.getTracks()).find((j)=>j.isAudioTrack());if(!Y)return null;return this._wrapAudioTrackWithCuePoints(Y,$)}async getSubtitleTracks(){let $=await this._ensureDemuxer();return(await this.getTracks()).filter((j)=>j.isSubtitleTrack()).map((j)=>this._wrapSubtitleTrackWithCuePoints(j,$))}get subtitleTracks(){return this.getSubtitleTracks()}_wrapVideoTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_wrapAudioTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_wrapSubtitleTrackWithCuePoints($,J){let Y=$,j=this._getCuePointsForTrack(J,$.id);return Y.getCuePoints=()=>j,Y}_getCuePointsForTrack($,J){let Y=this._findInternalTrack($,J);if(!Y)return[];return Y.cuePoints.map((j)=>({time:j.time/Y.segment.timestampFactor,trackId:j.trackId,clusterPosition:j.clusterPosition}))}_findInternalTrack($,J){for(let Y of $.segments){let j=Y.tracks.find((X)=>X.id===J);if(j)return j}return null}}x0();/*!
485
+ * Copyright (c) 2025-present, Vanilagy and contributors
486
+ *
487
+ * This Source Code Form is subject to the terms of the Mozilla Public
488
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
489
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
490
+ */export{$$ as splitSrtIntoCues,J$ as splitAssIntoCues,z7 as registerEncoder,R7 as registerDecoder,p6 as parseSrtTimestamp,m6 as parseAssTimestamp,n2 as getFirstEncodableVideoCodec,P7 as getFirstEncodableSubtitleCodec,O7 as getFirstEncodableAudioCodec,gJ as getEncodableVideoCodecs,kJ as getEncodableSubtitleCodecs,w7 as getEncodableCodecs,w8 as getEncodableAudioCodecs,l6 as formatSrtTimestamp,o6 as formatCuesToWebVTT,n6 as formatCuesToSrt,r6 as formatCuesToAss,d6 as formatAssTimestamp,F6 as canEncodeVideo,w6 as canEncodeSubtitles,B6 as canEncodeAudio,B7 as canEncode,$6 as WebMOutputFormat,C$ as WebMInputFormat,E$ as WaveInputFormat,oY as WavOutputFormat,jY as WEBM,ZY as WAVE,w1 as VideoSource,r8 as VideoSampleSource,X8 as VideoSampleSink,T8 as VideoSampleColorSpace,J0 as VideoSample,t2 as VIDEO_SAMPLE_PIXEL_FORMATS,j0 as VIDEO_CODECS,NY as UrlSource,B2 as TextSubtitleSource,P1 as Target,s8 as SubtitleSource,c$ as StreamTarget,x$ as StreamSource,i0 as Source,z0 as SUBTITLE_CODECS,I0 as RichImageData,RY as ReadableStreamSource,P$ as QuickTimeInputFormat,N0 as Quality,_7 as QUALITY_VERY_LOW,F7 as QUALITY_VERY_HIGH,M7 as QUALITY_MEDIUM,L7 as QUALITY_LOW,M6 as QUALITY_HIGH,YY as QTFF,o as PCM_AUDIO_CODECS,y0 as OutputFormat,Y6 as Output,rY as OggOutputFormat,T$ as OggInputFormat,GY as OGG,P2 as NullTarget,X1 as NON_PCM_AUDIO_CODECS,J6 as Mp4OutputFormat,O$ as Mp4InputFormat,nY as Mp3OutputFormat,D$ as Mp3InputFormat,e8 as MovOutputFormat,E2 as MkvOutputFormat,LY as MediaStreamVideoTrackSource,FY as MediaStreamAudioTrackSource,o8 as MediaSource,A2 as MatroskaInputFormat,Z7 as MatroskaInput,JY as MP4,XY as MP3,R2 as MATROSKA,T2 as IsobmffOutputFormat,N2 as IsobmffInputFormat,D0 as InputVideoTrack,g1 as InputTrack,p1 as InputSubtitleTrack,E0 as InputFormat,q0 as InputDisposedError,t as InputAudioTrack,z8 as Input,aY as FlacOutputFormat,y$ as FlacInputFormat,wY as FilePathTarget,AY as FilePathSource,QY as FLAC,_2 as EncodedVideoPacketSource,K1 as EncodedPacketSink,I as EncodedPacket,M2 as EncodedAudioPacketSource,d2 as CustomVideoEncoder,l2 as CustomVideoDecoder,c2 as CustomAudioEncoder,m2 as CustomAudioDecoder,QJ as Conversion,_Y as CanvasSource,u6 as CanvasSink,O2 as BufferTarget,WY as BufferSource,VY as BlobSource,k6 as BaseMediaSampleSink,sY as AviOutputFormat,b$ as AviInputFormat,O1 as AudioSource,i8 as AudioSampleSource,Z8 as AudioSampleSink,K0 as AudioSample,MY as AudioBufferSource,Q5 as AudioBufferSink,l1 as AttachedFile,iY as AdtsOutputFormat,v$ as AdtsInputFormat,qY as AVI,Z0 as AUDIO_CODECS,tY as ALL_TRACK_TYPES,Jj as ALL_FORMATS,KY as ADTS};