@remotion/media-parser 4.0.277 → 4.0.279

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 (365) hide show
  1. package/dist/aac-codecprivate.js +13 -6
  2. package/dist/add-avc-profile-to-track.js +9 -5
  3. package/dist/check-if-done.d.ts +2 -0
  4. package/dist/check-if-done.js +34 -0
  5. package/dist/combine-uint8-arrays.js +5 -1
  6. package/dist/containers/aac/parse-aac.js +27 -18
  7. package/dist/containers/aac/types.js +2 -1
  8. package/dist/containers/avc/codec-string.js +5 -1
  9. package/dist/containers/avc/color.js +9 -3
  10. package/dist/containers/avc/create-sps-pps-data.js +9 -5
  11. package/dist/containers/avc/interpret-sps.js +13 -7
  12. package/dist/containers/avc/key.js +5 -1
  13. package/dist/containers/avc/parse-avc.js +7 -3
  14. package/dist/containers/avc/sps-and-pps.js +5 -1
  15. package/dist/containers/flac/get-block-size.d.ts +1 -1
  16. package/dist/containers/flac/get-block-size.js +5 -1
  17. package/dist/containers/flac/get-channel-count.d.ts +2 -2
  18. package/dist/containers/flac/get-channel-count.js +5 -1
  19. package/dist/containers/flac/get-duration-from-flac.js +5 -1
  20. package/dist/containers/flac/get-metadata-from-flac.js +5 -1
  21. package/dist/containers/flac/get-sample-rate.d.ts +1 -1
  22. package/dist/containers/flac/get-sample-rate.js +5 -1
  23. package/dist/containers/flac/parse-flac-frame.d.ts +1 -1
  24. package/dist/containers/flac/parse-flac-frame.js +33 -23
  25. package/dist/containers/flac/parse-flac.d.ts +1 -1
  26. package/dist/containers/flac/parse-flac.js +19 -15
  27. package/dist/containers/flac/parse-header.d.ts +1 -1
  28. package/dist/containers/flac/parse-header.js +5 -1
  29. package/dist/containers/flac/parse-metadata.d.ts +1 -1
  30. package/dist/containers/flac/parse-metadata.js +5 -1
  31. package/dist/containers/flac/parse-streaminfo.d.ts +1 -1
  32. package/dist/containers/flac/parse-streaminfo.js +7 -3
  33. package/dist/containers/flac/parse-unknown-block.d.ts +1 -1
  34. package/dist/containers/flac/parse-unknown-block.js +5 -1
  35. package/dist/containers/flac/types.js +2 -1
  36. package/dist/containers/iso-base-media/base-media-box.js +2 -1
  37. package/dist/containers/iso-base-media/base-type.js +2 -1
  38. package/dist/containers/iso-base-media/esds/decoder-specific-config.d.ts +1 -1
  39. package/dist/containers/iso-base-media/esds/decoder-specific-config.js +5 -1
  40. package/dist/containers/iso-base-media/esds/esds-descriptors.d.ts +1 -1
  41. package/dist/containers/iso-base-media/esds/esds-descriptors.js +10 -5
  42. package/dist/containers/iso-base-media/esds/esds.d.ts +1 -1
  43. package/dist/containers/iso-base-media/esds/esds.js +7 -3
  44. package/dist/containers/iso-base-media/ftyp.d.ts +1 -1
  45. package/dist/containers/iso-base-media/ftyp.js +5 -1
  46. package/dist/containers/iso-base-media/get-actual-number-of-channels.js +8 -4
  47. package/dist/containers/iso-base-media/get-children.js +7 -3
  48. package/dist/containers/iso-base-media/get-keyframes.js +11 -7
  49. package/dist/containers/iso-base-media/get-moov-atom.js +26 -16
  50. package/dist/containers/iso-base-media/get-sample-positions-from-track.js +24 -20
  51. package/dist/containers/iso-base-media/get-seeking-from-mp4.d.ts +5 -0
  52. package/dist/containers/iso-base-media/get-seeking-from-mp4.js +56 -0
  53. package/dist/containers/iso-base-media/get-video-codec-from-iso-track.js +7 -3
  54. package/dist/containers/iso-base-media/make-track.js +34 -30
  55. package/dist/containers/iso-base-media/mdat/mdat.js +47 -34
  56. package/dist/containers/iso-base-media/mdhd.d.ts +1 -1
  57. package/dist/containers/iso-base-media/mdhd.js +5 -1
  58. package/dist/containers/iso-base-media/meta/hdlr.d.ts +1 -1
  59. package/dist/containers/iso-base-media/meta/hdlr.js +5 -1
  60. package/dist/containers/iso-base-media/meta/ilst.d.ts +1 -1
  61. package/dist/containers/iso-base-media/meta/ilst.js +5 -1
  62. package/dist/containers/iso-base-media/moov/moov.js +7 -3
  63. package/dist/containers/iso-base-media/mvhd.d.ts +1 -1
  64. package/dist/containers/iso-base-media/mvhd.js +11 -7
  65. package/dist/containers/iso-base-media/parse-boxes.js +9 -5
  66. package/dist/containers/iso-base-media/parse-icc-profile.js +8 -4
  67. package/dist/containers/iso-base-media/process-box.js +67 -63
  68. package/dist/containers/iso-base-media/stsd/av1c.d.ts +1 -1
  69. package/dist/containers/iso-base-media/stsd/av1c.js +5 -1
  70. package/dist/containers/iso-base-media/stsd/avcc.d.ts +1 -1
  71. package/dist/containers/iso-base-media/stsd/avcc.js +5 -1
  72. package/dist/containers/iso-base-media/stsd/colr.d.ts +1 -1
  73. package/dist/containers/iso-base-media/stsd/colr.js +7 -3
  74. package/dist/containers/iso-base-media/stsd/ctts.d.ts +1 -1
  75. package/dist/containers/iso-base-media/stsd/ctts.js +5 -1
  76. package/dist/containers/iso-base-media/stsd/hvcc.d.ts +1 -1
  77. package/dist/containers/iso-base-media/stsd/hvcc.js +7 -3
  78. package/dist/containers/iso-base-media/stsd/keys.d.ts +1 -1
  79. package/dist/containers/iso-base-media/stsd/keys.js +5 -1
  80. package/dist/containers/iso-base-media/stsd/mebx.js +7 -3
  81. package/dist/containers/iso-base-media/stsd/pasp.d.ts +1 -1
  82. package/dist/containers/iso-base-media/stsd/pasp.js +5 -1
  83. package/dist/containers/iso-base-media/stsd/samples.js +13 -8
  84. package/dist/containers/iso-base-media/stsd/stco.d.ts +1 -1
  85. package/dist/containers/iso-base-media/stsd/stco.js +5 -1
  86. package/dist/containers/iso-base-media/stsd/stsc.d.ts +1 -1
  87. package/dist/containers/iso-base-media/stsd/stsc.js +5 -1
  88. package/dist/containers/iso-base-media/stsd/stsd.js +7 -3
  89. package/dist/containers/iso-base-media/stsd/stss.d.ts +1 -1
  90. package/dist/containers/iso-base-media/stsd/stss.js +5 -1
  91. package/dist/containers/iso-base-media/stsd/stsz.d.ts +1 -1
  92. package/dist/containers/iso-base-media/stsd/stsz.js +5 -1
  93. package/dist/containers/iso-base-media/stsd/stts.d.ts +1 -1
  94. package/dist/containers/iso-base-media/stsd/stts.js +5 -1
  95. package/dist/containers/iso-base-media/tfdt.d.ts +1 -1
  96. package/dist/containers/iso-base-media/tfdt.js +5 -1
  97. package/dist/containers/iso-base-media/tfhd.d.ts +1 -1
  98. package/dist/containers/iso-base-media/tfhd.js +5 -1
  99. package/dist/containers/iso-base-media/tkhd.d.ts +1 -1
  100. package/dist/containers/iso-base-media/tkhd.js +8 -4
  101. package/dist/containers/iso-base-media/to-date.js +5 -1
  102. package/dist/containers/iso-base-media/trak/trak.js +7 -3
  103. package/dist/containers/iso-base-media/traversal.js +57 -33
  104. package/dist/containers/iso-base-media/trun.d.ts +1 -1
  105. package/dist/containers/iso-base-media/trun.js +5 -1
  106. package/dist/containers/iso-base-media/void-box.js +2 -1
  107. package/dist/containers/m3u/after-manifest-fetch.js +15 -11
  108. package/dist/containers/m3u/fetch-m3u8-stream.js +7 -3
  109. package/dist/containers/m3u/get-chunks.js +5 -1
  110. package/dist/containers/m3u/get-duration-from-m3u.js +8 -4
  111. package/dist/containers/m3u/get-playlist.js +12 -6
  112. package/dist/containers/m3u/get-streams.js +9 -3
  113. package/dist/containers/m3u/iterate-over-segment-files.js +15 -11
  114. package/dist/containers/m3u/parse-directive.js +10 -6
  115. package/dist/containers/m3u/parse-m3u-manifest.d.ts +1 -1
  116. package/dist/containers/m3u/parse-m3u-manifest.js +7 -3
  117. package/dist/containers/m3u/parse-m3u-media-directive.js +10 -5
  118. package/dist/containers/m3u/parse-m3u.js +11 -7
  119. package/dist/containers/m3u/parse-m3u8-text.js +7 -3
  120. package/dist/containers/m3u/parse-stream-inf.js +7 -2
  121. package/dist/containers/m3u/run-over-m3u.js +13 -9
  122. package/dist/containers/m3u/sample-sorter.js +8 -4
  123. package/dist/containers/m3u/select-stream.js +11 -4
  124. package/dist/containers/m3u/types.js +2 -1
  125. package/dist/containers/mp3/get-duration.js +9 -5
  126. package/dist/containers/mp3/get-frame-length.js +7 -2
  127. package/dist/containers/mp3/get-metadata-from-mp3.js +5 -1
  128. package/dist/containers/mp3/id3-v1.d.ts +1 -1
  129. package/dist/containers/mp3/id3-v1.js +5 -1
  130. package/dist/containers/mp3/id3.js +5 -1
  131. package/dist/containers/mp3/parse-mp3.js +11 -7
  132. package/dist/containers/mp3/parse-mpeg-header.js +28 -19
  133. package/dist/containers/mp3/samples-per-mpeg-file.js +5 -1
  134. package/dist/containers/riff/expect-riff-box.js +15 -11
  135. package/dist/containers/riff/get-duration.js +12 -7
  136. package/dist/containers/riff/get-tracks-from-avi.js +28 -20
  137. package/dist/containers/riff/is-movi.d.ts +1 -1
  138. package/dist/containers/riff/is-movi.js +5 -1
  139. package/dist/containers/riff/parse-avih.d.ts +1 -1
  140. package/dist/containers/riff/parse-avih.js +5 -1
  141. package/dist/containers/riff/parse-isft.d.ts +1 -1
  142. package/dist/containers/riff/parse-isft.js +5 -1
  143. package/dist/containers/riff/parse-list-box.js +7 -3
  144. package/dist/containers/riff/parse-movi.js +45 -31
  145. package/dist/containers/riff/parse-riff-body.js +13 -9
  146. package/dist/containers/riff/parse-riff-box.js +13 -9
  147. package/dist/containers/riff/parse-riff-header.js +5 -1
  148. package/dist/containers/riff/parse-riff.js +9 -5
  149. package/dist/containers/riff/parse-strf.d.ts +1 -1
  150. package/dist/containers/riff/parse-strf.js +5 -1
  151. package/dist/containers/riff/parse-strh.d.ts +1 -1
  152. package/dist/containers/riff/parse-strh.js +7 -3
  153. package/dist/containers/riff/parse-video-section.js +11 -7
  154. package/dist/containers/riff/riff-box.js +2 -1
  155. package/dist/containers/riff/timescale.js +4 -1
  156. package/dist/containers/riff/traversal.js +15 -7
  157. package/dist/containers/transport-stream/adts-header.js +10 -6
  158. package/dist/containers/transport-stream/boxes.js +2 -1
  159. package/dist/containers/transport-stream/discard-rest-of-packet.d.ts +1 -1
  160. package/dist/containers/transport-stream/discard-rest-of-packet.js +7 -2
  161. package/dist/containers/transport-stream/find-separator.js +4 -1
  162. package/dist/containers/transport-stream/get-tracks.js +16 -10
  163. package/dist/containers/transport-stream/handle-aac-packet.js +21 -12
  164. package/dist/containers/transport-stream/handle-avc-packet.js +31 -22
  165. package/dist/containers/transport-stream/next-pes-header-store.js +5 -1
  166. package/dist/containers/transport-stream/parse-packet.js +17 -13
  167. package/dist/containers/transport-stream/parse-pat.d.ts +1 -1
  168. package/dist/containers/transport-stream/parse-pat.js +10 -5
  169. package/dist/containers/transport-stream/parse-pes.d.ts +1 -1
  170. package/dist/containers/transport-stream/parse-pes.js +5 -1
  171. package/dist/containers/transport-stream/parse-pmt.d.ts +1 -1
  172. package/dist/containers/transport-stream/parse-pmt.js +7 -3
  173. package/dist/containers/transport-stream/parse-stream-packet.js +17 -13
  174. package/dist/containers/transport-stream/parse-transport-stream.js +9 -5
  175. package/dist/containers/transport-stream/process-stream-buffers.js +17 -12
  176. package/dist/containers/transport-stream/traversal.js +10 -4
  177. package/dist/containers/wav/get-duration-from-wav.js +8 -3
  178. package/dist/containers/wav/get-metadata-from-wav.js +5 -1
  179. package/dist/containers/wav/parse-data.js +9 -5
  180. package/dist/containers/wav/parse-fmt.js +7 -3
  181. package/dist/containers/wav/parse-header.js +5 -1
  182. package/dist/containers/wav/parse-id3.js +5 -1
  183. package/dist/containers/wav/parse-list.js +5 -1
  184. package/dist/containers/wav/parse-video-section.js +21 -12
  185. package/dist/containers/wav/parse-wav.js +19 -15
  186. package/dist/containers/wav/types.js +2 -1
  187. package/dist/containers/webm/allowed-partial-segments.js +4 -1
  188. package/dist/containers/webm/av1-codec-private.js +7 -3
  189. package/dist/containers/webm/color.js +10 -6
  190. package/dist/containers/webm/description.js +10 -6
  191. package/dist/containers/webm/get-ready-tracks.js +18 -13
  192. package/dist/containers/webm/get-sample-from-block.js +16 -12
  193. package/dist/containers/webm/make-track.js +48 -43
  194. package/dist/containers/webm/parse-ebml.js +35 -17
  195. package/dist/containers/webm/parse-webm-header.js +7 -3
  196. package/dist/containers/webm/segments/all-segments.js +173 -168
  197. package/dist/containers/webm/segments/block-simple-block-flags.d.ts +1 -1
  198. package/dist/containers/webm/segments/block-simple-block-flags.js +8 -4
  199. package/dist/containers/webm/segments/track-entry.js +5 -1
  200. package/dist/containers/webm/segments.js +13 -9
  201. package/dist/containers/webm/traversal.js +67 -37
  202. package/dist/convert-audio-or-video-sample.js +5 -1
  203. package/dist/download-and-parse-media.js +14 -10
  204. package/dist/emit-all-info.d.ts +3 -0
  205. package/dist/emit-all-info.js +30 -0
  206. package/dist/emit-audio-sample.d.ts +12 -0
  207. package/dist/emit-audio-sample.js +14 -0
  208. package/dist/emit-available-info.d.ts +2 -7
  209. package/dist/emit-available-info.js +70 -63
  210. package/dist/emitter.js +5 -1
  211. package/dist/errors.js +15 -6
  212. package/dist/esm/index.mjs +1921 -1618
  213. package/dist/esm/worker-server-entry.mjs +840 -537
  214. package/dist/esm/worker-web-entry.mjs +840 -537
  215. package/dist/esm/worker.mjs +4 -5
  216. package/dist/fetch.js +17 -1
  217. package/dist/fields.d.ts +61 -0
  218. package/dist/fields.js +2 -0
  219. package/dist/file-types/bmp.js +7 -3
  220. package/dist/file-types/detect-file-type.js +38 -24
  221. package/dist/file-types/index.js +26 -22
  222. package/dist/file-types/jpeg.js +9 -4
  223. package/dist/file-types/pdf.js +7 -3
  224. package/dist/file-types/png.js +9 -4
  225. package/dist/file-types/webp.js +7 -3
  226. package/dist/forward-controller.js +5 -1
  227. package/dist/get-audio-codec.js +38 -25
  228. package/dist/get-container.js +10 -5
  229. package/dist/get-dimensions.js +13 -8
  230. package/dist/get-duration.js +34 -27
  231. package/dist/get-fields-from-callbacks.d.ts +2 -1
  232. package/dist/get-fields-from-callbacks.js +5 -1
  233. package/dist/get-fps.js +34 -24
  234. package/dist/get-is-hdr.js +10 -5
  235. package/dist/get-keyframes.js +11 -6
  236. package/dist/get-location.js +9 -4
  237. package/dist/get-number-of-audio-channels.js +7 -2
  238. package/dist/get-sample-aspect-ratio.js +30 -17
  239. package/dist/get-sample-positions-from-lpcm.js +9 -5
  240. package/dist/get-sample-positions.js +5 -1
  241. package/dist/get-sample-rate.js +7 -2
  242. package/dist/get-seeking-info.d.ts +4 -0
  243. package/dist/get-seeking-info.js +22 -0
  244. package/dist/get-tracks.js +40 -29
  245. package/dist/get-video-codec.js +34 -26
  246. package/dist/has-all-info.d.ts +3 -5
  247. package/dist/has-all-info.js +39 -35
  248. package/dist/index.d.ts +53 -14
  249. package/dist/index.js +47 -32
  250. package/dist/init-video.d.ts +1 -4
  251. package/dist/init-video.js +29 -24
  252. package/dist/internal-parse-media.js +40 -199
  253. package/dist/is-audio-structure.js +5 -1
  254. package/dist/{buffer-iterator.d.ts → iterator/buffer-iterator.d.ts} +12 -15
  255. package/dist/{buffer-iterator.js → iterator/buffer-iterator.js} +16 -119
  256. package/dist/iterator/buffer-manager.d.ts +18 -0
  257. package/dist/iterator/buffer-manager.js +87 -0
  258. package/dist/iterator/offset-counter.d.ts +10 -0
  259. package/dist/iterator/offset-counter.js +31 -0
  260. package/dist/log.js +12 -8
  261. package/dist/make-hvc1-codec-strings.d.ts +1 -1
  262. package/dist/make-hvc1-codec-strings.js +5 -1
  263. package/dist/make-progress-object.d.ts +6 -0
  264. package/dist/make-progress-object.js +13 -0
  265. package/dist/media-parser-controller.d.ts +3 -0
  266. package/dist/media-parser-controller.js +15 -7
  267. package/dist/metadata/get-metadata.js +22 -17
  268. package/dist/metadata/metadata-from-iso.js +17 -12
  269. package/dist/metadata/metadata-from-matroska.js +7 -3
  270. package/dist/metadata/metadata-from-riff.js +7 -3
  271. package/dist/node-writer.js +17 -1
  272. package/dist/node.js +17 -1
  273. package/dist/options.d.ts +1 -61
  274. package/dist/options.js +2 -1
  275. package/dist/parse-loop.d.ts +8 -0
  276. package/dist/parse-loop.js +93 -0
  277. package/dist/parse-media-on-worker-entry.d.ts +2 -1
  278. package/dist/parse-media-on-worker-entry.js +7 -3
  279. package/dist/parse-media.js +12 -8
  280. package/dist/parse-result.js +2 -1
  281. package/dist/pause-signal.js +5 -1
  282. package/dist/perform-seek.d.ts +2 -7
  283. package/dist/perform-seek.js +29 -26
  284. package/dist/print-timings.d.ts +2 -0
  285. package/dist/print-timings.js +12 -0
  286. package/dist/readers/fetch/get-body-and-reader.js +5 -1
  287. package/dist/readers/fetch/resolve-url.js +5 -1
  288. package/dist/readers/from-fetch.js +21 -14
  289. package/dist/readers/from-node.js +23 -17
  290. package/dist/readers/from-web-file.js +13 -7
  291. package/dist/readers/reader.js +2 -1
  292. package/dist/readers/universal.js +16 -13
  293. package/dist/readers/web.js +12 -9
  294. package/dist/register-track.js +18 -9
  295. package/dist/remotion-license-acknowledge.js +8 -4
  296. package/dist/run-parse-iteration.d.ts +1 -4
  297. package/dist/run-parse-iteration.js +25 -24
  298. package/dist/samples-from-moof.js +10 -6
  299. package/dist/seek-backwards.d.ts +2 -0
  300. package/dist/seek-backwards.js +26 -0
  301. package/dist/seek-forwards.d.ts +2 -0
  302. package/dist/seek-forwards.js +28 -0
  303. package/dist/seek-signal.d.ts +22 -0
  304. package/dist/seek-signal.js +26 -0
  305. package/dist/seeking-info.d.ts +8 -0
  306. package/dist/seeking-info.js +2 -0
  307. package/dist/skip.js +5 -1
  308. package/dist/state/aac-state.js +5 -1
  309. package/dist/state/can-skip-tracks.d.ts +2 -2
  310. package/dist/state/can-skip-tracks.js +12 -4
  311. package/dist/state/emitted-fields.d.ts +1 -1
  312. package/dist/state/emitted-fields.js +5 -1
  313. package/dist/state/flac-state.js +5 -1
  314. package/dist/state/has-tracks-section.d.ts +2 -1
  315. package/dist/state/has-tracks-section.js +7 -3
  316. package/dist/state/images.js +5 -1
  317. package/dist/state/iso-base-media/cached-sample-positions.js +13 -8
  318. package/dist/state/iso-base-media/iso-state.js +9 -5
  319. package/dist/state/iso-base-media/moov-box.js +5 -1
  320. package/dist/state/keyframes.js +5 -1
  321. package/dist/state/m3u-state.js +9 -5
  322. package/dist/state/may-skip-video-data.js +7 -3
  323. package/dist/state/mp3.js +5 -1
  324. package/dist/state/need-samples-for-fields.d.ts +1 -1
  325. package/dist/state/need-samples-for-fields.js +5 -1
  326. package/dist/state/parser-state.d.ts +38 -8
  327. package/dist/state/parser-state.js +59 -35
  328. package/dist/state/riff.js +5 -1
  329. package/dist/state/sample-callbacks.d.ts +8 -3
  330. package/dist/state/sample-callbacks.js +27 -10
  331. package/dist/state/slow-duration-fps.js +5 -1
  332. package/dist/state/structure.js +5 -1
  333. package/dist/state/timings.d.ts +8 -0
  334. package/dist/state/timings.js +13 -0
  335. package/dist/state/transport-stream.js +7 -3
  336. package/dist/state/video-section.d.ts +1 -1
  337. package/dist/state/video-section.js +5 -1
  338. package/dist/state/webm.d.ts +1 -1
  339. package/dist/state/webm.js +9 -5
  340. package/dist/throttled-progress.d.ts +2 -3
  341. package/dist/throttled-progress.js +5 -1
  342. package/dist/truthy.js +4 -1
  343. package/dist/universal.js +5 -1
  344. package/dist/version.d.ts +1 -1
  345. package/dist/version.js +4 -1
  346. package/dist/web.js +5 -1
  347. package/dist/webcodec-sample-types.js +2 -1
  348. package/dist/work-on-seek-request.d.ts +2 -0
  349. package/dist/work-on-seek-request.js +43 -0
  350. package/dist/worker/forward-controller.js +7 -3
  351. package/dist/worker/serialize-error.js +19 -14
  352. package/dist/worker/worker-types.d.ts +2 -1
  353. package/dist/worker/worker-types.js +2 -1
  354. package/dist/worker-server-entry.js +5 -3
  355. package/dist/worker-server.js +16 -12
  356. package/dist/worker-web-entry.js +5 -3
  357. package/dist/worker.d.ts +3 -2
  358. package/dist/worker.js +11 -2
  359. package/dist/writers/node.js +23 -16
  360. package/dist/writers/writer.js +2 -1
  361. package/package.json +10 -10
  362. package/dist/parse-media-on-server-worker.d.ts +0 -2
  363. package/dist/parse-media-on-server-worker.js +0 -4
  364. package/dist/parse-media-on-web-worker.d.ts +0 -2
  365. package/dist/parse-media-on-web-worker.js +0 -4
@@ -1968,46 +1968,12 @@ var detectFileType = (data) => {
1968
1968
  return { type: "unknown" };
1969
1969
  };
1970
1970
 
1971
- // src/buffer-iterator.ts
1972
- class OffsetCounter {
1973
- #offset;
1974
- #discardedBytes;
1975
- constructor(initial) {
1976
- this.#offset = initial;
1977
- this.#discardedBytes = 0;
1978
- }
1979
- increment(amount) {
1980
- if (amount < 0) {
1981
- throw new Error("Cannot increment by a negative amount: " + amount);
1982
- }
1983
- this.#offset += amount;
1984
- }
1985
- getOffset() {
1986
- return this.#offset;
1987
- }
1988
- getDiscardedOffset() {
1989
- return this.#offset - this.#discardedBytes;
1990
- }
1991
- setDiscardedOffset(offset) {
1992
- this.#discardedBytes = offset;
1993
- }
1994
- getDiscardedBytes() {
1995
- return this.#discardedBytes;
1996
- }
1997
- discardBytes(amount) {
1998
- this.#discardedBytes += amount;
1999
- }
2000
- decrement(amount) {
2001
- if (amount < 0) {
2002
- throw new Error("Cannot decrement by a negative amount");
2003
- }
2004
- this.#offset -= amount;
2005
- }
2006
- }
2007
- var makeOffsetCounter = () => {
2008
- return new OffsetCounter(0);
2009
- };
2010
- var getArrayBufferIterator = (initialData, maxBytes) => {
1971
+ // src/iterator/buffer-manager.ts
1972
+ var bufferManager = ({
1973
+ initialData,
1974
+ maxBytes,
1975
+ counter
1976
+ }) => {
2011
1977
  const buf = new ArrayBuffer(initialData.byteLength, {
2012
1978
  maxByteLength: maxBytes === null ? initialData.byteLength : Math.min(maxBytes, 2 ** 32)
2013
1979
  });
@@ -2017,7 +1983,113 @@ var getArrayBufferIterator = (initialData, maxBytes) => {
2017
1983
  let uintArray = new Uint8Array(buf);
2018
1984
  uintArray.set(initialData);
2019
1985
  let view = new DataView(uintArray.buffer);
2020
- const counter = makeOffsetCounter();
1986
+ const destroy = () => {
1987
+ uintArray = new Uint8Array(0);
1988
+ buf.resize(0);
1989
+ };
1990
+ const flushBytesRead = (force, mode) => {
1991
+ const bytesToRemove = counter.getDiscardedOffset();
1992
+ if (bytesToRemove < 3000000 && !force) {
1993
+ return { bytesRemoved: 0, removedData: null };
1994
+ }
1995
+ if (view.byteLength < bytesToRemove && !force) {
1996
+ return { bytesRemoved: 0, removedData: null };
1997
+ }
1998
+ counter.discardBytes(bytesToRemove);
1999
+ const removedData = mode === "download" ? uintArray.slice(0, bytesToRemove) : null;
2000
+ const newData = uintArray.slice(bytesToRemove);
2001
+ uintArray.set(newData);
2002
+ buf.resize(newData.byteLength);
2003
+ view = new DataView(uintArray.buffer);
2004
+ return { bytesRemoved: bytesToRemove, removedData };
2005
+ };
2006
+ const skipTo = (offset) => {
2007
+ const becomesSmaller = offset < counter.getOffset();
2008
+ if (becomesSmaller) {
2009
+ const toDecrement = counter.getOffset() - offset;
2010
+ if (toDecrement > counter.getDiscardedOffset()) {
2011
+ throw new Error("Cannot count backwards, data has already been flushed");
2012
+ }
2013
+ counter.decrement(toDecrement);
2014
+ }
2015
+ const currentOffset = counter.getOffset();
2016
+ counter.increment(offset - currentOffset);
2017
+ };
2018
+ const addData = (newData) => {
2019
+ const oldLength = buf.byteLength;
2020
+ const newLength = oldLength + newData.byteLength;
2021
+ if (newLength < oldLength) {
2022
+ throw new Error("Cannot decrement size");
2023
+ }
2024
+ if (newLength > (maxBytes ?? Infinity)) {
2025
+ throw new Error(`Exceeded maximum byte length ${maxBytes} with ${newLength}`);
2026
+ }
2027
+ buf.resize(newLength);
2028
+ uintArray = new Uint8Array(buf);
2029
+ uintArray.set(newData, oldLength);
2030
+ view = new DataView(uintArray.buffer);
2031
+ };
2032
+ const replaceData = (newData, seekTo) => {
2033
+ buf.resize(newData.byteLength);
2034
+ uintArray = new Uint8Array(buf);
2035
+ uintArray.set(newData);
2036
+ view = new DataView(uintArray.buffer);
2037
+ counter.setDiscardedOffset(0);
2038
+ counter.decrement(counter.getOffset());
2039
+ counter.increment(seekTo);
2040
+ };
2041
+ return {
2042
+ view,
2043
+ uintArray,
2044
+ destroy,
2045
+ addData,
2046
+ skipTo,
2047
+ removeBytesRead: flushBytesRead,
2048
+ replaceData
2049
+ };
2050
+ };
2051
+
2052
+ // src/iterator/offset-counter.ts
2053
+ var makeOffsetCounter = (initial) => {
2054
+ let offset = initial;
2055
+ let discardedBytes = 0;
2056
+ return {
2057
+ getOffset: () => offset,
2058
+ discardBytes: (bytes) => {
2059
+ discardedBytes += bytes;
2060
+ },
2061
+ increment: (bytes) => {
2062
+ if (bytes < 0) {
2063
+ throw new Error("Cannot increment by a negative amount: " + bytes);
2064
+ }
2065
+ offset += bytes;
2066
+ },
2067
+ getDiscardedBytes: () => discardedBytes,
2068
+ setDiscardedOffset: (bytes) => {
2069
+ discardedBytes = bytes;
2070
+ },
2071
+ getDiscardedOffset: () => offset - discardedBytes,
2072
+ decrement: (bytes) => {
2073
+ if (bytes < 0) {
2074
+ throw new Error("Cannot decrement by a negative amount: " + bytes);
2075
+ }
2076
+ offset -= bytes;
2077
+ }
2078
+ };
2079
+ };
2080
+
2081
+ // src/iterator/buffer-iterator.ts
2082
+ var getArrayBufferIterator = (initialData, maxBytes) => {
2083
+ const counter = makeOffsetCounter(0);
2084
+ const {
2085
+ uintArray,
2086
+ view,
2087
+ addData,
2088
+ destroy,
2089
+ removeBytesRead,
2090
+ skipTo,
2091
+ replaceData
2092
+ } = bufferManager({ initialData, maxBytes, counter });
2021
2093
  const startCheckpoint = () => {
2022
2094
  const checkpoint = counter.getOffset();
2023
2095
  return {
@@ -2150,51 +2222,9 @@ var getArrayBufferIterator = (initialData, maxBytes) => {
2150
2222
  counter.increment(4);
2151
2223
  return val;
2152
2224
  };
2153
- const addData = (newData) => {
2154
- const oldLength = buf.byteLength;
2155
- const newLength = oldLength + newData.byteLength;
2156
- if (newLength < oldLength) {
2157
- throw new Error("Cannot decrement size");
2158
- }
2159
- if (newLength > (maxBytes ?? Infinity)) {
2160
- throw new Error(`Exceeded maximum byte length ${maxBytes} with ${newLength}`);
2161
- }
2162
- buf.resize(newLength);
2163
- const newArray = new Uint8Array(buf);
2164
- newArray.set(newData, oldLength);
2165
- uintArray = newArray;
2166
- view = new DataView(uintArray.buffer);
2167
- };
2168
2225
  const bytesRemaining = () => {
2169
2226
  return uintArray.byteLength - counter.getDiscardedOffset();
2170
2227
  };
2171
- const removeBytesRead = (force, mode) => {
2172
- const bytesToRemove = counter.getDiscardedOffset();
2173
- if (bytesToRemove < 3000000 && !force) {
2174
- return { bytesRemoved: 0, removedData: null };
2175
- }
2176
- if (view.byteLength < bytesToRemove && !force) {
2177
- return { bytesRemoved: 0, removedData: null };
2178
- }
2179
- counter.discardBytes(bytesToRemove);
2180
- const removedData = mode === "download" ? uintArray.slice(0, bytesToRemove) : null;
2181
- const newData = uintArray.slice(bytesToRemove);
2182
- uintArray.set(newData);
2183
- buf.resize(newData.byteLength);
2184
- view = new DataView(uintArray.buffer);
2185
- return { bytesRemoved: bytesToRemove, removedData };
2186
- };
2187
- const skipTo = (offset) => {
2188
- const becomesSmaller = offset < counter.getOffset();
2189
- if (!becomesSmaller) {
2190
- const currentOffset = counter.getOffset();
2191
- counter.increment(offset - currentOffset);
2192
- return;
2193
- }
2194
- buf.resize(0);
2195
- counter.decrement(counter.getOffset() - offset);
2196
- counter.setDiscardedOffset(offset);
2197
- };
2198
2228
  const readExpGolomb = () => {
2199
2229
  if (!bitReadingMode) {
2200
2230
  throw new Error("Not in bit reading mode");
@@ -2287,10 +2317,6 @@ var getArrayBufferIterator = (initialData, maxBytes) => {
2287
2317
  }
2288
2318
  return result;
2289
2319
  };
2290
- const destroy = () => {
2291
- uintArray = new Uint8Array(0);
2292
- buf.resize(0);
2293
- };
2294
2320
  return {
2295
2321
  startReadingBits,
2296
2322
  stopReadingBits,
@@ -2486,7 +2512,8 @@ var getArrayBufferIterator = (initialData, maxBytes) => {
2486
2512
  startCheckpoint,
2487
2513
  getFlacCodecNumber,
2488
2514
  readUntilLineEnd,
2489
- getSyncSafeInt32
2515
+ getSyncSafeInt32,
2516
+ replaceData
2490
2517
  };
2491
2518
  };
2492
2519
 
@@ -5078,22 +5105,237 @@ var hasSampleRate = (state) => {
5078
5105
  return state.callbacks.tracks.hasAllTracks();
5079
5106
  };
5080
5107
 
5108
+ // src/containers/iso-base-media/get-seeking-from-mp4.ts
5109
+ var getSeekingInfoFromMp4 = (state) => {
5110
+ const structure = state.getIsoStructure();
5111
+ const moovAtom = getMoovBoxFromState(state);
5112
+ const moofBoxes = getMoofBoxes(structure.boxes);
5113
+ if (!moovAtom) {
5114
+ return null;
5115
+ }
5116
+ return {
5117
+ type: "iso-base-media-seeking-info",
5118
+ moovBox: moovAtom,
5119
+ moofBoxes
5120
+ };
5121
+ };
5122
+ var getSeekingByteFromIsoBaseMedia = (info, time) => {
5123
+ const tracks2 = getTracksFromMoovBox(info.moovBox);
5124
+ const allTracks = [
5125
+ ...tracks2.videoTracks,
5126
+ ...tracks2.audioTracks,
5127
+ ...tracks2.otherTracks
5128
+ ];
5129
+ let byte = 0;
5130
+ let sam = null;
5131
+ for (const t of allTracks) {
5132
+ const { timescale: ts, type } = t;
5133
+ if (type !== "video") {
5134
+ continue;
5135
+ }
5136
+ const samplePositions = getSamplePositionsFromTrack({
5137
+ trakBox: t.trakBox,
5138
+ moofBoxes: info.moofBoxes
5139
+ });
5140
+ for (const sample of samplePositions) {
5141
+ const ctsInSeconds = sample.cts / ts;
5142
+ const dtsInSeconds = sample.dts / ts;
5143
+ if ((ctsInSeconds <= time || dtsInSeconds <= time) && byte <= sample.offset && type === "video" && sample.isKeyframe) {
5144
+ byte = sample.offset;
5145
+ sam = sample;
5146
+ }
5147
+ }
5148
+ }
5149
+ if (!sam) {
5150
+ throw new Error("No sample found");
5151
+ }
5152
+ return sam;
5153
+ };
5154
+
5155
+ // src/get-seeking-info.ts
5156
+ var getSeekingInfo = (state) => {
5157
+ const structure = state.getStructureOrNull();
5158
+ if (!structure) {
5159
+ return null;
5160
+ }
5161
+ if (structure.type === "iso-base-media") {
5162
+ return getSeekingInfoFromMp4(state);
5163
+ }
5164
+ return null;
5165
+ };
5166
+ var getSeekingByte = (info, time) => {
5167
+ if (info.type === "iso-base-media-seeking-info") {
5168
+ return getSeekingByteFromIsoBaseMedia(info, time).offset;
5169
+ }
5170
+ throw new Error(`Unknown seeking info type: ${info.type}`);
5171
+ };
5172
+
5173
+ // src/log.ts
5174
+ var logLevels = ["trace", "verbose", "info", "warn", "error"];
5175
+ var getNumberForLogLevel = (level) => {
5176
+ return logLevels.indexOf(level);
5177
+ };
5178
+ var isEqualOrBelowLogLevel = (currentLevel, level) => {
5179
+ return getNumberForLogLevel(currentLevel) <= getNumberForLogLevel(level);
5180
+ };
5181
+ var Log = {
5182
+ trace: (logLevel, ...args) => {
5183
+ if (isEqualOrBelowLogLevel(logLevel, "trace")) {
5184
+ return console.log(...args);
5185
+ }
5186
+ },
5187
+ verbose: (logLevel, ...args) => {
5188
+ if (isEqualOrBelowLogLevel(logLevel, "verbose")) {
5189
+ return console.log(...args);
5190
+ }
5191
+ },
5192
+ info: (logLevel, ...args) => {
5193
+ if (isEqualOrBelowLogLevel(logLevel, "info")) {
5194
+ return console.log(...args);
5195
+ }
5196
+ },
5197
+ warn: (logLevel, ...args) => {
5198
+ if (isEqualOrBelowLogLevel(logLevel, "warn")) {
5199
+ return console.warn(...args);
5200
+ }
5201
+ },
5202
+ error: (...args) => {
5203
+ return console.error(...args);
5204
+ }
5205
+ };
5206
+
5207
+ // src/seek-backwards.ts
5208
+ var seekBackwards = async (state, seekTo) => {
5209
+ const { iterator } = state;
5210
+ const howManyBytesNotYetDiscarded = iterator.counter.getDiscardedOffset();
5211
+ const howManyBytesWeCanGoBack = iterator.counter.getOffset() - howManyBytesNotYetDiscarded;
5212
+ if (iterator.counter.getOffset() - howManyBytesWeCanGoBack <= seekTo) {
5213
+ iterator.skipTo(seekTo);
5214
+ return;
5215
+ }
5216
+ const time = Date.now();
5217
+ Log.verbose(state.logLevel, `Seeking in video from position ${iterator.counter.getOffset()} -> ${seekTo}. Re-reading because this portion is not available`);
5218
+ const { reader: newReader } = await state.readerInterface.read({
5219
+ src: state.src,
5220
+ range: seekTo,
5221
+ controller: state.controller
5222
+ });
5223
+ iterator.replaceData(new Uint8Array([]), seekTo);
5224
+ Log.verbose(state.logLevel, `Re-reading took ${Date.now() - time}ms. New position: ${iterator.counter.getOffset()}`);
5225
+ state.currentReader = newReader;
5226
+ };
5227
+
5228
+ // src/seek-forwards.ts
5229
+ var seekForward = async (state, seekTo) => {
5230
+ const { iterator } = state;
5231
+ const alreadyHasBuffer = iterator.bytesRemaining() >= seekTo - iterator.counter.getOffset();
5232
+ Log.verbose(state.logLevel, `Performing seek from ${iterator.counter.getOffset()} to ${seekTo}`);
5233
+ if (alreadyHasBuffer) {
5234
+ iterator.skipTo(seekTo);
5235
+ Log.verbose(state.logLevel, `Already read ahead enough, skipping forward`);
5236
+ return state.currentReader;
5237
+ }
5238
+ const time = Date.now();
5239
+ Log.verbose(state.logLevel, `Skipping over video data from position ${iterator.counter.getOffset()} -> ${seekTo}. Re-reading because this portion is not available`);
5240
+ const { reader: newReader } = await state.readerInterface.read({
5241
+ src: state.src,
5242
+ range: seekTo,
5243
+ controller: state.controller
5244
+ });
5245
+ iterator.skipTo(seekTo);
5246
+ await state.discardReadBytes(true);
5247
+ Log.verbose(state.logLevel, `Re-reading took ${Date.now() - time}ms. New position: ${iterator.counter.getOffset()}`);
5248
+ state.currentReader = newReader;
5249
+ };
5250
+
5251
+ // src/perform-seek.ts
5252
+ var performSeek = async ({
5253
+ seekTo,
5254
+ state
5255
+ }) => {
5256
+ const { iterator, logLevel, mode, contentLength } = state;
5257
+ if (seekTo <= iterator.counter.getOffset() && mode === "download") {
5258
+ throw new Error(`Seeking backwards is not supported in parseAndDownloadMedia() mode. Current position: ${iterator.counter.getOffset()}, seekTo: ${seekTo}`);
5259
+ }
5260
+ if (seekTo > state.contentLength) {
5261
+ throw new Error(`Cannot seek beyond the end of the file: ${seekTo} > ${contentLength}`);
5262
+ }
5263
+ if (mode === "download") {
5264
+ Log.verbose(logLevel, `Skipping over video data from position ${iterator.counter.getOffset()} -> ${seekTo}. Fetching but not reading all the data inbetween because in download mode`);
5265
+ iterator.discard(seekTo - iterator.counter.getOffset());
5266
+ return;
5267
+ }
5268
+ await state.controller?._internals.checkForAbortAndPause();
5269
+ const alreadyAtByte = iterator.counter.getOffset() === seekTo;
5270
+ if (alreadyAtByte) {
5271
+ Log.verbose(logLevel, `Already at the desired position, seeking done`);
5272
+ return;
5273
+ }
5274
+ const skippingForward = seekTo > iterator.counter.getOffset();
5275
+ if (skippingForward) {
5276
+ await seekForward(state, seekTo);
5277
+ } else {
5278
+ await seekBackwards(state, seekTo);
5279
+ }
5280
+ await state.controller?._internals.checkForAbortAndPause();
5281
+ };
5282
+
5283
+ // src/work-on-seek-request.ts
5284
+ var turnSeekIntoByte = (seek2, state) => {
5285
+ if (seek2.type === "keyframe-before-time-in-seconds") {
5286
+ const seekingInfo = getSeekingInfo(state);
5287
+ if (!seekingInfo) {
5288
+ return {
5289
+ type: "valid-but-must-wait"
5290
+ };
5291
+ }
5292
+ const seekingByte = getSeekingByte(seekingInfo, seek2.time);
5293
+ return {
5294
+ type: "do-seek",
5295
+ byte: seekingByte
5296
+ };
5297
+ }
5298
+ throw new Error(`Cannot process seek request ${JSON.stringify(seek2)}`);
5299
+ };
5300
+ var workOnSeekRequest = async (state) => {
5301
+ const seek2 = state.controller._internals.seekSignal.getSeek();
5302
+ if (!seek2) {
5303
+ return;
5304
+ }
5305
+ Log.trace(state.logLevel, `Has seek request: ${JSON.stringify(seek2)}`);
5306
+ const resolution = turnSeekIntoByte(seek2, state);
5307
+ Log.trace(state.logLevel, `Seek action: ${JSON.stringify(resolution)}`);
5308
+ if (resolution.type === "do-seek") {
5309
+ await performSeek({ state, seekTo: resolution.byte });
5310
+ const { hasChanged } = state.controller._internals.seekSignal.clearSeekIfStillSame(seek2);
5311
+ if (hasChanged) {
5312
+ Log.trace(state.logLevel, `Seek request has changed while seeking, seeking again`);
5313
+ await workOnSeekRequest(state);
5314
+ }
5315
+ }
5316
+ if (resolution.type === "invalid") {
5317
+ throw new Error(`The seek request ${JSON.stringify(seek2)} cannot be processed`);
5318
+ }
5319
+ };
5320
+
5081
5321
  // src/emit-available-info.ts
5082
5322
  var emitAvailableInfo = async ({
5083
5323
  hasInfo,
5084
- callbacks,
5085
- state,
5086
- returnValue,
5087
- name,
5088
- mimeType,
5089
- fieldsInReturnValue
5324
+ state
5090
5325
  }) => {
5091
5326
  const keys = Object.keys(hasInfo);
5092
- const { emittedFields } = state;
5327
+ const {
5328
+ emittedFields,
5329
+ fieldsInReturnValue,
5330
+ returnValue,
5331
+ name,
5332
+ callbackFunctions
5333
+ } = state;
5093
5334
  for (const key of keys) {
5335
+ await workOnSeekRequest(state);
5094
5336
  if (key === "structure") {
5095
5337
  if (hasInfo.structure && !emittedFields.structure) {
5096
- await callbacks.onStructure?.(state.getStructure());
5338
+ await callbackFunctions.onStructure?.(state.getStructure());
5097
5339
  if (fieldsInReturnValue.structure) {
5098
5340
  returnValue.structure = state.getStructure();
5099
5341
  }
@@ -5105,7 +5347,7 @@ var emitAvailableInfo = async ({
5105
5347
  if (hasInfo.durationInSeconds) {
5106
5348
  if (!emittedFields.durationInSeconds) {
5107
5349
  const durationInSeconds = getDuration(state);
5108
- await callbacks.onDurationInSeconds?.(durationInSeconds);
5350
+ await callbackFunctions.onDurationInSeconds?.(durationInSeconds);
5109
5351
  if (fieldsInReturnValue.durationInSeconds) {
5110
5352
  returnValue.durationInSeconds = durationInSeconds;
5111
5353
  }
@@ -5117,7 +5359,7 @@ var emitAvailableInfo = async ({
5117
5359
  if (key === "slowDurationInSeconds") {
5118
5360
  if (hasInfo.slowDurationInSeconds && !emittedFields.slowDurationInSeconds) {
5119
5361
  const slowDurationInSeconds = getDuration(state) ?? state.slowDurationAndFps.getSlowDurationInSeconds();
5120
- await callbacks.onSlowDurationInSeconds?.(slowDurationInSeconds);
5362
+ await callbackFunctions.onSlowDurationInSeconds?.(slowDurationInSeconds);
5121
5363
  if (fieldsInReturnValue.slowDurationInSeconds) {
5122
5364
  returnValue.slowDurationInSeconds = slowDurationInSeconds;
5123
5365
  }
@@ -5129,7 +5371,7 @@ var emitAvailableInfo = async ({
5129
5371
  if (hasInfo.fps) {
5130
5372
  if (!emittedFields.fps) {
5131
5373
  const fps = getFps(state);
5132
- await callbacks.onFps?.(fps);
5374
+ await callbackFunctions.onFps?.(fps);
5133
5375
  if (fieldsInReturnValue.fps) {
5134
5376
  returnValue.fps = fps;
5135
5377
  }
@@ -5138,7 +5380,7 @@ var emitAvailableInfo = async ({
5138
5380
  if (!emittedFields.slowFps) {
5139
5381
  const fps = getFps(state);
5140
5382
  if (fps) {
5141
- await callbacks.onSlowFps?.(fps);
5383
+ await callbackFunctions.onSlowFps?.(fps);
5142
5384
  if (fieldsInReturnValue.slowFps) {
5143
5385
  returnValue.slowFps = fps;
5144
5386
  }
@@ -5151,7 +5393,7 @@ var emitAvailableInfo = async ({
5151
5393
  if (key === "slowFps") {
5152
5394
  if (hasInfo.slowFps && !emittedFields.slowFps) {
5153
5395
  const slowFps = state.slowDurationAndFps.getFps();
5154
- await callbacks.onSlowFps?.(slowFps);
5396
+ await callbackFunctions.onSlowFps?.(slowFps);
5155
5397
  if (fieldsInReturnValue.slowFps) {
5156
5398
  returnValue.slowFps = slowFps;
5157
5399
  }
@@ -5166,7 +5408,7 @@ var emitAvailableInfo = async ({
5166
5408
  height: dimensionsQueried.height,
5167
5409
  width: dimensionsQueried.width
5168
5410
  };
5169
- await callbacks.onDimensions?.(dimensions);
5411
+ await callbackFunctions.onDimensions?.(dimensions);
5170
5412
  if (fieldsInReturnValue.dimensions) {
5171
5413
  returnValue.dimensions = dimensions;
5172
5414
  }
@@ -5181,7 +5423,7 @@ var emitAvailableInfo = async ({
5181
5423
  height: dimensionsQueried.unrotatedHeight,
5182
5424
  width: dimensionsQueried.unrotatedWidth
5183
5425
  };
5184
- await callbacks.onUnrotatedDimensions?.(unrotatedDimensions);
5426
+ await callbackFunctions.onUnrotatedDimensions?.(unrotatedDimensions);
5185
5427
  if (fieldsInReturnValue.unrotatedDimensions) {
5186
5428
  returnValue.unrotatedDimensions = unrotatedDimensions;
5187
5429
  }
@@ -5193,7 +5435,7 @@ var emitAvailableInfo = async ({
5193
5435
  if (hasInfo.rotation && !emittedFields.rotation) {
5194
5436
  const dimensionsQueried = getDimensions(state);
5195
5437
  const rotation = dimensionsQueried?.rotation ?? 0;
5196
- await callbacks.onRotation?.(rotation);
5438
+ await callbackFunctions.onRotation?.(rotation);
5197
5439
  if (fieldsInReturnValue.rotation) {
5198
5440
  returnValue.rotation = rotation;
5199
5441
  }
@@ -5204,7 +5446,7 @@ var emitAvailableInfo = async ({
5204
5446
  if (key === "videoCodec") {
5205
5447
  if (!emittedFields.videoCodec && hasInfo.videoCodec) {
5206
5448
  const videoCodec = getVideoCodec(state);
5207
- await callbacks.onVideoCodec?.(videoCodec);
5449
+ await callbackFunctions.onVideoCodec?.(videoCodec);
5208
5450
  if (fieldsInReturnValue.videoCodec) {
5209
5451
  returnValue.videoCodec = videoCodec;
5210
5452
  }
@@ -5215,7 +5457,7 @@ var emitAvailableInfo = async ({
5215
5457
  if (key === "audioCodec") {
5216
5458
  if (!emittedFields.audioCodec && hasInfo.audioCodec) {
5217
5459
  const audioCodec = getAudioCodec(state);
5218
- await callbacks.onAudioCodec?.(audioCodec);
5460
+ await callbackFunctions.onAudioCodec?.(audioCodec);
5219
5461
  if (fieldsInReturnValue.audioCodec) {
5220
5462
  returnValue.audioCodec = audioCodec;
5221
5463
  }
@@ -5226,7 +5468,7 @@ var emitAvailableInfo = async ({
5226
5468
  if (key === "tracks") {
5227
5469
  if (!emittedFields.tracks && hasInfo.tracks) {
5228
5470
  const { videoTracks, audioTracks } = getTracks(state);
5229
- await callbacks.onTracks?.({ videoTracks, audioTracks });
5471
+ await callbackFunctions.onTracks?.({ videoTracks, audioTracks });
5230
5472
  if (fieldsInReturnValue.tracks) {
5231
5473
  returnValue.tracks = { videoTracks, audioTracks };
5232
5474
  }
@@ -5246,7 +5488,7 @@ var emitAvailableInfo = async ({
5246
5488
  }
5247
5489
  if (key === "size") {
5248
5490
  if (!emittedFields.size && hasInfo.size) {
5249
- await callbacks.onSize?.(state.contentLength);
5491
+ await callbackFunctions.onSize?.(state.contentLength);
5250
5492
  if (fieldsInReturnValue.size) {
5251
5493
  returnValue.size = state.contentLength;
5252
5494
  }
@@ -5256,9 +5498,9 @@ var emitAvailableInfo = async ({
5256
5498
  }
5257
5499
  if (key === "mimeType") {
5258
5500
  if (!emittedFields.mimeType && hasInfo.mimeType) {
5259
- await callbacks.onMimeType?.(mimeType);
5501
+ await callbackFunctions.onMimeType?.(state.mimeType);
5260
5502
  if (fieldsInReturnValue.mimeType) {
5261
- returnValue.mimeType = mimeType;
5503
+ returnValue.mimeType = state.mimeType;
5262
5504
  }
5263
5505
  emittedFields.mimeType = true;
5264
5506
  }
@@ -5266,7 +5508,7 @@ var emitAvailableInfo = async ({
5266
5508
  }
5267
5509
  if (key === "name") {
5268
5510
  if (!emittedFields.name && hasInfo.name) {
5269
- await callbacks.onName?.(name);
5511
+ await callbackFunctions.onName?.(name);
5270
5512
  if (fieldsInReturnValue.name) {
5271
5513
  returnValue.name = name;
5272
5514
  }
@@ -5277,7 +5519,7 @@ var emitAvailableInfo = async ({
5277
5519
  if (key === "isHdr") {
5278
5520
  if (!returnValue.isHdr && hasInfo.isHdr) {
5279
5521
  const isHdr = getIsHdr(state);
5280
- await callbacks.onIsHdr?.(isHdr);
5522
+ await callbackFunctions.onIsHdr?.(isHdr);
5281
5523
  if (fieldsInReturnValue.isHdr) {
5282
5524
  returnValue.isHdr = isHdr;
5283
5525
  }
@@ -5288,7 +5530,7 @@ var emitAvailableInfo = async ({
5288
5530
  if (key === "container") {
5289
5531
  if (!returnValue.container && hasInfo.container) {
5290
5532
  const container = getContainer(state.getStructure());
5291
- await callbacks.onContainer?.(container);
5533
+ await callbackFunctions.onContainer?.(container);
5292
5534
  if (fieldsInReturnValue.container) {
5293
5535
  returnValue.container = container;
5294
5536
  }
@@ -5299,7 +5541,7 @@ var emitAvailableInfo = async ({
5299
5541
  if (key === "metadata") {
5300
5542
  if (!emittedFields.metadata && hasInfo.metadata) {
5301
5543
  const metadata = getMetadata(state);
5302
- await callbacks.onMetadata?.(metadata);
5544
+ await callbackFunctions.onMetadata?.(metadata);
5303
5545
  if (fieldsInReturnValue.metadata) {
5304
5546
  returnValue.metadata = metadata;
5305
5547
  }
@@ -5310,7 +5552,7 @@ var emitAvailableInfo = async ({
5310
5552
  if (key === "location") {
5311
5553
  if (!emittedFields.location && hasInfo.location) {
5312
5554
  const location = getLocation(state);
5313
- await callbacks.onLocation?.(location);
5555
+ await callbackFunctions.onLocation?.(location);
5314
5556
  if (fieldsInReturnValue.location) {
5315
5557
  returnValue.location = location;
5316
5558
  }
@@ -5320,7 +5562,7 @@ var emitAvailableInfo = async ({
5320
5562
  }
5321
5563
  if (key === "slowKeyframes") {
5322
5564
  if (!emittedFields.slowKeyframes && hasInfo.slowKeyframes) {
5323
- await callbacks.onSlowKeyframes?.(state.keyframes.getKeyframes());
5565
+ await callbackFunctions.onSlowKeyframes?.(state.keyframes.getKeyframes());
5324
5566
  if (fieldsInReturnValue.slowKeyframes) {
5325
5567
  returnValue.slowKeyframes = state.keyframes.getKeyframes();
5326
5568
  }
@@ -5330,7 +5572,7 @@ var emitAvailableInfo = async ({
5330
5572
  }
5331
5573
  if (key === "slowNumberOfFrames") {
5332
5574
  if (!emittedFields.slowNumberOfFrames && hasInfo.slowNumberOfFrames) {
5333
- await callbacks.onSlowNumberOfFrames?.(state.slowDurationAndFps.getSlowNumberOfFrames());
5575
+ await callbackFunctions.onSlowNumberOfFrames?.(state.slowDurationAndFps.getSlowNumberOfFrames());
5334
5576
  if (fieldsInReturnValue.slowNumberOfFrames) {
5335
5577
  returnValue.slowNumberOfFrames = state.slowDurationAndFps.getSlowNumberOfFrames();
5336
5578
  }
@@ -5340,7 +5582,7 @@ var emitAvailableInfo = async ({
5340
5582
  }
5341
5583
  if (key === "slowAudioBitrate") {
5342
5584
  if (!emittedFields.slowAudioBitrate && hasInfo.slowAudioBitrate) {
5343
- await callbacks.onSlowAudioBitrate?.(state.slowDurationAndFps.getAudioBitrate());
5585
+ await callbackFunctions.onSlowAudioBitrate?.(state.slowDurationAndFps.getAudioBitrate());
5344
5586
  if (fieldsInReturnValue.slowAudioBitrate) {
5345
5587
  returnValue.slowAudioBitrate = state.slowDurationAndFps.getAudioBitrate();
5346
5588
  }
@@ -5350,7 +5592,7 @@ var emitAvailableInfo = async ({
5350
5592
  }
5351
5593
  if (key === "slowVideoBitrate") {
5352
5594
  if (!emittedFields.slowVideoBitrate && hasInfo.slowVideoBitrate) {
5353
- await callbacks.onSlowVideoBitrate?.(state.slowDurationAndFps.getVideoBitrate());
5595
+ await callbackFunctions.onSlowVideoBitrate?.(state.slowDurationAndFps.getVideoBitrate());
5354
5596
  if (fieldsInReturnValue.slowVideoBitrate) {
5355
5597
  returnValue.slowVideoBitrate = state.slowDurationAndFps.getVideoBitrate();
5356
5598
  }
@@ -5360,7 +5602,7 @@ var emitAvailableInfo = async ({
5360
5602
  }
5361
5603
  if (key === "keyframes") {
5362
5604
  if (!emittedFields.keyframes && hasInfo.keyframes) {
5363
- await callbacks.onKeyframes?.(getKeyframes(state));
5605
+ await callbackFunctions.onKeyframes?.(getKeyframes(state));
5364
5606
  if (fieldsInReturnValue.keyframes) {
5365
5607
  returnValue.keyframes = getKeyframes(state);
5366
5608
  }
@@ -5370,7 +5612,7 @@ var emitAvailableInfo = async ({
5370
5612
  }
5371
5613
  if (key === "images") {
5372
5614
  if (!emittedFields.images && hasInfo.images) {
5373
- await callbacks.onImages?.(state.images.images);
5615
+ await callbackFunctions.onImages?.(state.images.images);
5374
5616
  if (fieldsInReturnValue.images) {
5375
5617
  returnValue.images = state.images.images;
5376
5618
  }
@@ -5381,7 +5623,7 @@ var emitAvailableInfo = async ({
5381
5623
  if (key === "sampleRate") {
5382
5624
  if (!emittedFields.sampleRate && hasInfo.sampleRate) {
5383
5625
  const sampleRate = getSampleRate3(state);
5384
- await callbacks.onSampleRate?.(sampleRate);
5626
+ await callbackFunctions.onSampleRate?.(sampleRate);
5385
5627
  if (fieldsInReturnValue.sampleRate) {
5386
5628
  returnValue.sampleRate = sampleRate;
5387
5629
  }
@@ -5392,7 +5634,7 @@ var emitAvailableInfo = async ({
5392
5634
  if (key === "numberOfAudioChannels") {
5393
5635
  if (!emittedFields.numberOfAudioChannels && hasInfo.numberOfAudioChannels) {
5394
5636
  const numberOfAudioChannels = getNumberOfAudioChannels(state);
5395
- await callbacks.onNumberOfAudioChannels?.(numberOfAudioChannels);
5637
+ await callbackFunctions.onNumberOfAudioChannels?.(numberOfAudioChannels);
5396
5638
  if (fieldsInReturnValue.numberOfAudioChannels) {
5397
5639
  returnValue.numberOfAudioChannels = numberOfAudioChannels;
5398
5640
  }
@@ -5407,7 +5649,7 @@ var emitAvailableInfo = async ({
5407
5649
  originalSrc: state.src,
5408
5650
  readerInterface: state.readerInterface
5409
5651
  });
5410
- await callbacks.onM3uStreams?.(streams);
5652
+ await callbackFunctions.onM3uStreams?.(streams);
5411
5653
  if (fieldsInReturnValue.m3uStreams) {
5412
5654
  returnValue.m3uStreams = streams;
5413
5655
  }
@@ -5417,45 +5659,7 @@ var emitAvailableInfo = async ({
5417
5659
  }
5418
5660
  throw new Error(`Unhandled key: ${key}`);
5419
5661
  }
5420
- };
5421
-
5422
- // src/get-fields-from-callbacks.ts
5423
- var getFieldsFromCallback = ({
5424
- fields,
5425
- callbacks
5426
- }) => {
5427
- const newFields = {
5428
- audioCodec: Boolean(callbacks.onAudioCodec),
5429
- container: Boolean(callbacks.onContainer),
5430
- dimensions: Boolean(callbacks.onDimensions),
5431
- durationInSeconds: Boolean(callbacks.onDurationInSeconds),
5432
- fps: Boolean(callbacks.onFps),
5433
- internalStats: Boolean(callbacks.onInternalStats),
5434
- isHdr: Boolean(callbacks.onIsHdr),
5435
- location: Boolean(callbacks.onLocation),
5436
- metadata: Boolean(callbacks.onMetadata),
5437
- mimeType: Boolean(callbacks.onMimeType),
5438
- name: Boolean(callbacks.onName),
5439
- rotation: Boolean(callbacks.onRotation),
5440
- size: Boolean(callbacks.onSize),
5441
- structure: Boolean(callbacks.onStructure),
5442
- tracks: Boolean(callbacks.onTracks),
5443
- unrotatedDimensions: Boolean(callbacks.onUnrotatedDimensions),
5444
- videoCodec: Boolean(callbacks.onVideoCodec),
5445
- slowKeyframes: Boolean(callbacks.onSlowKeyframes),
5446
- slowDurationInSeconds: Boolean(callbacks.onSlowDurationInSeconds),
5447
- slowFps: Boolean(callbacks.onSlowFps),
5448
- slowNumberOfFrames: Boolean(callbacks.onSlowNumberOfFrames),
5449
- keyframes: Boolean(callbacks.onKeyframes),
5450
- images: Boolean(callbacks.onImages),
5451
- numberOfAudioChannels: Boolean(callbacks.onNumberOfAudioChannels),
5452
- sampleRate: Boolean(callbacks.onSampleRate),
5453
- slowAudioBitrate: Boolean(callbacks.onSlowAudioBitrate),
5454
- slowVideoBitrate: Boolean(callbacks.onSlowVideoBitrate),
5455
- m3uStreams: Boolean(callbacks.onM3uStreams),
5456
- ...fields
5457
- };
5458
- return newFields;
5662
+ await workOnSeekRequest(state);
5459
5663
  };
5460
5664
 
5461
5665
  // src/state/need-samples-for-fields.ts
@@ -5511,10 +5715,9 @@ var maySkipVideoData = ({ state }) => {
5511
5715
 
5512
5716
  // src/has-all-info.ts
5513
5717
  var getAvailableInfo = ({
5514
- fieldsToFetch,
5515
5718
  state
5516
5719
  }) => {
5517
- const keys = Object.entries(fieldsToFetch).filter(([, value]) => value);
5720
+ const keys = Object.entries(state.fields).filter(([, value]) => value);
5518
5721
  const structure = state.getStructureOrNull();
5519
5722
  const infos = keys.map(([_key]) => {
5520
5723
  const key = _key;
@@ -5590,12 +5793,8 @@ var getAvailableInfo = ({
5590
5793
  }
5591
5794
  return Object.fromEntries(entries);
5592
5795
  };
5593
- var hasAllInfo = ({
5594
- fields,
5595
- state
5596
- }) => {
5796
+ var hasAllInfo = ({ state }) => {
5597
5797
  const availableInfo = getAvailableInfo({
5598
- fieldsToFetch: fields ?? {},
5599
5798
  state
5600
5799
  });
5601
5800
  if (!Object.values(availableInfo).every(Boolean)) {
@@ -5610,38 +5809,27 @@ var hasAllInfo = ({
5610
5809
  return false;
5611
5810
  };
5612
5811
 
5613
- // src/log.ts
5614
- var logLevels = ["trace", "verbose", "info", "warn", "error"];
5615
- var getNumberForLogLevel = (level) => {
5616
- return logLevels.indexOf(level);
5617
- };
5618
- var isEqualOrBelowLogLevel = (currentLevel, level) => {
5619
- return getNumberForLogLevel(currentLevel) <= getNumberForLogLevel(level);
5620
- };
5621
- var Log = {
5622
- trace: (logLevel, ...args) => {
5623
- if (isEqualOrBelowLogLevel(logLevel, "trace")) {
5624
- return console.log(...args);
5812
+ // src/emit-all-info.ts
5813
+ var emitAllInfo = async (state) => {
5814
+ const allFields = Object.keys(state.fields).reduce((acc, key) => {
5815
+ if (state.fields?.[key]) {
5816
+ acc[key] = true;
5625
5817
  }
5626
- },
5627
- verbose: (logLevel, ...args) => {
5628
- if (isEqualOrBelowLogLevel(logLevel, "verbose")) {
5629
- return console.log(...args);
5630
- }
5631
- },
5632
- info: (logLevel, ...args) => {
5633
- if (isEqualOrBelowLogLevel(logLevel, "info")) {
5634
- return console.log(...args);
5635
- }
5636
- },
5637
- warn: (logLevel, ...args) => {
5638
- if (isEqualOrBelowLogLevel(logLevel, "warn")) {
5639
- return console.warn(...args);
5640
- }
5641
- },
5642
- error: (...args) => {
5643
- return console.error(...args);
5644
- }
5818
+ return acc;
5819
+ }, {});
5820
+ await emitAvailableInfo({
5821
+ hasInfo: allFields,
5822
+ state
5823
+ });
5824
+ };
5825
+ var triggerInfoEmit = async (state) => {
5826
+ const availableInfo = getAvailableInfo({
5827
+ state
5828
+ });
5829
+ await emitAvailableInfo({
5830
+ hasInfo: availableInfo,
5831
+ state
5832
+ });
5645
5833
  };
5646
5834
 
5647
5835
  // src/emitter.ts
@@ -5708,11 +5896,35 @@ var makePauseSignal = (emitter) => {
5708
5896
  };
5709
5897
  };
5710
5898
 
5899
+ // src/seek-signal.ts
5900
+ var makeSeekSignal = () => {
5901
+ let seek2;
5902
+ return {
5903
+ seek: (time) => {
5904
+ if (seek2) {
5905
+ throw new Error("Seek already requested, must wait");
5906
+ }
5907
+ seek2 = time;
5908
+ },
5909
+ getSeek() {
5910
+ return seek2;
5911
+ },
5912
+ clearSeekIfStillSame(previousSeek) {
5913
+ if (seek2 === previousSeek) {
5914
+ seek2 = undefined;
5915
+ return { hasChanged: false };
5916
+ }
5917
+ return { hasChanged: true };
5918
+ }
5919
+ };
5920
+ };
5921
+
5711
5922
  // src/media-parser-controller.ts
5712
5923
  var mediaParserController = () => {
5713
5924
  const abortController = new AbortController;
5714
5925
  const emitter = new MediaParserEmitter;
5715
5926
  const pauseSignal = makePauseSignal(emitter);
5927
+ const seekSignal = makeSeekSignal();
5716
5928
  const checkForAbortAndPause = async () => {
5717
5929
  if (abortController.signal.aborted) {
5718
5930
  throw new MediaParserAbortError("Aborted");
@@ -5724,73 +5936,53 @@ var mediaParserController = () => {
5724
5936
  abortController.abort(reason);
5725
5937
  emitter.dispatchAbort(reason);
5726
5938
  },
5939
+ _experimentalSeek: seekSignal.seek,
5727
5940
  pause: pauseSignal.pause,
5728
5941
  resume: pauseSignal.resume,
5729
5942
  addEventListener: emitter.addEventListener,
5730
5943
  removeEventListener: emitter.removeEventListener,
5731
5944
  _internals: {
5732
5945
  signal: abortController.signal,
5733
- checkForAbortAndPause
5946
+ checkForAbortAndPause,
5947
+ seekSignal
5734
5948
  }
5735
5949
  };
5736
5950
  };
5737
5951
 
5738
- // src/perform-seek.ts
5739
- var performSeek = async ({
5740
- seekTo,
5741
- state,
5742
- currentReader,
5743
- readerInterface,
5744
- src
5745
- }) => {
5746
- const { iterator, logLevel, controller, mode, contentLength } = state;
5747
- if (seekTo <= iterator.counter.getOffset()) {
5748
- throw new Error(`Seeking backwards is not supported. Current position: ${iterator.counter.getOffset()}, seekTo: ${seekTo}`);
5749
- }
5750
- if (seekTo > state.contentLength) {
5751
- throw new Error(`Unexpected seek: ${seekTo} > ${contentLength}`);
5952
+ // src/check-if-done.ts
5953
+ var checkIfDone = async (state) => {
5954
+ const startCheck = Date.now();
5955
+ const hasAll = hasAllInfo({
5956
+ state
5957
+ });
5958
+ state.timings.timeCheckingIfDone += Date.now() - startCheck;
5959
+ if (hasAll && state.mode === "query") {
5960
+ Log.verbose(state.logLevel, "Got all info, skipping to the end.");
5961
+ state.increaseSkippedBytes(state.contentLength - state.iterator.counter.getOffset());
5962
+ return true;
5752
5963
  }
5753
- if (iterator.counter.getOffset() + iterator.bytesRemaining() >= seekTo) {
5754
- Log.verbose(logLevel, `Skipping over video data from position ${iterator.counter.getOffset()} -> ${seekTo}. Data already fetched`);
5755
- iterator.discard(seekTo - iterator.counter.getOffset());
5756
- return currentReader;
5964
+ if (state.iterator.counter.getOffset() === state.contentLength) {
5965
+ if (state.getStructure().type === "m3u" && !state.m3u.getAllChunksProcessedOverall()) {
5966
+ return false;
5967
+ }
5968
+ Log.verbose(state.logLevel, "Reached end of file");
5969
+ await state.discardReadBytes(true);
5970
+ return true;
5757
5971
  }
5758
- if (mode === "download") {
5759
- Log.verbose(logLevel, `Skipping over video data from position ${iterator.counter.getOffset()} -> ${seekTo}. Fetching but not reading all the data inbetween because in download mode`);
5760
- iterator.discard(seekTo - iterator.counter.getOffset());
5761
- return currentReader;
5972
+ if (state.iterator.counter.getOffset() + state.iterator.bytesRemaining() === state.contentLength && state.errored) {
5973
+ Log.verbose(state.logLevel, "Reached end of file and errorred");
5974
+ return true;
5762
5975
  }
5763
- const time = Date.now();
5764
- Log.verbose(logLevel, `Skipping over video data from position ${iterator.counter.getOffset()} -> ${seekTo}. Re-reading because this portion is not available`);
5765
- currentReader.abort();
5766
- await controller?._internals.checkForAbortAndPause();
5767
- const { reader: newReader } = await readerInterface.read({
5768
- src,
5769
- range: seekTo,
5770
- controller
5771
- });
5772
- iterator.skipTo(seekTo);
5773
- await state.discardReadBytes(true);
5774
- Log.verbose(logLevel, `Re-reading took ${Date.now() - time}ms. New position: ${iterator.counter.getOffset()}`);
5775
- return newReader;
5976
+ return false;
5776
5977
  };
5777
5978
 
5778
- // src/remotion-license-acknowledge.ts
5779
- var warningShown = false;
5780
- var warnIfRemotionLicenseNotAcknowledged = ({
5781
- acknowledgeRemotionLicense,
5782
- logLevel,
5783
- apiName
5784
- }) => {
5785
- if (acknowledgeRemotionLicense) {
5786
- return;
5787
- }
5788
- if (warningShown) {
5789
- return;
5790
- }
5791
- warningShown = true;
5792
- Log.warn(logLevel, "Note: Some companies are required to obtain a license to use @remotion/media-parser. See: https://remotion.dev/license");
5793
- Log.warn(logLevel, `Pass \`acknowledgeRemotionLicense: true\` to \`${apiName}\` function to make this message disappear.`);
5979
+ // src/make-progress-object.ts
5980
+ var makeProgressObject = (state) => {
5981
+ return {
5982
+ bytes: state.iterator.counter.getOffset(),
5983
+ percentage: state.contentLength ? state.iterator.counter.getOffset() / state.contentLength : null,
5984
+ totalBytes: state.contentLength
5985
+ };
5794
5986
  };
5795
5987
 
5796
5988
  // src/convert-audio-or-video-sample.ts
@@ -5809,6 +6001,24 @@ var convertAudioOrVideoSampleToWebCodecsTimestamps = (sample, timescale) => {
5809
6001
  };
5810
6002
  };
5811
6003
 
6004
+ // src/emit-audio-sample.ts
6005
+ var emitAudioSample = async ({
6006
+ trackId,
6007
+ audioSample,
6008
+ state
6009
+ }) => {
6010
+ await state.callbacks.onAudioSample(trackId, audioSample);
6011
+ await workOnSeekRequest(state);
6012
+ };
6013
+ var emitVideoSample = async ({
6014
+ trackId,
6015
+ videoSample,
6016
+ state
6017
+ }) => {
6018
+ await state.callbacks.onVideoSample(trackId, videoSample);
6019
+ await workOnSeekRequest(state);
6020
+ };
6021
+
5812
6022
  // src/register-track.ts
5813
6023
  var registerVideoTrack = async ({
5814
6024
  state,
@@ -5828,6 +6038,7 @@ var registerVideoTrack = async ({
5828
6038
  }
5829
6039
  const callback = await state.onVideoTrack({ track, container });
5830
6040
  await state.callbacks.registerVideoSampleCallback(track.trackId, callback ?? null);
6041
+ await workOnSeekRequest(state);
5831
6042
  return callback;
5832
6043
  };
5833
6044
  var registerAudioTrack = async ({
@@ -5848,6 +6059,7 @@ var registerAudioTrack = async ({
5848
6059
  }
5849
6060
  const callback = await state.onAudioTrack({ track, container });
5850
6061
  await state.callbacks.registerAudioSampleCallback(track.trackId, callback ?? null);
6062
+ await workOnSeekRequest(state);
5851
6063
  return callback;
5852
6064
  };
5853
6065
  var registerVideoTrackWhenProfileIsAvailable = ({
@@ -5928,17 +6140,21 @@ var parseAac = async (state) => {
5928
6140
  const duration2 = 1024 / sampleRate;
5929
6141
  const { index } = state.aac.addSample({ offset: startOffset, size: frameLength });
5930
6142
  const timestamp = 1024 / sampleRate * index;
5931
- await state.callbacks.onAudioSample(0, convertAudioOrVideoSampleToWebCodecsTimestamps({
5932
- duration: duration2,
5933
- type: "key",
5934
- data,
5935
- offset: startOffset,
5936
- timescale: 1e6,
6143
+ await emitAudioSample({
5937
6144
  trackId: 0,
5938
- cts: timestamp,
5939
- dts: timestamp,
5940
- timestamp
5941
- }, 1));
6145
+ audioSample: convertAudioOrVideoSampleToWebCodecsTimestamps({
6146
+ duration: duration2,
6147
+ type: "key",
6148
+ data,
6149
+ offset: startOffset,
6150
+ timescale: 1e6,
6151
+ trackId: 0,
6152
+ cts: timestamp,
6153
+ dts: timestamp,
6154
+ timestamp
6155
+ }, 1),
6156
+ state
6157
+ });
5942
6158
  return Promise.resolve(null);
5943
6159
  };
5944
6160
 
@@ -6128,17 +6344,21 @@ var emitSample = async ({
6128
6344
  throw new Error("Cannot determine timestamp");
6129
6345
  }
6130
6346
  const timestamp = num * streamInfo.maximumBlockSize / streamInfo.sampleRate;
6131
- await state.callbacks.onAudioSample(0, convertAudioOrVideoSampleToWebCodecsTimestamps({
6132
- data,
6133
- duration: duration2,
6134
- cts: timestamp,
6135
- dts: timestamp,
6136
- timestamp,
6137
- type: "key",
6138
- offset,
6139
- timescale: 1e6,
6140
- trackId: 0
6141
- }, 1));
6347
+ await emitAudioSample({
6348
+ trackId: 0,
6349
+ audioSample: convertAudioOrVideoSampleToWebCodecsTimestamps({
6350
+ data,
6351
+ duration: duration2,
6352
+ cts: timestamp,
6353
+ dts: timestamp,
6354
+ timestamp,
6355
+ type: "key",
6356
+ offset,
6357
+ timescale: 1e6,
6358
+ trackId: 0
6359
+ }, 1),
6360
+ state
6361
+ });
6142
6362
  iterator.destroy();
6143
6363
  };
6144
6364
  var parseFlacFrame = async ({
@@ -6398,6 +6618,45 @@ var cachedSamplePositionsState = () => {
6398
6618
  };
6399
6619
  };
6400
6620
 
6621
+ // src/get-fields-from-callbacks.ts
6622
+ var getFieldsFromCallback = ({
6623
+ fields,
6624
+ callbacks
6625
+ }) => {
6626
+ const newFields = {
6627
+ audioCodec: Boolean(callbacks.onAudioCodec),
6628
+ container: Boolean(callbacks.onContainer),
6629
+ dimensions: Boolean(callbacks.onDimensions),
6630
+ durationInSeconds: Boolean(callbacks.onDurationInSeconds),
6631
+ fps: Boolean(callbacks.onFps),
6632
+ internalStats: Boolean(callbacks.onInternalStats),
6633
+ isHdr: Boolean(callbacks.onIsHdr),
6634
+ location: Boolean(callbacks.onLocation),
6635
+ metadata: Boolean(callbacks.onMetadata),
6636
+ mimeType: Boolean(callbacks.onMimeType),
6637
+ name: Boolean(callbacks.onName),
6638
+ rotation: Boolean(callbacks.onRotation),
6639
+ size: Boolean(callbacks.onSize),
6640
+ structure: Boolean(callbacks.onStructure),
6641
+ tracks: Boolean(callbacks.onTracks),
6642
+ unrotatedDimensions: Boolean(callbacks.onUnrotatedDimensions),
6643
+ videoCodec: Boolean(callbacks.onVideoCodec),
6644
+ slowKeyframes: Boolean(callbacks.onSlowKeyframes),
6645
+ slowDurationInSeconds: Boolean(callbacks.onSlowDurationInSeconds),
6646
+ slowFps: Boolean(callbacks.onSlowFps),
6647
+ slowNumberOfFrames: Boolean(callbacks.onSlowNumberOfFrames),
6648
+ keyframes: Boolean(callbacks.onKeyframes),
6649
+ images: Boolean(callbacks.onImages),
6650
+ numberOfAudioChannels: Boolean(callbacks.onNumberOfAudioChannels),
6651
+ sampleRate: Boolean(callbacks.onSampleRate),
6652
+ slowAudioBitrate: Boolean(callbacks.onSlowAudioBitrate),
6653
+ slowVideoBitrate: Boolean(callbacks.onSlowVideoBitrate),
6654
+ m3uStreams: Boolean(callbacks.onM3uStreams),
6655
+ ...fields
6656
+ };
6657
+ return newFields;
6658
+ };
6659
+
6401
6660
  // src/state/aac-state.ts
6402
6661
  var aacState = () => {
6403
6662
  const samples = [];
@@ -6747,7 +7006,7 @@ var needsTracksForField = ({
6747
7006
  structure
6748
7007
  }) => {
6749
7008
  if (field === "dimensions") {
6750
- if (structure.type === "riff") {
7009
+ if (structure?.type === "riff") {
6751
7010
  return false;
6752
7011
  }
6753
7012
  return true;
@@ -6773,7 +7032,10 @@ var makeCanSkipTracksState = ({
6773
7032
  }
6774
7033
  const keys = Object.keys(fields ?? {});
6775
7034
  const selectedKeys = keys.filter((k) => fields[k]);
6776
- return !selectedKeys.some((k) => needsTracksForField({ field: k, structure: structure.getStructure() }));
7035
+ return !selectedKeys.some((k) => needsTracksForField({
7036
+ field: k,
7037
+ structure: structure.getStructureOrNull()
7038
+ }));
6777
7039
  }
6778
7040
  };
6779
7041
  };
@@ -6820,7 +7082,9 @@ var sampleCallback = ({
6820
7082
  emittedFields,
6821
7083
  slowDurationAndFpsState,
6822
7084
  structure,
6823
- src
7085
+ src,
7086
+ seekSignal,
7087
+ logLevel
6824
7088
  }) => {
6825
7089
  const videoSampleCallbacks = {};
6826
7090
  const audioSampleCallbacks = {};
@@ -6857,7 +7121,11 @@ var sampleCallback = ({
6857
7121
  if (audioSample.data.length > 0) {
6858
7122
  samplesForTrack[trackId]++;
6859
7123
  if (callback) {
6860
- await callback(audioSample);
7124
+ if (seekSignal.getSeek()) {
7125
+ Log.verbose(logLevel, "Not emitting sample because seek is processing");
7126
+ } else {
7127
+ await callback(audioSample);
7128
+ }
6861
7129
  }
6862
7130
  }
6863
7131
  if (needsToIterateOverSamples({ emittedFields, fields })) {
@@ -6878,7 +7146,11 @@ var sampleCallback = ({
6878
7146
  samplesForTrack[trackId]++;
6879
7147
  const callback = videoSampleCallbacks[trackId];
6880
7148
  if (callback) {
6881
- await callback(videoSample);
7149
+ if (seekSignal.getSeek()) {
7150
+ Log.verbose(logLevel, "Not emitting sample because seek is processing");
7151
+ } else {
7152
+ await callback(videoSample);
7153
+ }
6882
7154
  }
6883
7155
  }
6884
7156
  if (needsToIterateOverSamples({
@@ -7074,6 +7346,17 @@ var structureState = () => {
7074
7346
  };
7075
7347
  };
7076
7348
 
7349
+ // src/state/timings.ts
7350
+ var timingsState = () => {
7351
+ return {
7352
+ timeIterating: 0,
7353
+ timeReadingData: 0,
7354
+ timeSeeking: 0,
7355
+ timeCheckingIfDone: 0,
7356
+ timeFreeingData: 0
7357
+ };
7358
+ };
7359
+
7077
7360
  // src/containers/transport-stream/next-pes-header-store.ts
7078
7361
  var makeNextPesHeaderStore = () => {
7079
7362
  let nextPesHeader = null;
@@ -7231,7 +7514,6 @@ var makeParserState = ({
7231
7514
  hasAudioTrackHandlers,
7232
7515
  hasVideoTrackHandlers,
7233
7516
  controller,
7234
- fields,
7235
7517
  onAudioTrack,
7236
7518
  onVideoTrack,
7237
7519
  contentLength,
@@ -7242,9 +7524,16 @@ var makeParserState = ({
7242
7524
  onDiscardedData,
7243
7525
  selectM3uStreamFn,
7244
7526
  selectM3uAssociatedPlaylistsFn,
7245
- mp4HeaderSegment
7527
+ mp4HeaderSegment,
7528
+ contentType,
7529
+ name,
7530
+ callbacks,
7531
+ fieldsInReturnValue,
7532
+ mimeType,
7533
+ initialReaderInstance
7246
7534
  }) => {
7247
7535
  let skippedBytes = 0;
7536
+ const returnValue = {};
7248
7537
  const iterator = getArrayBufferIterator(new Uint8Array([]), contentLength);
7249
7538
  const increaseSkippedBytes = (bytes) => {
7250
7539
  skippedBytes += bytes;
@@ -7255,6 +7544,8 @@ var makeParserState = ({
7255
7544
  const slowDurationAndFps = slowDurationAndFpsState();
7256
7545
  const mp3Info = makeMp3State();
7257
7546
  const images = imagesState();
7547
+ const timings = timingsState();
7548
+ const errored = null;
7258
7549
  const discardReadBytes = async (force) => {
7259
7550
  const { bytesRemoved, removedData } = iterator.removeBytesRead(force, mode);
7260
7551
  if (bytesRemoved) {
@@ -7264,6 +7555,10 @@ var makeParserState = ({
7264
7555
  await onDiscardedData(removedData);
7265
7556
  }
7266
7557
  };
7558
+ const fields = getFieldsFromCallback({
7559
+ fields: fieldsInReturnValue,
7560
+ callbacks
7561
+ });
7267
7562
  return {
7268
7563
  riff: riffSpecificState(),
7269
7564
  transportStream: transportStreamState(),
@@ -7273,6 +7568,7 @@ var makeParserState = ({
7273
7568
  aac: aacState(),
7274
7569
  flac: flacState(),
7275
7570
  m3u: m3uState(logLevel),
7571
+ timings,
7276
7572
  callbacks: sampleCallback({
7277
7573
  controller,
7278
7574
  hasAudioTrackHandlers,
@@ -7282,7 +7578,9 @@ var makeParserState = ({
7282
7578
  emittedFields,
7283
7579
  slowDurationAndFpsState: slowDurationAndFps,
7284
7580
  structure,
7285
- src
7581
+ src,
7582
+ seekSignal: controller._internals.seekSignal,
7583
+ logLevel
7286
7584
  }),
7287
7585
  getInternalStats: () => ({
7288
7586
  skippedBytes,
@@ -7309,7 +7607,15 @@ var makeParserState = ({
7309
7607
  discardReadBytes,
7310
7608
  selectM3uStreamFn,
7311
7609
  selectM3uAssociatedPlaylistsFn,
7312
- mp4HeaderSegment
7610
+ mp4HeaderSegment,
7611
+ contentType,
7612
+ name,
7613
+ returnValue,
7614
+ callbackFunctions: callbacks,
7615
+ fieldsInReturnValue,
7616
+ mimeType,
7617
+ errored,
7618
+ currentReader: initialReaderInstance
7313
7619
  };
7314
7620
  };
7315
7621
 
@@ -8965,9 +9271,6 @@ var getMoovAtom = async ({
8965
9271
  hasAudioTrackHandlers: false,
8966
9272
  hasVideoTrackHandlers: false,
8967
9273
  controller: state.controller,
8968
- fields: {
8969
- structure: true
8970
- },
8971
9274
  onAudioTrack: state.onAudioTrack ? async ({ track, container }) => {
8972
9275
  await registerAudioTrack({ state, track, container });
8973
9276
  return null;
@@ -8984,7 +9287,15 @@ var getMoovAtom = async ({
8984
9287
  onDiscardedData: null,
8985
9288
  selectM3uStreamFn: state.selectM3uStreamFn,
8986
9289
  selectM3uAssociatedPlaylistsFn: state.selectM3uAssociatedPlaylistsFn,
8987
- mp4HeaderSegment: state.mp4HeaderSegment
9290
+ mp4HeaderSegment: state.mp4HeaderSegment,
9291
+ callbacks: {},
9292
+ fieldsInReturnValue: {
9293
+ structure: true
9294
+ },
9295
+ contentType: null,
9296
+ mimeType: null,
9297
+ name: "",
9298
+ initialReaderInstance: reader
8988
9299
  });
8989
9300
  while (true) {
8990
9301
  const result = await reader.reader.read();
@@ -9056,17 +9367,21 @@ var parseMdatSection = async (state) => {
9056
9367
  const bytes = iterator.getSlice(samplesWithIndex.samplePosition.size);
9057
9368
  const { cts, dts, duration: duration2, isKeyframe, offset } = samplesWithIndex.samplePosition;
9058
9369
  if (samplesWithIndex.track.type === "audio") {
9059
- await state.callbacks.onAudioSample(samplesWithIndex.track.trackId, convertAudioOrVideoSampleToWebCodecsTimestamps({
9060
- data: bytes,
9061
- timestamp: cts,
9062
- duration: duration2,
9063
- cts,
9064
- dts,
9370
+ await emitAudioSample({
9065
9371
  trackId: samplesWithIndex.track.trackId,
9066
- type: isKeyframe ? "key" : "delta",
9067
- offset,
9068
- timescale: samplesWithIndex.track.timescale
9069
- }, samplesWithIndex.track.timescale));
9372
+ audioSample: convertAudioOrVideoSampleToWebCodecsTimestamps({
9373
+ data: bytes,
9374
+ timestamp: cts,
9375
+ duration: duration2,
9376
+ cts,
9377
+ dts,
9378
+ trackId: samplesWithIndex.track.trackId,
9379
+ type: isKeyframe ? "key" : "delta",
9380
+ offset,
9381
+ timescale: samplesWithIndex.track.timescale
9382
+ }, samplesWithIndex.track.timescale),
9383
+ state
9384
+ });
9070
9385
  }
9071
9386
  if (samplesWithIndex.track.type === "video") {
9072
9387
  const nalUnitType = bytes[4] & 31;
@@ -9075,17 +9390,21 @@ var parseMdatSection = async (state) => {
9075
9390
  const seiType = bytes[5];
9076
9391
  isRecoveryPoint = seiType === 6;
9077
9392
  }
9078
- await state.callbacks.onVideoSample(samplesWithIndex.track.trackId, convertAudioOrVideoSampleToWebCodecsTimestamps({
9079
- data: bytes,
9080
- timestamp: cts,
9081
- duration: duration2,
9082
- cts,
9083
- dts,
9393
+ await emitVideoSample({
9084
9394
  trackId: samplesWithIndex.track.trackId,
9085
- type: isKeyframe && !isRecoveryPoint ? "key" : "delta",
9086
- offset,
9087
- timescale: samplesWithIndex.track.timescale
9088
- }, samplesWithIndex.track.timescale));
9395
+ videoSample: convertAudioOrVideoSampleToWebCodecsTimestamps({
9396
+ data: bytes,
9397
+ timestamp: cts,
9398
+ duration: duration2,
9399
+ cts,
9400
+ dts,
9401
+ trackId: samplesWithIndex.track.trackId,
9402
+ type: isKeyframe && !isRecoveryPoint ? "key" : "delta",
9403
+ offset,
9404
+ timescale: samplesWithIndex.track.timescale
9405
+ }, samplesWithIndex.track.timescale),
9406
+ state
9407
+ });
9089
9408
  }
9090
9409
  return null;
9091
9410
  };
@@ -10123,16 +10442,20 @@ var parseMpegHeader = async ({
10123
10442
  const timeInSeconds = nthFrame * samplesPerFrame / sampleRate;
10124
10443
  const timestamp = Math.round(timeInSeconds * 1e6);
10125
10444
  const duration2 = Math.round(durationInSeconds * 1e6);
10126
- await state.callbacks.onAudioSample(0, {
10127
- data,
10128
- cts: timestamp,
10129
- dts: timestamp,
10130
- duration: duration2,
10131
- offset: initialOffset,
10132
- timescale: 1e6,
10133
- timestamp,
10445
+ await emitAudioSample({
10134
10446
  trackId: 0,
10135
- type: "key"
10447
+ audioSample: {
10448
+ data,
10449
+ cts: timestamp,
10450
+ dts: timestamp,
10451
+ duration: duration2,
10452
+ offset: initialOffset,
10453
+ timescale: 1e6,
10454
+ timestamp,
10455
+ trackId: 0,
10456
+ type: "key"
10457
+ },
10458
+ state
10136
10459
  });
10137
10460
  }
10138
10461
  };
@@ -10737,17 +11060,21 @@ var handleChunk = async ({
10737
11060
  await state.riff.onProfile({ pps: ppsProfile, sps: avcProfile });
10738
11061
  state.callbacks.tracks.setIsDone(state.logLevel);
10739
11062
  }
10740
- await state.callbacks.onVideoSample(trackId, convertAudioOrVideoSampleToWebCodecsTimestamps({
10741
- cts: timestamp,
10742
- dts: timestamp,
10743
- data,
10744
- duration: undefined,
10745
- timestamp,
11063
+ await emitVideoSample({
10746
11064
  trackId,
10747
- type: keyOrDelta,
10748
- offset,
10749
- timescale: samplesPerSecond
10750
- }, 1));
11065
+ videoSample: convertAudioOrVideoSampleToWebCodecsTimestamps({
11066
+ cts: timestamp,
11067
+ dts: timestamp,
11068
+ data,
11069
+ duration: undefined,
11070
+ timestamp,
11071
+ trackId,
11072
+ type: keyOrDelta,
11073
+ offset,
11074
+ timescale: samplesPerSecond
11075
+ }, 1),
11076
+ state
11077
+ });
10751
11078
  return;
10752
11079
  }
10753
11080
  const audioChunk = ckId.match(/^([0-9]{2})wb$/);
@@ -10759,17 +11086,21 @@ var handleChunk = async ({
10759
11086
  const timeInSec = nthSample / samplesPerSecond;
10760
11087
  const timestamp = timeInSec;
10761
11088
  const data = iterator.getSlice(ckSize);
10762
- await state.callbacks.onAudioSample(trackId, convertAudioOrVideoSampleToWebCodecsTimestamps({
10763
- cts: timestamp,
10764
- dts: timestamp,
10765
- data,
10766
- duration: undefined,
10767
- timestamp,
11089
+ await emitAudioSample({
10768
11090
  trackId,
10769
- type: "key",
10770
- offset,
10771
- timescale: samplesPerSecond
10772
- }, 1));
11091
+ audioSample: convertAudioOrVideoSampleToWebCodecsTimestamps({
11092
+ cts: timestamp,
11093
+ dts: timestamp,
11094
+ data,
11095
+ duration: undefined,
11096
+ timestamp,
11097
+ trackId,
11098
+ type: "key",
11099
+ offset,
11100
+ timescale: samplesPerSecond
11101
+ }, 1),
11102
+ state
11103
+ });
10773
11104
  }
10774
11105
  };
10775
11106
  var parseMovi = async ({
@@ -11231,7 +11562,11 @@ var handleAvcPacket = async ({
11231
11562
  offset,
11232
11563
  timescale: MPEG_TIMESCALE
11233
11564
  };
11234
- await state.callbacks.onVideoSample(programId, convertAudioOrVideoSampleToWebCodecsTimestamps(sample, MPEG_TIMESCALE));
11565
+ await emitVideoSample({
11566
+ trackId: programId,
11567
+ videoSample: convertAudioOrVideoSampleToWebCodecsTimestamps(sample, MPEG_TIMESCALE),
11568
+ state
11569
+ });
11235
11570
  };
11236
11571
 
11237
11572
  // src/containers/transport-stream/handle-aac-packet.ts
@@ -11279,7 +11614,11 @@ var handleAacPacket = async ({
11279
11614
  offset,
11280
11615
  timescale: MPEG_TIMESCALE
11281
11616
  };
11282
- await state.callbacks.onAudioSample(programId, convertAudioOrVideoSampleToWebCodecsTimestamps(sample, MPEG_TIMESCALE));
11617
+ await emitAudioSample({
11618
+ trackId: programId,
11619
+ audioSample: convertAudioOrVideoSampleToWebCodecsTimestamps(sample, MPEG_TIMESCALE),
11620
+ state
11621
+ });
11283
11622
  };
11284
11623
 
11285
11624
  // src/containers/transport-stream/process-stream-buffers.ts
@@ -11718,17 +12057,21 @@ var parseVideoSection2 = async ({
11718
12057
  const duration2 = toRead / (fmtBox.sampleRate * fmtBox.blockAlign);
11719
12058
  const timestamp = (offset - videoSection.start) / (fmtBox.sampleRate * fmtBox.blockAlign);
11720
12059
  const data = iterator.getSlice(toRead);
11721
- await state.callbacks.onAudioSample(0, convertAudioOrVideoSampleToWebCodecsTimestamps({
11722
- cts: timestamp,
11723
- dts: timestamp,
11724
- data,
11725
- duration: duration2,
11726
- timestamp,
12060
+ await emitAudioSample({
11727
12061
  trackId: 0,
11728
- type: "key",
11729
- offset,
11730
- timescale: 1e6
11731
- }, 1));
12062
+ audioSample: convertAudioOrVideoSampleToWebCodecsTimestamps({
12063
+ cts: timestamp,
12064
+ dts: timestamp,
12065
+ data,
12066
+ duration: duration2,
12067
+ timestamp,
12068
+ trackId: 0,
12069
+ type: "key",
12070
+ offset,
12071
+ timescale: 1e6
12072
+ }, 1),
12073
+ state
12074
+ });
11732
12075
  return null;
11733
12076
  };
11734
12077
 
@@ -12013,7 +12356,11 @@ var postprocessEbml = async ({
12013
12356
  if (ebml.type === "Block" || ebml.type === "SimpleBlock") {
12014
12357
  const sample = getSampleFromBlock(ebml, state, offset);
12015
12358
  if (sample.type === "video-sample") {
12016
- await state.callbacks.onVideoSample(sample.videoSample.trackId, sample.videoSample);
12359
+ await emitVideoSample({
12360
+ trackId: sample.videoSample.trackId,
12361
+ videoSample: sample.videoSample,
12362
+ state
12363
+ });
12017
12364
  return {
12018
12365
  type: "Block",
12019
12366
  value: new Uint8Array([]),
@@ -12021,7 +12368,11 @@ var postprocessEbml = async ({
12021
12368
  };
12022
12369
  }
12023
12370
  if (sample.type === "audio-sample") {
12024
- await state.callbacks.onAudioSample(sample.audioSample.trackId, sample.audioSample);
12371
+ await emitAudioSample({
12372
+ trackId: sample.audioSample.trackId,
12373
+ audioSample: sample.audioSample,
12374
+ state
12375
+ });
12025
12376
  return {
12026
12377
  type: "Block",
12027
12378
  value: new Uint8Array([]),
@@ -12048,7 +12399,11 @@ var postprocessEbml = async ({
12048
12399
  ...sample.partialVideoSample,
12049
12400
  type: hasReferenceBlock ? "delta" : "key"
12050
12401
  };
12051
- await state.callbacks.onVideoSample(sample.partialVideoSample.trackId, completeFrame);
12402
+ await emitVideoSample({
12403
+ trackId: sample.partialVideoSample.trackId,
12404
+ videoSample: completeFrame,
12405
+ state
12406
+ });
12052
12407
  }
12053
12408
  return {
12054
12409
  type: "BlockGroup",
@@ -12180,13 +12535,9 @@ var parseWebm = async (state) => {
12180
12535
  };
12181
12536
 
12182
12537
  // src/init-video.ts
12183
- var initVideo = async ({
12184
- state,
12185
- mimeType,
12186
- name,
12187
- contentLength
12188
- }) => {
12538
+ var initVideo = async ({ state }) => {
12189
12539
  const fileType = state.iterator.detectFileType();
12540
+ const { mimeType, name, contentLength } = state;
12190
12541
  if (fileType.type === "riff") {
12191
12542
  Log.verbose(state.logLevel, "Detected RIFF container");
12192
12543
  state.setStructure({
@@ -12329,10 +12680,7 @@ var initVideo = async ({
12329
12680
 
12330
12681
  // src/run-parse-iteration.ts
12331
12682
  var runParseIteration = async ({
12332
- state,
12333
- mimeType,
12334
- contentLength,
12335
- name
12683
+ state
12336
12684
  }) => {
12337
12685
  const structure = state.getStructureOrNull();
12338
12686
  if (structure && structure.type === "m3u") {
@@ -12343,10 +12691,7 @@ var runParseIteration = async ({
12343
12691
  }
12344
12692
  if (structure === null) {
12345
12693
  await initVideo({
12346
- state,
12347
- mimeType,
12348
- name,
12349
- contentLength
12694
+ state
12350
12695
  });
12351
12696
  return null;
12352
12697
  }
@@ -12377,6 +12722,116 @@ var runParseIteration = async ({
12377
12722
  return Promise.reject(new Error("Unknown video format " + structure));
12378
12723
  };
12379
12724
 
12725
+ // src/parse-loop.ts
12726
+ var fetchMoreData = async (state) => {
12727
+ await state.controller._internals.checkForAbortAndPause();
12728
+ const result = await state.currentReader.reader.read();
12729
+ if (result.value) {
12730
+ state.iterator.addData(result.value);
12731
+ }
12732
+ return result.done;
12733
+ };
12734
+ var parseLoop = async ({
12735
+ state,
12736
+ throttledState,
12737
+ onError
12738
+ }) => {
12739
+ let iterationWithThisOffset = 0;
12740
+ while (!await checkIfDone(state)) {
12741
+ await state.controller._internals.checkForAbortAndPause();
12742
+ await workOnSeekRequest(state);
12743
+ const offsetBefore = state.iterator.counter.getOffset();
12744
+ const readStart = Date.now();
12745
+ while (state.iterator.bytesRemaining() < 0) {
12746
+ const done = await fetchMoreData(state);
12747
+ if (done) {
12748
+ break;
12749
+ }
12750
+ }
12751
+ if (iterationWithThisOffset > 0 || state.iterator.bytesRemaining() <= 1e5) {
12752
+ await fetchMoreData(state);
12753
+ }
12754
+ state.timings.timeReadingData += Date.now() - readStart;
12755
+ throttledState.update?.(() => makeProgressObject(state));
12756
+ if (!state.errored) {
12757
+ Log.trace(state.logLevel, `Continuing parsing of file, currently at position ${state.iterator.counter.getOffset()}/${state.contentLength} (0x${state.iterator.counter.getOffset().toString(16)})`);
12758
+ if (iterationWithThisOffset > 300 && state.getStructure().type !== "m3u") {
12759
+ throw new Error("Infinite loop detected. The parser is not progressing. This is likely a bug in the parser. You can report this at https://remotion.dev/report and we will fix it as soon as possible.");
12760
+ }
12761
+ try {
12762
+ await triggerInfoEmit(state);
12763
+ const start = Date.now();
12764
+ await state.controller._internals.checkForAbortAndPause();
12765
+ const skip = await runParseIteration({
12766
+ state
12767
+ });
12768
+ state.timings.timeIterating += Date.now() - start;
12769
+ if (skip !== null) {
12770
+ state.increaseSkippedBytes(skip.skipTo - state.iterator.counter.getOffset());
12771
+ if (skip.skipTo === state.contentLength) {
12772
+ Log.verbose(state.logLevel, "Skipped to end of file, not fetching.");
12773
+ break;
12774
+ }
12775
+ const seekStart = Date.now();
12776
+ await performSeek({
12777
+ seekTo: skip.skipTo,
12778
+ state
12779
+ });
12780
+ state.timings.timeSeeking += Date.now() - seekStart;
12781
+ }
12782
+ } catch (e) {
12783
+ const err = await onError(e);
12784
+ if (!err.action) {
12785
+ throw new Error('onError was used but did not return an "action" field. See docs for this API on how to use onError.');
12786
+ }
12787
+ if (err.action === "fail") {
12788
+ throw e;
12789
+ }
12790
+ if (err.action === "download") {
12791
+ state.errored = e;
12792
+ Log.verbose(state.logLevel, "Error was handled by onError and deciding to continue.");
12793
+ }
12794
+ }
12795
+ }
12796
+ const timeFreeStart = Date.now();
12797
+ await state.discardReadBytes(false);
12798
+ state.timings.timeFreeingData += Date.now() - timeFreeStart;
12799
+ const didProgress = state.iterator.counter.getOffset() > offsetBefore;
12800
+ if (!didProgress) {
12801
+ iterationWithThisOffset++;
12802
+ } else {
12803
+ iterationWithThisOffset = 0;
12804
+ }
12805
+ }
12806
+ };
12807
+
12808
+ // src/print-timings.ts
12809
+ var printTimings = (state) => {
12810
+ Log.verbose(state.logLevel, `Time iterating over file: ${state.timings.timeIterating}ms`);
12811
+ Log.verbose(state.logLevel, `Time fetching data: ${state.timings.timeReadingData}ms`);
12812
+ Log.verbose(state.logLevel, `Time seeking: ${state.timings.timeSeeking}ms`);
12813
+ Log.verbose(state.logLevel, `Time checking if done: ${state.timings.timeCheckingIfDone}ms`);
12814
+ Log.verbose(state.logLevel, `Time freeing data: ${state.timings.timeFreeingData}ms`);
12815
+ };
12816
+
12817
+ // src/remotion-license-acknowledge.ts
12818
+ var warningShown = false;
12819
+ var warnIfRemotionLicenseNotAcknowledged = ({
12820
+ acknowledgeRemotionLicense,
12821
+ logLevel,
12822
+ apiName
12823
+ }) => {
12824
+ if (acknowledgeRemotionLicense) {
12825
+ return;
12826
+ }
12827
+ if (warningShown) {
12828
+ return;
12829
+ }
12830
+ warningShown = true;
12831
+ Log.warn(logLevel, "Note: Some companies are required to obtain a license to use @remotion/media-parser. See: https://remotion.dev/license");
12832
+ Log.warn(logLevel, `Pass \`acknowledgeRemotionLicense: true\` to \`${apiName}\` function to make this message disappear.`);
12833
+ };
12834
+
12380
12835
  // src/throttled-progress.ts
12381
12836
  var throttledStateUpdate = ({
12382
12837
  updateFn,
@@ -12462,11 +12917,6 @@ var internalParseMedia = async function({
12462
12917
  logLevel,
12463
12918
  apiName
12464
12919
  });
12465
- const fieldsInReturnValue = _fieldsInReturnValue ?? {};
12466
- const fields = getFieldsFromCallback({
12467
- fields: fieldsInReturnValue,
12468
- callbacks: more
12469
- });
12470
12920
  Log.verbose(logLevel, `Reading ${typeof src === "string" ? src : src instanceof URL ? src.toString() : src.name}`);
12471
12921
  const {
12472
12922
  reader: readerInstance,
@@ -12484,20 +12934,10 @@ var internalParseMedia = async function({
12484
12934
  }
12485
12935
  const hasAudioTrackHandlers = Boolean(onAudioTrack);
12486
12936
  const hasVideoTrackHandlers = Boolean(onVideoTrack);
12487
- if (!hasAudioTrackHandlers && !hasVideoTrackHandlers && Object.values(fields).every((v) => !v) && mode === "query") {
12488
- Log.warn(logLevel, new Error("Warning - No `fields` and no `on*` callbacks were passed to `parseMedia()`. Specify the data you would like to retrieve."));
12489
- }
12490
- let timeIterating = 0;
12491
- let timeReadingData = 0;
12492
- let timeSeeking = 0;
12493
- let timeCheckingIfDone = 0;
12494
- let timeFreeingData = 0;
12495
- let errored = null;
12496
12937
  const state = makeParserState({
12497
12938
  hasAudioTrackHandlers,
12498
12939
  hasVideoTrackHandlers,
12499
12940
  controller,
12500
- fields,
12501
12941
  onAudioTrack: onAudioTrack ?? null,
12502
12942
  onVideoTrack: onVideoTrack ?? null,
12503
12943
  contentLength,
@@ -12508,173 +12948,36 @@ var internalParseMedia = async function({
12508
12948
  onDiscardedData,
12509
12949
  selectM3uStreamFn,
12510
12950
  selectM3uAssociatedPlaylistsFn,
12511
- mp4HeaderSegment
12951
+ mp4HeaderSegment,
12952
+ contentType,
12953
+ name,
12954
+ callbacks: more,
12955
+ fieldsInReturnValue: _fieldsInReturnValue ?? {},
12956
+ mimeType: contentType,
12957
+ initialReaderInstance: readerInstance
12512
12958
  });
12513
- const { iterator } = state;
12514
- let currentReader = readerInstance;
12515
- const returnValue = {};
12516
- const moreFields = more;
12959
+ if (!hasAudioTrackHandlers && !hasVideoTrackHandlers && Object.values(state.fields).every((v) => !v) && mode === "query") {
12960
+ Log.warn(logLevel, new Error("Warning - No `fields` and no `on*` callbacks were passed to `parseMedia()`. Specify the data you would like to retrieve."));
12961
+ }
12517
12962
  const throttledState = throttledStateUpdate({
12518
12963
  updateFn: onParseProgressDoNotCallDirectly ?? null,
12519
12964
  everyMilliseconds: progressIntervalInMs ?? 100,
12520
12965
  controller,
12521
12966
  totalBytes: contentLength
12522
12967
  });
12523
- const triggerInfoEmit = async () => {
12524
- const availableInfo = getAvailableInfo({
12525
- fieldsToFetch: fields,
12526
- state
12527
- });
12528
- await emitAvailableInfo({
12529
- hasInfo: availableInfo,
12530
- callbacks: moreFields,
12531
- fieldsInReturnValue,
12532
- state,
12533
- returnValue,
12534
- name,
12535
- mimeType: contentType
12536
- });
12537
- };
12538
- const checkIfDone = async () => {
12539
- const startCheck = Date.now();
12540
- const hasAll = hasAllInfo({
12541
- fields,
12542
- state
12543
- });
12544
- timeCheckingIfDone += Date.now() - startCheck;
12545
- if (hasAll && mode === "query") {
12546
- Log.verbose(logLevel, "Got all info, skipping to the end.");
12547
- state.increaseSkippedBytes(contentLength - state.iterator.counter.getOffset());
12548
- return true;
12549
- }
12550
- if (state.iterator.counter.getOffset() === contentLength) {
12551
- if (state.getStructure().type === "m3u" && !state.m3u.getAllChunksProcessedOverall()) {
12552
- return false;
12553
- }
12554
- Log.verbose(logLevel, "Reached end of file");
12555
- await state.discardReadBytes(true);
12556
- return true;
12557
- }
12558
- if (state.iterator.counter.getOffset() + state.iterator.bytesRemaining() === contentLength && errored) {
12559
- Log.verbose(logLevel, "Reached end of file and errorred");
12560
- return true;
12561
- }
12562
- return false;
12563
- };
12564
- await triggerInfoEmit();
12565
- let iterationWithThisOffset = 0;
12566
- while (!await checkIfDone()) {
12567
- await controller._internals.checkForAbortAndPause();
12568
- const offsetBefore = iterator.counter.getOffset();
12569
- const fetchMoreData = async () => {
12570
- await controller._internals.checkForAbortAndPause();
12571
- const result = await currentReader.reader.read();
12572
- if (result.value) {
12573
- iterator.addData(result.value);
12574
- }
12575
- return result.done;
12576
- };
12577
- const readStart = Date.now();
12578
- while (iterator.bytesRemaining() < 0) {
12579
- const done = await fetchMoreData();
12580
- if (done) {
12581
- break;
12582
- }
12583
- }
12584
- const hasBigBuffer = iterator.bytesRemaining() > 1e5;
12585
- if (iterationWithThisOffset > 0 || !hasBigBuffer) {
12586
- await fetchMoreData();
12587
- }
12588
- timeReadingData += Date.now() - readStart;
12589
- throttledState.update?.(() => ({
12590
- bytes: iterator.counter.getOffset(),
12591
- percentage: contentLength ? iterator.counter.getOffset() / contentLength : null,
12592
- totalBytes: contentLength
12593
- }));
12594
- if (!errored) {
12595
- Log.trace(logLevel, `Continuing parsing of file, currently at position ${iterator.counter.getOffset()}/${contentLength} (0x${iterator.counter.getOffset().toString(16)})`);
12596
- if (iterationWithThisOffset > 300 && state.getStructure().type !== "m3u") {
12597
- throw new Error("Infinite loop detected. The parser is not progressing. This is likely a bug in the parser. You can report this at https://remotion.dev/report and we will fix it as soon as possible.");
12598
- }
12599
- try {
12600
- await triggerInfoEmit();
12601
- const start = Date.now();
12602
- await controller._internals.checkForAbortAndPause();
12603
- const skip = await runParseIteration({
12604
- state,
12605
- mimeType: contentType,
12606
- contentLength,
12607
- name
12608
- });
12609
- timeIterating += Date.now() - start;
12610
- if (skip !== null) {
12611
- state.increaseSkippedBytes(skip.skipTo - iterator.counter.getOffset());
12612
- if (skip.skipTo === contentLength) {
12613
- Log.verbose(logLevel, "Skipped to end of file, not fetching.");
12614
- break;
12615
- }
12616
- const seekStart = Date.now();
12617
- currentReader = await performSeek({
12618
- seekTo: skip.skipTo,
12619
- currentReader,
12620
- readerInterface,
12621
- src,
12622
- state
12623
- });
12624
- timeSeeking += Date.now() - seekStart;
12625
- }
12626
- } catch (e) {
12627
- const err = await onError(e);
12628
- if (!err.action) {
12629
- throw new Error('onError was used but did not return an "action" field. See docs for this API on how to use onError.');
12630
- }
12631
- if (err.action === "fail") {
12632
- throw e;
12633
- }
12634
- if (err.action === "download") {
12635
- errored = e;
12636
- Log.verbose(logLevel, "Error was handled by onError and deciding to continue.");
12637
- }
12638
- }
12639
- const didProgress = iterator.counter.getOffset() > offsetBefore;
12640
- if (!didProgress) {
12641
- iterationWithThisOffset++;
12642
- } else {
12643
- iterationWithThisOffset = 0;
12644
- }
12645
- }
12646
- const timeFreeStart = Date.now();
12647
- await state.discardReadBytes(false);
12648
- timeFreeingData += Date.now() - timeFreeStart;
12649
- }
12968
+ await triggerInfoEmit(state);
12969
+ await parseLoop({ state, throttledState, onError });
12650
12970
  Log.verbose(logLevel, "Finished parsing file");
12651
- await emitAvailableInfo({
12652
- hasInfo: Object.keys(fields).reduce((acc, key) => {
12653
- if (fields?.[key]) {
12654
- acc[key] = true;
12655
- }
12656
- return acc;
12657
- }, {}),
12658
- callbacks: moreFields,
12659
- fieldsInReturnValue,
12660
- state,
12661
- returnValue,
12662
- mimeType: contentType,
12663
- name
12664
- });
12665
- Log.verbose(logLevel, `Time iterating over file: ${timeIterating}ms`);
12666
- Log.verbose(logLevel, `Time fetching data: ${timeReadingData}ms`);
12667
- Log.verbose(logLevel, `Time seeking: ${timeSeeking}ms`);
12668
- Log.verbose(logLevel, `Time checking if done: ${timeCheckingIfDone}ms`);
12669
- Log.verbose(logLevel, `Time freeing data: ${timeFreeingData}ms`);
12670
- currentReader.abort();
12671
- iterator?.destroy();
12672
- state.callbacks.tracks.ensureHasTracksAtEnd(fields);
12971
+ await emitAllInfo(state);
12972
+ printTimings(state);
12973
+ state.currentReader.abort();
12974
+ state.iterator?.destroy();
12975
+ state.callbacks.tracks.ensureHasTracksAtEnd(state.fields);
12673
12976
  state.m3u.abortM3UStreamRuns();
12674
- if (errored) {
12675
- throw errored;
12977
+ if (state.errored) {
12978
+ throw state.errored;
12676
12979
  }
12677
- return returnValue;
12980
+ return state.returnValue;
12678
12981
  };
12679
12982
 
12680
12983
  // src/worker/forward-controller.ts