@torrent-tv/proxy 2.86.0 → 2.87.1

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 (385) hide show
  1. package/CHANGELOG.md +2142 -1915
  2. package/CLAUDE.md +322 -197
  3. package/assets/calibration/NOTICE.md +2 -2
  4. package/bin/cli.js +684 -616
  5. package/biome.json +409 -233
  6. package/docs/browser-proxy-contract.md +94 -0
  7. package/docs/container-architecture.md +218 -213
  8. package/docs/download-architecture.md +7 -7
  9. package/docs/encode-architecture.md +287 -11
  10. package/docs/encode-run-state.md +2 -2
  11. package/docs/logs.md +97 -97
  12. package/docs/{disk-architecture.md → storage-architecture.md} +107 -1
  13. package/openspec/changes/adaptive-bitrate/design.md +2 -2
  14. package/openspec/changes/adaptive-bitrate/proposal.md +1 -1
  15. package/openspec/changes/adaptive-bitrate/tasks.md +1 -1
  16. package/openspec/changes/chunked-request-bodies/design.md +1 -1
  17. package/openspec/changes/chunked-request-bodies/proposal.md +1 -1
  18. package/openspec/changes/chunked-request-bodies/tasks.md +1 -1
  19. package/openspec/changes/cold-start/design.md +1 -1
  20. package/openspec/changes/disk-cap/proposal.md +1 -1
  21. package/openspec/changes/proxy-observability/proposal.md +2 -2
  22. package/openspec/changes/track-selection/proposal.md +1 -1
  23. package/openspec/changes/transcode-quality/proposal.md +1 -1
  24. package/package.json +2 -2
  25. package/research/delivery-wedge-stand-ladder-2026-09-13.md +329 -329
  26. package/research/double-spawn-2026-09-10.md +171 -171
  27. package/routes/api/playback-plan/post.js +2 -2
  28. package/routes/api/sources/files/get.js +1 -1
  29. package/routes/api/sources/stats/get.js +1 -1
  30. package/routes/api/sources/warm/post.js +10 -3
  31. package/routes/api/subtitles/get.js +230 -230
  32. package/routes/api/transcode-sessions/fragment-far/post.js +3 -3
  33. package/routes/api/transcode-sessions/net-report/post.js +129 -94
  34. package/routes/api/transcode-sessions/post.js +160 -139
  35. package/routes/api/transcode-sessions/progress/get.js +3 -3
  36. package/routes/api/transcode-sessions/release/post.js +3 -3
  37. package/routes/api/transcode-sessions/seek/post.js +12 -3
  38. package/routes/stream/get.js +2 -2
  39. package/routes/transcode/audio-file/get.js +15 -6
  40. package/routes/transcode/audio-warm/get.js +9 -6
  41. package/routes/transcode/session-file/get.js +52 -268
  42. package/routes/transcode/variant-file/get.js +46 -7
  43. package/routes/transcode/variant-warm/get.js +19 -6
  44. package/scripts/render-run-graph.js +1 -1
  45. package/server.js +720 -465
  46. package/services/encode/CoverageMap.js +428 -428
  47. package/services/encode/CushionReport.js +345 -0
  48. package/services/encode/EncodeAdmission.js +332 -0
  49. package/services/{orchestrators → encode}/EncodeOrchestrator.js +307 -29
  50. package/services/encode/EncodeRun.js +16 -9
  51. package/services/encode/EncodeRuns.js +1229 -0
  52. package/services/encode/Encoder.js +18 -2
  53. package/services/encode/EncoderSelection.js +38 -0
  54. package/services/encode/LocalObservations.js +359 -0
  55. package/services/encode/NvencEncoder.js +5 -0
  56. package/services/encode/OutputOpening.js +755 -0
  57. package/services/encode/OutputTimes.js +579 -0
  58. package/services/encode/Renditions.js +2162 -0
  59. package/services/encode/RunProgress.js +84 -0
  60. package/services/encode/SoftwareEncoder.js +12 -7
  61. package/services/encode/args.js +402 -186
  62. package/services/encode/calibration.js +361 -0
  63. package/services/encode/contention.js +128 -128
  64. package/services/encode/encode-run-state.js +16 -20
  65. package/services/encode/fingerprint.js +322 -0
  66. package/services/{hwaccel.js → encode/hwaccel.js} +82 -42
  67. package/services/{learned-median.js → encode/learned-median.js} +11 -0
  68. package/services/encode/output/EncodedOutput.js +57 -0
  69. package/services/encode/output/Output.js +131 -0
  70. package/services/{output/LiveOutputs.js → encode/output/OutputCatalog.js} +141 -40
  71. package/services/encode/output/OutputSpec.js +390 -0
  72. package/services/{output → encode/output}/Timeline.js +12 -37
  73. package/services/encode/output/index.js +20 -0
  74. package/services/encode/output/ladder.js +32 -0
  75. package/services/{output → encode/output}/playlists.js +3 -0
  76. package/services/encode/output-key-format.js +21 -0
  77. package/services/encode/quality/EncodeCost.js +1083 -0
  78. package/services/encode/quality/HostLoad.js +525 -0
  79. package/services/encode/quality/HostTimings.js +249 -0
  80. package/services/encode/quality/OutputQualityState.js +28 -0
  81. package/services/encode/quality/QualityController.js +935 -0
  82. package/services/encode/quality/QualityOffer.js +416 -0
  83. package/services/encode/quality/drain-threat.js +47 -0
  84. package/services/encode/quality/link-budget.js +254 -0
  85. package/services/encode/quality/output-format.js +266 -0
  86. package/services/encode/quality/serving-output.js +216 -0
  87. package/services/encode/quality/visible-rung.js +57 -0
  88. package/services/encode/run-command.js +23 -20
  89. package/services/encode/run-inputs.js +42 -0
  90. package/services/{segment-formats → encode/segment-formats}/fmp4.js +63 -0
  91. package/services/{segment-formats → encode/segment-formats}/index.js +3 -3
  92. package/services/encode/segment-formats/init-compat.js +324 -0
  93. package/services/{segment-formats → encode/segment-formats}/mp4-boxes.js +8 -3
  94. package/services/encode/throughput.js +97 -0
  95. package/services/{orchestrators → media}/ContainerOrchestrator.js +45 -7
  96. package/services/media/KeyframeTables.js +316 -0
  97. package/services/{source → media}/SourceFile.js +7 -55
  98. package/services/{torrent-worker/subtitle-cues.js → media/SubtitleCues.js} +103 -132
  99. package/services/media/SubtitleOrchestrator.js +167 -0
  100. package/services/{audio-inventory.js → media/audio-inventory.js} +7 -1
  101. package/services/{container → media/container}/AviContainer.js +266 -266
  102. package/services/{container → media/container}/Container.js +596 -601
  103. package/services/media/container/ContainerFactory.js +56 -0
  104. package/services/media/container/KeyframeTable.js +272 -0
  105. package/services/{container → media/container}/MatroskaContainer.js +1485 -1485
  106. package/services/{container → media/container}/Mp4Container.js +1244 -1244
  107. package/services/{container → media/container}/SubtitleFileContainer.js +322 -322
  108. package/services/media/keyframe-probe.js +157 -0
  109. package/services/media/media-info-probe.js +93 -0
  110. package/services/{playback-planner.js → media/playback-planner.js} +82 -39
  111. package/services/{tracks → media/tracks}/AudioTrack.js +131 -131
  112. package/services/{tracks → media/tracks}/language-detect.js +174 -174
  113. package/services/server/OutputLifecycle.js +418 -0
  114. package/services/server/SegmentServing.js +1146 -0
  115. package/services/server/ViewerRequests.js +522 -0
  116. package/services/server/controllers/PlaybackController.js +36 -0
  117. package/services/{controllers → server/controllers}/SubtitleController.js +17 -33
  118. package/services/server/http-responses.js +60 -0
  119. package/services/server/transcode-session-files.js +325 -0
  120. package/services/server/wire-outputs.js +983 -0
  121. package/services/storage/Diagnostics.js +202 -0
  122. package/services/storage/MachineBudget.js +235 -0
  123. package/services/{piece-store → storage}/allowance.js +107 -107
  124. package/services/{core-dumps.js → storage/core-dumps.js} +1 -1
  125. package/services/{files → storage/files}/CompletedFiles.js +116 -1
  126. package/services/{disk → storage}/free.js +33 -0
  127. package/services/storage/machine-memory.js +56 -0
  128. package/services/{memory-report.js → storage/memory-report.js} +575 -596
  129. package/services/{piece-store → storage/piece-store}/piece-disk-store.js +0 -7
  130. package/services/{piece-store → storage/piece-store}/shared-piece-store.js +28 -21
  131. package/services/{encode → storage/segment-store}/SegmentStore.js +395 -8
  132. package/services/storage/wire.js +175 -0
  133. package/services/{download → torrent/download}/SwarmSelection.js +2 -2
  134. package/services/{download → torrent/download}/registry.js +2 -2
  135. package/services/torrent/files.js +1 -1
  136. package/services/torrent/piece-store-of.js +29 -0
  137. package/services/{torrent-pool.js → torrent/torrent-pool.js} +26 -119
  138. package/services/{torrent-worker → torrent/worker}/background-fill.js +2 -2
  139. package/services/{torrent-worker → torrent/worker}/channel.js +271 -250
  140. package/services/{torrent-worker → torrent/worker}/client.js +77 -58
  141. package/services/torrent/worker/held-bytes.js +155 -0
  142. package/services/{torrent-worker → torrent/worker}/install-webrtc-shim.js +1 -1
  143. package/services/{torrent-worker → torrent/worker}/piece-reader.js +21 -30
  144. package/services/{torrent-worker → torrent/worker}/pool-adapter.js +101 -137
  145. package/services/{torrent-worker → torrent/worker}/protocol.js +26 -30
  146. package/services/torrent/worker/resume-warm.js +107 -0
  147. package/services/{torrent-worker → torrent/worker}/webrtc-shim.js +2 -2
  148. package/services/{torrent-worker → torrent/worker}/worker.js +68 -159
  149. package/services/{data-channel-handler.js → transport/data-channel-handler.js} +1356 -1356
  150. package/services/{delivery-probe.js → transport/delivery-probe.js} +842 -842
  151. package/services/{health-collector.js → transport/health-collector.js} +6 -35
  152. package/services/{packet-witness.js → transport/packet-witness.js} +808 -784
  153. package/services/{port-mapper.js → transport/port-mapper.js} +1 -1
  154. package/services/{usrsctp-state.js → transport/usrsctp-state.js} +1 -1
  155. package/services/{webrtc-manager.js → transport/webrtc-manager.js} +1 -1
  156. package/services/viewer/Assignments.js +340 -0
  157. package/services/{priority → viewer}/PriorityMap.js +390 -390
  158. package/services/{priority → viewer}/PriorityOrchestrator.js +325 -320
  159. package/services/viewer/Viewer.js +657 -483
  160. package/services/viewer/Viewers.js +368 -257
  161. package/services/viewer/active-output.js +37 -54
  162. package/services/viewer/audio-start.js +4 -3
  163. package/services/viewer/buffer-trend.js +81 -0
  164. package/services/viewer/choices.js +647 -0
  165. package/services/viewer/positions.js +126 -120
  166. package/services/viewer/report-intake.js +46 -45
  167. package/test/asset-paths.test.js +28 -0
  168. package/test/audio-inventory.test.js +3 -3
  169. package/test/audio-track-bitrate.test.js +40 -0
  170. package/test/auto-quality-step.test.js +707 -515
  171. package/test/available-share.test.js +1 -1
  172. package/test/background-fill.test.js +1 -1
  173. package/test/client-log-file.test.js +110 -110
  174. package/test/completed-files.test.js +1 -1
  175. package/test/concurrent-cost.test.js +13 -3
  176. package/test/container-media-info.test.js +3 -3
  177. package/test/core-dumps.test.js +1 -1
  178. package/test/coverage-follows-the-disk.test.js +46 -9
  179. package/test/cue-push-carries-what-the-walk-found.test.js +58 -0
  180. package/test/cut-times-timeline.test.js +2 -2
  181. package/test/cuts-follow-published-grid.test.js +9 -8
  182. package/test/data-channel-frame.test.js +1 -1
  183. package/test/dead-torrent-handle.test.js +1 -1
  184. package/test/declared-rates.test.js +2 -2
  185. package/test/declared-tracks.test.js +2 -2
  186. package/test/decode-cost-fit.test.js +1 -1
  187. package/test/decode-cost.test.js +34 -25
  188. package/test/delivery-probe.test.js +1 -1
  189. package/test/demand-register.test.js +4 -4
  190. package/test/dht-bootstrap.test.js +1 -1
  191. package/test/drain-threat.test.js +65 -0
  192. package/test/duplicate-add.test.js +1 -1
  193. package/test/encode-admission.test.js +146 -0
  194. package/test/encode-cost.test.js +199 -10
  195. package/test/encode-orchestrator.test.js +39 -1
  196. package/test/encode-plan-viewers.test.js +2 -2
  197. package/test/encode-run.test.js +2 -2
  198. package/test/encode-slope.test.js +1 -1
  199. package/test/encoded-output.test.js +39 -0
  200. package/test/encoder-readings.test.js +1 -1
  201. package/test/every-claimant-is-told-its-share.test.js +152 -0
  202. package/test/failed-encoder-still-serves-what-exists.test.js +354 -0
  203. package/test/failed-start-breaker.test.js +81 -30
  204. package/test/fastest-wires.test.js +1 -1
  205. package/test/ffmpeg-stream-counts.test.js +1 -1
  206. package/test/file-edges.test.js +3 -3
  207. package/test/fmp4-self-contained.test.js +1 -1
  208. package/test/fmp4-timestamps.test.js +1 -1
  209. package/test/fmp4-track-completeness.test.js +1 -1
  210. package/test/format-keyed-outputs.test.js +78 -0
  211. package/test/health-metrics.test.js +3 -2
  212. package/test/held-request-width.test.js +22 -23
  213. package/test/helpers/encode-run.js +136 -136
  214. package/test/helpers/held-file.js +29 -0
  215. package/test/helpers/manager.js +57 -0
  216. package/test/helpers/output-spec.js +63 -0
  217. package/test/host-load.test.js +1 -1
  218. package/test/index-accuracy-is-about-the-file.test.js +128 -0
  219. package/test/init-compat.test.js +219 -0
  220. package/test/input-lost-quiets-the-plan.test.js +1 -1
  221. package/test/input-unavailable.test.js +1 -1
  222. package/test/keeping-period.test.js +4 -4
  223. package/test/keyframe-index-accuracy.test.js +97 -45
  224. package/test/keyframe-table-budget.test.js +28 -33
  225. package/test/keyframes-belong-to-the-file.test.js +174 -57
  226. package/test/learned-median.test.js +1 -1
  227. package/test/letting-go-asks-who-is-watching.test.js +191 -0
  228. package/test/limit-row-by-area.test.js +60 -0
  229. package/test/link-budget.test.js +111 -0
  230. package/test/link-probe.test.js +56 -56
  231. package/test/local-encoding-data.test.js +273 -0
  232. package/test/look-ahead-coverage.test.js +1 -1
  233. package/test/manager-surface.test.js +294 -0
  234. package/test/matroska-blocks.test.js +0 -0
  235. package/test/matroska-cues-track.test.js +1 -1
  236. package/test/memory-budget.test.js +2 -2
  237. package/test/mp4-composition-times.test.js +0 -0
  238. package/test/mp4-subtitles.test.js +1 -1
  239. package/test/one-authority.test.js +45 -41
  240. package/test/one-budget.test.js +149 -0
  241. package/test/one-output-one-session.test.js +204 -0
  242. package/test/{disk-space.test.js → one-resource-divided.test.js} +30 -10
  243. package/test/one-serving-output-per-height.test.js +458 -0
  244. package/test/orchestrator-wired.test.js +46 -45
  245. package/test/output-catalog.test.js +39 -0
  246. package/test/output-shape.test.js +4 -51
  247. package/test/output-spec.test.js +251 -157
  248. package/test/output-speed.test.js +17 -15
  249. package/test/outputs-being-prepared.test.js +40 -0
  250. package/test/packet-witness-ring.test.js +2 -2
  251. package/test/packet-witness.test.js +1 -1
  252. package/test/piece-disk-store.test.js +2 -2
  253. package/test/piece-from-whole-file.test.js +1 -1
  254. package/test/piece-lru.test.js +1 -1
  255. package/test/piece-reader.test.js +2 -2
  256. package/test/piece-store-eviction.test.js +1 -1
  257. package/test/piece-store-never-refuses.test.js +1 -1
  258. package/test/piece-store-reservations.test.js +1 -1
  259. package/test/piece-store-slow-disk.test.js +1 -1
  260. package/test/piece-tail.test.js +1 -1
  261. package/test/plan-host-timings.test.js +1 -1
  262. package/test/plan-is-steady.test.js +225 -225
  263. package/test/priority-map-download.test.js +4 -4
  264. package/test/priority-map-emptied.test.js +204 -205
  265. package/test/priority-map-per-output.test.js +215 -209
  266. package/test/priority-map.test.js +1 -1
  267. package/test/probe-wedge-certainty.test.js +1 -1
  268. package/test/produced-copy-choice.test.js +15 -60
  269. package/test/quality-offer.test.js +162 -0
  270. package/test/quality-variants.test.js +1229 -1167
  271. package/test/rate-control-in-the-output.test.js +180 -0
  272. package/test/read-survives-withdrawal.test.js +2 -2
  273. package/test/read-window.test.js +10 -3
  274. package/test/resume-warm.test.js +1 -1
  275. package/test/run-inputs.test.js +80 -0
  276. package/test/run-position-follows-published-grid.test.js +13 -11
  277. package/test/run-progress.test.js +65 -0
  278. package/test/same-height-switch.test.js +664 -0
  279. package/test/seek-frees-the-viewers-requests.test.js +217 -0
  280. package/test/seek-landing.test.js +13 -13
  281. package/test/seek-target-not-superseded.test.js +28 -29
  282. package/test/segment-closed-on-both-branches.test.js +96 -0
  283. package/test/segment-cut-times.test.js +1 -1
  284. package/test/segment-hold-supersede.test.js +28 -35
  285. package/test/segment-judged-by-its-own-header.test.js +221 -0
  286. package/test/segment-serve-wiring.test.js +130 -39
  287. package/test/segment-store-eviction.test.js +22 -7
  288. package/test/segment-store.test.js +98 -14
  289. package/test/segment-true-start.test.js +1 -1
  290. package/test/segments-are-shared.test.js +17 -16
  291. package/test/send-chunk-bytes.test.js +1 -1
  292. package/test/serving-existing-output.test.js +102 -0
  293. package/test/serving-output.test.js +102 -0
  294. package/test/shared-piece-store.test.js +1 -1
  295. package/test/source-file.test.js +1 -1
  296. package/test/stale-request-after-seek.test.js +17 -21
  297. package/test/startup-readings.test.js +10 -5
  298. package/test/subtitle-cue-framing.test.js +5 -5
  299. package/test/subtitle-cue-source.test.js +36 -38
  300. package/test/subtitle-cue-walk.test.js +11 -10
  301. package/test/subtitle-defaults.test.js +1 -1
  302. package/test/subtitle-language.test.js +4 -4
  303. package/test/subtitle-track-numbering.test.js +5 -4
  304. package/test/supply-margin.test.js +1 -1
  305. package/test/swarm-follows-readers.test.js +3 -3
  306. package/test/swarm-reach.test.js +1 -1
  307. package/test/swarm-selection.test.js +3 -3
  308. package/test/tail-duplication.test.js +1 -1
  309. package/test/the-channel-has-both-ends.test.js +91 -0
  310. package/test/the-torrent-thread-serves-bytes.test.js +107 -0
  311. package/test/thread-pool.test.js +3 -3
  312. package/test/timeline.test.js +1 -12
  313. package/test/torrent-cost.test.js +1 -1
  314. package/test/tracks-begin-together.test.js +38 -24
  315. package/test/tunnel-renewal.test.js +1 -1
  316. package/test/two-viewers-one-picture.test.js +120 -87
  317. package/test/upload-hurry.test.js +3 -3
  318. package/test/usrsctp-state.test.js +1 -1
  319. package/test/video-facts.test.js +1 -1
  320. package/test/viewer-assignments.test.js +143 -0
  321. package/test/viewer-outputs.test.js +60 -52
  322. package/test/viewer-presence.test.js +22 -25
  323. package/test/viewer-requests-admission.test.js +89 -0
  324. package/test/viewer-states.test.js +189 -202
  325. package/test/viewer-subtitle-subscription.test.js +1 -1
  326. package/test/viewer.test.js +139 -136
  327. package/test/viewing-generations.test.js +390 -0
  328. package/test/visible-rung.test.js +37 -0
  329. package/test/wait-ledger.test.js +1 -1
  330. package/test/webrtc-shim.test.js +3 -3
  331. package/test/wedge-certainty.test.js +2 -2
  332. package/test/withdraw-piece-claim.test.js +2 -2
  333. package/test/worker-channel.test.js +1 -31
  334. package/utils/client-log-file.js +151 -151
  335. package/scripts/read-container-index.mjs +0 -108
  336. package/services/container/ContainerFactory.js +0 -122
  337. package/services/controllers/PlaybackController.js +0 -33
  338. package/services/disk/DiskSpace.js +0 -150
  339. package/services/disk/wire.js +0 -61
  340. package/services/hls-session-manager.js +0 -9608
  341. package/services/orchestrators/SubtitleOrchestrator.js +0 -160
  342. package/services/output/Output.js +0 -94
  343. package/services/output/OutputSpec.js +0 -202
  344. package/services/output/index.js +0 -1
  345. package/services/output/ladder.js +0 -26
  346. package/services/produced-index.js +0 -222
  347. package/services/quality/EncodeCost.js +0 -555
  348. package/services/torrent-worker/container-tracks.js +0 -414
  349. package/services/viewer/link-readings.js +0 -56
  350. package/test/produced-index.test.js +0 -142
  351. /package/{services → bin}/thread-pool.js +0 -0
  352. /package/services/{available-share.js → encode/available-share.js} +0 -0
  353. /package/services/{decode-cost-fit.js → encode/decode-cost-fit.js} +0 -0
  354. /package/services/{encoder-readings.js → encode/encoder-readings.js} +0 -0
  355. /package/services/{host-load.js → encode/host-load.js} +0 -0
  356. /package/services/{output → encode/output}/cut-grid.js +0 -0
  357. /package/services/{output → encode/output}/rates.js +0 -0
  358. /package/services/{segment-formats → encode/segment-formats}/mpegts.js +0 -0
  359. /package/services/{torrent-cost.js → encode/torrent-cost.js} +0 -0
  360. /package/services/{container → media/container}/ebml-reader.js +0 -0
  361. /package/services/{ffmpeg-banner.js → media/ffmpeg-banner.js} +0 -0
  362. /package/services/{tracks → media/tracks}/ContainerTrack.js +0 -0
  363. /package/services/{tracks → media/tracks}/ImageSubtitleTrack.js +0 -0
  364. /package/services/{tracks → media/tracks}/SubtitleTrack.js +0 -0
  365. /package/services/{tracks → media/tracks}/TextSubtitleTrack.js +0 -0
  366. /package/services/{tracks → media/tracks}/VideoTrack.js +0 -0
  367. /package/services/{tracks → media/tracks}/index.js +0 -0
  368. /package/services/{files → storage/files}/piece-from-whole-file.js +0 -0
  369. /package/services/{disk → storage}/keep.js +0 -0
  370. /package/services/{piece-store → storage/piece-store}/piece-lru.js +0 -0
  371. /package/services/{disk → storage}/returns.js +0 -0
  372. /package/services/{demand → torrent/demand}/DemandRegister.js +0 -0
  373. /package/services/{demand → torrent/demand}/Urgency.js +0 -0
  374. /package/services/{demand → torrent/demand}/Window.js +0 -0
  375. /package/services/{demand → torrent/demand}/index.js +0 -0
  376. /package/services/{demand → torrent/demand}/pieces.js +0 -0
  377. /package/services/{download → torrent/download}/withdraw-claim.js +0 -0
  378. /package/services/{supply-margin.js → torrent/supply-margin.js} +0 -0
  379. /package/services/{torrent-source-key.js → torrent/torrent-source-key.js} +0 -0
  380. /package/services/{torrent-worker → torrent/worker}/fastest-wires.js +0 -0
  381. /package/services/{torrent-worker → torrent/worker}/handle-state.js +0 -0
  382. /package/services/{nat-classifier.js → transport/nat-classifier.js} +0 -0
  383. /package/services/{registry-api.js → transport/registry-api.js} +0 -0
  384. /package/services/{tunnel-client.js → transport/tunnel-client.js} +0 -0
  385. /package/services/{priority → viewer}/WaitLedger.js +0 -0
@@ -1,1485 +1,1485 @@
1
- /**
2
- * @file Matroska/WebM container — RFC 9559.
3
- *
4
- * Reads Tracks in one pass for all media types (video, audio, subtitle).
5
- * Implements spec-accurate flag handling:
6
- * - FlagEnabled 0xB9 default 1, zero-length element = default (not disabled)
7
- * - FlagDefault 0x88 default 1, declaresDefault tracks whether element was written
8
- * - FlagForced 0x55AA only for subtitles, FlagHearingImpaired 0x55AB, FlagVisualImpaired 0x55AC,
9
- * FlagTextDescriptions 0x55AD, FlagOriginal 0x55AE, FlagCommentary 0x55AF
10
- * - Language 0x22B59C default "eng", LanguageBCP47 0x22B59D MUST — when present, Language ignored
11
- * - CodecID 0x86, CodecPrivate 0x63A2, Name 0x536E, TrackType 0x83 (1 video, 2 audio, 17 subtitle)
12
- *
13
- * Byte-level EBML element walking is `ebml-reader.js`, which is the format's
14
- * grammar and not this container's own statements. Everything Matroska DOES
15
- * state about itself — the Tracks walk, the Cues, the keyframe times they name,
16
- * the cluster positions, the blocks inside a cluster —
17
- * is read in this module: each of those is RFC 9559 speaking about Matroska,
18
- * and the class is the only way in.
19
- */
20
-
21
- import { Container } from "./Container.js";
22
- import { VideoTrack } from "../tracks/VideoTrack.js";
23
- import { AudioTrack } from "../tracks/AudioTrack.js";
24
- import { TextSubtitleTrack, TEXT_CODECS_MATROSKA } from "../tracks/TextSubtitleTrack.js";
25
- import { ImageSubtitleTrack } from "../tracks/ImageSubtitleTrack.js";
26
- import { ContainerTrack } from "../tracks/ContainerTrack.js";
27
- import { findElement, iterateElements, readFloat, readUint, readVint } from "./ebml-reader.js";
28
-
29
- const HEAD_BYTES = 64 * 1024;
30
- /** Enough to read any cluster's own element header. */
31
- const CLUSTER_HEADER_PROBE = 64;
32
- /**
33
- * The largest cluster this will read whole. Real muxers write clusters of a few
34
- * megabytes; anything past this is not a cluster boundary we recognised and
35
- * reading it would be a large read for nothing.
36
- */
37
- const MAX_CLUSTER_BYTES = 32 * 1024 * 1024;
38
-
39
- const ID_SEGMENT = 0x18538067;
40
- const ID_SEEK_HEAD = 0x114d9b74;
41
- const ID_SEEK = 0x4dbb;
42
- const ID_SEEK_ID = 0x53ab;
43
- const ID_SEEK_POSITION = 0x53ac;
44
- const ID_INFO = 0x1549a966;
45
- const ID_TIMESTAMP_SCALE = 0x2ad7b1;
46
- const ID_DURATION = 0x4489;
47
- const ID_CLUSTER = 0x1f43b675;
48
- const ID_TIMESTAMP = 0xe7;
49
- const ID_SIMPLE_BLOCK = 0xa3;
50
- const ID_BLOCK_GROUP = 0xa0;
51
- /** RFC 9559 §5.1.2.1: nanoseconds per tick when Info omits TimestampScale. */
52
- const DEFAULT_TIMESTAMP_SCALE = 1_000_000;
53
- /**
54
- * How much to read at a cluster whose position came from the SeekHead. A
55
- * cluster's Timestamp is the first child every muxer writes, so this only has
56
- * to cover the element header and that one field.
57
- */
58
- const CLUSTER_PROBE_BYTES = 4 * 1024;
59
- const ID_TRACKS = 0x1654ae6b;
60
- const ID_TRACK_ENTRY = 0xae;
61
- const ID_TRACK_NUMBER = 0xd7;
62
- const ID_TRACK_TYPE = 0x83;
63
- const ID_FLAG_ENABLED = 0xb9;
64
- const ID_FLAG_DEFAULT = 0x88;
65
- const ID_FLAG_FORCED = 0x55aa;
66
- const ID_FLAG_HEARING = 0x55ab;
67
- const ID_FLAG_VISUAL = 0x55ac;
68
- const ID_FLAG_TEXT_DESCR = 0x55ad;
69
- const ID_FLAG_ORIGINAL = 0x55ae;
70
- const ID_FLAG_COMMENTARY = 0x55af;
71
- const ID_CODEC_ID = 0x86;
72
- const ID_CODEC_PRIVATE = 0x63a2;
73
- const ID_LANGUAGE = 0x22b59c;
74
- const ID_LANGUAGE_BCP47 = 0x22b59d;
75
- const ID_NAME = 0x536e;
76
- const ID_VIDEO = 0xe0;
77
- const ID_AUDIO = 0xe1;
78
- const ID_PIXEL_WIDTH = 0xb0;
79
- const ID_PIXEL_HEIGHT = 0xba;
80
- const ID_DISPLAY_WIDTH = 0x54b0;
81
- const ID_DISPLAY_HEIGHT = 0x54ba;
82
- const ID_SAMPLING_FREQUENCY = 0xb5;
83
- const ID_CHANNELS = 0x9f;
84
- /**
85
- * ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect — the eight
86
- * fields Matroska writes before the text of an SSA/ASS event. See
87
- * {@link MatroskaContainer.cueTextOf} for the quotation this comes from.
88
- */
89
- const ASS_FIELDS_BEFORE_TEXT = 8;
90
-
91
- function readString(buf, el) {
92
- return buf.toString("utf8", el.dataOffset, el.dataOffset + el.size).replace(/\0+$/, "");
93
- }
94
-
95
- export class MatroskaContainer extends Container {
96
- get formatName() {
97
- return "matroska";
98
- }
99
-
100
- static detect(head) {
101
- return isMatroska(head);
102
- }
103
-
104
- /**
105
- * The keyframe times this container's own index states, in ascending seconds.
106
- *
107
- * Static so a caller that has bytes and no container can ask; the instance
108
- * form is {@link Container#readKeyframeIndex}.
109
- *
110
- * @param {(start:number,end:number)=>Promise<Buffer|null>} readRange
111
- * @param {number} fileSize
112
- * @returns {Promise<number[]|null>} Null where the container has no index.
113
- */
114
- static readKeyframeTimes(readRange, fileSize) {
115
- return readMatroskaKeyframeTimes(readRange, fileSize);
116
- }
117
-
118
- /**
119
- * This container's subtitle tracks, its Cues table and the cluster positions
120
- * they name — RFC 9559 §5.1.4 and §5.1.3.
121
- *
122
- * @param {(start:number,end:number)=>Promise<Buffer|null>} readRange
123
- * @param {number} fileSize
124
- * @returns {Promise<object|null>}
125
- */
126
- static readSubtitlePlan(readRange, fileSize) {
127
- return readSubtitlePlan(readRange, fileSize);
128
- }
129
-
130
- /**
131
- * The same reading, over the file this container was built on.
132
- *
133
- * The static form exists for a caller that has bytes and no container; this
134
- * is the one to use otherwise, because the reader is already here.
135
- *
136
- * @returns {Promise<object|null>}
137
- */
138
- readSubtitlePlan() {
139
- return MatroskaContainer.readSubtitlePlan(this.readRange, this.fileSize);
140
- }
141
-
142
- /**
143
- * The blocks one track has inside a cluster, with their times.
144
- *
145
- * The payload is handed back as BYTES: what those bytes mean is
146
- * {@link MatroskaContainer.cueTextOf}'s answer, and this method's subject is
147
- * only where a block sits and how long it lasts.
148
- *
149
- * @param {Buffer} bytes - The cluster, from its own element header onward.
150
- * @param {number} trackNumber
151
- * @param {number} secondsPerTick
152
- * @returns {{ startSeconds: number, endSeconds: number | null, payload: Buffer }[]}
153
- */
154
- static blocksInCluster(bytes, trackNumber, secondsPerTick) {
155
- return harvestCluster(bytes, trackNumber, secondsPerTick);
156
- }
157
-
158
- /**
159
- * The blocks one track has inside a cluster whose bounds are already known —
160
- * RFC 9559 §5.1.3.4 (SimpleBlock) and §5.1.3.5 (BlockGroup).
161
- *
162
- * The same reading as {@link MatroskaContainer.blocksInCluster}, entered where
163
- * the caller has already parsed the cluster's own header.
164
- *
165
- * @param {Buffer} buffer
166
- * @param {{ dataOffset: number, size: number }} cluster
167
- * @param {number} trackNumber
168
- * @param {number} secondsPerTick
169
- * @returns {{ startSeconds: number, durationSeconds: number | null, payload: Buffer }[]}
170
- */
171
- static blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick) {
172
- return blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick);
173
- }
174
-
175
- /**
176
- * Duration and the start of this file's own timeline, per RFC 9559 §5.1.2.
177
- *
178
- * Duration is stated in `Info` as a FLOAT in ticks, so it needs the file's
179
- * `TimestampScale` to become seconds. The start of the timeline is not stated
180
- * anywhere — Matroska has no such element — so it is the timestamp of the
181
- * first Cluster, which is what the first frame is placed against.
182
- *
183
- * @returns {Promise<import("./Container.js").ContainerMediaInfo>}
184
- */
185
- async readMediaInfo() {
186
- if (this.mediaInfo) {
187
- return this.mediaInfo;
188
- }
189
- /** @type {import("./Container.js").ContainerMediaInfo} */
190
- const info = { format: this.formatName, durationSeconds: null, startTimeSeconds: null };
191
- this.mediaInfo = info;
192
- const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
193
- if (!head || !isMatroska(head)) {
194
- return info;
195
- }
196
- const segment = findElement(head, ID_SEGMENT, []);
197
- if (!segment) {
198
- return info;
199
- }
200
- const scale = MatroskaContainer.#timestampScaleOf(head, segment.dataOffset);
201
- const infoElement = findElement(head, ID_INFO, [], segment.dataOffset);
202
- if (infoElement) {
203
- const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
204
- for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
205
- if (field.id !== ID_DURATION) {
206
- continue;
207
- }
208
- const ticks = readFloat(head, field.dataOffset, field.size);
209
- if (ticks !== null && ticks > 0) {
210
- info.durationSeconds = (ticks * scale) / 1e9;
211
- }
212
- break;
213
- }
214
- }
215
- info.startTimeSeconds = await this.#firstClusterSeconds(head, segment.dataOffset, scale);
216
- return info;
217
- }
218
-
219
- /**
220
- * `TimestampScale` from Info, or the specification's default.
221
- *
222
- * @param {Buffer} head
223
- * @param {number} segmentDataOffset
224
- * @returns {number} Nanoseconds per tick.
225
- */
226
- static #timestampScaleOf(head, segmentDataOffset) {
227
- const infoElement = findElement(head, ID_INFO, [], segmentDataOffset);
228
- if (!infoElement) {
229
- return DEFAULT_TIMESTAMP_SCALE;
230
- }
231
- const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
232
- for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
233
- if (field.id === ID_TIMESTAMP_SCALE) {
234
- const scale = readUint(head, field.dataOffset, field.size);
235
- return scale > 0 ? scale : DEFAULT_TIMESTAMP_SCALE;
236
- }
237
- }
238
- return DEFAULT_TIMESTAMP_SCALE;
239
- }
240
-
241
- /**
242
- * The timestamp of the first Cluster, in seconds.
243
- *
244
- * Tried in the head window first, because a muxer writes the first cluster
245
- * straight after Tracks and both usually fit; a file whose Tracks element is
246
- * large enough to push it out is answered from the SeekHead instead, with one
247
- * short read at the position it names.
248
- *
249
- * @param {Buffer} head
250
- * @param {number} segmentDataOffset
251
- * @param {number} scale - Nanoseconds per tick.
252
- * @returns {Promise<number | null>} Null when no cluster could be read.
253
- */
254
- async #firstClusterSeconds(head, segmentDataOffset, scale) {
255
- /**
256
- * @param {Buffer} buffer
257
- * @param {number} dataOffset
258
- * @param {number} end
259
- * @returns {number | null}
260
- */
261
- const timestampIn = (buffer, dataOffset, end) => {
262
- for (const field of iterateElements(buffer, dataOffset, end)) {
263
- if (field.id === ID_TIMESTAMP) {
264
- const ticks = readUint(buffer, field.dataOffset, field.size);
265
- return Number.isFinite(ticks) ? (ticks * scale) / 1e9 : null;
266
- }
267
- // Timestamp is written before any frame. Stopping at the first one keeps
268
- // this from walking a cluster's whole payload, which is megabytes and
269
- // usually not in the buffer at all.
270
- if (field.id === ID_SIMPLE_BLOCK || field.id === ID_BLOCK_GROUP) {
271
- return null;
272
- }
273
- }
274
- return null;
275
- };
276
-
277
- for (const element of iterateElements(head, segmentDataOffset, head.length)) {
278
- if (element.id !== ID_CLUSTER) {
279
- continue;
280
- }
281
- return timestampIn(head, element.dataOffset, Math.min(head.length, element.dataOffset + element.size));
282
- }
283
-
284
- const position = MatroskaContainer.#seekPositionOf(head, segmentDataOffset, ID_CLUSTER);
285
- if (position === null) {
286
- return null;
287
- }
288
- const at = segmentDataOffset + position;
289
- if (at >= this.fileSize) {
290
- return null;
291
- }
292
- const chunk = await this.readRange(at, Math.min(this.fileSize - 1, at + CLUSTER_PROBE_BYTES - 1));
293
- if (!chunk) {
294
- return null;
295
- }
296
- for (const element of iterateElements(chunk, 0, chunk.length)) {
297
- if (element.id !== ID_CLUSTER) {
298
- continue;
299
- }
300
- return timestampIn(chunk, element.dataOffset, Math.min(chunk.length, element.dataOffset + element.size));
301
- }
302
- return null;
303
- }
304
-
305
- /**
306
- * Where the SeekHead says an element lives, relative to the Segment's payload.
307
- *
308
- * @param {Buffer} head
309
- * @param {number} segmentDataOffset
310
- * @param {number} wantedId
311
- * @returns {number | null}
312
- */
313
- static #seekPositionOf(head, segmentDataOffset, wantedId) {
314
- const seekHead = findElement(head, ID_SEEK_HEAD, [], segmentDataOffset);
315
- if (!seekHead) {
316
- return null;
317
- }
318
- const seekHeadEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
319
- for (const seek of iterateElements(head, seekHead.dataOffset, seekHeadEnd)) {
320
- if (seek.id !== ID_SEEK) {
321
- continue;
322
- }
323
- const seekEnd = Math.min(seekHeadEnd, seek.dataOffset + seek.size);
324
- let targetId = null;
325
- let position = null;
326
- for (const field of iterateElements(head, seek.dataOffset, seekEnd)) {
327
- if (field.id === ID_SEEK_ID) {
328
- targetId = readUint(head, field.dataOffset, field.size);
329
- } else if (field.id === ID_SEEK_POSITION) {
330
- position = readUint(head, field.dataOffset, field.size);
331
- }
332
- }
333
- if (targetId === wantedId && position !== null) {
334
- return position;
335
- }
336
- }
337
- return null;
338
- }
339
-
340
-
341
- /**
342
- * Walk the clusters this file's Cues table names and give up the blocks in
343
- * every one that is READABLE now, for every track at once.
344
- *
345
- * One walk for the whole file, not one per track: a Matroska cluster carries
346
- * the blocks of every track that has anything to say over its span, so the
347
- * bytes that answer one track answer them all. Reading them once per track
348
- * meant the same cluster was fetched and parsed as many times as the film has
349
- * subtitle tracks — measured 2026-08-20 on a film with five: five requests
350
- * every fifteen seconds, each costing 0.2-5.2 s, for a few kilobytes of cues.
351
- *
352
- * Nothing is fetched. `isHeld` decides whether a cluster can be read at all,
353
- * and one that is not here yet is left for the next call — turning subtitles
354
- * on must not pull bytes the viewer is not waiting for.
355
- *
356
- * @param {object} plan - From {@link MatroskaContainer.readSubtitlePlan}.
357
- * @param {Set<number>} walked - Cluster positions already read; added to.
358
- * @returns {Promise<Map<number, {startSeconds: number, endSeconds: number|null, text: string}[]>>}
359
- * Track number to the cues found in THIS pass.
360
- */
361
- async readHeldCues(plan, track, progress) {
362
- const found = await this.walkHeldClusters(plan, progress.walked);
363
- return {
364
- found,
365
- // Every track is filled by the same walk, so this is a fact about the
366
- // FILE and reads the same whichever track asked.
367
- covered: progress.walked.size,
368
- indexed: track?.clusterPositions?.length ?? 0
369
- };
370
- }
371
-
372
- async walkHeldClusters(plan, walked) {
373
- /** @type {Map<number, object[]>} */
374
- const found = new Map();
375
- // The union of the tracks' cluster lists: each track's list comes from its
376
- // own Cues entries, so they overlap but do not coincide.
377
- const positions = new Set();
378
- for (const candidate of plan?.tracks ?? []) {
379
- for (const position of candidate.clusterPositions ?? []) {
380
- positions.add(position);
381
- }
382
- }
383
- for (const position of [...positions].sort((left, right) => left - right)) {
384
- if (walked.has(position)) {
385
- continue;
386
- }
387
- // The header first: it says how long the cluster is, and a cluster whose
388
- // bytes are not all here is left for the next time round.
389
- const probeEnd = Math.min(this.fileSize - 1, position + CLUSTER_HEADER_PROBE - 1);
390
- if (!this.isHeld(position, probeEnd)) {
391
- continue;
392
- }
393
- const probe = await this.readHeld(position, probeEnd);
394
- const header = probe && [...iterateElements(probe, 0, probe.length)][0];
395
- if (!header || header.size <= 0 || header.size > MAX_CLUSTER_BYTES) {
396
- walked.add(position); // not a cluster this can read; do not look again
397
- continue;
398
- }
399
- const last = Math.min(this.fileSize - 1, position + header.dataOffset + header.size - 1);
400
- if (!this.isHeld(position, last)) {
401
- continue;
402
- }
403
- const bytes = await this.readHeld(position, last);
404
- if (!bytes) {
405
- continue;
406
- }
407
- walked.add(position);
408
- for (const candidate of plan.tracks) {
409
- const blocks = MatroskaContainer.blocksInCluster(bytes, candidate.trackNumber, plan.secondsPerTick);
410
- if (blocks.length === 0) {
411
- continue;
412
- }
413
- const into = found.get(candidate.trackNumber) ?? [];
414
- for (const block of blocks) {
415
- // The block's bytes become text HERE, where the container that framed
416
- // them is known. A cue kept framed and unframed later cannot be
417
- // unframed at all: nothing downstream knows which container it came
418
- // out of, and guessing from the field count is what showed the
419
- // dialogue row's own fields to the viewer.
420
- into.push({
421
- startSeconds: block.startSeconds,
422
- endSeconds: block.endSeconds,
423
- text: MatroskaContainer.cueTextOf(block.payload, candidate.codecId)
424
- });
425
- }
426
- found.set(candidate.trackNumber, into);
427
- }
428
- }
429
- return found;
430
- }
431
-
432
- async readTracks() {
433
- const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
434
- if (!head || !isMatroska(head)) return [];
435
-
436
- // Delegate to subtitle plan reader for subtitle tracks (already handles Flags spec-correct),
437
- // but we need video/audio tracks too. Do a dedicated Tracks walk here for all types,
438
- // then merge subtitle detail (clusterPositions, declaresDefault etc.) from the plan.
439
- const seg = findElement(head, 0x18538067, []);
440
- if (!seg) return [];
441
- const tracksEl = findElement(head, ID_TRACKS, [], seg.dataOffset);
442
- if (!tracksEl) return [];
443
-
444
- const tracksEnd = Math.min(head.length, tracksEl.dataOffset + tracksEl.size);
445
- /** @type {import("../tracks/index.js").ContainerTrack[]} */
446
- const result = [];
447
- // Subtitle declaredIndex is position among subtitle tracks, not global — track per-type counters.
448
- let subtitleDeclaredIndex = -1;
449
- let audioDeclaredIndex = -1;
450
- let videoDeclaredIndex = -1;
451
-
452
- // For subtitle flag enrichment, read the existing plan (it already does Cues walk)
453
- let subtitlePlan = null;
454
- try {
455
- const shim = async (s, e) => this.readRange(s, Math.min(e, this.fileSize - 1));
456
- subtitlePlan = await readSubtitlePlan(shim, this.fileSize);
457
- } catch {
458
- subtitlePlan = null;
459
- }
460
- const declaredByNumber = new Map();
461
- const planTracksByNumber = new Map();
462
- if (subtitlePlan?.declared) {
463
- for (const d of subtitlePlan.declared) declaredByNumber.set(d.trackNumber, d);
464
- }
465
- if (subtitlePlan?.tracks) {
466
- for (const t of subtitlePlan.tracks) planTracksByNumber.set(t.trackNumber, t);
467
- }
468
-
469
- for (const entry of iterateElements(head, tracksEl.dataOffset, tracksEnd)) {
470
- if (entry.id !== ID_TRACK_ENTRY) continue;
471
- const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
472
- let trackNumber = null;
473
- let typeNum = null;
474
- let codecId = "";
475
- let language = "";
476
- let languageBcp47 = "";
477
- let name = "";
478
- let codecPrivateB64 = "";
479
- let isEnabled = true;
480
- let isDefault = true;
481
- let declaresDefault = false;
482
- let isForced = false;
483
- let isHearing = false;
484
- let isVisual = false;
485
- let isOriginal = false;
486
- let isCommentary = false;
487
- let pixelWidth = null;
488
- let pixelHeight = null;
489
- let displayWidth = null;
490
- let displayHeight = null;
491
- let samplingFreq = null;
492
- let channels = null;
493
-
494
- for (const f of iterateElements(head, entry.dataOffset, entryEnd)) {
495
- switch (f.id) {
496
- case ID_TRACK_NUMBER: trackNumber = readUint(head, f.dataOffset, f.size); break;
497
- case ID_TRACK_TYPE: typeNum = readUint(head, f.dataOffset, f.size); break;
498
- case ID_CODEC_ID: codecId = readString(head, f); break;
499
- case ID_CODEC_PRIVATE: codecPrivateB64 = head.toString("base64", f.dataOffset, f.dataOffset + f.size); break;
500
- case ID_LANGUAGE: language = readString(head, f); break;
501
- case ID_LANGUAGE_BCP47: languageBcp47 = readString(head, f); break;
502
- case ID_NAME: name = readString(head, f); break;
503
- case ID_FLAG_ENABLED: isEnabled = f.size === 0 || readUint(head, f.dataOffset, f.size) !== 0; break;
504
- case ID_FLAG_DEFAULT: isDefault = f.size === 0 || readUint(head, f.dataOffset, f.size) === 1; declaresDefault = true; break;
505
- case ID_FLAG_FORCED: isForced = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
506
- case ID_FLAG_HEARING: isHearing = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
507
- case ID_FLAG_VISUAL: isVisual = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
508
- case ID_FLAG_TEXT_DESCR: break;
509
- case ID_FLAG_ORIGINAL: isOriginal = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
510
- case ID_FLAG_COMMENTARY: isCommentary = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
511
- default: break;
512
- }
513
- // Video/Audio sub-elements are nested, not at entry level — read separately below.
514
- }
515
- if (trackNumber === null) continue;
516
-
517
- // Parse Video/Audio sub-elements if present
518
- const videoEl = findElement(head, ID_VIDEO, [], entry.dataOffset, entryEnd);
519
- if (videoEl) {
520
- for (const vf of iterateElements(head, videoEl.dataOffset, Math.min(entryEnd, videoEl.dataOffset + videoEl.size))) {
521
- if (vf.id === ID_PIXEL_WIDTH) pixelWidth = readUint(head, vf.dataOffset, vf.size);
522
- else if (vf.id === ID_PIXEL_HEIGHT) pixelHeight = readUint(head, vf.dataOffset, vf.size);
523
- else if (vf.id === ID_DISPLAY_WIDTH) displayWidth = readUint(head, vf.dataOffset, vf.size);
524
- else if (vf.id === ID_DISPLAY_HEIGHT) displayHeight = readUint(head, vf.dataOffset, vf.size);
525
- }
526
- }
527
- const audioEl = findElement(head, ID_AUDIO, [], entry.dataOffset, entryEnd);
528
- if (audioEl) {
529
- for (const af of iterateElements(head, audioEl.dataOffset, Math.min(entryEnd, audioEl.dataOffset + audioEl.size))) {
530
- if (af.id === ID_SAMPLING_FREQUENCY) {
531
- // SamplingFrequency is float64
532
- if (af.size === 8) samplingFreq = head.readDoubleBE(af.dataOffset);
533
- else samplingFreq = readUint(head, af.dataOffset, af.size);
534
- } else if (af.id === ID_CHANNELS) channels = readUint(head, af.dataOffset, af.size);
535
- }
536
- }
537
-
538
- // RFC 9559 LanguageBCP47 MUST — when present, Language ignored
539
- const resolvedLang = languageBcp47 || language;
540
- const bcpTag = languageBcp47;
541
-
542
- if (typeNum === 1) {
543
- videoDeclaredIndex += 1;
544
- result.push(new VideoTrack({
545
- trackNumber,
546
- declaredIndex: videoDeclaredIndex,
547
- codecId,
548
- language: resolvedLang,
549
- languageBcp47: bcpTag,
550
- name,
551
- isEnabled,
552
- isDefault,
553
- declaresDefault,
554
- codecPrivateB64,
555
- width: pixelWidth,
556
- height: pixelHeight,
557
- displayWidth,
558
- displayHeight
559
- }));
560
- } else if (typeNum === 2) {
561
- audioDeclaredIndex += 1;
562
- result.push(new AudioTrack({
563
- trackNumber,
564
- declaredIndex: audioDeclaredIndex,
565
- codecId,
566
- language: resolvedLang,
567
- languageBcp47: bcpTag,
568
- name,
569
- isEnabled,
570
- isDefault,
571
- declaresDefault,
572
- codecPrivateB64,
573
- isOriginal,
574
- isCommentary,
575
- isVisualImpaired: isVisual,
576
- channels,
577
- samplingFrequency: samplingFreq
578
- }));
579
- } else if (typeNum === 17) {
580
- subtitleDeclaredIndex += 1;
581
- // Only Forced/Hearing belong to subtitles; Original/Commentary must not leak.
582
- const declared = declaredByNumber.get(trackNumber);
583
- const planTrack = planTracksByNumber.get(trackNumber);
584
- // Prefer plan's flags when available (already spec-correct), else use parsed.
585
- const finalForced = planTrack ? !!planTrack.isForced : isForced;
586
- const finalHearing = planTrack ? !!planTrack.isHearingImpaired : isHearing;
587
- const finalEnabled = declared ? declared.isEnabled !== false : isEnabled;
588
- const finalDefault = declared ? !!declared.isDefault : isDefault;
589
- const finalDeclares = declared ? !!declared.declaresDefault : declaresDefault;
590
- const clusterPositions = planTrack ? planTrack.clusterPositions ?? [] : [];
591
- const isText = TEXT_CODECS_MATROSKA.has(codecId);
592
- // disabled image/text tracks still counted (declaredIndex above) — offerable flag controls visibility
593
- if (isText && finalEnabled) {
594
- result.push(new TextSubtitleTrack({
595
- trackNumber,
596
- declaredIndex: subtitleDeclaredIndex,
597
- codecId,
598
- language: resolvedLang,
599
- languageBcp47: bcpTag,
600
- name,
601
- isEnabled: finalEnabled,
602
- isDefault: finalDefault,
603
- declaresDefault: finalDeclares,
604
- codecPrivateB64,
605
- isForced: finalForced,
606
- isHearingImpaired: finalHearing,
607
- clusterPositions
608
- }));
609
- } else {
610
- // Image or disabled — keep declaredIndex, not offerable if disabled
611
- const Target = isText ? TextSubtitleTrack : ImageSubtitleTrack;
612
- result.push(new Target({
613
- trackNumber,
614
- declaredIndex: subtitleDeclaredIndex,
615
- codecId,
616
- language: resolvedLang,
617
- languageBcp47: bcpTag,
618
- name,
619
- isEnabled: finalEnabled,
620
- isDefault: finalDefault,
621
- declaresDefault: finalDeclares,
622
- codecPrivateB64,
623
- isForced: finalForced,
624
- isHearingImpaired: finalHearing,
625
- clusterPositions: isText ? clusterPositions : []
626
- }));
627
- }
628
- } else {
629
- // Other TrackType (complex, logo, buttons, control) — keep as generic, not video
630
- result.push(new ContainerTrack({
631
- trackNumber,
632
- declaredIndex: -1,
633
- type: "other",
634
- codecId,
635
- language: resolvedLang,
636
- languageBcp47: bcpTag,
637
- name,
638
- isEnabled,
639
- isDefault,
640
- declaresDefault,
641
- codecPrivateB64
642
- }));
643
- }
644
- }
645
- return result;
646
- }
647
-
648
- /**
649
- * The text field of one cue as Matroska frames it.
650
- *
651
- * Two rules, both from `matroska.org/technical/subtitles.html`, "Now, how are
652
- * they stored in Matroska?":
653
- *
654
- * 1. "All text is converted to UTF-8", so the block is decoded as UTF-8 and
655
- * no other encoding is guessed at. A subtitle FILE is a different matter —
656
- * there the bytes may be Windows-1251 and `decodeSubtitleBytes` sniffs for
657
- * it — but a muxer had to convert before writing the block.
658
- * 2. "Events are stored in the Block in this order: ReadOrder, Layer, Style,
659
- * Name, MarginL, MarginR, MarginV, Effect, Text", and "Start & End field
660
- * are used to set TimeStamp and the BlockDuration element". So eight fields
661
- * stand before the text, the two timing fields of the file's own row are
662
- * NOT among them, and a read order takes their place at the front. The text
663
- * itself may hold commas, so everything from the ninth field on is joined
664
- * back together.
665
- *
666
- * `S_TEXT/UTF8` and `S_TEXT/WEBVTT` have no such framing: the block holds the
667
- * cue text and nothing else. (A WebVTT cue's settings, identifier and
668
- * preceding comments live in a BlockAddition, which this proxy does not read;
669
- * losing them costs positioning, not words.)
670
- *
671
- * @param {Buffer} payload - The block's own bytes.
672
- * @param {string} codecId - Matroska CodecID of the track the block belongs to.
673
- * @returns {string}
674
- */
675
- static cueTextOf(payload, codecId) {
676
- const text = Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "");
677
- if (codecId !== "S_TEXT/ASS" && codecId !== "S_TEXT/SSA") {
678
- return text;
679
- }
680
- const fields = text.split(",");
681
- return fields.length > ASS_FIELDS_BEFORE_TEXT ? fields.slice(ASS_FIELDS_BEFORE_TEXT).join(",") : "";
682
- }
683
-
684
- async parseKeyframeIndex() {
685
- const times = await readMatroskaKeyframeTimes(this.readRange, this.fileSize);
686
- if (!times) return null;
687
- if (Array.isArray(times)) return { times, tolerance: 0 };
688
- return times;
689
- }
690
- }
691
-
692
- // ---------------------------------------------------------------------------
693
- // Matroska's own reading of its subtitle tracks and its clusters. It lives in
694
- // this module because every line of it is a statement of RFC 9559 about how
695
- // this container stores a subtitle, and the class is the only way in.
696
- // ---------------------------------------------------------------------------
697
-
698
- const ID_BLOCK = 0xa1;
699
- const ID_BLOCK_DURATION = 0x9b;
700
-
701
- /** Bits 1-2 of the flags byte say how a block is laced, or that it is not. */
702
- const LACING_MASK = 0x06;
703
- const LACING_NONE = 0x00;
704
- const LACING_XIPH = 0x02;
705
- const LACING_FIXED = 0x04;
706
- const LACING_EBML = 0x06;
707
-
708
- /**
709
- * @typedef {object} SubtitleBlock
710
- * @property {number} startSeconds - When the cue appears.
711
- * @property {number | null} durationSeconds - How long it stays, or null when
712
- * the block carried no duration (a SimpleBlock; the caller decides).
713
- * @property {Buffer} payload - The block's own bytes, still in the codec's form.
714
- */
715
-
716
- /**
717
- * Read one block's header.
718
- *
719
- * @param {Buffer} buffer
720
- * @param {number} start - First byte of the block's payload.
721
- * @param {number} end - One past its last byte.
722
- * @returns {{ trackNumber: number, relativeTicks: number, flags: number, dataOffset: number } | null}
723
- */
724
- function readBlockHeader(buffer, start, end) {
725
- const track = readVint(buffer, start, false);
726
- if (!track || track.value === null) {
727
- return null;
728
- }
729
- const timestampAt = start + track.length;
730
- // Signed, and it can be negative: a block may belong slightly before the
731
- // cluster it is stored in.
732
- if (timestampAt + 3 > end) {
733
- return null;
734
- }
735
- return {
736
- trackNumber: Number(track.value),
737
- relativeTicks: buffer.readInt16BE(timestampAt),
738
- flags: buffer[timestampAt + 2],
739
- dataOffset: timestampAt + 3
740
- };
741
- }
742
-
743
- /**
744
- * Where a laced block's first frame begins.
745
- *
746
- * Subtitles are rarely laced, but a block that IS laced starts with a frame
747
- * count and a table of sizes, and reading the payload without stepping over
748
- * them yields the table as though it were text.
749
- *
750
- * @param {Buffer} buffer
751
- * @param {number} dataOffset - First byte after the block header.
752
- * @param {number} end
753
- * @param {number} flags
754
- * @returns {number | null} The offset of the first frame, or null when the
755
- * lacing cannot be read.
756
- */
757
- function firstFrameOffset(buffer, dataOffset, end, flags) {
758
- const lacing = flags & LACING_MASK;
759
- if (lacing === LACING_NONE) {
760
- return dataOffset;
761
- }
762
- if (dataOffset >= end) {
763
- return null;
764
- }
765
- const frames = buffer[dataOffset] + 1;
766
- let at = dataOffset + 1;
767
- if (lacing === LACING_FIXED) {
768
- return at;
769
- }
770
- if (lacing === LACING_XIPH) {
771
- // Each size but the last is a run of 0xFF bytes ending in a smaller one.
772
- for (let frame = 0; frame < frames - 1; frame += 1) {
773
- while (at < end && buffer[at] === 0xff) {
774
- at += 1;
775
- }
776
- at += 1;
777
- }
778
- return at <= end ? at : null;
779
- }
780
- if (lacing === LACING_EBML) {
781
- // The first size is a plain variable-length integer, the rest are signed
782
- // differences from it; either way each is one such integer to step over.
783
- for (let frame = 0; frame < frames - 1; frame += 1) {
784
- const size = readVint(buffer, at, false);
785
- if (!size) {
786
- return null;
787
- }
788
- at += size.length;
789
- }
790
- return at <= end ? at : null;
791
- }
792
- return null;
793
- }
794
-
795
- /**
796
- * Every block of one track inside one cluster.
797
- *
798
- * @param {Buffer} buffer - Bytes holding the cluster's payload.
799
- * @param {{ dataOffset: number, size: number }} cluster - Where that payload is.
800
- * @param {number} trackNumber - The track to keep.
801
- * @param {number} secondsPerTick - From the segment's timestamp scale.
802
- * @returns {SubtitleBlock[]}
803
- */
804
- function blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick) {
805
- const end = Math.min(buffer.length, cluster.dataOffset + cluster.size);
806
- /** @type {SubtitleBlock[]} */
807
- const blocks = [];
808
- let clusterTicks = null;
809
-
810
- const take = (blockStart, blockEnd, durationTicks) => {
811
- const header = readBlockHeader(buffer, blockStart, blockEnd);
812
- if (!header || header.trackNumber !== trackNumber || clusterTicks === null) {
813
- return;
814
- }
815
- const payloadAt = firstFrameOffset(buffer, header.dataOffset, blockEnd, header.flags);
816
- if (payloadAt === null || payloadAt >= blockEnd) {
817
- return;
818
- }
819
- blocks.push({
820
- startSeconds: (clusterTicks + header.relativeTicks) * secondsPerTick,
821
- durationSeconds: durationTicks === null ? null : durationTicks * secondsPerTick,
822
- payload: buffer.subarray(payloadAt, blockEnd)
823
- });
824
- };
825
-
826
- for (const element of iterateElements(buffer, cluster.dataOffset, end)) {
827
- const elementEnd = Math.min(end, element.dataOffset + element.size);
828
- if (element.id === ID_TIMESTAMP) {
829
- clusterTicks = readUint(buffer, element.dataOffset, element.size);
830
- continue;
831
- }
832
- if (element.id === ID_SIMPLE_BLOCK) {
833
- take(element.dataOffset, elementEnd, null);
834
- continue;
835
- }
836
- if (element.id !== ID_BLOCK_GROUP) {
837
- continue;
838
- }
839
- // A group holds the block and, for a subtitle, the duration that says when
840
- // the cue leaves the screen. Both are read before either is used, because
841
- // the duration may be written after the block.
842
- let blockStart = null;
843
- let blockEnd = null;
844
- let durationTicks = null;
845
- for (const field of iterateElements(buffer, element.dataOffset, elementEnd)) {
846
- const fieldEnd = Math.min(elementEnd, field.dataOffset + field.size);
847
- if (field.id === ID_BLOCK) {
848
- blockStart = field.dataOffset;
849
- blockEnd = fieldEnd;
850
- } else if (field.id === ID_BLOCK_DURATION) {
851
- durationTicks = readUint(buffer, field.dataOffset, field.size);
852
- }
853
- }
854
- if (blockStart !== null) {
855
- take(blockStart, blockEnd, durationTicks);
856
- }
857
- }
858
- return blocks;
859
- }
860
-
861
-
862
- /**
863
- * The rest of what a TrackEntry says about itself, RFC 9559 §5.1.4.1. Read
864
- * because the file states them and a releaser's own wording in `Name` is the
865
- * only thing we had before: "fors" and "SDH" in a menu were whatever text
866
- * someone happened to type.
867
- *
868
- * `FlagEnabled` defaults to 1 and means "the track is usable"; a track that
869
- * says 0 is counted but not offered. `FlagForced` applies only to subtitles and
870
- * defaults to 0. `FlagHearingImpaired` is set "if and only if the track is
871
- * suitable for users with hearing impairments". `FlagVisualImpaired`,
872
- * `FlagOriginal` and `FlagCommentary` bear on the AUDIO choice and are read
873
- * with that work, not here — see roadmap item 55.
874
- */
875
- const ID_FLAG_HEARING_IMPAIRED = 0x55ab;
876
- /**
877
- * The language as RFC 5646 writes it. The specification is a MUST: "If this
878
- * element is used, then any Language elements used in the same TrackEntry MUST
879
- * be ignored" — so where both are present, this one is the answer and the
880
- * three-letter code is not.
881
- */
882
- const ID_CUES = 0x1c53bb6b;
883
- const ID_CUE_POINT = 0xbb;
884
- const ID_CUE_TRACK_POSITIONS = 0xb7;
885
- const ID_CUE_TRACK = 0xf7;
886
- const ID_CUE_CLUSTER_POSITION = 0xf1;
887
-
888
- /** TrackType 17 is subtitles; 1 is video and 2 audio. */
889
- const TRACK_TYPE_SUBTITLE = 17;
890
- /** How much of the file start to read: the same window the keyframe reader uses. */
891
- /** Cap on the Cues read; a long film indexes to tens of KB. */
892
- const MAX_CUES_BYTES = 8 * 1024 * 1024;
893
-
894
- /**
895
- * The codecs whose blocks are text this proxy can turn into WebVTT.
896
- *
897
- * `S_TEXT/UTF8` is a plain line of text and needs nothing. `S_TEXT/ASS` and
898
- * `S_TEXT/SSA` carry a dialogue row whose fields have to be stripped, and their
899
- * header lives in CodecPrivate — supported, with the stripping done where the
900
- * cue is turned into WebVTT. `S_HDMV/PGS` and `S_VOBSUB` are pictures, not
901
- * text, and are deliberately absent: offering them would promise something this
902
- * path cannot deliver.
903
- */
904
- const TEXT_CODECS = new Set(["S_TEXT/UTF8", "S_TEXT/ASS", "S_TEXT/SSA"]);
905
-
906
- /**
907
- * @typedef {object} SubtitleTrackPlan
908
- * @property {number} trackNumber - As the blocks name it.
909
- * @property {number} declaredIndex - Its position among ALL of the file's
910
- * subtitle tracks, picture-based ones included — which is the number ffmpeg
911
- * gives the same stream in `0:s:N`, and therefore the only number the browser
912
- * ever names. Text tracks alone are not a numbering: a file whose PGS track
913
- * comes first would have every text track one lower here than in the browser.
914
- * @property {string} codecId
915
- * @property {string} language - The language the file declares: its RFC 5646
916
- * tag where it writes one, and the three-letter code otherwise. The
917
- * specification requires that order — where `LanguageBCP47` is present, the
918
- * `Language` element MUST be ignored.
919
- * @property {string} languageBcp47 - The RFC 5646 tag alone, or "".
920
- * @property {string} name - What the file calls the track, if anything.
921
- * @property {boolean} isDefault
922
- * @property {boolean} isForced - `FlagForced`: the track carries what a viewer
923
- * needs even when they asked for no subtitles — signs, and dialogue in
924
- * another language. It does NOT carry the film's own dialogue.
925
- * @property {boolean} isHearingImpaired - `FlagHearingImpaired`: suitable for
926
- * viewers who cannot hear, so it carries non-speech sound as well as speech.
927
- * @property {string} codecPrivate - The ASS/SSA header, base64, or "".
928
- * @property {number[]} clusterPositions - File offsets of clusters whose cue
929
- * points name this track, ascending. Empty when the file indexes only its
930
- * picture, and then the caller has to walk clusters as they arrive instead.
931
- */
932
-
933
-
934
- /**
935
- * Everything about a file's text subtitle tracks that can be learned without
936
- * reading the film.
937
- *
938
- * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
939
- * @param {number} fileSize
940
- * @returns {Promise<{ tracks: SubtitleTrackPlan[], declared: object[], secondsPerTick: number, segmentDataOffset: number } | null>}
941
- */
942
- async function readSubtitlePlan(readRange, fileSize) {
943
- const head = await readRange(0, Math.min(HEAD_BYTES, Math.max(0, fileSize - 1)));
944
- if (!head || head.length < 4 || head.readUInt32BE(0) !== 0x1a45dfa3) {
945
- return null;
946
- }
947
- const segment = findElement(head, ID_SEGMENT, []);
948
- if (!segment) {
949
- return null;
950
- }
951
- const base = segment.dataOffset;
952
-
953
- const info = findElement(head, ID_INFO, [], base);
954
- let scale = DEFAULT_TIMESTAMP_SCALE;
955
- if (info) {
956
- const declared = findElement(head, ID_TIMESTAMP_SCALE, [], info.dataOffset, info.dataOffset + info.size);
957
- if (declared) {
958
- const value = readUint(head, declared.dataOffset, declared.size);
959
- if (value > 0) {
960
- scale = value;
961
- }
962
- }
963
- }
964
-
965
- const tracksElement = findElement(head, ID_TRACKS, [], base);
966
- if (!tracksElement) {
967
- return null;
968
- }
969
- const tracksEnd = Math.min(head.length, tracksElement.dataOffset + tracksElement.size);
970
- /** @type {SubtitleTrackPlan[]} */
971
- const tracks = [];
972
- /**
973
- * Every subtitle track the file declares, in the order the Tracks element
974
- * names them, text or picture. This is not for extraction — `tracks` is —
975
- * but for lining ffmpeg's `0:s:N` numbering up against the container, which
976
- * only holds while nothing is missing from the middle of the list.
977
- *
978
- * @type {Array<{ trackNumber: number, codecId: string, language: string, name: string, isDefault: boolean, declaresDefault: boolean }>}
979
- */
980
- const declared = [];
981
- for (const entry of iterateElements(head, tracksElement.dataOffset, tracksEnd)) {
982
- if (entry.id !== ID_TRACK_ENTRY) {
983
- continue;
984
- }
985
- const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
986
- let trackNumber = null;
987
- let type = null;
988
- let codecId = "";
989
- let language = "";
990
- let name = "";
991
- let codecPrivate = "";
992
- // Matroska's `FlagDefault` DEFAULTS TO 1, so a file whose muxer wrote it on
993
- // no track is indistinguishable, once the default has been applied, from
994
- // one that wrote it on every track — which is how ffmpeg's banner prints it
995
- // and why the banner cannot answer this. Both are kept: what the flag
996
- // amounts to, and whether the file said anything at all.
997
- let isDefault = true;
998
- let declaresDefault = false;
999
- // Defaults straight from RFC 9559: a track is usable and not forced unless
1000
- // the file says otherwise, and the impaired flags are absent until claimed.
1001
- let isEnabled = true;
1002
- let isForced = false;
1003
- let isHearingImpaired = false;
1004
- let languageBcp47 = "";
1005
- for (const field of iterateElements(head, entry.dataOffset, entryEnd)) {
1006
- if (field.id === ID_TRACK_NUMBER) {
1007
- trackNumber = readUint(head, field.dataOffset, field.size);
1008
- } else if (field.id === ID_TRACK_TYPE) {
1009
- type = readUint(head, field.dataOffset, field.size);
1010
- } else if (field.id === ID_CODEC_ID) {
1011
- codecId = readString(head, field);
1012
- } else if (field.id === ID_LANGUAGE) {
1013
- language = readString(head, field);
1014
- } else if (field.id === ID_LANGUAGE_BCP47) {
1015
- languageBcp47 = readString(head, field);
1016
- } else if (field.id === ID_NAME) {
1017
- name = readString(head, field);
1018
- } else if (field.id === ID_FLAG_DEFAULT) {
1019
- isDefault = readUint(head, field.dataOffset, field.size) === 1;
1020
- declaresDefault = true;
1021
- } else if (field.id === ID_FLAG_ENABLED) {
1022
- // An element written with zero length carries its default, which for
1023
- // this one is 1 — so an empty element must not read as "unusable", and
1024
- // neither must a value outside the declared 0-1 range. Only an explicit
1025
- // zero takes a track away.
1026
- isEnabled = field.size === 0 || readUint(head, field.dataOffset, field.size) !== 0;
1027
- } else if (field.id === ID_FLAG_FORCED) {
1028
- isForced = field.size > 0 && readUint(head, field.dataOffset, field.size) !== 0;
1029
- } else if (field.id === ID_FLAG_HEARING_IMPAIRED) {
1030
- isHearingImpaired = field.size > 0 && readUint(head, field.dataOffset, field.size) !== 0;
1031
- } else if (field.id === ID_CODEC_PRIVATE) {
1032
- codecPrivate = head.toString("base64", field.dataOffset, field.dataOffset + field.size);
1033
- }
1034
- }
1035
- if (type !== TRACK_TYPE_SUBTITLE || trackNumber === null) {
1036
- continue;
1037
- }
1038
- // A track the file marks unusable is still COUNTED. FlagEnabled says "the
1039
- // track is usable", and a player should not offer it — but ffmpeg does not
1040
- // drop it: `matroskadec.c` parses `MATROSKA_ID_TRACKFLAGENABLED` as
1041
- // `EBML_NONE`, reading the element and keeping nothing, so the stream is
1042
- // created and numbered like any other. Leaving it out of this list would
1043
- // therefore shift `declaredIndex` off ffmpeg's `0:s:N` for every track
1044
- // after it, which is the numbering defect this file was fixed for a day
1045
- // earlier. It is counted here and refused where it is offered instead.
1046
- //
1047
- // `language` here stays the three-letter code, because this list exists to
1048
- // be lined up against ffmpeg's banner, which prints that code. The RFC 5646
1049
- // tag rides beside it for whoever displays the track.
1050
- declared.push({
1051
- trackNumber,
1052
- codecId,
1053
- language,
1054
- languageBcp47,
1055
- name,
1056
- isDefault,
1057
- declaresDefault,
1058
- isEnabled,
1059
- isForced,
1060
- isHearingImpaired
1061
- });
1062
- if (!TEXT_CODECS.has(codecId) || !isEnabled) {
1063
- continue;
1064
- }
1065
- tracks.push({
1066
- trackNumber,
1067
- declaredIndex: declared.length - 1,
1068
- codecId,
1069
- // This list is ours and is not compared with ffmpeg's, so it carries the
1070
- // language the file states most precisely: where RFC 5646 is written, the
1071
- // three-letter code MUST be ignored.
1072
- language: languageBcp47 || language,
1073
- languageBcp47,
1074
- name,
1075
- isDefault,
1076
- isForced,
1077
- isHearingImpaired,
1078
- codecPrivate,
1079
- clusterPositions: []
1080
- });
1081
- }
1082
- if (tracks.length === 0) {
1083
- return { tracks, declared, secondsPerTick: scale / 1e9, segmentDataOffset: base };
1084
- }
1085
-
1086
- // Where the clusters holding those tracks are. A file that indexes only its
1087
- // picture leaves these empty, which is not a failure: the caller then reads
1088
- // the clusters the viewer's own playback brings in.
1089
- const seekHead = findElement(head, ID_SEEK_HEAD, [], base);
1090
- let cuesRelative;
1091
- if (seekHead) {
1092
- const seekEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
1093
- for (const seek of iterateElements(head, seekHead.dataOffset, seekEnd)) {
1094
- if (seek.id !== ID_SEEK) {
1095
- continue;
1096
- }
1097
- let target = null;
1098
- let position = null;
1099
- for (const field of iterateElements(head, seek.dataOffset, Math.min(seekEnd, seek.dataOffset + seek.size))) {
1100
- if (field.id === ID_SEEK_ID) {
1101
- target = readUint(head, field.dataOffset, field.size);
1102
- } else if (field.id === ID_SEEK_POSITION) {
1103
- position = readUint(head, field.dataOffset, field.size);
1104
- }
1105
- }
1106
- if (target === ID_CUES && position !== null) {
1107
- cuesRelative = position;
1108
- }
1109
- }
1110
- }
1111
- if (cuesRelative !== undefined) {
1112
- const cuesAt = base + cuesRelative;
1113
- if (cuesAt > 0 && cuesAt < fileSize) {
1114
- const chunk = await readRange(cuesAt, Math.min(fileSize - 1, cuesAt + MAX_CUES_BYTES));
1115
- const element = chunk && [...iterateElements(chunk, 0, chunk.length)][0];
1116
- if (element && element.id === ID_CUES) {
1117
- const body = chunk.subarray(element.dataOffset, Math.min(chunk.length, element.dataOffset + element.size));
1118
- const byTrack = new Map(tracks.map((track) => [track.trackNumber, new Set()]));
1119
- for (const point of iterateElements(body, 0, body.length)) {
1120
- if (point.id !== ID_CUE_POINT) {
1121
- continue;
1122
- }
1123
- const pointEnd = Math.min(body.length, point.dataOffset + point.size);
1124
- for (const field of iterateElements(body, point.dataOffset, pointEnd)) {
1125
- if (field.id !== ID_CUE_TRACK_POSITIONS) {
1126
- continue;
1127
- }
1128
- let cueTrack = null;
1129
- let position = null;
1130
- for (const inner of iterateElements(body, field.dataOffset, Math.min(pointEnd, field.dataOffset + field.size))) {
1131
- if (inner.id === ID_CUE_TRACK) {
1132
- cueTrack = readUint(body, inner.dataOffset, inner.size);
1133
- } else if (inner.id === ID_CUE_CLUSTER_POSITION) {
1134
- position = readUint(body, inner.dataOffset, inner.size);
1135
- }
1136
- }
1137
- if (position !== null && byTrack.has(cueTrack)) {
1138
- byTrack.get(cueTrack).add(base + position);
1139
- }
1140
- }
1141
- }
1142
- for (const track of tracks) {
1143
- track.clusterPositions = [...byTrack.get(track.trackNumber)].sort((left, right) => left - right);
1144
- }
1145
- }
1146
- }
1147
- }
1148
- return { tracks, declared, secondsPerTick: scale / 1e9, segmentDataOffset: base };
1149
- }
1150
-
1151
- /**
1152
- * The cues of one track inside one cluster.
1153
- *
1154
- * @param {Buffer} bytes - The cluster, from its own element header onward.
1155
- * @param {number} trackNumber
1156
- * @param {number} secondsPerTick
1157
- * @returns {{ startSeconds: number, endSeconds: number | null, text: string }[]}
1158
- */
1159
- function harvestCluster(bytes, trackNumber, secondsPerTick) {
1160
- const header = [...iterateElements(bytes, 0, bytes.length)][0];
1161
- if (!header) {
1162
- return [];
1163
- }
1164
- const blocks = blocksOfTrack(
1165
- bytes,
1166
- { dataOffset: header.dataOffset, size: header.size },
1167
- trackNumber,
1168
- secondsPerTick
1169
- );
1170
- // The payload is handed on as BYTES. What those bytes mean — which of them
1171
- // are the text and which are the eight fields Matroska puts before it — is
1172
- // stated by the container's specification and answered by
1173
- // `MatroskaContainer.cueTextOf`, not here: this function's subject is where a
1174
- // block sits and how long it lasts.
1175
- return blocks.map((block) => ({
1176
- startSeconds: block.startSeconds,
1177
- endSeconds: block.durationSeconds === null ? null : block.startSeconds + block.durationSeconds,
1178
- payload: block.payload
1179
- }));
1180
- }
1181
-
1182
- // ---------------------------------------------------------------------------
1183
- // RFC 9559 speaking about Matroska: the Cues table that says where a keyframe is.
1184
- // Here because the class is the only way in.
1185
- // ---------------------------------------------------------------------------
1186
-
1187
- // Element ids, from the Matroska specification.
1188
- const ID_CUE_TIME = 0xb3;
1189
- // TrackType 1 is video; 2 is audio, 17 subtitles, and the rest are rarer still.
1190
- const TRACK_TYPE_VIDEO = 1;
1191
-
1192
- // How much of the file start to read. Must cover the EBML header, the SeekHead
1193
- // and Info; 64 KB is generous for every real muxer (the file measured needed
1194
- // under 4 KB) while still trivial to fetch.
1195
- // Cap on the Cues read. A two-hour film indexes to tens of KB; anything beyond
1196
- // this is not a normal index and not worth pulling over a torrent.
1197
- // Cap on a Tracks read, for the rare file whose Tracks element sits outside the
1198
- // head window. Track entries are small, so a file with dozens of them still
1199
- // fits well inside this.
1200
- const MAX_TRACKS_BYTES = 1024 * 1024;
1201
- // Matroska's default timestamp scale (nanoseconds per tick) when Info omits it.
1202
-
1203
- /**
1204
- * Whether this looks like a Matroska file (the EBML magic `0x1A45DFA3`).
1205
- *
1206
- * @param {Buffer} head
1207
- * @returns {boolean}
1208
- */
1209
- function isMatroska(head) {
1210
- return head.length >= 4 && head.readUInt32BE(0) === 0x1a45dfa3;
1211
- }
1212
-
1213
- /**
1214
- * Locate the Segment element and the SeekHead entries inside it.
1215
- *
1216
- * Seek positions are relative to the start of Segment's payload, not to the
1217
- * file, so that base has to come back with them.
1218
- *
1219
- * @param {Buffer} head
1220
- * @returns {{ segmentDataOffset: number, entries: Map<number, number> } | null}
1221
- */
1222
- function readSeekHead(head) {
1223
- let segmentDataOffset = -1;
1224
- for (const element of iterateElements(head)) {
1225
- if (element.id === ID_SEGMENT) {
1226
- segmentDataOffset = element.dataOffset;
1227
- break;
1228
- }
1229
- }
1230
- if (segmentDataOffset < 0) {
1231
- return null;
1232
- }
1233
-
1234
- const seekHead = findElement(head, ID_SEEK_HEAD, [], segmentDataOffset);
1235
- if (!seekHead) {
1236
- return null;
1237
- }
1238
-
1239
- const entries = new Map();
1240
- const seekHeadEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
1241
- for (const seek of iterateElements(head, seekHead.dataOffset, seekHeadEnd)) {
1242
- if (seek.id !== ID_SEEK) {
1243
- continue;
1244
- }
1245
- const seekEnd = Math.min(seekHeadEnd, seek.dataOffset + seek.size);
1246
- let targetId = null;
1247
- let position = null;
1248
- for (const field of iterateElements(head, seek.dataOffset, seekEnd)) {
1249
- if (field.id === ID_SEEK_ID) {
1250
- targetId = readUint(head, field.dataOffset, field.size);
1251
- } else if (field.id === ID_SEEK_POSITION) {
1252
- position = readUint(head, field.dataOffset, field.size);
1253
- }
1254
- }
1255
- if (targetId !== null && position !== null) {
1256
- entries.set(targetId, position);
1257
- }
1258
- }
1259
- return { segmentDataOffset, entries };
1260
- }
1261
-
1262
- /**
1263
- * Timestamp scale (nanoseconds per tick) declared in Info, or the default.
1264
- *
1265
- * @param {Buffer} head
1266
- * @param {number} segmentDataOffset
1267
- * @returns {number}
1268
- */
1269
- function readTimestampScale(head, segmentDataOffset) {
1270
- const info = findElement(head, ID_INFO, [], segmentDataOffset);
1271
- if (!info) {
1272
- return DEFAULT_TIMESTAMP_SCALE;
1273
- }
1274
- const infoEnd = Math.min(head.length, info.dataOffset + info.size);
1275
- for (const field of iterateElements(head, info.dataOffset, infoEnd)) {
1276
- if (field.id === ID_TIMESTAMP_SCALE) {
1277
- const scale = readUint(head, field.dataOffset, field.size);
1278
- return scale > 0 ? scale : DEFAULT_TIMESTAMP_SCALE;
1279
- }
1280
- }
1281
- return DEFAULT_TIMESTAMP_SCALE;
1282
- }
1283
-
1284
- /**
1285
- * The number of the first video track, from a Tracks payload.
1286
- *
1287
- * The FIRST one, because that is the track ffmpeg is told to copy (`0:v:0`).
1288
- *
1289
- * @param {Buffer} buffer
1290
- * @param {{ dataOffset: number, size: number }} tracks
1291
- * @returns {number | null}
1292
- */
1293
- function readVideoTrackNumber(buffer, tracks) {
1294
- const tracksEnd = Math.min(buffer.length, tracks.dataOffset + tracks.size);
1295
- for (const entry of iterateElements(buffer, tracks.dataOffset, tracksEnd)) {
1296
- if (entry.id !== ID_TRACK_ENTRY) {
1297
- continue;
1298
- }
1299
- const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
1300
- let number = null;
1301
- let type = null;
1302
- for (const field of iterateElements(buffer, entry.dataOffset, entryEnd)) {
1303
- if (field.id === ID_TRACK_NUMBER) {
1304
- number = readUint(buffer, field.dataOffset, field.size);
1305
- } else if (field.id === ID_TRACK_TYPE) {
1306
- type = readUint(buffer, field.dataOffset, field.size);
1307
- }
1308
- }
1309
- if (number !== null && type === TRACK_TYPE_VIDEO) {
1310
- return number;
1311
- }
1312
- }
1313
- return null;
1314
- }
1315
-
1316
- /**
1317
- * Cue times (seconds, ascending) of ONE track, from a Cues payload.
1318
- *
1319
- * The track is the whole point, and leaving it out is what this reader got
1320
- * wrong until 2026-08-18. A CuePoint belongs to the track named inside its
1321
- * CueTrackPositions, and a muxer indexes whatever tracks it likes: RFC 9559
1322
- * says each keyframe of a video track SHOULD be referenced, and that the Cues
1323
- * Element "can be used to index every single timestamp of every Block or they
1324
- * can be indexed selectively". Both field files index their SUBTITLE tracks as
1325
- * well — `Minions.and.Monsters.1080p.mkv` has 2778 video entries every 2.002 s
1326
- * plus 4669 across four subtitle tracks; `Moana.2 … MegaPeer.mkv` has 1055
1327
- * video entries plus 5007 across five.
1328
- *
1329
- * Read without the track, those extra times enter the cut list as though they
1330
- * were keyframes. ffmpeg can only cut a COPIED picture at a real keyframe at or
1331
- * after the time it is given, so every cut asked for at one of them lands late
1332
- * — which is exactly what the field measured: on the first file every deviation
1333
- * was 2.002 s, that file's own keyframe spacing, and on the second the median
1334
- * was 6.3 s with a worst case of 21 s. Never once negative.
1335
- *
1336
- * @param {Buffer} cues
1337
- * @param {number} timestampScale - Nanoseconds per tick.
1338
- * @param {number | null} trackNumber - Null keeps every entry, which is right
1339
- * only for a file that indexes one track.
1340
- * @returns {number[]}
1341
- */
1342
- function readCueTimes(cues, timestampScale, trackNumber) {
1343
- const times = [];
1344
- const secondsPerTick = timestampScale / 1e9;
1345
- for (const point of iterateElements(cues)) {
1346
- if (point.id !== ID_CUE_POINT) {
1347
- continue;
1348
- }
1349
- const pointEnd = Math.min(cues.length, point.dataOffset + point.size);
1350
- let time = null;
1351
- let belongsToTrack = trackNumber === null;
1352
- for (const field of iterateElements(cues, point.dataOffset, pointEnd)) {
1353
- if (field.id === ID_CUE_TIME) {
1354
- time = readUint(cues, field.dataOffset, field.size) * secondsPerTick;
1355
- continue;
1356
- }
1357
- if (field.id !== ID_CUE_TRACK_POSITIONS || belongsToTrack) {
1358
- continue;
1359
- }
1360
- const positionsEnd = Math.min(pointEnd, field.dataOffset + field.size);
1361
- for (const inner of iterateElements(cues, field.dataOffset, positionsEnd)) {
1362
- if (inner.id === ID_CUE_TRACK && readUint(cues, inner.dataOffset, inner.size) === trackNumber) {
1363
- belongsToTrack = true;
1364
- break;
1365
- }
1366
- }
1367
- }
1368
- if (time !== null && belongsToTrack) {
1369
- times.push(time);
1370
- }
1371
- }
1372
- times.sort((left, right) => left - right);
1373
- return times;
1374
- }
1375
-
1376
- /**
1377
- * Read the keyframe times of a Matroska file using only two point reads.
1378
- *
1379
- * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
1380
- * Inclusive byte range reader; returns null when the range is unavailable.
1381
- * @param {number} fileSize
1382
- * @returns {Promise<number[] | null>} Ascending seconds, or null when the file
1383
- * carries no usable index (see the module doc for when that happens).
1384
- */
1385
- async function readMatroskaKeyframeTimes(readRange, fileSize) {
1386
- const head = await readRange(0, Math.min(HEAD_BYTES, Math.max(0, fileSize - 1)));
1387
- if (!head || !isMatroska(head)) {
1388
- return null;
1389
- }
1390
-
1391
- const seekHead = readSeekHead(head);
1392
- if (!seekHead) {
1393
- return null; // No SeekHead — a streamed or truncated mux.
1394
- }
1395
-
1396
- const cuesRelative = seekHead.entries.get(ID_CUES);
1397
- if (cuesRelative === undefined) {
1398
- return null; // Indexless file: live capture, interrupted write, damaged upload.
1399
- }
1400
-
1401
- // SeekHead positions are relative to Segment's payload.
1402
- const cuesOffset = seekHead.segmentDataOffset + cuesRelative;
1403
- if (!Number.isFinite(cuesOffset) || cuesOffset <= 0 || cuesOffset >= fileSize) {
1404
- return null;
1405
- }
1406
-
1407
- // The element header states the payload size, but reading it costs a round
1408
- // trip; fetch a bounded window instead and let the parser stop at the end of
1409
- // what it got. Cues sits near the file end, so the window is clamped there.
1410
- const cuesEnd = Math.min(fileSize - 1, cuesOffset + MAX_CUES_BYTES);
1411
- const cuesChunk = await readRange(cuesOffset, cuesEnd);
1412
- if (!cuesChunk || cuesChunk.length === 0) {
1413
- return null;
1414
- }
1415
-
1416
- // The window starts exactly at the Cues element, so its own header comes
1417
- // first; step over it to reach the CuePoints.
1418
- const cuesElement = [...iterateElements(cuesChunk, 0, cuesChunk.length)][0];
1419
- if (!cuesElement || cuesElement.id !== ID_CUES) {
1420
- return null;
1421
- }
1422
- const payloadEnd = Math.min(cuesChunk.length, cuesElement.dataOffset + cuesElement.size);
1423
- const payload = cuesChunk.subarray(cuesElement.dataOffset, payloadEnd);
1424
-
1425
- // Whose entries to keep. Tracks sits near the head and is normally inside the
1426
- // bytes already fetched; when it is not, SeekHead says where it is and one
1427
- // more short read gets it. Nothing is fetched twice and nothing is scanned.
1428
- const videoTrack = await readVideoTrack(readRange, head, seekHead, fileSize);
1429
- const timestampScale = readTimestampScale(head, seekHead.segmentDataOffset);
1430
- const times = readCueTimes(payload, timestampScale, videoTrack);
1431
- if (times.length > 0) {
1432
- return times;
1433
- }
1434
- if (videoTrack === null) {
1435
- return null;
1436
- }
1437
- // The filter left nothing, and that is not an answer about the file: a table
1438
- // exists, and this reader simply failed to recognise which of its entries
1439
- // belong to the picture — a track numbered one way in Tracks and another in
1440
- // the cue points, or an entry with no CueTrack at all. Returning null here
1441
- // would put an EVEN grid on a copied picture, which is the failure this
1442
- // module exists to prevent, so the unfiltered table is used instead: less
1443
- // exact than the picture's own keyframes, better than a grid that has nothing
1444
- // to do with the file.
1445
- const unfiltered = readCueTimes(payload, timestampScale, null);
1446
- return unfiltered.length > 0 ? unfiltered : null;
1447
- }
1448
-
1449
- /**
1450
- * The video track's number — from the head when it is there, and from one extra
1451
- * short read when it is not.
1452
- *
1453
- * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
1454
- * @param {Buffer} head
1455
- * @param {{ segmentDataOffset: number, entries: Map<number, number> }} seekHead
1456
- * @param {number} fileSize
1457
- * @returns {Promise<number | null>} Null when Tracks cannot be read at all, and
1458
- * then every cue entry is kept — right for a file that indexes only its
1459
- * picture, wrong for one that does not, and nothing here can tell them apart.
1460
- * Refusing the index instead would put an even grid on a copied picture,
1461
- * which is the failure this reader exists to prevent.
1462
- */
1463
- async function readVideoTrack(readRange, head, seekHead, fileSize) {
1464
- const inHead = findElement(head, ID_TRACKS, [], seekHead.segmentDataOffset);
1465
- if (inHead && inHead.dataOffset + inHead.size <= head.length) {
1466
- return readVideoTrackNumber(head, inHead);
1467
- }
1468
- const relative = seekHead.entries.get(ID_TRACKS);
1469
- if (relative === undefined) {
1470
- return null;
1471
- }
1472
- const offset = seekHead.segmentDataOffset + relative;
1473
- if (!Number.isFinite(offset) || offset <= 0 || offset >= fileSize) {
1474
- return null;
1475
- }
1476
- const chunk = await readRange(offset, Math.min(fileSize - 1, offset + MAX_TRACKS_BYTES));
1477
- if (!chunk || chunk.length === 0) {
1478
- return null;
1479
- }
1480
- const element = [...iterateElements(chunk, 0, chunk.length)][0];
1481
- if (!element || element.id !== ID_TRACKS) {
1482
- return null;
1483
- }
1484
- return readVideoTrackNumber(chunk, { dataOffset: element.dataOffset, size: element.size });
1485
- }
1
+ /**
2
+ * @file Matroska/WebM container — RFC 9559.
3
+ *
4
+ * Reads Tracks in one pass for all media types (video, audio, subtitle).
5
+ * Implements spec-accurate flag handling:
6
+ * - FlagEnabled 0xB9 default 1, zero-length element = default (not disabled)
7
+ * - FlagDefault 0x88 default 1, declaresDefault tracks whether element was written
8
+ * - FlagForced 0x55AA only for subtitles, FlagHearingImpaired 0x55AB, FlagVisualImpaired 0x55AC,
9
+ * FlagTextDescriptions 0x55AD, FlagOriginal 0x55AE, FlagCommentary 0x55AF
10
+ * - Language 0x22B59C default "eng", LanguageBCP47 0x22B59D MUST — when present, Language ignored
11
+ * - CodecID 0x86, CodecPrivate 0x63A2, Name 0x536E, TrackType 0x83 (1 video, 2 audio, 17 subtitle)
12
+ *
13
+ * Byte-level EBML element walking is `ebml-reader.js`, which is the format's
14
+ * grammar and not this container's own statements. Everything Matroska DOES
15
+ * state about itself — the Tracks walk, the Cues, the keyframe times they name,
16
+ * the cluster positions, the blocks inside a cluster —
17
+ * is read in this module: each of those is RFC 9559 speaking about Matroska,
18
+ * and the class is the only way in.
19
+ */
20
+
21
+ import { Container } from "./Container.js";
22
+ import { VideoTrack } from "../tracks/VideoTrack.js";
23
+ import { AudioTrack } from "../tracks/AudioTrack.js";
24
+ import { TextSubtitleTrack, TEXT_CODECS_MATROSKA } from "../tracks/TextSubtitleTrack.js";
25
+ import { ImageSubtitleTrack } from "../tracks/ImageSubtitleTrack.js";
26
+ import { ContainerTrack } from "../tracks/ContainerTrack.js";
27
+ import { findElement, iterateElements, readFloat, readUint, readVint } from "./ebml-reader.js";
28
+
29
+ const HEAD_BYTES = 64 * 1024;
30
+ /** Enough to read any cluster's own element header. */
31
+ const CLUSTER_HEADER_PROBE = 64;
32
+ /**
33
+ * The largest cluster this will read whole. Real muxers write clusters of a few
34
+ * megabytes; anything past this is not a cluster boundary we recognised and
35
+ * reading it would be a large read for nothing.
36
+ */
37
+ const MAX_CLUSTER_BYTES = 32 * 1024 * 1024;
38
+
39
+ const ID_SEGMENT = 0x18538067;
40
+ const ID_SEEK_HEAD = 0x114d9b74;
41
+ const ID_SEEK = 0x4dbb;
42
+ const ID_SEEK_ID = 0x53ab;
43
+ const ID_SEEK_POSITION = 0x53ac;
44
+ const ID_INFO = 0x1549a966;
45
+ const ID_TIMESTAMP_SCALE = 0x2ad7b1;
46
+ const ID_DURATION = 0x4489;
47
+ const ID_CLUSTER = 0x1f43b675;
48
+ const ID_TIMESTAMP = 0xe7;
49
+ const ID_SIMPLE_BLOCK = 0xa3;
50
+ const ID_BLOCK_GROUP = 0xa0;
51
+ /** RFC 9559 §5.1.2.1: nanoseconds per tick when Info omits TimestampScale. */
52
+ const DEFAULT_TIMESTAMP_SCALE = 1_000_000;
53
+ /**
54
+ * How much to read at a cluster whose position came from the SeekHead. A
55
+ * cluster's Timestamp is the first child every muxer writes, so this only has
56
+ * to cover the element header and that one field.
57
+ */
58
+ const CLUSTER_PROBE_BYTES = 4 * 1024;
59
+ const ID_TRACKS = 0x1654ae6b;
60
+ const ID_TRACK_ENTRY = 0xae;
61
+ const ID_TRACK_NUMBER = 0xd7;
62
+ const ID_TRACK_TYPE = 0x83;
63
+ const ID_FLAG_ENABLED = 0xb9;
64
+ const ID_FLAG_DEFAULT = 0x88;
65
+ const ID_FLAG_FORCED = 0x55aa;
66
+ const ID_FLAG_HEARING = 0x55ab;
67
+ const ID_FLAG_VISUAL = 0x55ac;
68
+ const ID_FLAG_TEXT_DESCR = 0x55ad;
69
+ const ID_FLAG_ORIGINAL = 0x55ae;
70
+ const ID_FLAG_COMMENTARY = 0x55af;
71
+ const ID_CODEC_ID = 0x86;
72
+ const ID_CODEC_PRIVATE = 0x63a2;
73
+ const ID_LANGUAGE = 0x22b59c;
74
+ const ID_LANGUAGE_BCP47 = 0x22b59d;
75
+ const ID_NAME = 0x536e;
76
+ const ID_VIDEO = 0xe0;
77
+ const ID_AUDIO = 0xe1;
78
+ const ID_PIXEL_WIDTH = 0xb0;
79
+ const ID_PIXEL_HEIGHT = 0xba;
80
+ const ID_DISPLAY_WIDTH = 0x54b0;
81
+ const ID_DISPLAY_HEIGHT = 0x54ba;
82
+ const ID_SAMPLING_FREQUENCY = 0xb5;
83
+ const ID_CHANNELS = 0x9f;
84
+ /**
85
+ * ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect — the eight
86
+ * fields Matroska writes before the text of an SSA/ASS event. See
87
+ * {@link MatroskaContainer.cueTextOf} for the quotation this comes from.
88
+ */
89
+ const ASS_FIELDS_BEFORE_TEXT = 8;
90
+
91
+ function readString(buf, el) {
92
+ return buf.toString("utf8", el.dataOffset, el.dataOffset + el.size).replace(/\0+$/, "");
93
+ }
94
+
95
+ export class MatroskaContainer extends Container {
96
+ get formatName() {
97
+ return "matroska";
98
+ }
99
+
100
+ static detect(head) {
101
+ return isMatroska(head);
102
+ }
103
+
104
+ /**
105
+ * The keyframe times this container's own index states, in ascending seconds.
106
+ *
107
+ * Static so a caller that has bytes and no container can ask; the instance
108
+ * form is {@link Container#readKeyframeIndex}.
109
+ *
110
+ * @param {(start:number,end:number)=>Promise<Buffer|null>} readRange
111
+ * @param {number} fileSize
112
+ * @returns {Promise<number[]|null>} Null where the container has no index.
113
+ */
114
+ static readKeyframeTimes(readRange, fileSize) {
115
+ return readMatroskaKeyframeTimes(readRange, fileSize);
116
+ }
117
+
118
+ /**
119
+ * This container's subtitle tracks, its Cues table and the cluster positions
120
+ * they name — RFC 9559 §5.1.4 and §5.1.3.
121
+ *
122
+ * @param {(start:number,end:number)=>Promise<Buffer|null>} readRange
123
+ * @param {number} fileSize
124
+ * @returns {Promise<object|null>}
125
+ */
126
+ static readSubtitlePlan(readRange, fileSize) {
127
+ return readSubtitlePlan(readRange, fileSize);
128
+ }
129
+
130
+ /**
131
+ * The same reading, over the file this container was built on.
132
+ *
133
+ * The static form exists for a caller that has bytes and no container; this
134
+ * is the one to use otherwise, because the reader is already here.
135
+ *
136
+ * @returns {Promise<object|null>}
137
+ */
138
+ readSubtitlePlan() {
139
+ return MatroskaContainer.readSubtitlePlan(this.readRange, this.fileSize);
140
+ }
141
+
142
+ /**
143
+ * The blocks one track has inside a cluster, with their times.
144
+ *
145
+ * The payload is handed back as BYTES: what those bytes mean is
146
+ * {@link MatroskaContainer.cueTextOf}'s answer, and this method's subject is
147
+ * only where a block sits and how long it lasts.
148
+ *
149
+ * @param {Buffer} bytes - The cluster, from its own element header onward.
150
+ * @param {number} trackNumber
151
+ * @param {number} secondsPerTick
152
+ * @returns {{ startSeconds: number, endSeconds: number | null, payload: Buffer }[]}
153
+ */
154
+ static blocksInCluster(bytes, trackNumber, secondsPerTick) {
155
+ return harvestCluster(bytes, trackNumber, secondsPerTick);
156
+ }
157
+
158
+ /**
159
+ * The blocks one track has inside a cluster whose bounds are already known —
160
+ * RFC 9559 §5.1.3.4 (SimpleBlock) and §5.1.3.5 (BlockGroup).
161
+ *
162
+ * The same reading as {@link MatroskaContainer.blocksInCluster}, entered where
163
+ * the caller has already parsed the cluster's own header.
164
+ *
165
+ * @param {Buffer} buffer
166
+ * @param {{ dataOffset: number, size: number }} cluster
167
+ * @param {number} trackNumber
168
+ * @param {number} secondsPerTick
169
+ * @returns {{ startSeconds: number, durationSeconds: number | null, payload: Buffer }[]}
170
+ */
171
+ static blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick) {
172
+ return blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick);
173
+ }
174
+
175
+ /**
176
+ * Duration and the start of this file's own timeline, per RFC 9559 §5.1.2.
177
+ *
178
+ * Duration is stated in `Info` as a FLOAT in ticks, so it needs the file's
179
+ * `TimestampScale` to become seconds. The start of the timeline is not stated
180
+ * anywhere — Matroska has no such element — so it is the timestamp of the
181
+ * first Cluster, which is what the first frame is placed against.
182
+ *
183
+ * @returns {Promise<import("./Container.js").ContainerMediaInfo>}
184
+ */
185
+ async readMediaInfo() {
186
+ if (this.mediaInfo) {
187
+ return this.mediaInfo;
188
+ }
189
+ /** @type {import("./Container.js").ContainerMediaInfo} */
190
+ const info = { format: this.formatName, durationSeconds: null, startTimeSeconds: null };
191
+ this.mediaInfo = info;
192
+ const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
193
+ if (!head || !isMatroska(head)) {
194
+ return info;
195
+ }
196
+ const segment = findElement(head, ID_SEGMENT, []);
197
+ if (!segment) {
198
+ return info;
199
+ }
200
+ const scale = MatroskaContainer.#timestampScaleOf(head, segment.dataOffset);
201
+ const infoElement = findElement(head, ID_INFO, [], segment.dataOffset);
202
+ if (infoElement) {
203
+ const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
204
+ for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
205
+ if (field.id !== ID_DURATION) {
206
+ continue;
207
+ }
208
+ const ticks = readFloat(head, field.dataOffset, field.size);
209
+ if (ticks !== null && ticks > 0) {
210
+ info.durationSeconds = (ticks * scale) / 1e9;
211
+ }
212
+ break;
213
+ }
214
+ }
215
+ info.startTimeSeconds = await this.#firstClusterSeconds(head, segment.dataOffset, scale);
216
+ return info;
217
+ }
218
+
219
+ /**
220
+ * `TimestampScale` from Info, or the specification's default.
221
+ *
222
+ * @param {Buffer} head
223
+ * @param {number} segmentDataOffset
224
+ * @returns {number} Nanoseconds per tick.
225
+ */
226
+ static #timestampScaleOf(head, segmentDataOffset) {
227
+ const infoElement = findElement(head, ID_INFO, [], segmentDataOffset);
228
+ if (!infoElement) {
229
+ return DEFAULT_TIMESTAMP_SCALE;
230
+ }
231
+ const infoEnd = Math.min(head.length, infoElement.dataOffset + infoElement.size);
232
+ for (const field of iterateElements(head, infoElement.dataOffset, infoEnd)) {
233
+ if (field.id === ID_TIMESTAMP_SCALE) {
234
+ const scale = readUint(head, field.dataOffset, field.size);
235
+ return scale > 0 ? scale : DEFAULT_TIMESTAMP_SCALE;
236
+ }
237
+ }
238
+ return DEFAULT_TIMESTAMP_SCALE;
239
+ }
240
+
241
+ /**
242
+ * The timestamp of the first Cluster, in seconds.
243
+ *
244
+ * Tried in the head window first, because a muxer writes the first cluster
245
+ * straight after Tracks and both usually fit; a file whose Tracks element is
246
+ * large enough to push it out is answered from the SeekHead instead, with one
247
+ * short read at the position it names.
248
+ *
249
+ * @param {Buffer} head
250
+ * @param {number} segmentDataOffset
251
+ * @param {number} scale - Nanoseconds per tick.
252
+ * @returns {Promise<number | null>} Null when no cluster could be read.
253
+ */
254
+ async #firstClusterSeconds(head, segmentDataOffset, scale) {
255
+ /**
256
+ * @param {Buffer} buffer
257
+ * @param {number} dataOffset
258
+ * @param {number} end
259
+ * @returns {number | null}
260
+ */
261
+ const timestampIn = (buffer, dataOffset, end) => {
262
+ for (const field of iterateElements(buffer, dataOffset, end)) {
263
+ if (field.id === ID_TIMESTAMP) {
264
+ const ticks = readUint(buffer, field.dataOffset, field.size);
265
+ return Number.isFinite(ticks) ? (ticks * scale) / 1e9 : null;
266
+ }
267
+ // Timestamp is written before any frame. Stopping at the first one keeps
268
+ // this from walking a cluster's whole payload, which is megabytes and
269
+ // usually not in the buffer at all.
270
+ if (field.id === ID_SIMPLE_BLOCK || field.id === ID_BLOCK_GROUP) {
271
+ return null;
272
+ }
273
+ }
274
+ return null;
275
+ };
276
+
277
+ for (const element of iterateElements(head, segmentDataOffset, head.length)) {
278
+ if (element.id !== ID_CLUSTER) {
279
+ continue;
280
+ }
281
+ return timestampIn(head, element.dataOffset, Math.min(head.length, element.dataOffset + element.size));
282
+ }
283
+
284
+ const position = MatroskaContainer.#seekPositionOf(head, segmentDataOffset, ID_CLUSTER);
285
+ if (position === null) {
286
+ return null;
287
+ }
288
+ const at = segmentDataOffset + position;
289
+ if (at >= this.fileSize) {
290
+ return null;
291
+ }
292
+ const chunk = await this.readRange(at, Math.min(this.fileSize - 1, at + CLUSTER_PROBE_BYTES - 1));
293
+ if (!chunk) {
294
+ return null;
295
+ }
296
+ for (const element of iterateElements(chunk, 0, chunk.length)) {
297
+ if (element.id !== ID_CLUSTER) {
298
+ continue;
299
+ }
300
+ return timestampIn(chunk, element.dataOffset, Math.min(chunk.length, element.dataOffset + element.size));
301
+ }
302
+ return null;
303
+ }
304
+
305
+ /**
306
+ * Where the SeekHead says an element lives, relative to the Segment's payload.
307
+ *
308
+ * @param {Buffer} head
309
+ * @param {number} segmentDataOffset
310
+ * @param {number} wantedId
311
+ * @returns {number | null}
312
+ */
313
+ static #seekPositionOf(head, segmentDataOffset, wantedId) {
314
+ const seekHead = findElement(head, ID_SEEK_HEAD, [], segmentDataOffset);
315
+ if (!seekHead) {
316
+ return null;
317
+ }
318
+ const seekHeadEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
319
+ for (const seek of iterateElements(head, seekHead.dataOffset, seekHeadEnd)) {
320
+ if (seek.id !== ID_SEEK) {
321
+ continue;
322
+ }
323
+ const seekEnd = Math.min(seekHeadEnd, seek.dataOffset + seek.size);
324
+ let targetId = null;
325
+ let position = null;
326
+ for (const field of iterateElements(head, seek.dataOffset, seekEnd)) {
327
+ if (field.id === ID_SEEK_ID) {
328
+ targetId = readUint(head, field.dataOffset, field.size);
329
+ } else if (field.id === ID_SEEK_POSITION) {
330
+ position = readUint(head, field.dataOffset, field.size);
331
+ }
332
+ }
333
+ if (targetId === wantedId && position !== null) {
334
+ return position;
335
+ }
336
+ }
337
+ return null;
338
+ }
339
+
340
+
341
+ /**
342
+ * Walk the clusters this file's Cues table names and give up the blocks in
343
+ * every one that is READABLE now, for every track at once.
344
+ *
345
+ * One walk for the whole file, not one per track: a Matroska cluster carries
346
+ * the blocks of every track that has anything to say over its span, so the
347
+ * bytes that answer one track answer them all. Reading them once per track
348
+ * meant the same cluster was fetched and parsed as many times as the film has
349
+ * subtitle tracks — measured 2026-08-20 on a film with five: five requests
350
+ * every fifteen seconds, each costing 0.2-5.2 s, for a few kilobytes of cues.
351
+ *
352
+ * Nothing is fetched. `isHeld` decides whether a cluster can be read at all,
353
+ * and one that is not here yet is left for the next call — turning subtitles
354
+ * on must not pull bytes the viewer is not waiting for.
355
+ *
356
+ * @param {object} plan - From {@link MatroskaContainer.readSubtitlePlan}.
357
+ * @param {Set<number>} walked - Cluster positions already read; added to.
358
+ * @returns {Promise<Map<number, {startSeconds: number, endSeconds: number|null, text: string}[]>>}
359
+ * Track number to the cues found in THIS pass.
360
+ */
361
+ async readHeldCues(plan, track, progress) {
362
+ const found = await this.walkHeldClusters(plan, progress.walked);
363
+ return {
364
+ found,
365
+ // Every track is filled by the same walk, so this is a fact about the
366
+ // FILE and reads the same whichever track asked.
367
+ covered: progress.walked.size,
368
+ indexed: track?.clusterPositions?.length ?? 0
369
+ };
370
+ }
371
+
372
+ async walkHeldClusters(plan, walked) {
373
+ /** @type {Map<number, object[]>} */
374
+ const found = new Map();
375
+ // The union of the tracks' cluster lists: each track's list comes from its
376
+ // own Cues entries, so they overlap but do not coincide.
377
+ const positions = new Set();
378
+ for (const candidate of plan?.tracks ?? []) {
379
+ for (const position of candidate.clusterPositions ?? []) {
380
+ positions.add(position);
381
+ }
382
+ }
383
+ for (const position of [...positions].sort((left, right) => left - right)) {
384
+ if (walked.has(position)) {
385
+ continue;
386
+ }
387
+ // The header first: it says how long the cluster is, and a cluster whose
388
+ // bytes are not all here is left for the next time round.
389
+ const probeEnd = Math.min(this.fileSize - 1, position + CLUSTER_HEADER_PROBE - 1);
390
+ if (!this.isHeld(position, probeEnd)) {
391
+ continue;
392
+ }
393
+ const probe = await this.readHeld(position, probeEnd);
394
+ const header = probe && [...iterateElements(probe, 0, probe.length)][0];
395
+ if (!header || header.size <= 0 || header.size > MAX_CLUSTER_BYTES) {
396
+ walked.add(position); // not a cluster this can read; do not look again
397
+ continue;
398
+ }
399
+ const last = Math.min(this.fileSize - 1, position + header.dataOffset + header.size - 1);
400
+ if (!this.isHeld(position, last)) {
401
+ continue;
402
+ }
403
+ const bytes = await this.readHeld(position, last);
404
+ if (!bytes) {
405
+ continue;
406
+ }
407
+ walked.add(position);
408
+ for (const candidate of plan.tracks) {
409
+ const blocks = MatroskaContainer.blocksInCluster(bytes, candidate.trackNumber, plan.secondsPerTick);
410
+ if (blocks.length === 0) {
411
+ continue;
412
+ }
413
+ const into = found.get(candidate.trackNumber) ?? [];
414
+ for (const block of blocks) {
415
+ // The block's bytes become text HERE, where the container that framed
416
+ // them is known. A cue kept framed and unframed later cannot be
417
+ // unframed at all: nothing downstream knows which container it came
418
+ // out of, and guessing from the field count is what showed the
419
+ // dialogue row's own fields to the viewer.
420
+ into.push({
421
+ startSeconds: block.startSeconds,
422
+ endSeconds: block.endSeconds,
423
+ text: MatroskaContainer.cueTextOf(block.payload, candidate.codecId)
424
+ });
425
+ }
426
+ found.set(candidate.trackNumber, into);
427
+ }
428
+ }
429
+ return found;
430
+ }
431
+
432
+ async readTracks() {
433
+ const head = await this.readRange(0, Math.min(HEAD_BYTES - 1, this.fileSize - 1));
434
+ if (!head || !isMatroska(head)) return [];
435
+
436
+ // Delegate to subtitle plan reader for subtitle tracks (already handles Flags spec-correct),
437
+ // but we need video/audio tracks too. Do a dedicated Tracks walk here for all types,
438
+ // then merge subtitle detail (clusterPositions, declaresDefault etc.) from the plan.
439
+ const seg = findElement(head, 0x18538067, []);
440
+ if (!seg) return [];
441
+ const tracksEl = findElement(head, ID_TRACKS, [], seg.dataOffset);
442
+ if (!tracksEl) return [];
443
+
444
+ const tracksEnd = Math.min(head.length, tracksEl.dataOffset + tracksEl.size);
445
+ /** @type {import("../tracks/index.js").ContainerTrack[]} */
446
+ const result = [];
447
+ // Subtitle declaredIndex is position among subtitle tracks, not global — track per-type counters.
448
+ let subtitleDeclaredIndex = -1;
449
+ let audioDeclaredIndex = -1;
450
+ let videoDeclaredIndex = -1;
451
+
452
+ // For subtitle flag enrichment, read the existing plan (it already does Cues walk)
453
+ let subtitlePlan = null;
454
+ try {
455
+ const shim = async (s, e) => this.readRange(s, Math.min(e, this.fileSize - 1));
456
+ subtitlePlan = await readSubtitlePlan(shim, this.fileSize);
457
+ } catch {
458
+ subtitlePlan = null;
459
+ }
460
+ const declaredByNumber = new Map();
461
+ const planTracksByNumber = new Map();
462
+ if (subtitlePlan?.declared) {
463
+ for (const d of subtitlePlan.declared) declaredByNumber.set(d.trackNumber, d);
464
+ }
465
+ if (subtitlePlan?.tracks) {
466
+ for (const t of subtitlePlan.tracks) planTracksByNumber.set(t.trackNumber, t);
467
+ }
468
+
469
+ for (const entry of iterateElements(head, tracksEl.dataOffset, tracksEnd)) {
470
+ if (entry.id !== ID_TRACK_ENTRY) continue;
471
+ const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
472
+ let trackNumber = null;
473
+ let typeNum = null;
474
+ let codecId = "";
475
+ let language = "";
476
+ let languageBcp47 = "";
477
+ let name = "";
478
+ let codecPrivateB64 = "";
479
+ let isEnabled = true;
480
+ let isDefault = true;
481
+ let declaresDefault = false;
482
+ let isForced = false;
483
+ let isHearing = false;
484
+ let isVisual = false;
485
+ let isOriginal = false;
486
+ let isCommentary = false;
487
+ let pixelWidth = null;
488
+ let pixelHeight = null;
489
+ let displayWidth = null;
490
+ let displayHeight = null;
491
+ let samplingFreq = null;
492
+ let channels = null;
493
+
494
+ for (const f of iterateElements(head, entry.dataOffset, entryEnd)) {
495
+ switch (f.id) {
496
+ case ID_TRACK_NUMBER: trackNumber = readUint(head, f.dataOffset, f.size); break;
497
+ case ID_TRACK_TYPE: typeNum = readUint(head, f.dataOffset, f.size); break;
498
+ case ID_CODEC_ID: codecId = readString(head, f); break;
499
+ case ID_CODEC_PRIVATE: codecPrivateB64 = head.toString("base64", f.dataOffset, f.dataOffset + f.size); break;
500
+ case ID_LANGUAGE: language = readString(head, f); break;
501
+ case ID_LANGUAGE_BCP47: languageBcp47 = readString(head, f); break;
502
+ case ID_NAME: name = readString(head, f); break;
503
+ case ID_FLAG_ENABLED: isEnabled = f.size === 0 || readUint(head, f.dataOffset, f.size) !== 0; break;
504
+ case ID_FLAG_DEFAULT: isDefault = f.size === 0 || readUint(head, f.dataOffset, f.size) === 1; declaresDefault = true; break;
505
+ case ID_FLAG_FORCED: isForced = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
506
+ case ID_FLAG_HEARING: isHearing = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
507
+ case ID_FLAG_VISUAL: isVisual = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
508
+ case ID_FLAG_TEXT_DESCR: break;
509
+ case ID_FLAG_ORIGINAL: isOriginal = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
510
+ case ID_FLAG_COMMENTARY: isCommentary = f.size > 0 && readUint(head, f.dataOffset, f.size) !== 0; break;
511
+ default: break;
512
+ }
513
+ // Video/Audio sub-elements are nested, not at entry level — read separately below.
514
+ }
515
+ if (trackNumber === null) continue;
516
+
517
+ // Parse Video/Audio sub-elements if present
518
+ const videoEl = findElement(head, ID_VIDEO, [], entry.dataOffset, entryEnd);
519
+ if (videoEl) {
520
+ for (const vf of iterateElements(head, videoEl.dataOffset, Math.min(entryEnd, videoEl.dataOffset + videoEl.size))) {
521
+ if (vf.id === ID_PIXEL_WIDTH) pixelWidth = readUint(head, vf.dataOffset, vf.size);
522
+ else if (vf.id === ID_PIXEL_HEIGHT) pixelHeight = readUint(head, vf.dataOffset, vf.size);
523
+ else if (vf.id === ID_DISPLAY_WIDTH) displayWidth = readUint(head, vf.dataOffset, vf.size);
524
+ else if (vf.id === ID_DISPLAY_HEIGHT) displayHeight = readUint(head, vf.dataOffset, vf.size);
525
+ }
526
+ }
527
+ const audioEl = findElement(head, ID_AUDIO, [], entry.dataOffset, entryEnd);
528
+ if (audioEl) {
529
+ for (const af of iterateElements(head, audioEl.dataOffset, Math.min(entryEnd, audioEl.dataOffset + audioEl.size))) {
530
+ if (af.id === ID_SAMPLING_FREQUENCY) {
531
+ // SamplingFrequency is float64
532
+ if (af.size === 8) samplingFreq = head.readDoubleBE(af.dataOffset);
533
+ else samplingFreq = readUint(head, af.dataOffset, af.size);
534
+ } else if (af.id === ID_CHANNELS) channels = readUint(head, af.dataOffset, af.size);
535
+ }
536
+ }
537
+
538
+ // RFC 9559 LanguageBCP47 MUST — when present, Language ignored
539
+ const resolvedLang = languageBcp47 || language;
540
+ const bcpTag = languageBcp47;
541
+
542
+ if (typeNum === 1) {
543
+ videoDeclaredIndex += 1;
544
+ result.push(new VideoTrack({
545
+ trackNumber,
546
+ declaredIndex: videoDeclaredIndex,
547
+ codecId,
548
+ language: resolvedLang,
549
+ languageBcp47: bcpTag,
550
+ name,
551
+ isEnabled,
552
+ isDefault,
553
+ declaresDefault,
554
+ codecPrivateB64,
555
+ width: pixelWidth,
556
+ height: pixelHeight,
557
+ displayWidth,
558
+ displayHeight
559
+ }));
560
+ } else if (typeNum === 2) {
561
+ audioDeclaredIndex += 1;
562
+ result.push(new AudioTrack({
563
+ trackNumber,
564
+ declaredIndex: audioDeclaredIndex,
565
+ codecId,
566
+ language: resolvedLang,
567
+ languageBcp47: bcpTag,
568
+ name,
569
+ isEnabled,
570
+ isDefault,
571
+ declaresDefault,
572
+ codecPrivateB64,
573
+ isOriginal,
574
+ isCommentary,
575
+ isVisualImpaired: isVisual,
576
+ channels,
577
+ samplingFrequency: samplingFreq
578
+ }));
579
+ } else if (typeNum === 17) {
580
+ subtitleDeclaredIndex += 1;
581
+ // Only Forced/Hearing belong to subtitles; Original/Commentary must not leak.
582
+ const declared = declaredByNumber.get(trackNumber);
583
+ const planTrack = planTracksByNumber.get(trackNumber);
584
+ // Prefer plan's flags when available (already spec-correct), else use parsed.
585
+ const finalForced = planTrack ? !!planTrack.isForced : isForced;
586
+ const finalHearing = planTrack ? !!planTrack.isHearingImpaired : isHearing;
587
+ const finalEnabled = declared ? declared.isEnabled !== false : isEnabled;
588
+ const finalDefault = declared ? !!declared.isDefault : isDefault;
589
+ const finalDeclares = declared ? !!declared.declaresDefault : declaresDefault;
590
+ const clusterPositions = planTrack ? planTrack.clusterPositions ?? [] : [];
591
+ const isText = TEXT_CODECS_MATROSKA.has(codecId);
592
+ // disabled image/text tracks still counted (declaredIndex above) — offerable flag controls visibility
593
+ if (isText && finalEnabled) {
594
+ result.push(new TextSubtitleTrack({
595
+ trackNumber,
596
+ declaredIndex: subtitleDeclaredIndex,
597
+ codecId,
598
+ language: resolvedLang,
599
+ languageBcp47: bcpTag,
600
+ name,
601
+ isEnabled: finalEnabled,
602
+ isDefault: finalDefault,
603
+ declaresDefault: finalDeclares,
604
+ codecPrivateB64,
605
+ isForced: finalForced,
606
+ isHearingImpaired: finalHearing,
607
+ clusterPositions
608
+ }));
609
+ } else {
610
+ // Image or disabled — keep declaredIndex, not offerable if disabled
611
+ const Target = isText ? TextSubtitleTrack : ImageSubtitleTrack;
612
+ result.push(new Target({
613
+ trackNumber,
614
+ declaredIndex: subtitleDeclaredIndex,
615
+ codecId,
616
+ language: resolvedLang,
617
+ languageBcp47: bcpTag,
618
+ name,
619
+ isEnabled: finalEnabled,
620
+ isDefault: finalDefault,
621
+ declaresDefault: finalDeclares,
622
+ codecPrivateB64,
623
+ isForced: finalForced,
624
+ isHearingImpaired: finalHearing,
625
+ clusterPositions: isText ? clusterPositions : []
626
+ }));
627
+ }
628
+ } else {
629
+ // Other TrackType (complex, logo, buttons, control) — keep as generic, not video
630
+ result.push(new ContainerTrack({
631
+ trackNumber,
632
+ declaredIndex: -1,
633
+ type: "other",
634
+ codecId,
635
+ language: resolvedLang,
636
+ languageBcp47: bcpTag,
637
+ name,
638
+ isEnabled,
639
+ isDefault,
640
+ declaresDefault,
641
+ codecPrivateB64
642
+ }));
643
+ }
644
+ }
645
+ return result;
646
+ }
647
+
648
+ /**
649
+ * The text field of one cue as Matroska frames it.
650
+ *
651
+ * Two rules, both from `matroska.org/technical/subtitles.html`, "Now, how are
652
+ * they stored in Matroska?":
653
+ *
654
+ * 1. "All text is converted to UTF-8", so the block is decoded as UTF-8 and
655
+ * no other encoding is guessed at. A subtitle FILE is a different matter —
656
+ * there the bytes may be Windows-1251 and `decodeSubtitleBytes` sniffs for
657
+ * it — but a muxer had to convert before writing the block.
658
+ * 2. "Events are stored in the Block in this order: ReadOrder, Layer, Style,
659
+ * Name, MarginL, MarginR, MarginV, Effect, Text", and "Start & End field
660
+ * are used to set TimeStamp and the BlockDuration element". So eight fields
661
+ * stand before the text, the two timing fields of the file's own row are
662
+ * NOT among them, and a read order takes their place at the front. The text
663
+ * itself may hold commas, so everything from the ninth field on is joined
664
+ * back together.
665
+ *
666
+ * `S_TEXT/UTF8` and `S_TEXT/WEBVTT` have no such framing: the block holds the
667
+ * cue text and nothing else. (A WebVTT cue's settings, identifier and
668
+ * preceding comments live in a BlockAddition, which this proxy does not read;
669
+ * losing them costs positioning, not words.)
670
+ *
671
+ * @param {Buffer} payload - The block's own bytes.
672
+ * @param {string} codecId - Matroska CodecID of the track the block belongs to.
673
+ * @returns {string}
674
+ */
675
+ static cueTextOf(payload, codecId) {
676
+ const text = Buffer.isBuffer(payload) ? payload.toString("utf8") : String(payload ?? "");
677
+ if (codecId !== "S_TEXT/ASS" && codecId !== "S_TEXT/SSA") {
678
+ return text;
679
+ }
680
+ const fields = text.split(",");
681
+ return fields.length > ASS_FIELDS_BEFORE_TEXT ? fields.slice(ASS_FIELDS_BEFORE_TEXT).join(",") : "";
682
+ }
683
+
684
+ async parseKeyframeIndex() {
685
+ const times = await readMatroskaKeyframeTimes(this.readRange, this.fileSize);
686
+ if (!times) return null;
687
+ if (Array.isArray(times)) return { times, tolerance: 0 };
688
+ return times;
689
+ }
690
+ }
691
+
692
+ // ---------------------------------------------------------------------------
693
+ // Matroska's own reading of its subtitle tracks and its clusters. It lives in
694
+ // this module because every line of it is a statement of RFC 9559 about how
695
+ // this container stores a subtitle, and the class is the only way in.
696
+ // ---------------------------------------------------------------------------
697
+
698
+ const ID_BLOCK = 0xa1;
699
+ const ID_BLOCK_DURATION = 0x9b;
700
+
701
+ /** Bits 1-2 of the flags byte say how a block is laced, or that it is not. */
702
+ const LACING_MASK = 0x06;
703
+ const LACING_NONE = 0x00;
704
+ const LACING_XIPH = 0x02;
705
+ const LACING_FIXED = 0x04;
706
+ const LACING_EBML = 0x06;
707
+
708
+ /**
709
+ * @typedef {object} SubtitleBlock
710
+ * @property {number} startSeconds - When the cue appears.
711
+ * @property {number | null} durationSeconds - How long it stays, or null when
712
+ * the block carried no duration (a SimpleBlock; the caller decides).
713
+ * @property {Buffer} payload - The block's own bytes, still in the codec's form.
714
+ */
715
+
716
+ /**
717
+ * Read one block's header.
718
+ *
719
+ * @param {Buffer} buffer
720
+ * @param {number} start - First byte of the block's payload.
721
+ * @param {number} end - One past its last byte.
722
+ * @returns {{ trackNumber: number, relativeTicks: number, flags: number, dataOffset: number } | null}
723
+ */
724
+ function readBlockHeader(buffer, start, end) {
725
+ const track = readVint(buffer, start, false);
726
+ if (!track || track.value === null) {
727
+ return null;
728
+ }
729
+ const timestampAt = start + track.length;
730
+ // Signed, and it can be negative: a block may belong slightly before the
731
+ // cluster it is stored in.
732
+ if (timestampAt + 3 > end) {
733
+ return null;
734
+ }
735
+ return {
736
+ trackNumber: Number(track.value),
737
+ relativeTicks: buffer.readInt16BE(timestampAt),
738
+ flags: buffer[timestampAt + 2],
739
+ dataOffset: timestampAt + 3
740
+ };
741
+ }
742
+
743
+ /**
744
+ * Where a laced block's first frame begins.
745
+ *
746
+ * Subtitles are rarely laced, but a block that IS laced starts with a frame
747
+ * count and a table of sizes, and reading the payload without stepping over
748
+ * them yields the table as though it were text.
749
+ *
750
+ * @param {Buffer} buffer
751
+ * @param {number} dataOffset - First byte after the block header.
752
+ * @param {number} end
753
+ * @param {number} flags
754
+ * @returns {number | null} The offset of the first frame, or null when the
755
+ * lacing cannot be read.
756
+ */
757
+ function firstFrameOffset(buffer, dataOffset, end, flags) {
758
+ const lacing = flags & LACING_MASK;
759
+ if (lacing === LACING_NONE) {
760
+ return dataOffset;
761
+ }
762
+ if (dataOffset >= end) {
763
+ return null;
764
+ }
765
+ const frames = buffer[dataOffset] + 1;
766
+ let at = dataOffset + 1;
767
+ if (lacing === LACING_FIXED) {
768
+ return at;
769
+ }
770
+ if (lacing === LACING_XIPH) {
771
+ // Each size but the last is a run of 0xFF bytes ending in a smaller one.
772
+ for (let frame = 0; frame < frames - 1; frame += 1) {
773
+ while (at < end && buffer[at] === 0xff) {
774
+ at += 1;
775
+ }
776
+ at += 1;
777
+ }
778
+ return at <= end ? at : null;
779
+ }
780
+ if (lacing === LACING_EBML) {
781
+ // The first size is a plain variable-length integer, the rest are signed
782
+ // differences from it; either way each is one such integer to step over.
783
+ for (let frame = 0; frame < frames - 1; frame += 1) {
784
+ const size = readVint(buffer, at, false);
785
+ if (!size) {
786
+ return null;
787
+ }
788
+ at += size.length;
789
+ }
790
+ return at <= end ? at : null;
791
+ }
792
+ return null;
793
+ }
794
+
795
+ /**
796
+ * Every block of one track inside one cluster.
797
+ *
798
+ * @param {Buffer} buffer - Bytes holding the cluster's payload.
799
+ * @param {{ dataOffset: number, size: number }} cluster - Where that payload is.
800
+ * @param {number} trackNumber - The track to keep.
801
+ * @param {number} secondsPerTick - From the segment's timestamp scale.
802
+ * @returns {SubtitleBlock[]}
803
+ */
804
+ function blocksOfTrack(buffer, cluster, trackNumber, secondsPerTick) {
805
+ const end = Math.min(buffer.length, cluster.dataOffset + cluster.size);
806
+ /** @type {SubtitleBlock[]} */
807
+ const blocks = [];
808
+ let clusterTicks = null;
809
+
810
+ const take = (blockStart, blockEnd, durationTicks) => {
811
+ const header = readBlockHeader(buffer, blockStart, blockEnd);
812
+ if (!header || header.trackNumber !== trackNumber || clusterTicks === null) {
813
+ return;
814
+ }
815
+ const payloadAt = firstFrameOffset(buffer, header.dataOffset, blockEnd, header.flags);
816
+ if (payloadAt === null || payloadAt >= blockEnd) {
817
+ return;
818
+ }
819
+ blocks.push({
820
+ startSeconds: (clusterTicks + header.relativeTicks) * secondsPerTick,
821
+ durationSeconds: durationTicks === null ? null : durationTicks * secondsPerTick,
822
+ payload: buffer.subarray(payloadAt, blockEnd)
823
+ });
824
+ };
825
+
826
+ for (const element of iterateElements(buffer, cluster.dataOffset, end)) {
827
+ const elementEnd = Math.min(end, element.dataOffset + element.size);
828
+ if (element.id === ID_TIMESTAMP) {
829
+ clusterTicks = readUint(buffer, element.dataOffset, element.size);
830
+ continue;
831
+ }
832
+ if (element.id === ID_SIMPLE_BLOCK) {
833
+ take(element.dataOffset, elementEnd, null);
834
+ continue;
835
+ }
836
+ if (element.id !== ID_BLOCK_GROUP) {
837
+ continue;
838
+ }
839
+ // A group holds the block and, for a subtitle, the duration that says when
840
+ // the cue leaves the screen. Both are read before either is used, because
841
+ // the duration may be written after the block.
842
+ let blockStart = null;
843
+ let blockEnd = null;
844
+ let durationTicks = null;
845
+ for (const field of iterateElements(buffer, element.dataOffset, elementEnd)) {
846
+ const fieldEnd = Math.min(elementEnd, field.dataOffset + field.size);
847
+ if (field.id === ID_BLOCK) {
848
+ blockStart = field.dataOffset;
849
+ blockEnd = fieldEnd;
850
+ } else if (field.id === ID_BLOCK_DURATION) {
851
+ durationTicks = readUint(buffer, field.dataOffset, field.size);
852
+ }
853
+ }
854
+ if (blockStart !== null) {
855
+ take(blockStart, blockEnd, durationTicks);
856
+ }
857
+ }
858
+ return blocks;
859
+ }
860
+
861
+
862
+ /**
863
+ * The rest of what a TrackEntry says about itself, RFC 9559 §5.1.4.1. Read
864
+ * because the file states them and a releaser's own wording in `Name` is the
865
+ * only thing we had before: "fors" and "SDH" in a menu were whatever text
866
+ * someone happened to type.
867
+ *
868
+ * `FlagEnabled` defaults to 1 and means "the track is usable"; a track that
869
+ * says 0 is counted but not offered. `FlagForced` applies only to subtitles and
870
+ * defaults to 0. `FlagHearingImpaired` is set "if and only if the track is
871
+ * suitable for users with hearing impairments". `FlagVisualImpaired`,
872
+ * `FlagOriginal` and `FlagCommentary` bear on the AUDIO choice and are read
873
+ * with that work, not here — see roadmap item 55.
874
+ */
875
+ const ID_FLAG_HEARING_IMPAIRED = 0x55ab;
876
+ /**
877
+ * The language as RFC 5646 writes it. The specification is a MUST: "If this
878
+ * element is used, then any Language elements used in the same TrackEntry MUST
879
+ * be ignored" — so where both are present, this one is the answer and the
880
+ * three-letter code is not.
881
+ */
882
+ const ID_CUES = 0x1c53bb6b;
883
+ const ID_CUE_POINT = 0xbb;
884
+ const ID_CUE_TRACK_POSITIONS = 0xb7;
885
+ const ID_CUE_TRACK = 0xf7;
886
+ const ID_CUE_CLUSTER_POSITION = 0xf1;
887
+
888
+ /** TrackType 17 is subtitles; 1 is video and 2 audio. */
889
+ const TRACK_TYPE_SUBTITLE = 17;
890
+ /** How much of the file start to read: the same window the keyframe reader uses. */
891
+ /** Cap on the Cues read; a long film indexes to tens of KB. */
892
+ const MAX_CUES_BYTES = 8 * 1024 * 1024;
893
+
894
+ /**
895
+ * The codecs whose blocks are text this proxy can turn into WebVTT.
896
+ *
897
+ * `S_TEXT/UTF8` is a plain line of text and needs nothing. `S_TEXT/ASS` and
898
+ * `S_TEXT/SSA` carry a dialogue row whose fields have to be stripped, and their
899
+ * header lives in CodecPrivate — supported, with the stripping done where the
900
+ * cue is turned into WebVTT. `S_HDMV/PGS` and `S_VOBSUB` are pictures, not
901
+ * text, and are deliberately absent: offering them would promise something this
902
+ * path cannot deliver.
903
+ */
904
+ const TEXT_CODECS = new Set(["S_TEXT/UTF8", "S_TEXT/ASS", "S_TEXT/SSA"]);
905
+
906
+ /**
907
+ * @typedef {object} SubtitleTrackPlan
908
+ * @property {number} trackNumber - As the blocks name it.
909
+ * @property {number} declaredIndex - Its position among ALL of the file's
910
+ * subtitle tracks, picture-based ones included — which is the number ffmpeg
911
+ * gives the same stream in `0:s:N`, and therefore the only number the browser
912
+ * ever names. Text tracks alone are not a numbering: a file whose PGS track
913
+ * comes first would have every text track one lower here than in the browser.
914
+ * @property {string} codecId
915
+ * @property {string} language - The language the file declares: its RFC 5646
916
+ * tag where it writes one, and the three-letter code otherwise. The
917
+ * specification requires that order — where `LanguageBCP47` is present, the
918
+ * `Language` element MUST be ignored.
919
+ * @property {string} languageBcp47 - The RFC 5646 tag alone, or "".
920
+ * @property {string} name - What the file calls the track, if anything.
921
+ * @property {boolean} isDefault
922
+ * @property {boolean} isForced - `FlagForced`: the track carries what a viewer
923
+ * needs even when they asked for no subtitles — signs, and dialogue in
924
+ * another language. It does NOT carry the film's own dialogue.
925
+ * @property {boolean} isHearingImpaired - `FlagHearingImpaired`: suitable for
926
+ * viewers who cannot hear, so it carries non-speech sound as well as speech.
927
+ * @property {string} codecPrivate - The ASS/SSA header, base64, or "".
928
+ * @property {number[]} clusterPositions - File offsets of clusters whose cue
929
+ * points name this track, ascending. Empty when the file indexes only its
930
+ * picture, and then the caller has to walk clusters as they arrive instead.
931
+ */
932
+
933
+
934
+ /**
935
+ * Everything about a file's text subtitle tracks that can be learned without
936
+ * reading the film.
937
+ *
938
+ * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
939
+ * @param {number} fileSize
940
+ * @returns {Promise<{ tracks: SubtitleTrackPlan[], declared: object[], secondsPerTick: number, segmentDataOffset: number } | null>}
941
+ */
942
+ async function readSubtitlePlan(readRange, fileSize) {
943
+ const head = await readRange(0, Math.min(HEAD_BYTES, Math.max(0, fileSize - 1)));
944
+ if (!head || head.length < 4 || head.readUInt32BE(0) !== 0x1a45dfa3) {
945
+ return null;
946
+ }
947
+ const segment = findElement(head, ID_SEGMENT, []);
948
+ if (!segment) {
949
+ return null;
950
+ }
951
+ const base = segment.dataOffset;
952
+
953
+ const info = findElement(head, ID_INFO, [], base);
954
+ let scale = DEFAULT_TIMESTAMP_SCALE;
955
+ if (info) {
956
+ const declared = findElement(head, ID_TIMESTAMP_SCALE, [], info.dataOffset, info.dataOffset + info.size);
957
+ if (declared) {
958
+ const value = readUint(head, declared.dataOffset, declared.size);
959
+ if (value > 0) {
960
+ scale = value;
961
+ }
962
+ }
963
+ }
964
+
965
+ const tracksElement = findElement(head, ID_TRACKS, [], base);
966
+ if (!tracksElement) {
967
+ return null;
968
+ }
969
+ const tracksEnd = Math.min(head.length, tracksElement.dataOffset + tracksElement.size);
970
+ /** @type {SubtitleTrackPlan[]} */
971
+ const tracks = [];
972
+ /**
973
+ * Every subtitle track the file declares, in the order the Tracks element
974
+ * names them, text or picture. This is not for extraction — `tracks` is —
975
+ * but for lining ffmpeg's `0:s:N` numbering up against the container, which
976
+ * only holds while nothing is missing from the middle of the list.
977
+ *
978
+ * @type {Array<{ trackNumber: number, codecId: string, language: string, name: string, isDefault: boolean, declaresDefault: boolean }>}
979
+ */
980
+ const declared = [];
981
+ for (const entry of iterateElements(head, tracksElement.dataOffset, tracksEnd)) {
982
+ if (entry.id !== ID_TRACK_ENTRY) {
983
+ continue;
984
+ }
985
+ const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
986
+ let trackNumber = null;
987
+ let type = null;
988
+ let codecId = "";
989
+ let language = "";
990
+ let name = "";
991
+ let codecPrivate = "";
992
+ // Matroska's `FlagDefault` DEFAULTS TO 1, so a file whose muxer wrote it on
993
+ // no track is indistinguishable, once the default has been applied, from
994
+ // one that wrote it on every track — which is how ffmpeg's banner prints it
995
+ // and why the banner cannot answer this. Both are kept: what the flag
996
+ // amounts to, and whether the file said anything at all.
997
+ let isDefault = true;
998
+ let declaresDefault = false;
999
+ // Defaults straight from RFC 9559: a track is usable and not forced unless
1000
+ // the file says otherwise, and the impaired flags are absent until claimed.
1001
+ let isEnabled = true;
1002
+ let isForced = false;
1003
+ let isHearingImpaired = false;
1004
+ let languageBcp47 = "";
1005
+ for (const field of iterateElements(head, entry.dataOffset, entryEnd)) {
1006
+ if (field.id === ID_TRACK_NUMBER) {
1007
+ trackNumber = readUint(head, field.dataOffset, field.size);
1008
+ } else if (field.id === ID_TRACK_TYPE) {
1009
+ type = readUint(head, field.dataOffset, field.size);
1010
+ } else if (field.id === ID_CODEC_ID) {
1011
+ codecId = readString(head, field);
1012
+ } else if (field.id === ID_LANGUAGE) {
1013
+ language = readString(head, field);
1014
+ } else if (field.id === ID_LANGUAGE_BCP47) {
1015
+ languageBcp47 = readString(head, field);
1016
+ } else if (field.id === ID_NAME) {
1017
+ name = readString(head, field);
1018
+ } else if (field.id === ID_FLAG_DEFAULT) {
1019
+ isDefault = readUint(head, field.dataOffset, field.size) === 1;
1020
+ declaresDefault = true;
1021
+ } else if (field.id === ID_FLAG_ENABLED) {
1022
+ // An element written with zero length carries its default, which for
1023
+ // this one is 1 — so an empty element must not read as "unusable", and
1024
+ // neither must a value outside the declared 0-1 range. Only an explicit
1025
+ // zero takes a track away.
1026
+ isEnabled = field.size === 0 || readUint(head, field.dataOffset, field.size) !== 0;
1027
+ } else if (field.id === ID_FLAG_FORCED) {
1028
+ isForced = field.size > 0 && readUint(head, field.dataOffset, field.size) !== 0;
1029
+ } else if (field.id === ID_FLAG_HEARING_IMPAIRED) {
1030
+ isHearingImpaired = field.size > 0 && readUint(head, field.dataOffset, field.size) !== 0;
1031
+ } else if (field.id === ID_CODEC_PRIVATE) {
1032
+ codecPrivate = head.toString("base64", field.dataOffset, field.dataOffset + field.size);
1033
+ }
1034
+ }
1035
+ if (type !== TRACK_TYPE_SUBTITLE || trackNumber === null) {
1036
+ continue;
1037
+ }
1038
+ // A track the file marks unusable is still COUNTED. FlagEnabled says "the
1039
+ // track is usable", and a player should not offer it — but ffmpeg does not
1040
+ // drop it: `matroskadec.c` parses `MATROSKA_ID_TRACKFLAGENABLED` as
1041
+ // `EBML_NONE`, reading the element and keeping nothing, so the stream is
1042
+ // created and numbered like any other. Leaving it out of this list would
1043
+ // therefore shift `declaredIndex` off ffmpeg's `0:s:N` for every track
1044
+ // after it, which is the numbering defect this file was fixed for a day
1045
+ // earlier. It is counted here and refused where it is offered instead.
1046
+ //
1047
+ // `language` here stays the three-letter code, because this list exists to
1048
+ // be lined up against ffmpeg's banner, which prints that code. The RFC 5646
1049
+ // tag rides beside it for whoever displays the track.
1050
+ declared.push({
1051
+ trackNumber,
1052
+ codecId,
1053
+ language,
1054
+ languageBcp47,
1055
+ name,
1056
+ isDefault,
1057
+ declaresDefault,
1058
+ isEnabled,
1059
+ isForced,
1060
+ isHearingImpaired
1061
+ });
1062
+ if (!TEXT_CODECS.has(codecId) || !isEnabled) {
1063
+ continue;
1064
+ }
1065
+ tracks.push({
1066
+ trackNumber,
1067
+ declaredIndex: declared.length - 1,
1068
+ codecId,
1069
+ // This list is ours and is not compared with ffmpeg's, so it carries the
1070
+ // language the file states most precisely: where RFC 5646 is written, the
1071
+ // three-letter code MUST be ignored.
1072
+ language: languageBcp47 || language,
1073
+ languageBcp47,
1074
+ name,
1075
+ isDefault,
1076
+ isForced,
1077
+ isHearingImpaired,
1078
+ codecPrivate,
1079
+ clusterPositions: []
1080
+ });
1081
+ }
1082
+ if (tracks.length === 0) {
1083
+ return { tracks, declared, secondsPerTick: scale / 1e9, segmentDataOffset: base };
1084
+ }
1085
+
1086
+ // Where the clusters holding those tracks are. A file that indexes only its
1087
+ // picture leaves these empty, which is not a failure: the caller then reads
1088
+ // the clusters the viewer's own playback brings in.
1089
+ const seekHead = findElement(head, ID_SEEK_HEAD, [], base);
1090
+ let cuesRelative;
1091
+ if (seekHead) {
1092
+ const seekEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
1093
+ for (const seek of iterateElements(head, seekHead.dataOffset, seekEnd)) {
1094
+ if (seek.id !== ID_SEEK) {
1095
+ continue;
1096
+ }
1097
+ let target = null;
1098
+ let position = null;
1099
+ for (const field of iterateElements(head, seek.dataOffset, Math.min(seekEnd, seek.dataOffset + seek.size))) {
1100
+ if (field.id === ID_SEEK_ID) {
1101
+ target = readUint(head, field.dataOffset, field.size);
1102
+ } else if (field.id === ID_SEEK_POSITION) {
1103
+ position = readUint(head, field.dataOffset, field.size);
1104
+ }
1105
+ }
1106
+ if (target === ID_CUES && position !== null) {
1107
+ cuesRelative = position;
1108
+ }
1109
+ }
1110
+ }
1111
+ if (cuesRelative !== undefined) {
1112
+ const cuesAt = base + cuesRelative;
1113
+ if (cuesAt > 0 && cuesAt < fileSize) {
1114
+ const chunk = await readRange(cuesAt, Math.min(fileSize - 1, cuesAt + MAX_CUES_BYTES));
1115
+ const element = chunk && [...iterateElements(chunk, 0, chunk.length)][0];
1116
+ if (element && element.id === ID_CUES) {
1117
+ const body = chunk.subarray(element.dataOffset, Math.min(chunk.length, element.dataOffset + element.size));
1118
+ const byTrack = new Map(tracks.map((track) => [track.trackNumber, new Set()]));
1119
+ for (const point of iterateElements(body, 0, body.length)) {
1120
+ if (point.id !== ID_CUE_POINT) {
1121
+ continue;
1122
+ }
1123
+ const pointEnd = Math.min(body.length, point.dataOffset + point.size);
1124
+ for (const field of iterateElements(body, point.dataOffset, pointEnd)) {
1125
+ if (field.id !== ID_CUE_TRACK_POSITIONS) {
1126
+ continue;
1127
+ }
1128
+ let cueTrack = null;
1129
+ let position = null;
1130
+ for (const inner of iterateElements(body, field.dataOffset, Math.min(pointEnd, field.dataOffset + field.size))) {
1131
+ if (inner.id === ID_CUE_TRACK) {
1132
+ cueTrack = readUint(body, inner.dataOffset, inner.size);
1133
+ } else if (inner.id === ID_CUE_CLUSTER_POSITION) {
1134
+ position = readUint(body, inner.dataOffset, inner.size);
1135
+ }
1136
+ }
1137
+ if (position !== null && byTrack.has(cueTrack)) {
1138
+ byTrack.get(cueTrack).add(base + position);
1139
+ }
1140
+ }
1141
+ }
1142
+ for (const track of tracks) {
1143
+ track.clusterPositions = [...byTrack.get(track.trackNumber)].sort((left, right) => left - right);
1144
+ }
1145
+ }
1146
+ }
1147
+ }
1148
+ return { tracks, declared, secondsPerTick: scale / 1e9, segmentDataOffset: base };
1149
+ }
1150
+
1151
+ /**
1152
+ * The cues of one track inside one cluster.
1153
+ *
1154
+ * @param {Buffer} bytes - The cluster, from its own element header onward.
1155
+ * @param {number} trackNumber
1156
+ * @param {number} secondsPerTick
1157
+ * @returns {{ startSeconds: number, endSeconds: number | null, text: string }[]}
1158
+ */
1159
+ function harvestCluster(bytes, trackNumber, secondsPerTick) {
1160
+ const header = [...iterateElements(bytes, 0, bytes.length)][0];
1161
+ if (!header) {
1162
+ return [];
1163
+ }
1164
+ const blocks = blocksOfTrack(
1165
+ bytes,
1166
+ { dataOffset: header.dataOffset, size: header.size },
1167
+ trackNumber,
1168
+ secondsPerTick
1169
+ );
1170
+ // The payload is handed on as BYTES. What those bytes mean — which of them
1171
+ // are the text and which are the eight fields Matroska puts before it — is
1172
+ // stated by the container's specification and answered by
1173
+ // `MatroskaContainer.cueTextOf`, not here: this function's subject is where a
1174
+ // block sits and how long it lasts.
1175
+ return blocks.map((block) => ({
1176
+ startSeconds: block.startSeconds,
1177
+ endSeconds: block.durationSeconds === null ? null : block.startSeconds + block.durationSeconds,
1178
+ payload: block.payload
1179
+ }));
1180
+ }
1181
+
1182
+ // ---------------------------------------------------------------------------
1183
+ // RFC 9559 speaking about Matroska: the Cues table that says where a keyframe is.
1184
+ // Here because the class is the only way in.
1185
+ // ---------------------------------------------------------------------------
1186
+
1187
+ // Element ids, from the Matroska specification.
1188
+ const ID_CUE_TIME = 0xb3;
1189
+ // TrackType 1 is video; 2 is audio, 17 subtitles, and the rest are rarer still.
1190
+ const TRACK_TYPE_VIDEO = 1;
1191
+
1192
+ // How much of the file start to read. Must cover the EBML header, the SeekHead
1193
+ // and Info; 64 KB is generous for every real muxer (the file measured needed
1194
+ // under 4 KB) while still trivial to fetch.
1195
+ // Cap on the Cues read. A two-hour film indexes to tens of KB; anything beyond
1196
+ // this is not a normal index and not worth pulling over a torrent.
1197
+ // Cap on a Tracks read, for the rare file whose Tracks element sits outside the
1198
+ // head window. Track entries are small, so a file with dozens of them still
1199
+ // fits well inside this.
1200
+ const MAX_TRACKS_BYTES = 1024 * 1024;
1201
+ // Matroska's default timestamp scale (nanoseconds per tick) when Info omits it.
1202
+
1203
+ /**
1204
+ * Whether this looks like a Matroska file (the EBML magic `0x1A45DFA3`).
1205
+ *
1206
+ * @param {Buffer} head
1207
+ * @returns {boolean}
1208
+ */
1209
+ function isMatroska(head) {
1210
+ return head.length >= 4 && head.readUInt32BE(0) === 0x1a45dfa3;
1211
+ }
1212
+
1213
+ /**
1214
+ * Locate the Segment element and the SeekHead entries inside it.
1215
+ *
1216
+ * Seek positions are relative to the start of Segment's payload, not to the
1217
+ * file, so that base has to come back with them.
1218
+ *
1219
+ * @param {Buffer} head
1220
+ * @returns {{ segmentDataOffset: number, entries: Map<number, number> } | null}
1221
+ */
1222
+ function readSeekHead(head) {
1223
+ let segmentDataOffset = -1;
1224
+ for (const element of iterateElements(head)) {
1225
+ if (element.id === ID_SEGMENT) {
1226
+ segmentDataOffset = element.dataOffset;
1227
+ break;
1228
+ }
1229
+ }
1230
+ if (segmentDataOffset < 0) {
1231
+ return null;
1232
+ }
1233
+
1234
+ const seekHead = findElement(head, ID_SEEK_HEAD, [], segmentDataOffset);
1235
+ if (!seekHead) {
1236
+ return null;
1237
+ }
1238
+
1239
+ const entries = new Map();
1240
+ const seekHeadEnd = Math.min(head.length, seekHead.dataOffset + seekHead.size);
1241
+ for (const seek of iterateElements(head, seekHead.dataOffset, seekHeadEnd)) {
1242
+ if (seek.id !== ID_SEEK) {
1243
+ continue;
1244
+ }
1245
+ const seekEnd = Math.min(seekHeadEnd, seek.dataOffset + seek.size);
1246
+ let targetId = null;
1247
+ let position = null;
1248
+ for (const field of iterateElements(head, seek.dataOffset, seekEnd)) {
1249
+ if (field.id === ID_SEEK_ID) {
1250
+ targetId = readUint(head, field.dataOffset, field.size);
1251
+ } else if (field.id === ID_SEEK_POSITION) {
1252
+ position = readUint(head, field.dataOffset, field.size);
1253
+ }
1254
+ }
1255
+ if (targetId !== null && position !== null) {
1256
+ entries.set(targetId, position);
1257
+ }
1258
+ }
1259
+ return { segmentDataOffset, entries };
1260
+ }
1261
+
1262
+ /**
1263
+ * Timestamp scale (nanoseconds per tick) declared in Info, or the default.
1264
+ *
1265
+ * @param {Buffer} head
1266
+ * @param {number} segmentDataOffset
1267
+ * @returns {number}
1268
+ */
1269
+ function readTimestampScale(head, segmentDataOffset) {
1270
+ const info = findElement(head, ID_INFO, [], segmentDataOffset);
1271
+ if (!info) {
1272
+ return DEFAULT_TIMESTAMP_SCALE;
1273
+ }
1274
+ const infoEnd = Math.min(head.length, info.dataOffset + info.size);
1275
+ for (const field of iterateElements(head, info.dataOffset, infoEnd)) {
1276
+ if (field.id === ID_TIMESTAMP_SCALE) {
1277
+ const scale = readUint(head, field.dataOffset, field.size);
1278
+ return scale > 0 ? scale : DEFAULT_TIMESTAMP_SCALE;
1279
+ }
1280
+ }
1281
+ return DEFAULT_TIMESTAMP_SCALE;
1282
+ }
1283
+
1284
+ /**
1285
+ * The number of the first video track, from a Tracks payload.
1286
+ *
1287
+ * The FIRST one, because that is the track ffmpeg is told to copy (`0:v:0`).
1288
+ *
1289
+ * @param {Buffer} buffer
1290
+ * @param {{ dataOffset: number, size: number }} tracks
1291
+ * @returns {number | null}
1292
+ */
1293
+ function readVideoTrackNumber(buffer, tracks) {
1294
+ const tracksEnd = Math.min(buffer.length, tracks.dataOffset + tracks.size);
1295
+ for (const entry of iterateElements(buffer, tracks.dataOffset, tracksEnd)) {
1296
+ if (entry.id !== ID_TRACK_ENTRY) {
1297
+ continue;
1298
+ }
1299
+ const entryEnd = Math.min(tracksEnd, entry.dataOffset + entry.size);
1300
+ let number = null;
1301
+ let type = null;
1302
+ for (const field of iterateElements(buffer, entry.dataOffset, entryEnd)) {
1303
+ if (field.id === ID_TRACK_NUMBER) {
1304
+ number = readUint(buffer, field.dataOffset, field.size);
1305
+ } else if (field.id === ID_TRACK_TYPE) {
1306
+ type = readUint(buffer, field.dataOffset, field.size);
1307
+ }
1308
+ }
1309
+ if (number !== null && type === TRACK_TYPE_VIDEO) {
1310
+ return number;
1311
+ }
1312
+ }
1313
+ return null;
1314
+ }
1315
+
1316
+ /**
1317
+ * Cue times (seconds, ascending) of ONE track, from a Cues payload.
1318
+ *
1319
+ * The track is the whole point, and leaving it out is what this reader got
1320
+ * wrong until 2026-08-18. A CuePoint belongs to the track named inside its
1321
+ * CueTrackPositions, and a muxer indexes whatever tracks it likes: RFC 9559
1322
+ * says each keyframe of a video track SHOULD be referenced, and that the Cues
1323
+ * Element "can be used to index every single timestamp of every Block or they
1324
+ * can be indexed selectively". Both field files index their SUBTITLE tracks as
1325
+ * well — `Minions.and.Monsters.1080p.mkv` has 2778 video entries every 2.002 s
1326
+ * plus 4669 across four subtitle tracks; `Moana.2 … MegaPeer.mkv` has 1055
1327
+ * video entries plus 5007 across five.
1328
+ *
1329
+ * Read without the track, those extra times enter the cut list as though they
1330
+ * were keyframes. ffmpeg can only cut a COPIED picture at a real keyframe at or
1331
+ * after the time it is given, so every cut asked for at one of them lands late
1332
+ * — which is exactly what the field measured: on the first file every deviation
1333
+ * was 2.002 s, that file's own keyframe spacing, and on the second the median
1334
+ * was 6.3 s with a worst case of 21 s. Never once negative.
1335
+ *
1336
+ * @param {Buffer} cues
1337
+ * @param {number} timestampScale - Nanoseconds per tick.
1338
+ * @param {number | null} trackNumber - Null keeps every entry, which is right
1339
+ * only for a file that indexes one track.
1340
+ * @returns {number[]}
1341
+ */
1342
+ function readCueTimes(cues, timestampScale, trackNumber) {
1343
+ const times = [];
1344
+ const secondsPerTick = timestampScale / 1e9;
1345
+ for (const point of iterateElements(cues)) {
1346
+ if (point.id !== ID_CUE_POINT) {
1347
+ continue;
1348
+ }
1349
+ const pointEnd = Math.min(cues.length, point.dataOffset + point.size);
1350
+ let time = null;
1351
+ let belongsToTrack = trackNumber === null;
1352
+ for (const field of iterateElements(cues, point.dataOffset, pointEnd)) {
1353
+ if (field.id === ID_CUE_TIME) {
1354
+ time = readUint(cues, field.dataOffset, field.size) * secondsPerTick;
1355
+ continue;
1356
+ }
1357
+ if (field.id !== ID_CUE_TRACK_POSITIONS || belongsToTrack) {
1358
+ continue;
1359
+ }
1360
+ const positionsEnd = Math.min(pointEnd, field.dataOffset + field.size);
1361
+ for (const inner of iterateElements(cues, field.dataOffset, positionsEnd)) {
1362
+ if (inner.id === ID_CUE_TRACK && readUint(cues, inner.dataOffset, inner.size) === trackNumber) {
1363
+ belongsToTrack = true;
1364
+ break;
1365
+ }
1366
+ }
1367
+ }
1368
+ if (time !== null && belongsToTrack) {
1369
+ times.push(time);
1370
+ }
1371
+ }
1372
+ times.sort((left, right) => left - right);
1373
+ return times;
1374
+ }
1375
+
1376
+ /**
1377
+ * Read the keyframe times of a Matroska file using only two point reads.
1378
+ *
1379
+ * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
1380
+ * Inclusive byte range reader; returns null when the range is unavailable.
1381
+ * @param {number} fileSize
1382
+ * @returns {Promise<number[] | null>} Ascending seconds, or null when the file
1383
+ * carries no usable index (see the module doc for when that happens).
1384
+ */
1385
+ async function readMatroskaKeyframeTimes(readRange, fileSize) {
1386
+ const head = await readRange(0, Math.min(HEAD_BYTES, Math.max(0, fileSize - 1)));
1387
+ if (!head || !isMatroska(head)) {
1388
+ return null;
1389
+ }
1390
+
1391
+ const seekHead = readSeekHead(head);
1392
+ if (!seekHead) {
1393
+ return null; // No SeekHead — a streamed or truncated mux.
1394
+ }
1395
+
1396
+ const cuesRelative = seekHead.entries.get(ID_CUES);
1397
+ if (cuesRelative === undefined) {
1398
+ return null; // Indexless file: live capture, interrupted write, damaged upload.
1399
+ }
1400
+
1401
+ // SeekHead positions are relative to Segment's payload.
1402
+ const cuesOffset = seekHead.segmentDataOffset + cuesRelative;
1403
+ if (!Number.isFinite(cuesOffset) || cuesOffset <= 0 || cuesOffset >= fileSize) {
1404
+ return null;
1405
+ }
1406
+
1407
+ // The element header states the payload size, but reading it costs a round
1408
+ // trip; fetch a bounded window instead and let the parser stop at the end of
1409
+ // what it got. Cues sits near the file end, so the window is clamped there.
1410
+ const cuesEnd = Math.min(fileSize - 1, cuesOffset + MAX_CUES_BYTES);
1411
+ const cuesChunk = await readRange(cuesOffset, cuesEnd);
1412
+ if (!cuesChunk || cuesChunk.length === 0) {
1413
+ return null;
1414
+ }
1415
+
1416
+ // The window starts exactly at the Cues element, so its own header comes
1417
+ // first; step over it to reach the CuePoints.
1418
+ const cuesElement = [...iterateElements(cuesChunk, 0, cuesChunk.length)][0];
1419
+ if (!cuesElement || cuesElement.id !== ID_CUES) {
1420
+ return null;
1421
+ }
1422
+ const payloadEnd = Math.min(cuesChunk.length, cuesElement.dataOffset + cuesElement.size);
1423
+ const payload = cuesChunk.subarray(cuesElement.dataOffset, payloadEnd);
1424
+
1425
+ // Whose entries to keep. Tracks sits near the head and is normally inside the
1426
+ // bytes already fetched; when it is not, SeekHead says where it is and one
1427
+ // more short read gets it. Nothing is fetched twice and nothing is scanned.
1428
+ const videoTrack = await readVideoTrack(readRange, head, seekHead, fileSize);
1429
+ const timestampScale = readTimestampScale(head, seekHead.segmentDataOffset);
1430
+ const times = readCueTimes(payload, timestampScale, videoTrack);
1431
+ if (times.length > 0) {
1432
+ return times;
1433
+ }
1434
+ if (videoTrack === null) {
1435
+ return null;
1436
+ }
1437
+ // The filter left nothing, and that is not an answer about the file: a table
1438
+ // exists, and this reader simply failed to recognise which of its entries
1439
+ // belong to the picture — a track numbered one way in Tracks and another in
1440
+ // the cue points, or an entry with no CueTrack at all. Returning null here
1441
+ // would put an EVEN grid on a copied picture, which is the failure this
1442
+ // module exists to prevent, so the unfiltered table is used instead: less
1443
+ // exact than the picture's own keyframes, better than a grid that has nothing
1444
+ // to do with the file.
1445
+ const unfiltered = readCueTimes(payload, timestampScale, null);
1446
+ return unfiltered.length > 0 ? unfiltered : null;
1447
+ }
1448
+
1449
+ /**
1450
+ * The video track's number — from the head when it is there, and from one extra
1451
+ * short read when it is not.
1452
+ *
1453
+ * @param {(start: number, end: number) => Promise<Buffer | null>} readRange
1454
+ * @param {Buffer} head
1455
+ * @param {{ segmentDataOffset: number, entries: Map<number, number> }} seekHead
1456
+ * @param {number} fileSize
1457
+ * @returns {Promise<number | null>} Null when Tracks cannot be read at all, and
1458
+ * then every cue entry is kept — right for a file that indexes only its
1459
+ * picture, wrong for one that does not, and nothing here can tell them apart.
1460
+ * Refusing the index instead would put an even grid on a copied picture,
1461
+ * which is the failure this reader exists to prevent.
1462
+ */
1463
+ async function readVideoTrack(readRange, head, seekHead, fileSize) {
1464
+ const inHead = findElement(head, ID_TRACKS, [], seekHead.segmentDataOffset);
1465
+ if (inHead && inHead.dataOffset + inHead.size <= head.length) {
1466
+ return readVideoTrackNumber(head, inHead);
1467
+ }
1468
+ const relative = seekHead.entries.get(ID_TRACKS);
1469
+ if (relative === undefined) {
1470
+ return null;
1471
+ }
1472
+ const offset = seekHead.segmentDataOffset + relative;
1473
+ if (!Number.isFinite(offset) || offset <= 0 || offset >= fileSize) {
1474
+ return null;
1475
+ }
1476
+ const chunk = await readRange(offset, Math.min(fileSize - 1, offset + MAX_TRACKS_BYTES));
1477
+ if (!chunk || chunk.length === 0) {
1478
+ return null;
1479
+ }
1480
+ const element = [...iterateElements(chunk, 0, chunk.length)][0];
1481
+ if (!element || element.id !== ID_TRACKS) {
1482
+ return null;
1483
+ }
1484
+ return readVideoTrackNumber(chunk, { dataOffset: element.dataOffset, size: element.size });
1485
+ }